sqlite3.c revision 74bd39cb46f3e9465fe069b650f40ffd8298a538
1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.14.0.  By combining all the individual C code files into this
4** single large file, the entire code can be compiled as a single translation
5** unit.  This allows many compilers to do optimizations that would not be
6** possible if the files were compiled separately.  Performance improvements
7** of 5% or more are commonly seen when SQLite is compiled as a single
8** translation unit.
9**
10** This file is all you need to compile SQLite.  To use SQLite in other
11** programs, you need this file and the "sqlite3.h" header file that defines
12** the programming interface to the SQLite library.  (If you do not have
13** the "sqlite3.h" header file at hand, you will find a copy embedded within
14** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15** of the embedded sqlite3.h header file.) Additional code files may be needed
16** if you want a wrapper to interface SQLite with your choice of programming
17** language. The code for the "sqlite3" command-line shell is also in a
18** separate file. This file contains only code for the core SQLite library.
19*/
20#define SQLITE_CORE 1
21#define SQLITE_AMALGAMATION 1
22#ifndef SQLITE_PRIVATE
23# define SQLITE_PRIVATE static
24#endif
25/************** Begin file sqliteInt.h ***************************************/
26/*
27** 2001 September 15
28**
29** The author disclaims copyright to this source code.  In place of
30** a legal notice, here is a blessing:
31**
32**    May you do good and not evil.
33**    May you find forgiveness for yourself and forgive others.
34**    May you share freely, never taking more than you give.
35**
36*************************************************************************
37** Internal interface definitions for SQLite.
38**
39*/
40#ifndef SQLITEINT_H
41#define SQLITEINT_H
42
43/* Special Comments:
44**
45** Some comments have special meaning to the tools that measure test
46** coverage:
47**
48**    NO_TEST                     - The branches on this line are not
49**                                  measured by branch coverage.  This is
50**                                  used on lines of code that actually
51**                                  implement parts of coverage testing.
52**
53**    OPTIMIZATION-IF-TRUE        - This branch is allowed to alway be false
54**                                  and the correct answer is still obtained,
55**                                  though perhaps more slowly.
56**
57**    OPTIMIZATION-IF-FALSE       - This branch is allowed to alway be true
58**                                  and the correct answer is still obtained,
59**                                  though perhaps more slowly.
60**
61**    PREVENTS-HARMLESS-OVERREAD  - This branch prevents a buffer overread
62**                                  that would be harmless and undetectable
63**                                  if it did occur.
64**
65** In all cases, the special comment must be enclosed in the usual
66** slash-asterisk...asterisk-slash comment marks, with no spaces between the
67** asterisks and the comment text.
68*/
69
70/*
71** Make sure the Tcl calling convention macro is defined.  This macro is
72** only used by test code and Tcl integration code.
73*/
74#ifndef SQLITE_TCLAPI
75#  define SQLITE_TCLAPI
76#endif
77
78/*
79** Make sure that rand_s() is available on Windows systems with MSVC 2005
80** or higher.
81*/
82#if defined(_MSC_VER) && _MSC_VER>=1400
83#  define _CRT_RAND_S
84#endif
85
86/*
87** Include the header file used to customize the compiler options for MSVC.
88** This should be done first so that it can successfully prevent spurious
89** compiler warnings due to subsequent content in this file and other files
90** that are included by this file.
91*/
92/************** Include msvc.h in the middle of sqliteInt.h ******************/
93/************** Begin file msvc.h ********************************************/
94/*
95** 2015 January 12
96**
97** The author disclaims copyright to this source code.  In place of
98** a legal notice, here is a blessing:
99**
100**    May you do good and not evil.
101**    May you find forgiveness for yourself and forgive others.
102**    May you share freely, never taking more than you give.
103**
104******************************************************************************
105**
106** This file contains code that is specific to MSVC.
107*/
108#ifndef SQLITE_MSVC_H
109#define SQLITE_MSVC_H
110
111#if defined(_MSC_VER)
112#pragma warning(disable : 4054)
113#pragma warning(disable : 4055)
114#pragma warning(disable : 4100)
115#pragma warning(disable : 4127)
116#pragma warning(disable : 4130)
117#pragma warning(disable : 4152)
118#pragma warning(disable : 4189)
119#pragma warning(disable : 4206)
120#pragma warning(disable : 4210)
121#pragma warning(disable : 4232)
122#pragma warning(disable : 4244)
123#pragma warning(disable : 4305)
124#pragma warning(disable : 4306)
125#pragma warning(disable : 4702)
126#pragma warning(disable : 4706)
127#endif /* defined(_MSC_VER) */
128
129#endif /* SQLITE_MSVC_H */
130
131/************** End of msvc.h ************************************************/
132/************** Continuing where we left off in sqliteInt.h ******************/
133
134/*
135** Special setup for VxWorks
136*/
137/************** Include vxworks.h in the middle of sqliteInt.h ***************/
138/************** Begin file vxworks.h *****************************************/
139/*
140** 2015-03-02
141**
142** The author disclaims copyright to this source code.  In place of
143** a legal notice, here is a blessing:
144**
145**    May you do good and not evil.
146**    May you find forgiveness for yourself and forgive others.
147**    May you share freely, never taking more than you give.
148**
149******************************************************************************
150**
151** This file contains code that is specific to Wind River's VxWorks
152*/
153#if defined(__RTP__) || defined(_WRS_KERNEL)
154/* This is VxWorks.  Set up things specially for that OS
155*/
156#include <vxWorks.h>
157#include <pthread.h>  /* amalgamator: dontcache */
158#define OS_VXWORKS 1
159#define SQLITE_OS_OTHER 0
160#define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
161#define SQLITE_OMIT_LOAD_EXTENSION 1
162#define SQLITE_ENABLE_LOCKING_STYLE 0
163#define HAVE_UTIME 1
164#else
165/* This is not VxWorks. */
166#define OS_VXWORKS 0
167#define HAVE_FCHOWN 1
168#define HAVE_READLINK 1
169#define HAVE_LSTAT 1
170#endif /* defined(_WRS_KERNEL) */
171
172/************** End of vxworks.h *********************************************/
173/************** Continuing where we left off in sqliteInt.h ******************/
174
175/*
176** These #defines should enable >2GB file support on POSIX if the
177** underlying operating system supports it.  If the OS lacks
178** large file support, or if the OS is windows, these should be no-ops.
179**
180** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
181** system #includes.  Hence, this block of code must be the very first
182** code in all source files.
183**
184** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
185** on the compiler command line.  This is necessary if you are compiling
186** on a recent machine (ex: Red Hat 7.2) but you want your code to work
187** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
188** without this option, LFS is enable.  But LFS does not exist in the kernel
189** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
190** portability you should omit LFS.
191**
192** The previous paragraph was written in 2005.  (This paragraph is written
193** on 2008-11-28.) These days, all Linux kernels support large files, so
194** you should probably leave LFS enabled.  But some embedded platforms might
195** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
196**
197** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
198*/
199#ifndef SQLITE_DISABLE_LFS
200# define _LARGE_FILE       1
201# ifndef _FILE_OFFSET_BITS
202#   define _FILE_OFFSET_BITS 64
203# endif
204# define _LARGEFILE_SOURCE 1
205#endif
206
207/* What version of GCC is being used.  0 means GCC is not being used */
208#ifdef __GNUC__
209# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
210#else
211# define GCC_VERSION 0
212#endif
213
214/* Needed for various definitions... */
215#if defined(__GNUC__) && !defined(_GNU_SOURCE)
216# define _GNU_SOURCE
217#endif
218
219#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
220# define _BSD_SOURCE
221#endif
222
223/*
224** For MinGW, check to see if we can include the header file containing its
225** version information, among other things.  Normally, this internal MinGW
226** header file would [only] be included automatically by other MinGW header
227** files; however, the contained version information is now required by this
228** header file to work around binary compatibility issues (see below) and
229** this is the only known way to reliably obtain it.  This entire #if block
230** would be completely unnecessary if there was any other way of detecting
231** MinGW via their preprocessor (e.g. if they customized their GCC to define
232** some MinGW-specific macros).  When compiling for MinGW, either the
233** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
234** defined; otherwise, detection of conditions specific to MinGW will be
235** disabled.
236*/
237#if defined(_HAVE_MINGW_H)
238# include "mingw.h"
239#elif defined(_HAVE__MINGW_H)
240# include "_mingw.h"
241#endif
242
243/*
244** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
245** define is required to maintain binary compatibility with the MSVC runtime
246** library in use (e.g. for Windows XP).
247*/
248#if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
249    defined(_WIN32) && !defined(_WIN64) && \
250    defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
251    defined(__MSVCRT__)
252# define _USE_32BIT_TIME_T
253#endif
254
255/* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
256** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
257** MinGW.
258*/
259/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
260/************** Begin file sqlite3.h *****************************************/
261/*
262** 2001 September 15
263**
264** The author disclaims copyright to this source code.  In place of
265** a legal notice, here is a blessing:
266**
267**    May you do good and not evil.
268**    May you find forgiveness for yourself and forgive others.
269**    May you share freely, never taking more than you give.
270**
271*************************************************************************
272** This header file defines the interface that the SQLite library
273** presents to client programs.  If a C-function, structure, datatype,
274** or constant definition does not appear in this file, then it is
275** not a published API of SQLite, is subject to change without
276** notice, and should not be referenced by programs that use SQLite.
277**
278** Some of the definitions that are in this file are marked as
279** "experimental".  Experimental interfaces are normally new
280** features recently added to SQLite.  We do not anticipate changes
281** to experimental interfaces but reserve the right to make minor changes
282** if experience from use "in the wild" suggest such changes are prudent.
283**
284** The official C-language API documentation for SQLite is derived
285** from comments in this file.  This file is the authoritative source
286** on how SQLite interfaces are supposed to operate.
287**
288** The name of this file under configuration management is "sqlite.h.in".
289** The makefile makes some minor changes to this file (such as inserting
290** the version number) and changes its name to "sqlite3.h" as
291** part of the build process.
292*/
293#ifndef SQLITE3_H
294#define SQLITE3_H
295#include <stdarg.h>     /* Needed for the definition of va_list */
296
297/*
298** Make sure we can call this stuff from C++.
299*/
300#if 0
301extern "C" {
302#endif
303
304
305/*
306** Provide the ability to override linkage features of the interface.
307*/
308#ifndef SQLITE_EXTERN
309# define SQLITE_EXTERN extern
310#endif
311#ifndef SQLITE_API
312# define SQLITE_API
313#endif
314#ifndef SQLITE_CDECL
315# define SQLITE_CDECL
316#endif
317#ifndef SQLITE_APICALL
318# define SQLITE_APICALL
319#endif
320#ifndef SQLITE_STDCALL
321# define SQLITE_STDCALL SQLITE_APICALL
322#endif
323#ifndef SQLITE_CALLBACK
324# define SQLITE_CALLBACK
325#endif
326#ifndef SQLITE_SYSAPI
327# define SQLITE_SYSAPI
328#endif
329
330/*
331** These no-op macros are used in front of interfaces to mark those
332** interfaces as either deprecated or experimental.  New applications
333** should not use deprecated interfaces - they are supported for backwards
334** compatibility only.  Application writers should be aware that
335** experimental interfaces are subject to change in point releases.
336**
337** These macros used to resolve to various kinds of compiler magic that
338** would generate warning messages when they were used.  But that
339** compiler magic ended up generating such a flurry of bug reports
340** that we have taken it all out and gone back to using simple
341** noop macros.
342*/
343#define SQLITE_DEPRECATED
344#define SQLITE_EXPERIMENTAL
345
346/*
347** Ensure these symbols were not defined by some previous header file.
348*/
349#ifdef SQLITE_VERSION
350# undef SQLITE_VERSION
351#endif
352#ifdef SQLITE_VERSION_NUMBER
353# undef SQLITE_VERSION_NUMBER
354#endif
355
356/*
357** CAPI3REF: Compile-Time Library Version Numbers
358**
359** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
360** evaluates to a string literal that is the SQLite version in the
361** format "X.Y.Z" where X is the major version number (always 3 for
362** SQLite3) and Y is the minor version number and Z is the release number.)^
363** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
364** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
365** numbers used in [SQLITE_VERSION].)^
366** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
367** be larger than the release from which it is derived.  Either Y will
368** be held constant and Z will be incremented or else Y will be incremented
369** and Z will be reset to zero.
370**
371** Since version 3.6.18, SQLite source code has been stored in the
372** <a href="http://www.fossil-scm.org/">Fossil configuration management
373** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
374** a string which identifies a particular check-in of SQLite
375** within its configuration management system.  ^The SQLITE_SOURCE_ID
376** string contains the date and time of the check-in (UTC) and an SHA1
377** hash of the entire source tree.
378**
379** See also: [sqlite3_libversion()],
380** [sqlite3_libversion_number()], [sqlite3_sourceid()],
381** [sqlite_version()] and [sqlite_source_id()].
382*/
383#define SQLITE_VERSION        "3.14.0"
384#define SQLITE_VERSION_NUMBER 3014000
385#define SQLITE_SOURCE_ID      "2016-08-08 13:40:27 d5e98057028abcf7217d0d2b2e29bbbcdf09d6de"
386
387/*
388** CAPI3REF: Run-Time Library Version Numbers
389** KEYWORDS: sqlite3_version, sqlite3_sourceid
390**
391** These interfaces provide the same information as the [SQLITE_VERSION],
392** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
393** but are associated with the library instead of the header file.  ^(Cautious
394** programmers might include assert() statements in their application to
395** verify that values returned by these interfaces match the macros in
396** the header, and thus ensure that the application is
397** compiled with matching library and header files.
398**
399** <blockquote><pre>
400** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
401** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
402** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
403** </pre></blockquote>)^
404**
405** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
406** macro.  ^The sqlite3_libversion() function returns a pointer to the
407** to the sqlite3_version[] string constant.  The sqlite3_libversion()
408** function is provided for use in DLLs since DLL users usually do not have
409** direct access to string constants within the DLL.  ^The
410** sqlite3_libversion_number() function returns an integer equal to
411** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
412** a pointer to a string constant whose value is the same as the
413** [SQLITE_SOURCE_ID] C preprocessor macro.
414**
415** See also: [sqlite_version()] and [sqlite_source_id()].
416*/
417SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
418SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void);
419SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void);
420SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void);
421
422/*
423** CAPI3REF: Run-Time Library Compilation Options Diagnostics
424**
425** ^The sqlite3_compileoption_used() function returns 0 or 1
426** indicating whether the specified option was defined at
427** compile time.  ^The SQLITE_ prefix may be omitted from the
428** option name passed to sqlite3_compileoption_used().
429**
430** ^The sqlite3_compileoption_get() function allows iterating
431** over the list of options that were defined at compile time by
432** returning the N-th compile time option string.  ^If N is out of range,
433** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
434** prefix is omitted from any strings returned by
435** sqlite3_compileoption_get().
436**
437** ^Support for the diagnostic functions sqlite3_compileoption_used()
438** and sqlite3_compileoption_get() may be omitted by specifying the
439** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
440**
441** See also: SQL functions [sqlite_compileoption_used()] and
442** [sqlite_compileoption_get()] and the [compile_options pragma].
443*/
444#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
445SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName);
446SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N);
447#endif
448
449/*
450** CAPI3REF: Test To See If The Library Is Threadsafe
451**
452** ^The sqlite3_threadsafe() function returns zero if and only if
453** SQLite was compiled with mutexing code omitted due to the
454** [SQLITE_THREADSAFE] compile-time option being set to 0.
455**
456** SQLite can be compiled with or without mutexes.  When
457** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
458** are enabled and SQLite is threadsafe.  When the
459** [SQLITE_THREADSAFE] macro is 0,
460** the mutexes are omitted.  Without the mutexes, it is not safe
461** to use SQLite concurrently from more than one thread.
462**
463** Enabling mutexes incurs a measurable performance penalty.
464** So if speed is of utmost importance, it makes sense to disable
465** the mutexes.  But for maximum safety, mutexes should be enabled.
466** ^The default behavior is for mutexes to be enabled.
467**
468** This interface can be used by an application to make sure that the
469** version of SQLite that it is linking against was compiled with
470** the desired setting of the [SQLITE_THREADSAFE] macro.
471**
472** This interface only reports on the compile-time mutex setting
473** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
474** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
475** can be fully or partially disabled using a call to [sqlite3_config()]
476** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
477** or [SQLITE_CONFIG_SERIALIZED].  ^(The return value of the
478** sqlite3_threadsafe() function shows only the compile-time setting of
479** thread safety, not any run-time changes to that setting made by
480** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
481** is unchanged by calls to sqlite3_config().)^
482**
483** See the [threading mode] documentation for additional information.
484*/
485SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void);
486
487/*
488** CAPI3REF: Database Connection Handle
489** KEYWORDS: {database connection} {database connections}
490**
491** Each open SQLite database is represented by a pointer to an instance of
492** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
493** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
494** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
495** and [sqlite3_close_v2()] are its destructors.  There are many other
496** interfaces (such as
497** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
498** [sqlite3_busy_timeout()] to name but three) that are methods on an
499** sqlite3 object.
500*/
501typedef struct sqlite3 sqlite3;
502
503/*
504** CAPI3REF: 64-Bit Integer Types
505** KEYWORDS: sqlite_int64 sqlite_uint64
506**
507** Because there is no cross-platform way to specify 64-bit integer types
508** SQLite includes typedefs for 64-bit signed and unsigned integers.
509**
510** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
511** The sqlite_int64 and sqlite_uint64 types are supported for backwards
512** compatibility only.
513**
514** ^The sqlite3_int64 and sqlite_int64 types can store integer values
515** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
516** sqlite3_uint64 and sqlite_uint64 types can store integer values
517** between 0 and +18446744073709551615 inclusive.
518*/
519#ifdef SQLITE_INT64_TYPE
520  typedef SQLITE_INT64_TYPE sqlite_int64;
521  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
522#elif defined(_MSC_VER) || defined(__BORLANDC__)
523  typedef __int64 sqlite_int64;
524  typedef unsigned __int64 sqlite_uint64;
525#else
526  typedef long long int sqlite_int64;
527  typedef unsigned long long int sqlite_uint64;
528#endif
529typedef sqlite_int64 sqlite3_int64;
530typedef sqlite_uint64 sqlite3_uint64;
531
532/*
533** If compiling for a processor that lacks floating point support,
534** substitute integer for floating-point.
535*/
536#ifdef SQLITE_OMIT_FLOATING_POINT
537# define double sqlite3_int64
538#endif
539
540/*
541** CAPI3REF: Closing A Database Connection
542** DESTRUCTOR: sqlite3
543**
544** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
545** for the [sqlite3] object.
546** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
547** the [sqlite3] object is successfully destroyed and all associated
548** resources are deallocated.
549**
550** ^If the database connection is associated with unfinalized prepared
551** statements or unfinished sqlite3_backup objects then sqlite3_close()
552** will leave the database connection open and return [SQLITE_BUSY].
553** ^If sqlite3_close_v2() is called with unfinalized prepared statements
554** and/or unfinished sqlite3_backups, then the database connection becomes
555** an unusable "zombie" which will automatically be deallocated when the
556** last prepared statement is finalized or the last sqlite3_backup is
557** finished.  The sqlite3_close_v2() interface is intended for use with
558** host languages that are garbage collected, and where the order in which
559** destructors are called is arbitrary.
560**
561** Applications should [sqlite3_finalize | finalize] all [prepared statements],
562** [sqlite3_blob_close | close] all [BLOB handles], and
563** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
564** with the [sqlite3] object prior to attempting to close the object.  ^If
565** sqlite3_close_v2() is called on a [database connection] that still has
566** outstanding [prepared statements], [BLOB handles], and/or
567** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
568** of resources is deferred until all [prepared statements], [BLOB handles],
569** and [sqlite3_backup] objects are also destroyed.
570**
571** ^If an [sqlite3] object is destroyed while a transaction is open,
572** the transaction is automatically rolled back.
573**
574** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
575** must be either a NULL
576** pointer or an [sqlite3] object pointer obtained
577** from [sqlite3_open()], [sqlite3_open16()], or
578** [sqlite3_open_v2()], and not previously closed.
579** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
580** argument is a harmless no-op.
581*/
582SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3*);
583SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3*);
584
585/*
586** The type for a callback function.
587** This is legacy and deprecated.  It is included for historical
588** compatibility and is not documented.
589*/
590typedef int (*sqlite3_callback)(void*,int,char**, char**);
591
592/*
593** CAPI3REF: One-Step Query Execution Interface
594** METHOD: sqlite3
595**
596** The sqlite3_exec() interface is a convenience wrapper around
597** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
598** that allows an application to run multiple statements of SQL
599** without having to use a lot of C code.
600**
601** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
602** semicolon-separate SQL statements passed into its 2nd argument,
603** in the context of the [database connection] passed in as its 1st
604** argument.  ^If the callback function of the 3rd argument to
605** sqlite3_exec() is not NULL, then it is invoked for each result row
606** coming out of the evaluated SQL statements.  ^The 4th argument to
607** sqlite3_exec() is relayed through to the 1st argument of each
608** callback invocation.  ^If the callback pointer to sqlite3_exec()
609** is NULL, then no callback is ever invoked and result rows are
610** ignored.
611**
612** ^If an error occurs while evaluating the SQL statements passed into
613** sqlite3_exec(), then execution of the current statement stops and
614** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
615** is not NULL then any error message is written into memory obtained
616** from [sqlite3_malloc()] and passed back through the 5th parameter.
617** To avoid memory leaks, the application should invoke [sqlite3_free()]
618** on error message strings returned through the 5th parameter of
619** sqlite3_exec() after the error message string is no longer needed.
620** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
621** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
622** NULL before returning.
623**
624** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
625** routine returns SQLITE_ABORT without invoking the callback again and
626** without running any subsequent SQL statements.
627**
628** ^The 2nd argument to the sqlite3_exec() callback function is the
629** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
630** callback is an array of pointers to strings obtained as if from
631** [sqlite3_column_text()], one for each column.  ^If an element of a
632** result row is NULL then the corresponding string pointer for the
633** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
634** sqlite3_exec() callback is an array of pointers to strings where each
635** entry represents the name of corresponding result column as obtained
636** from [sqlite3_column_name()].
637**
638** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
639** to an empty string, or a pointer that contains only whitespace and/or
640** SQL comments, then no SQL statements are evaluated and the database
641** is not changed.
642**
643** Restrictions:
644**
645** <ul>
646** <li> The application must ensure that the 1st parameter to sqlite3_exec()
647**      is a valid and open [database connection].
648** <li> The application must not close the [database connection] specified by
649**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
650** <li> The application must not modify the SQL statement text passed into
651**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
652** </ul>
653*/
654SQLITE_API int SQLITE_STDCALL sqlite3_exec(
655  sqlite3*,                                  /* An open database */
656  const char *sql,                           /* SQL to be evaluated */
657  int (*callback)(void*,int,char**,char**),  /* Callback function */
658  void *,                                    /* 1st argument to callback */
659  char **errmsg                              /* Error msg written here */
660);
661
662/*
663** CAPI3REF: Result Codes
664** KEYWORDS: {result code definitions}
665**
666** Many SQLite functions return an integer result code from the set shown
667** here in order to indicate success or failure.
668**
669** New error codes may be added in future versions of SQLite.
670**
671** See also: [extended result code definitions]
672*/
673#define SQLITE_OK           0   /* Successful result */
674/* beginning-of-error-codes */
675#define SQLITE_ERROR        1   /* SQL error or missing database */
676#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
677#define SQLITE_PERM         3   /* Access permission denied */
678#define SQLITE_ABORT        4   /* Callback routine requested an abort */
679#define SQLITE_BUSY         5   /* The database file is locked */
680#define SQLITE_LOCKED       6   /* A table in the database is locked */
681#define SQLITE_NOMEM        7   /* A malloc() failed */
682#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
683#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
684#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
685#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
686#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
687#define SQLITE_FULL        13   /* Insertion failed because database is full */
688#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
689#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
690#define SQLITE_EMPTY       16   /* Database is empty */
691#define SQLITE_SCHEMA      17   /* The database schema changed */
692#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
693#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
694#define SQLITE_MISMATCH    20   /* Data type mismatch */
695#define SQLITE_MISUSE      21   /* Library used incorrectly */
696#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
697#define SQLITE_AUTH        23   /* Authorization denied */
698#define SQLITE_FORMAT      24   /* Auxiliary database format error */
699#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
700#define SQLITE_NOTADB      26   /* File opened that is not a database file */
701#define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
702#define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
703#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
704#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
705/* end-of-error-codes */
706
707/*
708** CAPI3REF: Extended Result Codes
709** KEYWORDS: {extended result code definitions}
710**
711** In its default configuration, SQLite API routines return one of 30 integer
712** [result codes].  However, experience has shown that many of
713** these result codes are too coarse-grained.  They do not provide as
714** much information about problems as programmers might like.  In an effort to
715** address this, newer versions of SQLite (version 3.3.8 and later) include
716** support for additional result codes that provide more detailed information
717** about errors. These [extended result codes] are enabled or disabled
718** on a per database connection basis using the
719** [sqlite3_extended_result_codes()] API.  Or, the extended code for
720** the most recent error can be obtained using
721** [sqlite3_extended_errcode()].
722*/
723#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
724#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
725#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
726#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
727#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
728#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
729#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
730#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
731#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
732#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
733#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
734#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
735#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
736#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
737#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
738#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
739#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
740#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
741#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
742#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
743#define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
744#define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
745#define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
746#define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
747#define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
748#define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
749#define SQLITE_IOERR_VNODE             (SQLITE_IOERR | (27<<8))
750#define SQLITE_IOERR_AUTH              (SQLITE_IOERR | (28<<8))
751#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
752#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
753#define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
754#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
755#define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
756#define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
757#define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
758#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
759#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
760#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
761#define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
762#define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
763#define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
764#define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
765#define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
766#define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
767#define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
768#define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
769#define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
770#define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
771#define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
772#define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
773#define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
774#define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
775#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
776#define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
777#define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
778#define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))
779
780/*
781** CAPI3REF: Flags For File Open Operations
782**
783** These bit values are intended for use in the
784** 3rd parameter to the [sqlite3_open_v2()] interface and
785** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
786*/
787#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
788#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
789#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
790#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
791#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
792#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
793#define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
794#define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
795#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
796#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
797#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
798#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
799#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
800#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
801#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
802#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
803#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
804#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
805#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
806#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
807
808/* Reserved:                         0x00F00000 */
809
810/*
811** CAPI3REF: Device Characteristics
812**
813** The xDeviceCharacteristics method of the [sqlite3_io_methods]
814** object returns an integer which is a vector of these
815** bit values expressing I/O characteristics of the mass storage
816** device that holds the file that the [sqlite3_io_methods]
817** refers to.
818**
819** The SQLITE_IOCAP_ATOMIC property means that all writes of
820** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
821** mean that writes of blocks that are nnn bytes in size and
822** are aligned to an address which is an integer multiple of
823** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
824** that when data is appended to a file, the data is appended
825** first then the size of the file is extended, never the other
826** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
827** information is written to disk in the same order as calls
828** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
829** after reboot following a crash or power loss, the only bytes in a
830** file that were written at the application level might have changed
831** and that adjacent bytes, even bytes within the same sector are
832** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
833** flag indicate that a file cannot be deleted when open.  The
834** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
835** read-only media and cannot be changed even by processes with
836** elevated privileges.
837*/
838#define SQLITE_IOCAP_ATOMIC                 0x00000001
839#define SQLITE_IOCAP_ATOMIC512              0x00000002
840#define SQLITE_IOCAP_ATOMIC1K               0x00000004
841#define SQLITE_IOCAP_ATOMIC2K               0x00000008
842#define SQLITE_IOCAP_ATOMIC4K               0x00000010
843#define SQLITE_IOCAP_ATOMIC8K               0x00000020
844#define SQLITE_IOCAP_ATOMIC16K              0x00000040
845#define SQLITE_IOCAP_ATOMIC32K              0x00000080
846#define SQLITE_IOCAP_ATOMIC64K              0x00000100
847#define SQLITE_IOCAP_SAFE_APPEND            0x00000200
848#define SQLITE_IOCAP_SEQUENTIAL             0x00000400
849#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
850#define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
851#define SQLITE_IOCAP_IMMUTABLE              0x00002000
852
853/*
854** CAPI3REF: File Locking Levels
855**
856** SQLite uses one of these integer values as the second
857** argument to calls it makes to the xLock() and xUnlock() methods
858** of an [sqlite3_io_methods] object.
859*/
860#define SQLITE_LOCK_NONE          0
861#define SQLITE_LOCK_SHARED        1
862#define SQLITE_LOCK_RESERVED      2
863#define SQLITE_LOCK_PENDING       3
864#define SQLITE_LOCK_EXCLUSIVE     4
865
866/*
867** CAPI3REF: Synchronization Type Flags
868**
869** When SQLite invokes the xSync() method of an
870** [sqlite3_io_methods] object it uses a combination of
871** these integer values as the second argument.
872**
873** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
874** sync operation only needs to flush data to mass storage.  Inode
875** information need not be flushed. If the lower four bits of the flag
876** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
877** If the lower four bits equal SQLITE_SYNC_FULL, that means
878** to use Mac OS X style fullsync instead of fsync().
879**
880** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
881** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
882** settings.  The [synchronous pragma] determines when calls to the
883** xSync VFS method occur and applies uniformly across all platforms.
884** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
885** energetic or rigorous or forceful the sync operations are and
886** only make a difference on Mac OSX for the default SQLite code.
887** (Third-party VFS implementations might also make the distinction
888** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
889** operating systems natively supported by SQLite, only Mac OSX
890** cares about the difference.)
891*/
892#define SQLITE_SYNC_NORMAL        0x00002
893#define SQLITE_SYNC_FULL          0x00003
894#define SQLITE_SYNC_DATAONLY      0x00010
895
896/*
897** CAPI3REF: OS Interface Open File Handle
898**
899** An [sqlite3_file] object represents an open file in the
900** [sqlite3_vfs | OS interface layer].  Individual OS interface
901** implementations will
902** want to subclass this object by appending additional fields
903** for their own use.  The pMethods entry is a pointer to an
904** [sqlite3_io_methods] object that defines methods for performing
905** I/O operations on the open file.
906*/
907typedef struct sqlite3_file sqlite3_file;
908struct sqlite3_file {
909  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
910};
911
912/*
913** CAPI3REF: OS Interface File Virtual Methods Object
914**
915** Every file opened by the [sqlite3_vfs.xOpen] method populates an
916** [sqlite3_file] object (or, more commonly, a subclass of the
917** [sqlite3_file] object) with a pointer to an instance of this object.
918** This object defines the methods used to perform various operations
919** against the open file represented by the [sqlite3_file] object.
920**
921** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
922** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
923** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
924** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
925** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
926** to NULL.
927**
928** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
929** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
930** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
931** flag may be ORed in to indicate that only the data of the file
932** and not its inode needs to be synced.
933**
934** The integer values to xLock() and xUnlock() are one of
935** <ul>
936** <li> [SQLITE_LOCK_NONE],
937** <li> [SQLITE_LOCK_SHARED],
938** <li> [SQLITE_LOCK_RESERVED],
939** <li> [SQLITE_LOCK_PENDING], or
940** <li> [SQLITE_LOCK_EXCLUSIVE].
941** </ul>
942** xLock() increases the lock. xUnlock() decreases the lock.
943** The xCheckReservedLock() method checks whether any database connection,
944** either in this process or in some other process, is holding a RESERVED,
945** PENDING, or EXCLUSIVE lock on the file.  It returns true
946** if such a lock exists and false otherwise.
947**
948** The xFileControl() method is a generic interface that allows custom
949** VFS implementations to directly control an open file using the
950** [sqlite3_file_control()] interface.  The second "op" argument is an
951** integer opcode.  The third argument is a generic pointer intended to
952** point to a structure that may contain arguments or space in which to
953** write return values.  Potential uses for xFileControl() might be
954** functions to enable blocking locks with timeouts, to change the
955** locking strategy (for example to use dot-file locks), to inquire
956** about the status of a lock, or to break stale locks.  The SQLite
957** core reserves all opcodes less than 100 for its own use.
958** A [file control opcodes | list of opcodes] less than 100 is available.
959** Applications that define a custom xFileControl method should use opcodes
960** greater than 100 to avoid conflicts.  VFS implementations should
961** return [SQLITE_NOTFOUND] for file control opcodes that they do not
962** recognize.
963**
964** The xSectorSize() method returns the sector size of the
965** device that underlies the file.  The sector size is the
966** minimum write that can be performed without disturbing
967** other bytes in the file.  The xDeviceCharacteristics()
968** method returns a bit vector describing behaviors of the
969** underlying device:
970**
971** <ul>
972** <li> [SQLITE_IOCAP_ATOMIC]
973** <li> [SQLITE_IOCAP_ATOMIC512]
974** <li> [SQLITE_IOCAP_ATOMIC1K]
975** <li> [SQLITE_IOCAP_ATOMIC2K]
976** <li> [SQLITE_IOCAP_ATOMIC4K]
977** <li> [SQLITE_IOCAP_ATOMIC8K]
978** <li> [SQLITE_IOCAP_ATOMIC16K]
979** <li> [SQLITE_IOCAP_ATOMIC32K]
980** <li> [SQLITE_IOCAP_ATOMIC64K]
981** <li> [SQLITE_IOCAP_SAFE_APPEND]
982** <li> [SQLITE_IOCAP_SEQUENTIAL]
983** </ul>
984**
985** The SQLITE_IOCAP_ATOMIC property means that all writes of
986** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
987** mean that writes of blocks that are nnn bytes in size and
988** are aligned to an address which is an integer multiple of
989** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
990** that when data is appended to a file, the data is appended
991** first then the size of the file is extended, never the other
992** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
993** information is written to disk in the same order as calls
994** to xWrite().
995**
996** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
997** in the unread portions of the buffer with zeros.  A VFS that
998** fails to zero-fill short reads might seem to work.  However,
999** failure to zero-fill short reads will eventually lead to
1000** database corruption.
1001*/
1002typedef struct sqlite3_io_methods sqlite3_io_methods;
1003struct sqlite3_io_methods {
1004  int iVersion;
1005  int (*xClose)(sqlite3_file*);
1006  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1007  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1008  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1009  int (*xSync)(sqlite3_file*, int flags);
1010  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1011  int (*xLock)(sqlite3_file*, int);
1012  int (*xUnlock)(sqlite3_file*, int);
1013  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1014  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1015  int (*xSectorSize)(sqlite3_file*);
1016  int (*xDeviceCharacteristics)(sqlite3_file*);
1017  /* Methods above are valid for version 1 */
1018  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1019  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1020  void (*xShmBarrier)(sqlite3_file*);
1021  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1022  /* Methods above are valid for version 2 */
1023  int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
1024  int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
1025  /* Methods above are valid for version 3 */
1026  /* Additional methods may be added in future releases */
1027};
1028
1029/*
1030** CAPI3REF: Standard File Control Opcodes
1031** KEYWORDS: {file control opcodes} {file control opcode}
1032**
1033** These integer constants are opcodes for the xFileControl method
1034** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1035** interface.
1036**
1037** <ul>
1038** <li>[[SQLITE_FCNTL_LOCKSTATE]]
1039** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1040** opcode causes the xFileControl method to write the current state of
1041** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1042** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1043** into an integer that the pArg argument points to. This capability
1044** is used during testing and is only available when the SQLITE_TEST
1045** compile-time option is used.
1046**
1047** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1048** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1049** layer a hint of how large the database file will grow to be during the
1050** current transaction.  This hint is not guaranteed to be accurate but it
1051** is often close.  The underlying VFS might choose to preallocate database
1052** file space based on this hint in order to help writes to the database
1053** file run faster.
1054**
1055** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1056** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1057** extends and truncates the database file in chunks of a size specified
1058** by the user. The fourth argument to [sqlite3_file_control()] should
1059** point to an integer (type int) containing the new chunk-size to use
1060** for the nominated database. Allocating database file space in large
1061** chunks (say 1MB at a time), may reduce file-system fragmentation and
1062** improve performance on some systems.
1063**
1064** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1065** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1066** to the [sqlite3_file] object associated with a particular database
1067** connection.  See also [SQLITE_FCNTL_JOURNAL_POINTER].
1068**
1069** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
1070** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
1071** to the [sqlite3_file] object associated with the journal file (either
1072** the [rollback journal] or the [write-ahead log]) for a particular database
1073** connection.  See also [SQLITE_FCNTL_FILE_POINTER].
1074**
1075** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1076** No longer in use.
1077**
1078** <li>[[SQLITE_FCNTL_SYNC]]
1079** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
1080** sent to the VFS immediately before the xSync method is invoked on a
1081** database file descriptor. Or, if the xSync method is not invoked
1082** because the user has configured SQLite with
1083** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
1084** of the xSync method. In most cases, the pointer argument passed with
1085** this file-control is NULL. However, if the database file is being synced
1086** as part of a multi-database commit, the argument points to a nul-terminated
1087** string containing the transactions master-journal file name. VFSes that
1088** do not need this signal should silently ignore this opcode. Applications
1089** should not call [sqlite3_file_control()] with this opcode as doing so may
1090** disrupt the operation of the specialized VFSes that do require it.
1091**
1092** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
1093** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
1094** and sent to the VFS after a transaction has been committed immediately
1095** but before the database is unlocked. VFSes that do not need this signal
1096** should silently ignore this opcode. Applications should not call
1097** [sqlite3_file_control()] with this opcode as doing so may disrupt the
1098** operation of the specialized VFSes that do require it.
1099**
1100** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1101** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1102** retry counts and intervals for certain disk I/O operations for the
1103** windows [VFS] in order to provide robustness in the presence of
1104** anti-virus programs.  By default, the windows VFS will retry file read,
1105** file write, and file delete operations up to 10 times, with a delay
1106** of 25 milliseconds before the first retry and with the delay increasing
1107** by an additional 25 milliseconds with each subsequent retry.  This
1108** opcode allows these two values (10 retries and 25 milliseconds of delay)
1109** to be adjusted.  The values are changed for all database connections
1110** within the same process.  The argument is a pointer to an array of two
1111** integers where the first integer i the new retry count and the second
1112** integer is the delay.  If either integer is negative, then the setting
1113** is not changed but instead the prior value of that setting is written
1114** into the array entry, allowing the current retry settings to be
1115** interrogated.  The zDbName parameter is ignored.
1116**
1117** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1118** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1119** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
1120** write ahead log and shared memory files used for transaction control
1121** are automatically deleted when the latest connection to the database
1122** closes.  Setting persistent WAL mode causes those files to persist after
1123** close.  Persisting the files is useful when other processes that do not
1124** have write permission on the directory containing the database file want
1125** to read the database file, as the WAL and shared memory files must exist
1126** in order for the database to be readable.  The fourth parameter to
1127** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1128** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1129** WAL mode.  If the integer is -1, then it is overwritten with the current
1130** WAL persistence setting.
1131**
1132** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1133** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1134** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
1135** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1136** xDeviceCharacteristics methods. The fourth parameter to
1137** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1138** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1139** mode.  If the integer is -1, then it is overwritten with the current
1140** zero-damage mode setting.
1141**
1142** <li>[[SQLITE_FCNTL_OVERWRITE]]
1143** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1144** a write transaction to indicate that, unless it is rolled back for some
1145** reason, the entire database file will be overwritten by the current
1146** transaction. This is used by VACUUM operations.
1147**
1148** <li>[[SQLITE_FCNTL_VFSNAME]]
1149** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1150** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
1151** final bottom-level VFS are written into memory obtained from
1152** [sqlite3_malloc()] and the result is stored in the char* variable
1153** that the fourth parameter of [sqlite3_file_control()] points to.
1154** The caller is responsible for freeing the memory when done.  As with
1155** all file-control actions, there is no guarantee that this will actually
1156** do anything.  Callers should initialize the char* variable to a NULL
1157** pointer in case this file-control is not implemented.  This file-control
1158** is intended for diagnostic use only.
1159**
1160** <li>[[SQLITE_FCNTL_VFS_POINTER]]
1161** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
1162** [VFSes] currently in use.  ^(The argument X in
1163** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
1164** of type "[sqlite3_vfs] **".  This opcodes will set *X
1165** to a pointer to the top-level VFS.)^
1166** ^When there are multiple VFS shims in the stack, this opcode finds the
1167** upper-most shim only.
1168**
1169** <li>[[SQLITE_FCNTL_PRAGMA]]
1170** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1171** file control is sent to the open [sqlite3_file] object corresponding
1172** to the database file to which the pragma statement refers. ^The argument
1173** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1174** pointers to strings (char**) in which the second element of the array
1175** is the name of the pragma and the third element is the argument to the
1176** pragma or NULL if the pragma has no argument.  ^The handler for an
1177** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1178** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1179** or the equivalent and that string will become the result of the pragma or
1180** the error message if the pragma fails. ^If the
1181** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1182** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1183** file control returns [SQLITE_OK], then the parser assumes that the
1184** VFS has handled the PRAGMA itself and the parser generates a no-op
1185** prepared statement if result string is NULL, or that returns a copy
1186** of the result string if the string is non-NULL.
1187** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1188** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1189** that the VFS encountered an error while handling the [PRAGMA] and the
1190** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1191** file control occurs at the beginning of pragma statement analysis and so
1192** it is able to override built-in [PRAGMA] statements.
1193**
1194** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1195** ^The [SQLITE_FCNTL_BUSYHANDLER]
1196** file-control may be invoked by SQLite on the database file handle
1197** shortly after it is opened in order to provide a custom VFS with access
1198** to the connections busy-handler callback. The argument is of type (void **)
1199** - an array of two (void *) values. The first (void *) actually points
1200** to a function of type (int (*)(void *)). In order to invoke the connections
1201** busy-handler, this function should be invoked with the second (void *) in
1202** the array as the only argument. If it returns non-zero, then the operation
1203** should be retried. If it returns zero, the custom VFS should abandon the
1204** current operation.
1205**
1206** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1207** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1208** to have SQLite generate a
1209** temporary filename using the same algorithm that is followed to generate
1210** temporary filenames for TEMP tables and other internal uses.  The
1211** argument should be a char** which will be filled with the filename
1212** written into memory obtained from [sqlite3_malloc()].  The caller should
1213** invoke [sqlite3_free()] on the result to avoid a memory leak.
1214**
1215** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1216** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1217** maximum number of bytes that will be used for memory-mapped I/O.
1218** The argument is a pointer to a value of type sqlite3_int64 that
1219** is an advisory maximum number of bytes in the file to memory map.  The
1220** pointer is overwritten with the old value.  The limit is not changed if
1221** the value originally pointed to is negative, and so the current limit
1222** can be queried by passing in a pointer to a negative number.  This
1223** file-control is used internally to implement [PRAGMA mmap_size].
1224**
1225** <li>[[SQLITE_FCNTL_TRACE]]
1226** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1227** to the VFS about what the higher layers of the SQLite stack are doing.
1228** This file control is used by some VFS activity tracing [shims].
1229** The argument is a zero-terminated string.  Higher layers in the
1230** SQLite stack may generate instances of this file control if
1231** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1232**
1233** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1234** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1235** pointer to an integer and it writes a boolean into that integer depending
1236** on whether or not the file has been renamed, moved, or deleted since it
1237** was first opened.
1238**
1239** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1240** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging.  This
1241** opcode causes the xFileControl method to swap the file handle with the one
1242** pointed to by the pArg argument.  This capability is used during testing
1243** and only needs to be supported when SQLITE_TEST is defined.
1244**
1245** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
1246** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
1247** be advantageous to block on the next WAL lock if the lock is not immediately
1248** available.  The WAL subsystem issues this signal during rare
1249** circumstances in order to fix a problem with priority inversion.
1250** Applications should <em>not</em> use this file-control.
1251**
1252** <li>[[SQLITE_FCNTL_ZIPVFS]]
1253** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
1254** VFS should return SQLITE_NOTFOUND for this opcode.
1255**
1256** <li>[[SQLITE_FCNTL_RBU]]
1257** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
1258** the RBU extension only.  All other VFS should return SQLITE_NOTFOUND for
1259** this opcode.
1260** </ul>
1261*/
1262#define SQLITE_FCNTL_LOCKSTATE               1
1263#define SQLITE_FCNTL_GET_LOCKPROXYFILE       2
1264#define SQLITE_FCNTL_SET_LOCKPROXYFILE       3
1265#define SQLITE_FCNTL_LAST_ERRNO              4
1266#define SQLITE_FCNTL_SIZE_HINT               5
1267#define SQLITE_FCNTL_CHUNK_SIZE              6
1268#define SQLITE_FCNTL_FILE_POINTER            7
1269#define SQLITE_FCNTL_SYNC_OMITTED            8
1270#define SQLITE_FCNTL_WIN32_AV_RETRY          9
1271#define SQLITE_FCNTL_PERSIST_WAL            10
1272#define SQLITE_FCNTL_OVERWRITE              11
1273#define SQLITE_FCNTL_VFSNAME                12
1274#define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
1275#define SQLITE_FCNTL_PRAGMA                 14
1276#define SQLITE_FCNTL_BUSYHANDLER            15
1277#define SQLITE_FCNTL_TEMPFILENAME           16
1278#define SQLITE_FCNTL_MMAP_SIZE              18
1279#define SQLITE_FCNTL_TRACE                  19
1280#define SQLITE_FCNTL_HAS_MOVED              20
1281#define SQLITE_FCNTL_SYNC                   21
1282#define SQLITE_FCNTL_COMMIT_PHASETWO        22
1283#define SQLITE_FCNTL_WIN32_SET_HANDLE       23
1284#define SQLITE_FCNTL_WAL_BLOCK              24
1285#define SQLITE_FCNTL_ZIPVFS                 25
1286#define SQLITE_FCNTL_RBU                    26
1287#define SQLITE_FCNTL_VFS_POINTER            27
1288#define SQLITE_FCNTL_JOURNAL_POINTER        28
1289
1290/* deprecated names */
1291#define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE
1292#define SQLITE_SET_LOCKPROXYFILE      SQLITE_FCNTL_SET_LOCKPROXYFILE
1293#define SQLITE_LAST_ERRNO             SQLITE_FCNTL_LAST_ERRNO
1294
1295
1296/*
1297** CAPI3REF: Mutex Handle
1298**
1299** The mutex module within SQLite defines [sqlite3_mutex] to be an
1300** abstract type for a mutex object.  The SQLite core never looks
1301** at the internal representation of an [sqlite3_mutex].  It only
1302** deals with pointers to the [sqlite3_mutex] object.
1303**
1304** Mutexes are created using [sqlite3_mutex_alloc()].
1305*/
1306typedef struct sqlite3_mutex sqlite3_mutex;
1307
1308/*
1309** CAPI3REF: Loadable Extension Thunk
1310**
1311** A pointer to the opaque sqlite3_api_routines structure is passed as
1312** the third parameter to entry points of [loadable extensions].  This
1313** structure must be typedefed in order to work around compiler warnings
1314** on some platforms.
1315*/
1316typedef struct sqlite3_api_routines sqlite3_api_routines;
1317
1318/*
1319** CAPI3REF: OS Interface Object
1320**
1321** An instance of the sqlite3_vfs object defines the interface between
1322** the SQLite core and the underlying operating system.  The "vfs"
1323** in the name of the object stands for "virtual file system".  See
1324** the [VFS | VFS documentation] for further information.
1325**
1326** The value of the iVersion field is initially 1 but may be larger in
1327** future versions of SQLite.  Additional fields may be appended to this
1328** object when the iVersion value is increased.  Note that the structure
1329** of the sqlite3_vfs object changes in the transaction between
1330** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1331** modified.
1332**
1333** The szOsFile field is the size of the subclassed [sqlite3_file]
1334** structure used by this VFS.  mxPathname is the maximum length of
1335** a pathname in this VFS.
1336**
1337** Registered sqlite3_vfs objects are kept on a linked list formed by
1338** the pNext pointer.  The [sqlite3_vfs_register()]
1339** and [sqlite3_vfs_unregister()] interfaces manage this list
1340** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1341** searches the list.  Neither the application code nor the VFS
1342** implementation should use the pNext pointer.
1343**
1344** The pNext field is the only field in the sqlite3_vfs
1345** structure that SQLite will ever modify.  SQLite will only access
1346** or modify this field while holding a particular static mutex.
1347** The application should never modify anything within the sqlite3_vfs
1348** object once the object has been registered.
1349**
1350** The zName field holds the name of the VFS module.  The name must
1351** be unique across all VFS modules.
1352**
1353** [[sqlite3_vfs.xOpen]]
1354** ^SQLite guarantees that the zFilename parameter to xOpen
1355** is either a NULL pointer or string obtained
1356** from xFullPathname() with an optional suffix added.
1357** ^If a suffix is added to the zFilename parameter, it will
1358** consist of a single "-" character followed by no more than
1359** 11 alphanumeric and/or "-" characters.
1360** ^SQLite further guarantees that
1361** the string will be valid and unchanged until xClose() is
1362** called. Because of the previous sentence,
1363** the [sqlite3_file] can safely store a pointer to the
1364** filename if it needs to remember the filename for some reason.
1365** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1366** must invent its own temporary name for the file.  ^Whenever the
1367** xFilename parameter is NULL it will also be the case that the
1368** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1369**
1370** The flags argument to xOpen() includes all bits set in
1371** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1372** or [sqlite3_open16()] is used, then flags includes at least
1373** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1374** If xOpen() opens a file read-only then it sets *pOutFlags to
1375** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1376**
1377** ^(SQLite will also add one of the following flags to the xOpen()
1378** call, depending on the object being opened:
1379**
1380** <ul>
1381** <li>  [SQLITE_OPEN_MAIN_DB]
1382** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1383** <li>  [SQLITE_OPEN_TEMP_DB]
1384** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1385** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1386** <li>  [SQLITE_OPEN_SUBJOURNAL]
1387** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1388** <li>  [SQLITE_OPEN_WAL]
1389** </ul>)^
1390**
1391** The file I/O implementation can use the object type flags to
1392** change the way it deals with files.  For example, an application
1393** that does not care about crash recovery or rollback might make
1394** the open of a journal file a no-op.  Writes to this journal would
1395** also be no-ops, and any attempt to read the journal would return
1396** SQLITE_IOERR.  Or the implementation might recognize that a database
1397** file will be doing page-aligned sector reads and writes in a random
1398** order and set up its I/O subsystem accordingly.
1399**
1400** SQLite might also add one of the following flags to the xOpen method:
1401**
1402** <ul>
1403** <li> [SQLITE_OPEN_DELETEONCLOSE]
1404** <li> [SQLITE_OPEN_EXCLUSIVE]
1405** </ul>
1406**
1407** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1408** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1409** will be set for TEMP databases and their journals, transient
1410** databases, and subjournals.
1411**
1412** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1413** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1414** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1415** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1416** SQLITE_OPEN_CREATE, is used to indicate that file should always
1417** be created, and that it is an error if it already exists.
1418** It is <i>not</i> used to indicate the file should be opened
1419** for exclusive access.
1420**
1421** ^At least szOsFile bytes of memory are allocated by SQLite
1422** to hold the  [sqlite3_file] structure passed as the third
1423** argument to xOpen.  The xOpen method does not have to
1424** allocate the structure; it should just fill it in.  Note that
1425** the xOpen method must set the sqlite3_file.pMethods to either
1426** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1427** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1428** element will be valid after xOpen returns regardless of the success
1429** or failure of the xOpen call.
1430**
1431** [[sqlite3_vfs.xAccess]]
1432** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1433** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1434** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1435** to test whether a file is at least readable.   The file can be a
1436** directory.
1437**
1438** ^SQLite will always allocate at least mxPathname+1 bytes for the
1439** output buffer xFullPathname.  The exact size of the output buffer
1440** is also passed as a parameter to both  methods. If the output buffer
1441** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1442** handled as a fatal error by SQLite, vfs implementations should endeavor
1443** to prevent this by setting mxPathname to a sufficiently large value.
1444**
1445** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1446** interfaces are not strictly a part of the filesystem, but they are
1447** included in the VFS structure for completeness.
1448** The xRandomness() function attempts to return nBytes bytes
1449** of good-quality randomness into zOut.  The return value is
1450** the actual number of bytes of randomness obtained.
1451** The xSleep() method causes the calling thread to sleep for at
1452** least the number of microseconds given.  ^The xCurrentTime()
1453** method returns a Julian Day Number for the current date and time as
1454** a floating point value.
1455** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1456** Day Number multiplied by 86400000 (the number of milliseconds in
1457** a 24-hour day).
1458** ^SQLite will use the xCurrentTimeInt64() method to get the current
1459** date and time if that method is available (if iVersion is 2 or
1460** greater and the function pointer is not NULL) and will fall back
1461** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1462**
1463** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1464** are not used by the SQLite core.  These optional interfaces are provided
1465** by some VFSes to facilitate testing of the VFS code. By overriding
1466** system calls with functions under its control, a test program can
1467** simulate faults and error conditions that would otherwise be difficult
1468** or impossible to induce.  The set of system calls that can be overridden
1469** varies from one VFS to another, and from one version of the same VFS to the
1470** next.  Applications that use these interfaces must be prepared for any
1471** or all of these interfaces to be NULL or for their behavior to change
1472** from one release to the next.  Applications must not attempt to access
1473** any of these methods if the iVersion of the VFS is less than 3.
1474*/
1475typedef struct sqlite3_vfs sqlite3_vfs;
1476typedef void (*sqlite3_syscall_ptr)(void);
1477struct sqlite3_vfs {
1478  int iVersion;            /* Structure version number (currently 3) */
1479  int szOsFile;            /* Size of subclassed sqlite3_file */
1480  int mxPathname;          /* Maximum file pathname length */
1481  sqlite3_vfs *pNext;      /* Next registered VFS */
1482  const char *zName;       /* Name of this virtual file system */
1483  void *pAppData;          /* Pointer to application-specific data */
1484  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1485               int flags, int *pOutFlags);
1486  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1487  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1488  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1489  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1490  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1491  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1492  void (*xDlClose)(sqlite3_vfs*, void*);
1493  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1494  int (*xSleep)(sqlite3_vfs*, int microseconds);
1495  int (*xCurrentTime)(sqlite3_vfs*, double*);
1496  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1497  /*
1498  ** The methods above are in version 1 of the sqlite_vfs object
1499  ** definition.  Those that follow are added in version 2 or later
1500  */
1501  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1502  /*
1503  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1504  ** Those below are for version 3 and greater.
1505  */
1506  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1507  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1508  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1509  /*
1510  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1511  ** New fields may be appended in future versions.  The iVersion
1512  ** value will increment whenever this happens.
1513  */
1514};
1515
1516/*
1517** CAPI3REF: Flags for the xAccess VFS method
1518**
1519** These integer constants can be used as the third parameter to
1520** the xAccess method of an [sqlite3_vfs] object.  They determine
1521** what kind of permissions the xAccess method is looking for.
1522** With SQLITE_ACCESS_EXISTS, the xAccess method
1523** simply checks whether the file exists.
1524** With SQLITE_ACCESS_READWRITE, the xAccess method
1525** checks whether the named directory is both readable and writable
1526** (in other words, if files can be added, removed, and renamed within
1527** the directory).
1528** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1529** [temp_store_directory pragma], though this could change in a future
1530** release of SQLite.
1531** With SQLITE_ACCESS_READ, the xAccess method
1532** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1533** currently unused, though it might be used in a future release of
1534** SQLite.
1535*/
1536#define SQLITE_ACCESS_EXISTS    0
1537#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1538#define SQLITE_ACCESS_READ      2   /* Unused */
1539
1540/*
1541** CAPI3REF: Flags for the xShmLock VFS method
1542**
1543** These integer constants define the various locking operations
1544** allowed by the xShmLock method of [sqlite3_io_methods].  The
1545** following are the only legal combinations of flags to the
1546** xShmLock method:
1547**
1548** <ul>
1549** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1550** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1551** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1552** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1553** </ul>
1554**
1555** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1556** was given on the corresponding lock.
1557**
1558** The xShmLock method can transition between unlocked and SHARED or
1559** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1560** and EXCLUSIVE.
1561*/
1562#define SQLITE_SHM_UNLOCK       1
1563#define SQLITE_SHM_LOCK         2
1564#define SQLITE_SHM_SHARED       4
1565#define SQLITE_SHM_EXCLUSIVE    8
1566
1567/*
1568** CAPI3REF: Maximum xShmLock index
1569**
1570** The xShmLock method on [sqlite3_io_methods] may use values
1571** between 0 and this upper bound as its "offset" argument.
1572** The SQLite core will never attempt to acquire or release a
1573** lock outside of this range
1574*/
1575#define SQLITE_SHM_NLOCK        8
1576
1577
1578/*
1579** CAPI3REF: Initialize The SQLite Library
1580**
1581** ^The sqlite3_initialize() routine initializes the
1582** SQLite library.  ^The sqlite3_shutdown() routine
1583** deallocates any resources that were allocated by sqlite3_initialize().
1584** These routines are designed to aid in process initialization and
1585** shutdown on embedded systems.  Workstation applications using
1586** SQLite normally do not need to invoke either of these routines.
1587**
1588** A call to sqlite3_initialize() is an "effective" call if it is
1589** the first time sqlite3_initialize() is invoked during the lifetime of
1590** the process, or if it is the first time sqlite3_initialize() is invoked
1591** following a call to sqlite3_shutdown().  ^(Only an effective call
1592** of sqlite3_initialize() does any initialization.  All other calls
1593** are harmless no-ops.)^
1594**
1595** A call to sqlite3_shutdown() is an "effective" call if it is the first
1596** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1597** an effective call to sqlite3_shutdown() does any deinitialization.
1598** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1599**
1600** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1601** is not.  The sqlite3_shutdown() interface must only be called from a
1602** single thread.  All open [database connections] must be closed and all
1603** other SQLite resources must be deallocated prior to invoking
1604** sqlite3_shutdown().
1605**
1606** Among other things, ^sqlite3_initialize() will invoke
1607** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1608** will invoke sqlite3_os_end().
1609**
1610** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1611** ^If for some reason, sqlite3_initialize() is unable to initialize
1612** the library (perhaps it is unable to allocate a needed resource such
1613** as a mutex) it returns an [error code] other than [SQLITE_OK].
1614**
1615** ^The sqlite3_initialize() routine is called internally by many other
1616** SQLite interfaces so that an application usually does not need to
1617** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1618** calls sqlite3_initialize() so the SQLite library will be automatically
1619** initialized when [sqlite3_open()] is called if it has not be initialized
1620** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1621** compile-time option, then the automatic calls to sqlite3_initialize()
1622** are omitted and the application must call sqlite3_initialize() directly
1623** prior to using any other SQLite interface.  For maximum portability,
1624** it is recommended that applications always invoke sqlite3_initialize()
1625** directly prior to using any other SQLite interface.  Future releases
1626** of SQLite may require this.  In other words, the behavior exhibited
1627** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1628** default behavior in some future release of SQLite.
1629**
1630** The sqlite3_os_init() routine does operating-system specific
1631** initialization of the SQLite library.  The sqlite3_os_end()
1632** routine undoes the effect of sqlite3_os_init().  Typical tasks
1633** performed by these routines include allocation or deallocation
1634** of static resources, initialization of global variables,
1635** setting up a default [sqlite3_vfs] module, or setting up
1636** a default configuration using [sqlite3_config()].
1637**
1638** The application should never invoke either sqlite3_os_init()
1639** or sqlite3_os_end() directly.  The application should only invoke
1640** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1641** interface is called automatically by sqlite3_initialize() and
1642** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1643** implementations for sqlite3_os_init() and sqlite3_os_end()
1644** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1645** When [custom builds | built for other platforms]
1646** (using the [SQLITE_OS_OTHER=1] compile-time
1647** option) the application must supply a suitable implementation for
1648** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1649** implementation of sqlite3_os_init() or sqlite3_os_end()
1650** must return [SQLITE_OK] on success and some other [error code] upon
1651** failure.
1652*/
1653SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void);
1654SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void);
1655SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void);
1656SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void);
1657
1658/*
1659** CAPI3REF: Configuring The SQLite Library
1660**
1661** The sqlite3_config() interface is used to make global configuration
1662** changes to SQLite in order to tune SQLite to the specific needs of
1663** the application.  The default configuration is recommended for most
1664** applications and so this routine is usually not necessary.  It is
1665** provided to support rare applications with unusual needs.
1666**
1667** <b>The sqlite3_config() interface is not threadsafe. The application
1668** must ensure that no other SQLite interfaces are invoked by other
1669** threads while sqlite3_config() is running.</b>
1670**
1671** The sqlite3_config() interface
1672** may only be invoked prior to library initialization using
1673** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1674** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1675** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1676** Note, however, that ^sqlite3_config() can be called as part of the
1677** implementation of an application-defined [sqlite3_os_init()].
1678**
1679** The first argument to sqlite3_config() is an integer
1680** [configuration option] that determines
1681** what property of SQLite is to be configured.  Subsequent arguments
1682** vary depending on the [configuration option]
1683** in the first argument.
1684**
1685** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1686** ^If the option is unknown or SQLite is unable to set the option
1687** then this routine returns a non-zero [error code].
1688*/
1689SQLITE_API int SQLITE_CDECL sqlite3_config(int, ...);
1690
1691/*
1692** CAPI3REF: Configure database connections
1693** METHOD: sqlite3
1694**
1695** The sqlite3_db_config() interface is used to make configuration
1696** changes to a [database connection].  The interface is similar to
1697** [sqlite3_config()] except that the changes apply to a single
1698** [database connection] (specified in the first argument).
1699**
1700** The second argument to sqlite3_db_config(D,V,...)  is the
1701** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1702** that indicates what aspect of the [database connection] is being configured.
1703** Subsequent arguments vary depending on the configuration verb.
1704**
1705** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1706** the call is considered successful.
1707*/
1708SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3*, int op, ...);
1709
1710/*
1711** CAPI3REF: Memory Allocation Routines
1712**
1713** An instance of this object defines the interface between SQLite
1714** and low-level memory allocation routines.
1715**
1716** This object is used in only one place in the SQLite interface.
1717** A pointer to an instance of this object is the argument to
1718** [sqlite3_config()] when the configuration option is
1719** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1720** By creating an instance of this object
1721** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1722** during configuration, an application can specify an alternative
1723** memory allocation subsystem for SQLite to use for all of its
1724** dynamic memory needs.
1725**
1726** Note that SQLite comes with several [built-in memory allocators]
1727** that are perfectly adequate for the overwhelming majority of applications
1728** and that this object is only useful to a tiny minority of applications
1729** with specialized memory allocation requirements.  This object is
1730** also used during testing of SQLite in order to specify an alternative
1731** memory allocator that simulates memory out-of-memory conditions in
1732** order to verify that SQLite recovers gracefully from such
1733** conditions.
1734**
1735** The xMalloc, xRealloc, and xFree methods must work like the
1736** malloc(), realloc() and free() functions from the standard C library.
1737** ^SQLite guarantees that the second argument to
1738** xRealloc is always a value returned by a prior call to xRoundup.
1739**
1740** xSize should return the allocated size of a memory allocation
1741** previously obtained from xMalloc or xRealloc.  The allocated size
1742** is always at least as big as the requested size but may be larger.
1743**
1744** The xRoundup method returns what would be the allocated size of
1745** a memory allocation given a particular requested size.  Most memory
1746** allocators round up memory allocations at least to the next multiple
1747** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1748** Every memory allocation request coming in through [sqlite3_malloc()]
1749** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1750** that causes the corresponding memory allocation to fail.
1751**
1752** The xInit method initializes the memory allocator.  For example,
1753** it might allocate any require mutexes or initialize internal data
1754** structures.  The xShutdown method is invoked (indirectly) by
1755** [sqlite3_shutdown()] and should deallocate any resources acquired
1756** by xInit.  The pAppData pointer is used as the only parameter to
1757** xInit and xShutdown.
1758**
1759** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1760** the xInit method, so the xInit method need not be threadsafe.  The
1761** xShutdown method is only called from [sqlite3_shutdown()] so it does
1762** not need to be threadsafe either.  For all other methods, SQLite
1763** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1764** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1765** it is by default) and so the methods are automatically serialized.
1766** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1767** methods must be threadsafe or else make their own arrangements for
1768** serialization.
1769**
1770** SQLite will never invoke xInit() more than once without an intervening
1771** call to xShutdown().
1772*/
1773typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1774struct sqlite3_mem_methods {
1775  void *(*xMalloc)(int);         /* Memory allocation function */
1776  void (*xFree)(void*);          /* Free a prior allocation */
1777  void *(*xRealloc)(void*,int);  /* Resize an allocation */
1778  int (*xSize)(void*);           /* Return the size of an allocation */
1779  int (*xRoundup)(int);          /* Round up request size to allocation size */
1780  int (*xInit)(void*);           /* Initialize the memory allocator */
1781  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1782  void *pAppData;                /* Argument to xInit() and xShutdown() */
1783};
1784
1785/*
1786** CAPI3REF: Configuration Options
1787** KEYWORDS: {configuration option}
1788**
1789** These constants are the available integer configuration options that
1790** can be passed as the first argument to the [sqlite3_config()] interface.
1791**
1792** New configuration options may be added in future releases of SQLite.
1793** Existing configuration options might be discontinued.  Applications
1794** should check the return code from [sqlite3_config()] to make sure that
1795** the call worked.  The [sqlite3_config()] interface will return a
1796** non-zero [error code] if a discontinued or unsupported configuration option
1797** is invoked.
1798**
1799** <dl>
1800** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1801** <dd>There are no arguments to this option.  ^This option sets the
1802** [threading mode] to Single-thread.  In other words, it disables
1803** all mutexing and puts SQLite into a mode where it can only be used
1804** by a single thread.   ^If SQLite is compiled with
1805** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1806** it is not possible to change the [threading mode] from its default
1807** value of Single-thread and so [sqlite3_config()] will return
1808** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1809** configuration option.</dd>
1810**
1811** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1812** <dd>There are no arguments to this option.  ^This option sets the
1813** [threading mode] to Multi-thread.  In other words, it disables
1814** mutexing on [database connection] and [prepared statement] objects.
1815** The application is responsible for serializing access to
1816** [database connections] and [prepared statements].  But other mutexes
1817** are enabled so that SQLite will be safe to use in a multi-threaded
1818** environment as long as no two threads attempt to use the same
1819** [database connection] at the same time.  ^If SQLite is compiled with
1820** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1821** it is not possible to set the Multi-thread [threading mode] and
1822** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1823** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1824**
1825** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1826** <dd>There are no arguments to this option.  ^This option sets the
1827** [threading mode] to Serialized. In other words, this option enables
1828** all mutexes including the recursive
1829** mutexes on [database connection] and [prepared statement] objects.
1830** In this mode (which is the default when SQLite is compiled with
1831** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1832** to [database connections] and [prepared statements] so that the
1833** application is free to use the same [database connection] or the
1834** same [prepared statement] in different threads at the same time.
1835** ^If SQLite is compiled with
1836** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1837** it is not possible to set the Serialized [threading mode] and
1838** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1839** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1840**
1841** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1842** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
1843** a pointer to an instance of the [sqlite3_mem_methods] structure.
1844** The argument specifies
1845** alternative low-level memory allocation routines to be used in place of
1846** the memory allocation routines built into SQLite.)^ ^SQLite makes
1847** its own private copy of the content of the [sqlite3_mem_methods] structure
1848** before the [sqlite3_config()] call returns.</dd>
1849**
1850** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1851** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
1852** is a pointer to an instance of the [sqlite3_mem_methods] structure.
1853** The [sqlite3_mem_methods]
1854** structure is filled with the currently defined memory allocation routines.)^
1855** This option can be used to overload the default memory allocation
1856** routines with a wrapper that simulations memory allocation failure or
1857** tracks memory usage, for example. </dd>
1858**
1859** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1860** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
1861** interpreted as a boolean, which enables or disables the collection of
1862** memory allocation statistics. ^(When memory allocation statistics are
1863** disabled, the following SQLite interfaces become non-operational:
1864**   <ul>
1865**   <li> [sqlite3_memory_used()]
1866**   <li> [sqlite3_memory_highwater()]
1867**   <li> [sqlite3_soft_heap_limit64()]
1868**   <li> [sqlite3_status64()]
1869**   </ul>)^
1870** ^Memory allocation statistics are enabled by default unless SQLite is
1871** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1872** allocation statistics are disabled by default.
1873** </dd>
1874**
1875** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1876** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
1877** that SQLite can use for scratch memory.  ^(There are three arguments
1878** to SQLITE_CONFIG_SCRATCH:  A pointer an 8-byte
1879** aligned memory buffer from which the scratch allocations will be
1880** drawn, the size of each scratch allocation (sz),
1881** and the maximum number of scratch allocations (N).)^
1882** The first argument must be a pointer to an 8-byte aligned buffer
1883** of at least sz*N bytes of memory.
1884** ^SQLite will not use more than one scratch buffers per thread.
1885** ^SQLite will never request a scratch buffer that is more than 6
1886** times the database page size.
1887** ^If SQLite needs needs additional
1888** scratch memory beyond what is provided by this configuration option, then
1889** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
1890** ^When the application provides any amount of scratch memory using
1891** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
1892** [sqlite3_malloc|heap allocations].
1893** This can help [Robson proof|prevent memory allocation failures] due to heap
1894** fragmentation in low-memory embedded systems.
1895** </dd>
1896**
1897** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1898** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
1899** that SQLite can use for the database page cache with the default page
1900** cache implementation.
1901** This configuration option is a no-op if an application-define page
1902** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
1903** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
1904** 8-byte aligned memory (pMem), the size of each page cache line (sz),
1905** and the number of cache lines (N).
1906** The sz argument should be the size of the largest database page
1907** (a power of two between 512 and 65536) plus some extra bytes for each
1908** page header.  ^The number of extra bytes needed by the page header
1909** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
1910** ^It is harmless, apart from the wasted memory,
1911** for the sz parameter to be larger than necessary.  The pMem
1912** argument must be either a NULL pointer or a pointer to an 8-byte
1913** aligned block of memory of at least sz*N bytes, otherwise
1914** subsequent behavior is undefined.
1915** ^When pMem is not NULL, SQLite will strive to use the memory provided
1916** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
1917** a page cache line is larger than sz bytes or if all of the pMem buffer
1918** is exhausted.
1919** ^If pMem is NULL and N is non-zero, then each database connection
1920** does an initial bulk allocation for page cache memory
1921** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
1922** of -1024*N bytes if N is negative, . ^If additional
1923** page cache memory is needed beyond what is provided by the initial
1924** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
1925** additional cache line. </dd>
1926**
1927** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
1928** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
1929** that SQLite will use for all of its dynamic memory allocation needs
1930** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
1931** [SQLITE_CONFIG_PAGECACHE].
1932** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
1933** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
1934** [SQLITE_ERROR] if invoked otherwise.
1935** ^There are three arguments to SQLITE_CONFIG_HEAP:
1936** An 8-byte aligned pointer to the memory,
1937** the number of bytes in the memory buffer, and the minimum allocation size.
1938** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1939** to using its default memory allocator (the system malloc() implementation),
1940** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1941** memory pointer is not NULL then the alternative memory
1942** allocator is engaged to handle all of SQLites memory allocation needs.
1943** The first pointer (the memory pointer) must be aligned to an 8-byte
1944** boundary or subsequent behavior of SQLite will be undefined.
1945** The minimum allocation size is capped at 2**12. Reasonable values
1946** for the minimum allocation size are 2**5 through 2**8.</dd>
1947**
1948** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
1949** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
1950** pointer to an instance of the [sqlite3_mutex_methods] structure.
1951** The argument specifies alternative low-level mutex routines to be used
1952** in place the mutex routines built into SQLite.)^  ^SQLite makes a copy of
1953** the content of the [sqlite3_mutex_methods] structure before the call to
1954** [sqlite3_config()] returns. ^If SQLite is compiled with
1955** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1956** the entire mutexing subsystem is omitted from the build and hence calls to
1957** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1958** return [SQLITE_ERROR].</dd>
1959**
1960** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
1961** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
1962** is a pointer to an instance of the [sqlite3_mutex_methods] structure.  The
1963** [sqlite3_mutex_methods]
1964** structure is filled with the currently defined mutex routines.)^
1965** This option can be used to overload the default mutex allocation
1966** routines with a wrapper used to track mutex usage for performance
1967** profiling or testing, for example.   ^If SQLite is compiled with
1968** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1969** the entire mutexing subsystem is omitted from the build and hence calls to
1970** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1971** return [SQLITE_ERROR].</dd>
1972**
1973** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1974** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
1975** the default size of lookaside memory on each [database connection].
1976** The first argument is the
1977** size of each lookaside buffer slot and the second is the number of
1978** slots allocated to each database connection.)^  ^(SQLITE_CONFIG_LOOKASIDE
1979** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1980** option to [sqlite3_db_config()] can be used to change the lookaside
1981** configuration on individual connections.)^ </dd>
1982**
1983** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
1984** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
1985** a pointer to an [sqlite3_pcache_methods2] object.  This object specifies
1986** the interface to a custom page cache implementation.)^
1987** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
1988**
1989** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
1990** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
1991** is a pointer to an [sqlite3_pcache_methods2] object.  SQLite copies of
1992** the current page cache implementation into that object.)^ </dd>
1993**
1994** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
1995** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
1996** global [error log].
1997** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1998** function with a call signature of void(*)(void*,int,const char*),
1999** and a pointer to void. ^If the function pointer is not NULL, it is
2000** invoked by [sqlite3_log()] to process each logging event.  ^If the
2001** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2002** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2003** passed through as the first parameter to the application-defined logger
2004** function whenever that function is invoked.  ^The second parameter to
2005** the logger function is a copy of the first parameter to the corresponding
2006** [sqlite3_log()] call and is intended to be a [result code] or an
2007** [extended result code].  ^The third parameter passed to the logger is
2008** log message after formatting via [sqlite3_snprintf()].
2009** The SQLite logging interface is not reentrant; the logger function
2010** supplied by the application must not invoke any SQLite interface.
2011** In a multi-threaded application, the application-defined logger
2012** function must be threadsafe. </dd>
2013**
2014** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2015** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
2016** If non-zero, then URI handling is globally enabled. If the parameter is zero,
2017** then URI handling is globally disabled.)^ ^If URI handling is globally
2018** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
2019** [sqlite3_open16()] or
2020** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2021** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2022** connection is opened. ^If it is globally disabled, filenames are
2023** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2024** database connection is opened. ^(By default, URI handling is globally
2025** disabled. The default value may be changed by compiling with the
2026** [SQLITE_USE_URI] symbol defined.)^
2027**
2028** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
2029** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
2030** argument which is interpreted as a boolean in order to enable or disable
2031** the use of covering indices for full table scans in the query optimizer.
2032** ^The default setting is determined
2033** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2034** if that compile-time option is omitted.
2035** The ability to disable the use of covering indices for full table scans
2036** is because some incorrectly coded legacy applications might malfunction
2037** when the optimization is enabled.  Providing the ability to
2038** disable the optimization allows the older, buggy application code to work
2039** without change even with newer versions of SQLite.
2040**
2041** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2042** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2043** <dd> These options are obsolete and should not be used by new code.
2044** They are retained for backwards compatibility but are now no-ops.
2045** </dd>
2046**
2047** [[SQLITE_CONFIG_SQLLOG]]
2048** <dt>SQLITE_CONFIG_SQLLOG
2049** <dd>This option is only available if sqlite is compiled with the
2050** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
2051** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
2052** The second should be of type (void*). The callback is invoked by the library
2053** in three separate circumstances, identified by the value passed as the
2054** fourth parameter. If the fourth parameter is 0, then the database connection
2055** passed as the second argument has just been opened. The third argument
2056** points to a buffer containing the name of the main database file. If the
2057** fourth parameter is 1, then the SQL statement that the third parameter
2058** points to has just been executed. Or, if the fourth parameter is 2, then
2059** the connection being passed as the second parameter is being closed. The
2060** third parameter is passed NULL In this case.  An example of using this
2061** configuration option can be seen in the "test_sqllog.c" source file in
2062** the canonical SQLite source tree.</dd>
2063**
2064** [[SQLITE_CONFIG_MMAP_SIZE]]
2065** <dt>SQLITE_CONFIG_MMAP_SIZE
2066** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
2067** that are the default mmap size limit (the default setting for
2068** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
2069** ^The default setting can be overridden by each database connection using
2070** either the [PRAGMA mmap_size] command, or by using the
2071** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
2072** will be silently truncated if necessary so that it does not exceed the
2073** compile-time maximum mmap size set by the
2074** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
2075** ^If either argument to this option is negative, then that argument is
2076** changed to its compile-time default.
2077**
2078** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
2079** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
2080** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
2081** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
2082** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
2083** that specifies the maximum size of the created heap.
2084**
2085** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
2086** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
2087** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
2088** is a pointer to an integer and writes into that integer the number of extra
2089** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
2090** The amount of extra space required can change depending on the compiler,
2091** target platform, and SQLite version.
2092**
2093** [[SQLITE_CONFIG_PMASZ]]
2094** <dt>SQLITE_CONFIG_PMASZ
2095** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
2096** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
2097** sorter to that integer.  The default minimum PMA Size is set by the
2098** [SQLITE_SORTER_PMASZ] compile-time option.  New threads are launched
2099** to help with sort operations when multithreaded sorting
2100** is enabled (using the [PRAGMA threads] command) and the amount of content
2101** to be sorted exceeds the page size times the minimum of the
2102** [PRAGMA cache_size] setting and this value.
2103**
2104** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
2105** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
2106** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
2107** becomes the [statement journal] spill-to-disk threshold.
2108** [Statement journals] are held in memory until their size (in bytes)
2109** exceeds this threshold, at which point they are written to disk.
2110** Or if the threshold is -1, statement journals are always held
2111** exclusively in memory.
2112** Since many statement journals never become large, setting the spill
2113** threshold to a value such as 64KiB can greatly reduce the amount of
2114** I/O required to support statement rollback.
2115** The default value for this setting is controlled by the
2116** [SQLITE_STMTJRNL_SPILL] compile-time option.
2117** </dl>
2118*/
2119#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
2120#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
2121#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
2122#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
2123#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
2124#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2125#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2126#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
2127#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
2128#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
2129#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
2130/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2131#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
2132#define SQLITE_CONFIG_PCACHE       14  /* no-op */
2133#define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
2134#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
2135#define SQLITE_CONFIG_URI          17  /* int */
2136#define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
2137#define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
2138#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
2139#define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
2140#define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
2141#define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
2142#define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */
2143#define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */
2144#define SQLITE_CONFIG_STMTJRNL_SPILL      26  /* int nByte */
2145
2146/*
2147** CAPI3REF: Database Connection Configuration Options
2148**
2149** These constants are the available integer configuration options that
2150** can be passed as the second argument to the [sqlite3_db_config()] interface.
2151**
2152** New configuration options may be added in future releases of SQLite.
2153** Existing configuration options might be discontinued.  Applications
2154** should check the return code from [sqlite3_db_config()] to make sure that
2155** the call worked.  ^The [sqlite3_db_config()] interface will return a
2156** non-zero [error code] if a discontinued or unsupported configuration option
2157** is invoked.
2158**
2159** <dl>
2160** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2161** <dd> ^This option takes three additional arguments that determine the
2162** [lookaside memory allocator] configuration for the [database connection].
2163** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2164** pointer to a memory buffer to use for lookaside memory.
2165** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2166** may be NULL in which case SQLite will allocate the
2167** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2168** size of each lookaside buffer slot.  ^The third argument is the number of
2169** slots.  The size of the buffer in the first argument must be greater than
2170** or equal to the product of the second and third arguments.  The buffer
2171** must be aligned to an 8-byte boundary.  ^If the second argument to
2172** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2173** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2174** configuration for a database connection can only be changed when that
2175** connection is not currently using lookaside memory, or in other words
2176** when the "current value" returned by
2177** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2178** Any attempt to change the lookaside memory configuration when lookaside
2179** memory is in use leaves the configuration unchanged and returns
2180** [SQLITE_BUSY].)^</dd>
2181**
2182** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2183** <dd> ^This option is used to enable or disable the enforcement of
2184** [foreign key constraints].  There should be two additional arguments.
2185** The first argument is an integer which is 0 to disable FK enforcement,
2186** positive to enable FK enforcement or negative to leave FK enforcement
2187** unchanged.  The second parameter is a pointer to an integer into which
2188** is written 0 or 1 to indicate whether FK enforcement is off or on
2189** following this call.  The second parameter may be a NULL pointer, in
2190** which case the FK enforcement setting is not reported back. </dd>
2191**
2192** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2193** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2194** There should be two additional arguments.
2195** The first argument is an integer which is 0 to disable triggers,
2196** positive to enable triggers or negative to leave the setting unchanged.
2197** The second parameter is a pointer to an integer into which
2198** is written 0 or 1 to indicate whether triggers are disabled or enabled
2199** following this call.  The second parameter may be a NULL pointer, in
2200** which case the trigger setting is not reported back. </dd>
2201**
2202** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
2203** <dd> ^This option is used to enable or disable the two-argument
2204** version of the [fts3_tokenizer()] function which is part of the
2205** [FTS3] full-text search engine extension.
2206** There should be two additional arguments.
2207** The first argument is an integer which is 0 to disable fts3_tokenizer() or
2208** positive to enable fts3_tokenizer() or negative to leave the setting
2209** unchanged.
2210** The second parameter is a pointer to an integer into which
2211** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
2212** following this call.  The second parameter may be a NULL pointer, in
2213** which case the new setting is not reported back. </dd>
2214**
2215** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
2216** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
2217** interface independently of the [load_extension()] SQL function.
2218** The [sqlite3_enable_load_extension()] API enables or disables both the
2219** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
2220** There should be two additional arguments.
2221** When the first argument to this interface is 1, then only the C-API is
2222** enabled and the SQL function remains disabled.  If the first argument to
2223** this interface is 0, then both the C-API and the SQL function are disabled.
2224** If the first argument is -1, then no changes are made to state of either the
2225** C-API or the SQL function.
2226** The second parameter is a pointer to an integer into which
2227** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
2228** is disabled or enabled following this call.  The second parameter may
2229** be a NULL pointer, in which case the new setting is not reported back.
2230** </dd>
2231**
2232** </dl>
2233*/
2234#define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */
2235#define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */
2236#define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */
2237#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
2238#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
2239
2240
2241/*
2242** CAPI3REF: Enable Or Disable Extended Result Codes
2243** METHOD: sqlite3
2244**
2245** ^The sqlite3_extended_result_codes() routine enables or disables the
2246** [extended result codes] feature of SQLite. ^The extended result
2247** codes are disabled by default for historical compatibility.
2248*/
2249SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3*, int onoff);
2250
2251/*
2252** CAPI3REF: Last Insert Rowid
2253** METHOD: sqlite3
2254**
2255** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
2256** has a unique 64-bit signed
2257** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2258** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2259** names are not also used by explicitly declared columns. ^If
2260** the table has a column of type [INTEGER PRIMARY KEY] then that column
2261** is another alias for the rowid.
2262**
2263** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
2264** most recent successful [INSERT] into a rowid table or [virtual table]
2265** on database connection D.
2266** ^Inserts into [WITHOUT ROWID] tables are not recorded.
2267** ^If no successful [INSERT]s into rowid tables
2268** have ever occurred on the database connection D,
2269** then sqlite3_last_insert_rowid(D) returns zero.
2270**
2271** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2272** method, then this routine will return the [rowid] of the inserted
2273** row as long as the trigger or virtual table method is running.
2274** But once the trigger or virtual table method ends, the value returned
2275** by this routine reverts to what it was before the trigger or virtual
2276** table method began.)^
2277**
2278** ^An [INSERT] that fails due to a constraint violation is not a
2279** successful [INSERT] and does not change the value returned by this
2280** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2281** and INSERT OR ABORT make no changes to the return value of this
2282** routine when their insertion fails.  ^(When INSERT OR REPLACE
2283** encounters a constraint violation, it does not fail.  The
2284** INSERT continues to completion after deleting rows that caused
2285** the constraint problem so INSERT OR REPLACE will always change
2286** the return value of this interface.)^
2287**
2288** ^For the purposes of this routine, an [INSERT] is considered to
2289** be successful even if it is subsequently rolled back.
2290**
2291** This function is accessible to SQL statements via the
2292** [last_insert_rowid() SQL function].
2293**
2294** If a separate thread performs a new [INSERT] on the same
2295** database connection while the [sqlite3_last_insert_rowid()]
2296** function is running and thus changes the last insert [rowid],
2297** then the value returned by [sqlite3_last_insert_rowid()] is
2298** unpredictable and might not equal either the old or the new
2299** last insert [rowid].
2300*/
2301SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3*);
2302
2303/*
2304** CAPI3REF: Count The Number Of Rows Modified
2305** METHOD: sqlite3
2306**
2307** ^This function returns the number of rows modified, inserted or
2308** deleted by the most recently completed INSERT, UPDATE or DELETE
2309** statement on the database connection specified by the only parameter.
2310** ^Executing any other type of SQL statement does not modify the value
2311** returned by this function.
2312**
2313** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
2314** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
2315** [foreign key actions] or [REPLACE] constraint resolution are not counted.
2316**
2317** Changes to a view that are intercepted by
2318** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
2319** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
2320** DELETE statement run on a view is always zero. Only changes made to real
2321** tables are counted.
2322**
2323** Things are more complicated if the sqlite3_changes() function is
2324** executed while a trigger program is running. This may happen if the
2325** program uses the [changes() SQL function], or if some other callback
2326** function invokes sqlite3_changes() directly. Essentially:
2327**
2328** <ul>
2329**   <li> ^(Before entering a trigger program the value returned by
2330**        sqlite3_changes() function is saved. After the trigger program
2331**        has finished, the original value is restored.)^
2332**
2333**   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
2334**        statement sets the value returned by sqlite3_changes()
2335**        upon completion as normal. Of course, this value will not include
2336**        any changes performed by sub-triggers, as the sqlite3_changes()
2337**        value will be saved and restored after each sub-trigger has run.)^
2338** </ul>
2339**
2340** ^This means that if the changes() SQL function (or similar) is used
2341** by the first INSERT, UPDATE or DELETE statement within a trigger, it
2342** returns the value as set when the calling statement began executing.
2343** ^If it is used by the second or subsequent such statement within a trigger
2344** program, the value returned reflects the number of rows modified by the
2345** previous INSERT, UPDATE or DELETE statement within the same trigger.
2346**
2347** See also the [sqlite3_total_changes()] interface, the
2348** [count_changes pragma], and the [changes() SQL function].
2349**
2350** If a separate thread makes changes on the same database connection
2351** while [sqlite3_changes()] is running then the value returned
2352** is unpredictable and not meaningful.
2353*/
2354SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3*);
2355
2356/*
2357** CAPI3REF: Total Number Of Rows Modified
2358** METHOD: sqlite3
2359**
2360** ^This function returns the total number of rows inserted, modified or
2361** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
2362** since the database connection was opened, including those executed as
2363** part of trigger programs. ^Executing any other type of SQL statement
2364** does not affect the value returned by sqlite3_total_changes().
2365**
2366** ^Changes made as part of [foreign key actions] are included in the
2367** count, but those made as part of REPLACE constraint resolution are
2368** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
2369** are not counted.
2370**
2371** See also the [sqlite3_changes()] interface, the
2372** [count_changes pragma], and the [total_changes() SQL function].
2373**
2374** If a separate thread makes changes on the same database connection
2375** while [sqlite3_total_changes()] is running then the value
2376** returned is unpredictable and not meaningful.
2377*/
2378SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3*);
2379
2380/*
2381** CAPI3REF: Interrupt A Long-Running Query
2382** METHOD: sqlite3
2383**
2384** ^This function causes any pending database operation to abort and
2385** return at its earliest opportunity. This routine is typically
2386** called in response to a user action such as pressing "Cancel"
2387** or Ctrl-C where the user wants a long query operation to halt
2388** immediately.
2389**
2390** ^It is safe to call this routine from a thread different from the
2391** thread that is currently running the database operation.  But it
2392** is not safe to call this routine with a [database connection] that
2393** is closed or might close before sqlite3_interrupt() returns.
2394**
2395** ^If an SQL operation is very nearly finished at the time when
2396** sqlite3_interrupt() is called, then it might not have an opportunity
2397** to be interrupted and might continue to completion.
2398**
2399** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2400** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2401** that is inside an explicit transaction, then the entire transaction
2402** will be rolled back automatically.
2403**
2404** ^The sqlite3_interrupt(D) call is in effect until all currently running
2405** SQL statements on [database connection] D complete.  ^Any new SQL statements
2406** that are started after the sqlite3_interrupt() call and before the
2407** running statements reaches zero are interrupted as if they had been
2408** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2409** that are started after the running statement count reaches zero are
2410** not effected by the sqlite3_interrupt().
2411** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2412** SQL statements is a no-op and has no effect on SQL statements
2413** that are started after the sqlite3_interrupt() call returns.
2414**
2415** If the database connection closes while [sqlite3_interrupt()]
2416** is running then bad things will likely happen.
2417*/
2418SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3*);
2419
2420/*
2421** CAPI3REF: Determine If An SQL Statement Is Complete
2422**
2423** These routines are useful during command-line input to determine if the
2424** currently entered text seems to form a complete SQL statement or
2425** if additional input is needed before sending the text into
2426** SQLite for parsing.  ^These routines return 1 if the input string
2427** appears to be a complete SQL statement.  ^A statement is judged to be
2428** complete if it ends with a semicolon token and is not a prefix of a
2429** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2430** string literals or quoted identifier names or comments are not
2431** independent tokens (they are part of the token in which they are
2432** embedded) and thus do not count as a statement terminator.  ^Whitespace
2433** and comments that follow the final semicolon are ignored.
2434**
2435** ^These routines return 0 if the statement is incomplete.  ^If a
2436** memory allocation fails, then SQLITE_NOMEM is returned.
2437**
2438** ^These routines do not parse the SQL statements thus
2439** will not detect syntactically incorrect SQL.
2440**
2441** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2442** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2443** automatically by sqlite3_complete16().  If that initialization fails,
2444** then the return value from sqlite3_complete16() will be non-zero
2445** regardless of whether or not the input SQL is complete.)^
2446**
2447** The input to [sqlite3_complete()] must be a zero-terminated
2448** UTF-8 string.
2449**
2450** The input to [sqlite3_complete16()] must be a zero-terminated
2451** UTF-16 string in native byte order.
2452*/
2453SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *sql);
2454SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *sql);
2455
2456/*
2457** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2458** KEYWORDS: {busy-handler callback} {busy handler}
2459** METHOD: sqlite3
2460**
2461** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
2462** that might be invoked with argument P whenever
2463** an attempt is made to access a database table associated with
2464** [database connection] D when another thread
2465** or process has the table locked.
2466** The sqlite3_busy_handler() interface is used to implement
2467** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
2468**
2469** ^If the busy callback is NULL, then [SQLITE_BUSY]
2470** is returned immediately upon encountering the lock.  ^If the busy callback
2471** is not NULL, then the callback might be invoked with two arguments.
2472**
2473** ^The first argument to the busy handler is a copy of the void* pointer which
2474** is the third argument to sqlite3_busy_handler().  ^The second argument to
2475** the busy handler callback is the number of times that the busy handler has
2476** been invoked previously for the same locking event.  ^If the
2477** busy callback returns 0, then no additional attempts are made to
2478** access the database and [SQLITE_BUSY] is returned
2479** to the application.
2480** ^If the callback returns non-zero, then another attempt
2481** is made to access the database and the cycle repeats.
2482**
2483** The presence of a busy handler does not guarantee that it will be invoked
2484** when there is lock contention. ^If SQLite determines that invoking the busy
2485** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2486** to the application instead of invoking the
2487** busy handler.
2488** Consider a scenario where one process is holding a read lock that
2489** it is trying to promote to a reserved lock and
2490** a second process is holding a reserved lock that it is trying
2491** to promote to an exclusive lock.  The first process cannot proceed
2492** because it is blocked by the second and the second process cannot
2493** proceed because it is blocked by the first.  If both processes
2494** invoke the busy handlers, neither will make any progress.  Therefore,
2495** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2496** will induce the first process to release its read lock and allow
2497** the second process to proceed.
2498**
2499** ^The default busy callback is NULL.
2500**
2501** ^(There can only be a single busy handler defined for each
2502** [database connection].  Setting a new busy handler clears any
2503** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2504** or evaluating [PRAGMA busy_timeout=N] will change the
2505** busy handler and thus clear any previously set busy handler.
2506**
2507** The busy callback should not take any actions which modify the
2508** database connection that invoked the busy handler.  In other words,
2509** the busy handler is not reentrant.  Any such actions
2510** result in undefined behavior.
2511**
2512** A busy handler must not close the database connection
2513** or [prepared statement] that invoked the busy handler.
2514*/
2515SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
2516
2517/*
2518** CAPI3REF: Set A Busy Timeout
2519** METHOD: sqlite3
2520**
2521** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2522** for a specified amount of time when a table is locked.  ^The handler
2523** will sleep multiple times until at least "ms" milliseconds of sleeping
2524** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2525** the handler returns 0 which causes [sqlite3_step()] to return
2526** [SQLITE_BUSY].
2527**
2528** ^Calling this routine with an argument less than or equal to zero
2529** turns off all busy handlers.
2530**
2531** ^(There can only be a single busy handler for a particular
2532** [database connection] at any given moment.  If another busy handler
2533** was defined  (using [sqlite3_busy_handler()]) prior to calling
2534** this routine, that other busy handler is cleared.)^
2535**
2536** See also:  [PRAGMA busy_timeout]
2537*/
2538SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3*, int ms);
2539
2540/*
2541** CAPI3REF: Convenience Routines For Running Queries
2542** METHOD: sqlite3
2543**
2544** This is a legacy interface that is preserved for backwards compatibility.
2545** Use of this interface is not recommended.
2546**
2547** Definition: A <b>result table</b> is memory data structure created by the
2548** [sqlite3_get_table()] interface.  A result table records the
2549** complete query results from one or more queries.
2550**
2551** The table conceptually has a number of rows and columns.  But
2552** these numbers are not part of the result table itself.  These
2553** numbers are obtained separately.  Let N be the number of rows
2554** and M be the number of columns.
2555**
2556** A result table is an array of pointers to zero-terminated UTF-8 strings.
2557** There are (N+1)*M elements in the array.  The first M pointers point
2558** to zero-terminated strings that  contain the names of the columns.
2559** The remaining entries all point to query results.  NULL values result
2560** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2561** string representation as returned by [sqlite3_column_text()].
2562**
2563** A result table might consist of one or more memory allocations.
2564** It is not safe to pass a result table directly to [sqlite3_free()].
2565** A result table should be deallocated using [sqlite3_free_table()].
2566**
2567** ^(As an example of the result table format, suppose a query result
2568** is as follows:
2569**
2570** <blockquote><pre>
2571**        Name        | Age
2572**        -----------------------
2573**        Alice       | 43
2574**        Bob         | 28
2575**        Cindy       | 21
2576** </pre></blockquote>
2577**
2578** There are two column (M==2) and three rows (N==3).  Thus the
2579** result table has 8 entries.  Suppose the result table is stored
2580** in an array names azResult.  Then azResult holds this content:
2581**
2582** <blockquote><pre>
2583**        azResult&#91;0] = "Name";
2584**        azResult&#91;1] = "Age";
2585**        azResult&#91;2] = "Alice";
2586**        azResult&#91;3] = "43";
2587**        azResult&#91;4] = "Bob";
2588**        azResult&#91;5] = "28";
2589**        azResult&#91;6] = "Cindy";
2590**        azResult&#91;7] = "21";
2591** </pre></blockquote>)^
2592**
2593** ^The sqlite3_get_table() function evaluates one or more
2594** semicolon-separated SQL statements in the zero-terminated UTF-8
2595** string of its 2nd parameter and returns a result table to the
2596** pointer given in its 3rd parameter.
2597**
2598** After the application has finished with the result from sqlite3_get_table(),
2599** it must pass the result table pointer to sqlite3_free_table() in order to
2600** release the memory that was malloced.  Because of the way the
2601** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2602** function must not try to call [sqlite3_free()] directly.  Only
2603** [sqlite3_free_table()] is able to release the memory properly and safely.
2604**
2605** The sqlite3_get_table() interface is implemented as a wrapper around
2606** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2607** to any internal data structures of SQLite.  It uses only the public
2608** interface defined here.  As a consequence, errors that occur in the
2609** wrapper layer outside of the internal [sqlite3_exec()] call are not
2610** reflected in subsequent calls to [sqlite3_errcode()] or
2611** [sqlite3_errmsg()].
2612*/
2613SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
2614  sqlite3 *db,          /* An open database */
2615  const char *zSql,     /* SQL to be evaluated */
2616  char ***pazResult,    /* Results of the query */
2617  int *pnRow,           /* Number of result rows written here */
2618  int *pnColumn,        /* Number of result columns written here */
2619  char **pzErrmsg       /* Error msg written here */
2620);
2621SQLITE_API void SQLITE_STDCALL sqlite3_free_table(char **result);
2622
2623/*
2624** CAPI3REF: Formatted String Printing Functions
2625**
2626** These routines are work-alikes of the "printf()" family of functions
2627** from the standard C library.
2628** These routines understand most of the common K&R formatting options,
2629** plus some additional non-standard formats, detailed below.
2630** Note that some of the more obscure formatting options from recent
2631** C-library standards are omitted from this implementation.
2632**
2633** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2634** results into memory obtained from [sqlite3_malloc()].
2635** The strings returned by these two routines should be
2636** released by [sqlite3_free()].  ^Both routines return a
2637** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2638** memory to hold the resulting string.
2639**
2640** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2641** the standard C library.  The result is written into the
2642** buffer supplied as the second parameter whose size is given by
2643** the first parameter. Note that the order of the
2644** first two parameters is reversed from snprintf().)^  This is an
2645** historical accident that cannot be fixed without breaking
2646** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2647** returns a pointer to its buffer instead of the number of
2648** characters actually written into the buffer.)^  We admit that
2649** the number of characters written would be a more useful return
2650** value but we cannot change the implementation of sqlite3_snprintf()
2651** now without breaking compatibility.
2652**
2653** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2654** guarantees that the buffer is always zero-terminated.  ^The first
2655** parameter "n" is the total size of the buffer, including space for
2656** the zero terminator.  So the longest string that can be completely
2657** written will be n-1 characters.
2658**
2659** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2660**
2661** These routines all implement some additional formatting
2662** options that are useful for constructing SQL statements.
2663** All of the usual printf() formatting options apply.  In addition, there
2664** is are "%q", "%Q", "%w" and "%z" options.
2665**
2666** ^(The %q option works like %s in that it substitutes a nul-terminated
2667** string from the argument list.  But %q also doubles every '\'' character.
2668** %q is designed for use inside a string literal.)^  By doubling each '\''
2669** character it escapes that character and allows it to be inserted into
2670** the string.
2671**
2672** For example, assume the string variable zText contains text as follows:
2673**
2674** <blockquote><pre>
2675**  char *zText = "It's a happy day!";
2676** </pre></blockquote>
2677**
2678** One can use this text in an SQL statement as follows:
2679**
2680** <blockquote><pre>
2681**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2682**  sqlite3_exec(db, zSQL, 0, 0, 0);
2683**  sqlite3_free(zSQL);
2684** </pre></blockquote>
2685**
2686** Because the %q format string is used, the '\'' character in zText
2687** is escaped and the SQL generated is as follows:
2688**
2689** <blockquote><pre>
2690**  INSERT INTO table1 VALUES('It''s a happy day!')
2691** </pre></blockquote>
2692**
2693** This is correct.  Had we used %s instead of %q, the generated SQL
2694** would have looked like this:
2695**
2696** <blockquote><pre>
2697**  INSERT INTO table1 VALUES('It's a happy day!');
2698** </pre></blockquote>
2699**
2700** This second example is an SQL syntax error.  As a general rule you should
2701** always use %q instead of %s when inserting text into a string literal.
2702**
2703** ^(The %Q option works like %q except it also adds single quotes around
2704** the outside of the total string.  Additionally, if the parameter in the
2705** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2706** single quotes).)^  So, for example, one could say:
2707**
2708** <blockquote><pre>
2709**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2710**  sqlite3_exec(db, zSQL, 0, 0, 0);
2711**  sqlite3_free(zSQL);
2712** </pre></blockquote>
2713**
2714** The code above will render a correct SQL statement in the zSQL
2715** variable even if the zText variable is a NULL pointer.
2716**
2717** ^(The "%w" formatting option is like "%q" except that it expects to
2718** be contained within double-quotes instead of single quotes, and it
2719** escapes the double-quote character instead of the single-quote
2720** character.)^  The "%w" formatting option is intended for safely inserting
2721** table and column names into a constructed SQL statement.
2722**
2723** ^(The "%z" formatting option works like "%s" but with the
2724** addition that after the string has been read and copied into
2725** the result, [sqlite3_free()] is called on the input string.)^
2726*/
2727SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char*,...);
2728SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char*, va_list);
2729SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int,char*,const char*, ...);
2730SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int,char*,const char*, va_list);
2731
2732/*
2733** CAPI3REF: Memory Allocation Subsystem
2734**
2735** The SQLite core uses these three routines for all of its own
2736** internal memory allocation needs. "Core" in the previous sentence
2737** does not include operating-system specific VFS implementation.  The
2738** Windows VFS uses native malloc() and free() for some operations.
2739**
2740** ^The sqlite3_malloc() routine returns a pointer to a block
2741** of memory at least N bytes in length, where N is the parameter.
2742** ^If sqlite3_malloc() is unable to obtain sufficient free
2743** memory, it returns a NULL pointer.  ^If the parameter N to
2744** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2745** a NULL pointer.
2746**
2747** ^The sqlite3_malloc64(N) routine works just like
2748** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
2749** of a signed 32-bit integer.
2750**
2751** ^Calling sqlite3_free() with a pointer previously returned
2752** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2753** that it might be reused.  ^The sqlite3_free() routine is
2754** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2755** to sqlite3_free() is harmless.  After being freed, memory
2756** should neither be read nor written.  Even reading previously freed
2757** memory might result in a segmentation fault or other severe error.
2758** Memory corruption, a segmentation fault, or other severe error
2759** might result if sqlite3_free() is called with a non-NULL pointer that
2760** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2761**
2762** ^The sqlite3_realloc(X,N) interface attempts to resize a
2763** prior memory allocation X to be at least N bytes.
2764** ^If the X parameter to sqlite3_realloc(X,N)
2765** is a NULL pointer then its behavior is identical to calling
2766** sqlite3_malloc(N).
2767** ^If the N parameter to sqlite3_realloc(X,N) is zero or
2768** negative then the behavior is exactly the same as calling
2769** sqlite3_free(X).
2770** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
2771** of at least N bytes in size or NULL if insufficient memory is available.
2772** ^If M is the size of the prior allocation, then min(N,M) bytes
2773** of the prior allocation are copied into the beginning of buffer returned
2774** by sqlite3_realloc(X,N) and the prior allocation is freed.
2775** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
2776** prior allocation is not freed.
2777**
2778** ^The sqlite3_realloc64(X,N) interfaces works the same as
2779** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
2780** of a 32-bit signed integer.
2781**
2782** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
2783** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
2784** sqlite3_msize(X) returns the size of that memory allocation in bytes.
2785** ^The value returned by sqlite3_msize(X) might be larger than the number
2786** of bytes requested when X was allocated.  ^If X is a NULL pointer then
2787** sqlite3_msize(X) returns zero.  If X points to something that is not
2788** the beginning of memory allocation, or if it points to a formerly
2789** valid memory allocation that has now been freed, then the behavior
2790** of sqlite3_msize(X) is undefined and possibly harmful.
2791**
2792** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
2793** sqlite3_malloc64(), and sqlite3_realloc64()
2794** is always aligned to at least an 8 byte boundary, or to a
2795** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2796** option is used.
2797**
2798** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2799** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2800** implementation of these routines to be omitted.  That capability
2801** is no longer provided.  Only built-in memory allocators can be used.
2802**
2803** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2804** the system malloc() and free() directly when converting
2805** filenames between the UTF-8 encoding used by SQLite
2806** and whatever filename encoding is used by the particular Windows
2807** installation.  Memory allocation errors were detected, but
2808** they were reported back as [SQLITE_CANTOPEN] or
2809** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2810**
2811** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2812** must be either NULL or else pointers obtained from a prior
2813** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2814** not yet been released.
2815**
2816** The application must not read or write any part of
2817** a block of memory after it has been released using
2818** [sqlite3_free()] or [sqlite3_realloc()].
2819*/
2820SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int);
2821SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64);
2822SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void*, int);
2823SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void*, sqlite3_uint64);
2824SQLITE_API void SQLITE_STDCALL sqlite3_free(void*);
2825SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void*);
2826
2827/*
2828** CAPI3REF: Memory Allocator Statistics
2829**
2830** SQLite provides these two interfaces for reporting on the status
2831** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2832** routines, which form the built-in memory allocation subsystem.
2833**
2834** ^The [sqlite3_memory_used()] routine returns the number of bytes
2835** of memory currently outstanding (malloced but not freed).
2836** ^The [sqlite3_memory_highwater()] routine returns the maximum
2837** value of [sqlite3_memory_used()] since the high-water mark
2838** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2839** [sqlite3_memory_highwater()] include any overhead
2840** added by SQLite in its implementation of [sqlite3_malloc()],
2841** but not overhead added by the any underlying system library
2842** routines that [sqlite3_malloc()] may call.
2843**
2844** ^The memory high-water mark is reset to the current value of
2845** [sqlite3_memory_used()] if and only if the parameter to
2846** [sqlite3_memory_highwater()] is true.  ^The value returned
2847** by [sqlite3_memory_highwater(1)] is the high-water mark
2848** prior to the reset.
2849*/
2850SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void);
2851SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag);
2852
2853/*
2854** CAPI3REF: Pseudo-Random Number Generator
2855**
2856** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2857** select random [ROWID | ROWIDs] when inserting new records into a table that
2858** already uses the largest possible [ROWID].  The PRNG is also used for
2859** the build-in random() and randomblob() SQL functions.  This interface allows
2860** applications to access the same PRNG for other purposes.
2861**
2862** ^A call to this routine stores N bytes of randomness into buffer P.
2863** ^The P parameter can be a NULL pointer.
2864**
2865** ^If this routine has not been previously called or if the previous
2866** call had N less than one or a NULL pointer for P, then the PRNG is
2867** seeded using randomness obtained from the xRandomness method of
2868** the default [sqlite3_vfs] object.
2869** ^If the previous call to this routine had an N of 1 or more and a
2870** non-NULL P then the pseudo-randomness is generated
2871** internally and without recourse to the [sqlite3_vfs] xRandomness
2872** method.
2873*/
2874SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *P);
2875
2876/*
2877** CAPI3REF: Compile-Time Authorization Callbacks
2878** METHOD: sqlite3
2879**
2880** ^This routine registers an authorizer callback with a particular
2881** [database connection], supplied in the first argument.
2882** ^The authorizer callback is invoked as SQL statements are being compiled
2883** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2884** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2885** points during the compilation process, as logic is being created
2886** to perform various actions, the authorizer callback is invoked to
2887** see if those actions are allowed.  ^The authorizer callback should
2888** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2889** specific action but allow the SQL statement to continue to be
2890** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2891** rejected with an error.  ^If the authorizer callback returns
2892** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2893** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2894** the authorizer will fail with an error message.
2895**
2896** When the callback returns [SQLITE_OK], that means the operation
2897** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2898** [sqlite3_prepare_v2()] or equivalent call that triggered the
2899** authorizer will fail with an error message explaining that
2900** access is denied.
2901**
2902** ^The first parameter to the authorizer callback is a copy of the third
2903** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2904** to the callback is an integer [SQLITE_COPY | action code] that specifies
2905** the particular action to be authorized. ^The third through sixth parameters
2906** to the callback are zero-terminated strings that contain additional
2907** details about the action to be authorized.
2908**
2909** ^If the action code is [SQLITE_READ]
2910** and the callback returns [SQLITE_IGNORE] then the
2911** [prepared statement] statement is constructed to substitute
2912** a NULL value in place of the table column that would have
2913** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2914** return can be used to deny an untrusted user access to individual
2915** columns of a table.
2916** ^If the action code is [SQLITE_DELETE] and the callback returns
2917** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2918** [truncate optimization] is disabled and all rows are deleted individually.
2919**
2920** An authorizer is used when [sqlite3_prepare | preparing]
2921** SQL statements from an untrusted source, to ensure that the SQL statements
2922** do not try to access data they are not allowed to see, or that they do not
2923** try to execute malicious statements that damage the database.  For
2924** example, an application may allow a user to enter arbitrary
2925** SQL queries for evaluation by a database.  But the application does
2926** not want the user to be able to make arbitrary changes to the
2927** database.  An authorizer could then be put in place while the
2928** user-entered SQL is being [sqlite3_prepare | prepared] that
2929** disallows everything except [SELECT] statements.
2930**
2931** Applications that need to process SQL from untrusted sources
2932** might also consider lowering resource limits using [sqlite3_limit()]
2933** and limiting database size using the [max_page_count] [PRAGMA]
2934** in addition to using an authorizer.
2935**
2936** ^(Only a single authorizer can be in place on a database connection
2937** at a time.  Each call to sqlite3_set_authorizer overrides the
2938** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2939** The authorizer is disabled by default.
2940**
2941** The authorizer callback must not do anything that will modify
2942** the database connection that invoked the authorizer callback.
2943** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2944** database connections for the meaning of "modify" in this paragraph.
2945**
2946** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2947** statement might be re-prepared during [sqlite3_step()] due to a
2948** schema change.  Hence, the application should ensure that the
2949** correct authorizer callback remains in place during the [sqlite3_step()].
2950**
2951** ^Note that the authorizer callback is invoked only during
2952** [sqlite3_prepare()] or its variants.  Authorization is not
2953** performed during statement evaluation in [sqlite3_step()], unless
2954** as stated in the previous paragraph, sqlite3_step() invokes
2955** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2956*/
2957SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
2958  sqlite3*,
2959  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2960  void *pUserData
2961);
2962
2963/*
2964** CAPI3REF: Authorizer Return Codes
2965**
2966** The [sqlite3_set_authorizer | authorizer callback function] must
2967** return either [SQLITE_OK] or one of these two constants in order
2968** to signal SQLite whether or not the action is permitted.  See the
2969** [sqlite3_set_authorizer | authorizer documentation] for additional
2970** information.
2971**
2972** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
2973** returned from the [sqlite3_vtab_on_conflict()] interface.
2974*/
2975#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2976#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2977
2978/*
2979** CAPI3REF: Authorizer Action Codes
2980**
2981** The [sqlite3_set_authorizer()] interface registers a callback function
2982** that is invoked to authorize certain SQL statement actions.  The
2983** second parameter to the callback is an integer code that specifies
2984** what action is being authorized.  These are the integer action codes that
2985** the authorizer callback may be passed.
2986**
2987** These action code values signify what kind of operation is to be
2988** authorized.  The 3rd and 4th parameters to the authorization
2989** callback function will be parameters or NULL depending on which of these
2990** codes is used as the second parameter.  ^(The 5th parameter to the
2991** authorizer callback is the name of the database ("main", "temp",
2992** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2993** is the name of the inner-most trigger or view that is responsible for
2994** the access attempt or NULL if this access attempt is directly from
2995** top-level SQL code.
2996*/
2997/******************************************* 3rd ************ 4th ***********/
2998#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2999#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
3000#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
3001#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
3002#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
3003#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
3004#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
3005#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
3006#define SQLITE_DELETE                9   /* Table Name      NULL            */
3007#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
3008#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
3009#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
3010#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
3011#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
3012#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
3013#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
3014#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
3015#define SQLITE_INSERT               18   /* Table Name      NULL            */
3016#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
3017#define SQLITE_READ                 20   /* Table Name      Column Name     */
3018#define SQLITE_SELECT               21   /* NULL            NULL            */
3019#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
3020#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
3021#define SQLITE_ATTACH               24   /* Filename        NULL            */
3022#define SQLITE_DETACH               25   /* Database Name   NULL            */
3023#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
3024#define SQLITE_REINDEX              27   /* Index Name      NULL            */
3025#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
3026#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
3027#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
3028#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
3029#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
3030#define SQLITE_COPY                  0   /* No longer used */
3031#define SQLITE_RECURSIVE            33   /* NULL            NULL            */
3032
3033/*
3034** CAPI3REF: Tracing And Profiling Functions
3035** METHOD: sqlite3
3036**
3037** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
3038** instead of the routines described here.
3039**
3040** These routines register callback functions that can be used for
3041** tracing and profiling the execution of SQL statements.
3042**
3043** ^The callback function registered by sqlite3_trace() is invoked at
3044** various times when an SQL statement is being run by [sqlite3_step()].
3045** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3046** SQL statement text as the statement first begins executing.
3047** ^(Additional sqlite3_trace() callbacks might occur
3048** as each triggered subprogram is entered.  The callbacks for triggers
3049** contain a UTF-8 SQL comment that identifies the trigger.)^
3050**
3051** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
3052** the length of [bound parameter] expansion in the output of sqlite3_trace().
3053**
3054** ^The callback function registered by sqlite3_profile() is invoked
3055** as each SQL statement finishes.  ^The profile callback contains
3056** the original statement text and an estimate of wall-clock time
3057** of how long that statement took to run.  ^The profile callback
3058** time is in units of nanoseconds, however the current implementation
3059** is only capable of millisecond resolution so the six least significant
3060** digits in the time are meaningless.  Future versions of SQLite
3061** might provide greater resolution on the profiler callback.  The
3062** sqlite3_profile() function is considered experimental and is
3063** subject to change in future versions of SQLite.
3064*/
3065SQLITE_API SQLITE_DEPRECATED void *SQLITE_STDCALL sqlite3_trace(sqlite3*,
3066   void(*xTrace)(void*,const char*), void*);
3067SQLITE_API SQLITE_DEPRECATED void *SQLITE_STDCALL sqlite3_profile(sqlite3*,
3068   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3069
3070/*
3071** CAPI3REF: SQL Trace Event Codes
3072** KEYWORDS: SQLITE_TRACE
3073**
3074** These constants identify classes of events that can be monitored
3075** using the [sqlite3_trace_v2()] tracing logic.  The third argument
3076** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of
3077** the following constants.  ^The first argument to the trace callback
3078** is one of the following constants.
3079**
3080** New tracing constants may be added in future releases.
3081**
3082** ^A trace callback has four arguments: xCallback(T,C,P,X).
3083** ^The T argument is one of the integer type codes above.
3084** ^The C argument is a copy of the context pointer passed in as the
3085** fourth argument to [sqlite3_trace_v2()].
3086** The P and X arguments are pointers whose meanings depend on T.
3087**
3088** <dl>
3089** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
3090** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
3091** first begins running and possibly at other times during the
3092** execution of the prepared statement, such as at the start of each
3093** trigger subprogram. ^The P argument is a pointer to the
3094** [prepared statement]. ^The X argument is a pointer to a string which
3095** is the unexpanded SQL text of the prepared statement or an SQL comment
3096** that indicates the invocation of a trigger.  ^The callback can compute
3097** the same text that would have been returned by the legacy [sqlite3_trace()]
3098** interface by using the X argument when X begins with "--" and invoking
3099** [sqlite3_expanded_sql(P)] otherwise.
3100**
3101** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
3102** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
3103** information as is provided by the [sqlite3_profile()] callback.
3104** ^The P argument is a pointer to the [prepared statement] and the
3105** X argument points to a 64-bit integer which is the estimated of
3106** the number of nanosecond that the prepared statement took to run.
3107** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
3108**
3109** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
3110** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
3111** statement generates a single row of result.
3112** ^The P argument is a pointer to the [prepared statement] and the
3113** X argument is unused.
3114**
3115** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
3116** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
3117** connection closes.
3118** ^The P argument is a pointer to the [database connection] object
3119** and the X argument is unused.
3120** </dl>
3121*/
3122#define SQLITE_TRACE_STMT       0x01
3123#define SQLITE_TRACE_PROFILE    0x02
3124#define SQLITE_TRACE_ROW        0x04
3125#define SQLITE_TRACE_CLOSE      0x08
3126
3127/*
3128** CAPI3REF: SQL Trace Hook
3129** METHOD: sqlite3
3130**
3131** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
3132** function X against [database connection] D, using property mask M
3133** and context pointer P.  ^If the X callback is
3134** NULL or if the M mask is zero, then tracing is disabled.  The
3135** M argument should be the bitwise OR-ed combination of
3136** zero or more [SQLITE_TRACE] constants.
3137**
3138** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
3139** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
3140**
3141** ^The X callback is invoked whenever any of the events identified by
3142** mask M occur.  ^The integer return value from the callback is currently
3143** ignored, though this may change in future releases.  Callback
3144** implementations should return zero to ensure future compatibility.
3145**
3146** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
3147** ^The T argument is one of the [SQLITE_TRACE]
3148** constants to indicate why the callback was invoked.
3149** ^The C argument is a copy of the context pointer.
3150** The P and X arguments are pointers whose meanings depend on T.
3151**
3152** The sqlite3_trace_v2() interface is intended to replace the legacy
3153** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
3154** are deprecated.
3155*/
3156SQLITE_API int SQLITE_STDCALL sqlite3_trace_v2(
3157  sqlite3*,
3158  unsigned uMask,
3159  int(*xCallback)(unsigned,void*,void*,void*),
3160  void *pCtx
3161);
3162
3163/*
3164** CAPI3REF: Query Progress Callbacks
3165** METHOD: sqlite3
3166**
3167** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
3168** function X to be invoked periodically during long running calls to
3169** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
3170** database connection D.  An example use for this
3171** interface is to keep a GUI updated during a large query.
3172**
3173** ^The parameter P is passed through as the only parameter to the
3174** callback function X.  ^The parameter N is the approximate number of
3175** [virtual machine instructions] that are evaluated between successive
3176** invocations of the callback X.  ^If N is less than one then the progress
3177** handler is disabled.
3178**
3179** ^Only a single progress handler may be defined at one time per
3180** [database connection]; setting a new progress handler cancels the
3181** old one.  ^Setting parameter X to NULL disables the progress handler.
3182** ^The progress handler is also disabled by setting N to a value less
3183** than 1.
3184**
3185** ^If the progress callback returns non-zero, the operation is
3186** interrupted.  This feature can be used to implement a
3187** "Cancel" button on a GUI progress dialog box.
3188**
3189** The progress handler callback must not do anything that will modify
3190** the database connection that invoked the progress handler.
3191** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3192** database connections for the meaning of "modify" in this paragraph.
3193**
3194*/
3195SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3196
3197/*
3198** CAPI3REF: Opening A New Database Connection
3199** CONSTRUCTOR: sqlite3
3200**
3201** ^These routines open an SQLite database file as specified by the
3202** filename argument. ^The filename argument is interpreted as UTF-8 for
3203** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3204** order for sqlite3_open16(). ^(A [database connection] handle is usually
3205** returned in *ppDb, even if an error occurs.  The only exception is that
3206** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3207** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3208** object.)^ ^(If the database is opened (and/or created) successfully, then
3209** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
3210** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3211** an English language description of the error following a failure of any
3212** of the sqlite3_open() routines.
3213**
3214** ^The default encoding will be UTF-8 for databases created using
3215** sqlite3_open() or sqlite3_open_v2().  ^The default encoding for databases
3216** created using sqlite3_open16() will be UTF-16 in the native byte order.
3217**
3218** Whether or not an error occurs when it is opened, resources
3219** associated with the [database connection] handle should be released by
3220** passing it to [sqlite3_close()] when it is no longer required.
3221**
3222** The sqlite3_open_v2() interface works like sqlite3_open()
3223** except that it accepts two additional parameters for additional control
3224** over the new database connection.  ^(The flags parameter to
3225** sqlite3_open_v2() can take one of
3226** the following three values, optionally combined with the
3227** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
3228** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
3229**
3230** <dl>
3231** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3232** <dd>The database is opened in read-only mode.  If the database does not
3233** already exist, an error is returned.</dd>)^
3234**
3235** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3236** <dd>The database is opened for reading and writing if possible, or reading
3237** only if the file is write protected by the operating system.  In either
3238** case the database must already exist, otherwise an error is returned.</dd>)^
3239**
3240** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3241** <dd>The database is opened for reading and writing, and is created if
3242** it does not already exist. This is the behavior that is always used for
3243** sqlite3_open() and sqlite3_open16().</dd>)^
3244** </dl>
3245**
3246** If the 3rd parameter to sqlite3_open_v2() is not one of the
3247** combinations shown above optionally combined with other
3248** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3249** then the behavior is undefined.
3250**
3251** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3252** opens in the multi-thread [threading mode] as long as the single-thread
3253** mode has not been set at compile-time or start-time.  ^If the
3254** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3255** in the serialized [threading mode] unless single-thread was
3256** previously selected at compile-time or start-time.
3257** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3258** eligible to use [shared cache mode], regardless of whether or not shared
3259** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
3260** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3261** participate in [shared cache mode] even if it is enabled.
3262**
3263** ^The fourth parameter to sqlite3_open_v2() is the name of the
3264** [sqlite3_vfs] object that defines the operating system interface that
3265** the new database connection should use.  ^If the fourth parameter is
3266** a NULL pointer then the default [sqlite3_vfs] object is used.
3267**
3268** ^If the filename is ":memory:", then a private, temporary in-memory database
3269** is created for the connection.  ^This in-memory database will vanish when
3270** the database connection is closed.  Future versions of SQLite might
3271** make use of additional special filenames that begin with the ":" character.
3272** It is recommended that when a database filename actually does begin with
3273** a ":" character you should prefix the filename with a pathname such as
3274** "./" to avoid ambiguity.
3275**
3276** ^If the filename is an empty string, then a private, temporary
3277** on-disk database will be created.  ^This private database will be
3278** automatically deleted as soon as the database connection is closed.
3279**
3280** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3281**
3282** ^If [URI filename] interpretation is enabled, and the filename argument
3283** begins with "file:", then the filename is interpreted as a URI. ^URI
3284** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3285** set in the fourth argument to sqlite3_open_v2(), or if it has
3286** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3287** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3288** As of SQLite version 3.7.7, URI filename interpretation is turned off
3289** by default, but future releases of SQLite might enable URI filename
3290** interpretation by default.  See "[URI filenames]" for additional
3291** information.
3292**
3293** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3294** authority, then it must be either an empty string or the string
3295** "localhost". ^If the authority is not an empty string or "localhost", an
3296** error is returned to the caller. ^The fragment component of a URI, if
3297** present, is ignored.
3298**
3299** ^SQLite uses the path component of the URI as the name of the disk file
3300** which contains the database. ^If the path begins with a '/' character,
3301** then it is interpreted as an absolute path. ^If the path does not begin
3302** with a '/' (meaning that the authority section is omitted from the URI)
3303** then the path is interpreted as a relative path.
3304** ^(On windows, the first component of an absolute path
3305** is a drive specification (e.g. "C:").)^
3306**
3307** [[core URI query parameters]]
3308** The query component of a URI may contain parameters that are interpreted
3309** either by SQLite itself, or by a [VFS | custom VFS implementation].
3310** SQLite and its built-in [VFSes] interpret the
3311** following query parameters:
3312**
3313** <ul>
3314**   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3315**     a VFS object that provides the operating system interface that should
3316**     be used to access the database file on disk. ^If this option is set to
3317**     an empty string the default VFS object is used. ^Specifying an unknown
3318**     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3319**     present, then the VFS specified by the option takes precedence over
3320**     the value passed as the fourth parameter to sqlite3_open_v2().
3321**
3322**   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3323**     "rwc", or "memory". Attempting to set it to any other value is
3324**     an error)^.
3325**     ^If "ro" is specified, then the database is opened for read-only
3326**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3327**     third argument to sqlite3_open_v2(). ^If the mode option is set to
3328**     "rw", then the database is opened for read-write (but not create)
3329**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3330**     been set. ^Value "rwc" is equivalent to setting both
3331**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
3332**     set to "memory" then a pure [in-memory database] that never reads
3333**     or writes from disk is used. ^It is an error to specify a value for
3334**     the mode parameter that is less restrictive than that specified by
3335**     the flags passed in the third parameter to sqlite3_open_v2().
3336**
3337**   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3338**     "private". ^Setting it to "shared" is equivalent to setting the
3339**     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3340**     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3341**     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3342**     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3343**     a URI filename, its value overrides any behavior requested by setting
3344**     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3345**
3346**  <li> <b>psow</b>: ^The psow parameter indicates whether or not the
3347**     [powersafe overwrite] property does or does not apply to the
3348**     storage media on which the database file resides.
3349**
3350**  <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
3351**     which if set disables file locking in rollback journal modes.  This
3352**     is useful for accessing a database on a filesystem that does not
3353**     support locking.  Caution:  Database corruption might result if two
3354**     or more processes write to the same database and any one of those
3355**     processes uses nolock=1.
3356**
3357**  <li> <b>immutable</b>: ^The immutable parameter is a boolean query
3358**     parameter that indicates that the database file is stored on
3359**     read-only media.  ^When immutable is set, SQLite assumes that the
3360**     database file cannot be changed, even by a process with higher
3361**     privilege, and so the database is opened read-only and all locking
3362**     and change detection is disabled.  Caution: Setting the immutable
3363**     property on a database file that does in fact change can result
3364**     in incorrect query results and/or [SQLITE_CORRUPT] errors.
3365**     See also: [SQLITE_IOCAP_IMMUTABLE].
3366**
3367** </ul>
3368**
3369** ^Specifying an unknown parameter in the query component of a URI is not an
3370** error.  Future versions of SQLite might understand additional query
3371** parameters.  See "[query parameters with special meaning to SQLite]" for
3372** additional information.
3373**
3374** [[URI filename examples]] <h3>URI filename examples</h3>
3375**
3376** <table border="1" align=center cellpadding=5>
3377** <tr><th> URI filenames <th> Results
3378** <tr><td> file:data.db <td>
3379**          Open the file "data.db" in the current directory.
3380** <tr><td> file:/home/fred/data.db<br>
3381**          file:///home/fred/data.db <br>
3382**          file://localhost/home/fred/data.db <br> <td>
3383**          Open the database file "/home/fred/data.db".
3384** <tr><td> file://darkstar/home/fred/data.db <td>
3385**          An error. "darkstar" is not a recognized authority.
3386** <tr><td style="white-space:nowrap">
3387**          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3388**     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3389**          C:. Note that the %20 escaping in this example is not strictly
3390**          necessary - space characters can be used literally
3391**          in URI filenames.
3392** <tr><td> file:data.db?mode=ro&cache=private <td>
3393**          Open file "data.db" in the current directory for read-only access.
3394**          Regardless of whether or not shared-cache mode is enabled by
3395**          default, use a private cache.
3396** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
3397**          Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
3398**          that uses dot-files in place of posix advisory locking.
3399** <tr><td> file:data.db?mode=readonly <td>
3400**          An error. "readonly" is not a valid option for the "mode" parameter.
3401** </table>
3402**
3403** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3404** query components of a URI. A hexadecimal escape sequence consists of a
3405** percent sign - "%" - followed by exactly two hexadecimal digits
3406** specifying an octet value. ^Before the path or query components of a
3407** URI filename are interpreted, they are encoded using UTF-8 and all
3408** hexadecimal escape sequences replaced by a single byte containing the
3409** corresponding octet. If this process generates an invalid UTF-8 encoding,
3410** the results are undefined.
3411**
3412** <b>Note to Windows users:</b>  The encoding used for the filename argument
3413** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3414** codepage is currently defined.  Filenames containing international
3415** characters must be converted to UTF-8 prior to passing them into
3416** sqlite3_open() or sqlite3_open_v2().
3417**
3418** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
3419** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
3420** features that require the use of temporary files may fail.
3421**
3422** See also: [sqlite3_temp_directory]
3423*/
3424SQLITE_API int SQLITE_STDCALL sqlite3_open(
3425  const char *filename,   /* Database filename (UTF-8) */
3426  sqlite3 **ppDb          /* OUT: SQLite db handle */
3427);
3428SQLITE_API int SQLITE_STDCALL sqlite3_open16(
3429  const void *filename,   /* Database filename (UTF-16) */
3430  sqlite3 **ppDb          /* OUT: SQLite db handle */
3431);
3432SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
3433  const char *filename,   /* Database filename (UTF-8) */
3434  sqlite3 **ppDb,         /* OUT: SQLite db handle */
3435  int flags,              /* Flags */
3436  const char *zVfs        /* Name of VFS module to use */
3437);
3438
3439/*
3440** CAPI3REF: Obtain Values For URI Parameters
3441**
3442** These are utility routines, useful to VFS implementations, that check
3443** to see if a database file was a URI that contained a specific query
3444** parameter, and if so obtains the value of that query parameter.
3445**
3446** If F is the database filename pointer passed into the xOpen() method of
3447** a VFS implementation when the flags parameter to xOpen() has one or
3448** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3449** P is the name of the query parameter, then
3450** sqlite3_uri_parameter(F,P) returns the value of the P
3451** parameter if it exists or a NULL pointer if P does not appear as a
3452** query parameter on F.  If P is a query parameter of F
3453** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3454** a pointer to an empty string.
3455**
3456** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3457** parameter and returns true (1) or false (0) according to the value
3458** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3459** value of query parameter P is one of "yes", "true", or "on" in any
3460** case or if the value begins with a non-zero number.  The
3461** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3462** query parameter P is one of "no", "false", or "off" in any case or
3463** if the value begins with a numeric zero.  If P is not a query
3464** parameter on F or if the value of P is does not match any of the
3465** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3466**
3467** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3468** 64-bit signed integer and returns that integer, or D if P does not
3469** exist.  If the value of P is something other than an integer, then
3470** zero is returned.
3471**
3472** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3473** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
3474** is not a database file pathname pointer that SQLite passed into the xOpen
3475** VFS method, then the behavior of this routine is undefined and probably
3476** undesirable.
3477*/
3478SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3479SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3480SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3481
3482
3483/*
3484** CAPI3REF: Error Codes And Messages
3485** METHOD: sqlite3
3486**
3487** ^If the most recent sqlite3_* API call associated with
3488** [database connection] D failed, then the sqlite3_errcode(D) interface
3489** returns the numeric [result code] or [extended result code] for that
3490** API call.
3491** If the most recent API call was successful,
3492** then the return value from sqlite3_errcode() is undefined.
3493** ^The sqlite3_extended_errcode()
3494** interface is the same except that it always returns the
3495** [extended result code] even when extended result codes are
3496** disabled.
3497**
3498** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3499** text that describes the error, as either UTF-8 or UTF-16 respectively.
3500** ^(Memory to hold the error message string is managed internally.
3501** The application does not need to worry about freeing the result.
3502** However, the error string might be overwritten or deallocated by
3503** subsequent calls to other SQLite interface functions.)^
3504**
3505** ^The sqlite3_errstr() interface returns the English-language text
3506** that describes the [result code], as UTF-8.
3507** ^(Memory to hold the error message string is managed internally
3508** and must not be freed by the application)^.
3509**
3510** When the serialized [threading mode] is in use, it might be the
3511** case that a second error occurs on a separate thread in between
3512** the time of the first error and the call to these interfaces.
3513** When that happens, the second error will be reported since these
3514** interfaces always report the most recent result.  To avoid
3515** this, each thread can obtain exclusive use of the [database connection] D
3516** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3517** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3518** all calls to the interfaces listed here are completed.
3519**
3520** If an interface fails with SQLITE_MISUSE, that means the interface
3521** was invoked incorrectly by the application.  In that case, the
3522** error code and message may or may not be set.
3523*/
3524SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db);
3525SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db);
3526SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3*);
3527SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3*);
3528SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int);
3529
3530/*
3531** CAPI3REF: Prepared Statement Object
3532** KEYWORDS: {prepared statement} {prepared statements}
3533**
3534** An instance of this object represents a single SQL statement that
3535** has been compiled into binary form and is ready to be evaluated.
3536**
3537** Think of each SQL statement as a separate computer program.  The
3538** original SQL text is source code.  A prepared statement object
3539** is the compiled object code.  All SQL must be converted into a
3540** prepared statement before it can be run.
3541**
3542** The life-cycle of a prepared statement object usually goes like this:
3543**
3544** <ol>
3545** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
3546** <li> Bind values to [parameters] using the sqlite3_bind_*()
3547**      interfaces.
3548** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3549** <li> Reset the prepared statement using [sqlite3_reset()] then go back
3550**      to step 2.  Do this zero or more times.
3551** <li> Destroy the object using [sqlite3_finalize()].
3552** </ol>
3553*/
3554typedef struct sqlite3_stmt sqlite3_stmt;
3555
3556/*
3557** CAPI3REF: Run-time Limits
3558** METHOD: sqlite3
3559**
3560** ^(This interface allows the size of various constructs to be limited
3561** on a connection by connection basis.  The first parameter is the
3562** [database connection] whose limit is to be set or queried.  The
3563** second parameter is one of the [limit categories] that define a
3564** class of constructs to be size limited.  The third parameter is the
3565** new limit for that construct.)^
3566**
3567** ^If the new limit is a negative number, the limit is unchanged.
3568** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3569** [limits | hard upper bound]
3570** set at compile-time by a C preprocessor macro called
3571** [limits | SQLITE_MAX_<i>NAME</i>].
3572** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3573** ^Attempts to increase a limit above its hard upper bound are
3574** silently truncated to the hard upper bound.
3575**
3576** ^Regardless of whether or not the limit was changed, the
3577** [sqlite3_limit()] interface returns the prior value of the limit.
3578** ^Hence, to find the current value of a limit without changing it,
3579** simply invoke this interface with the third parameter set to -1.
3580**
3581** Run-time limits are intended for use in applications that manage
3582** both their own internal database and also databases that are controlled
3583** by untrusted external sources.  An example application might be a
3584** web browser that has its own databases for storing history and
3585** separate databases controlled by JavaScript applications downloaded
3586** off the Internet.  The internal databases can be given the
3587** large, default limits.  Databases managed by external sources can
3588** be given much smaller limits designed to prevent a denial of service
3589** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3590** interface to further control untrusted SQL.  The size of the database
3591** created by an untrusted script can be contained using the
3592** [max_page_count] [PRAGMA].
3593**
3594** New run-time limit categories may be added in future releases.
3595*/
3596SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3*, int id, int newVal);
3597
3598/*
3599** CAPI3REF: Run-Time Limit Categories
3600** KEYWORDS: {limit category} {*limit categories}
3601**
3602** These constants define various performance limits
3603** that can be lowered at run-time using [sqlite3_limit()].
3604** The synopsis of the meanings of the various limits is shown below.
3605** Additional information is available at [limits | Limits in SQLite].
3606**
3607** <dl>
3608** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3609** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3610**
3611** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3612** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3613**
3614** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3615** <dd>The maximum number of columns in a table definition or in the
3616** result set of a [SELECT] or the maximum number of columns in an index
3617** or in an ORDER BY or GROUP BY clause.</dd>)^
3618**
3619** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3620** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3621**
3622** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3623** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3624**
3625** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3626** <dd>The maximum number of instructions in a virtual machine program
3627** used to implement an SQL statement.  This limit is not currently
3628** enforced, though that might be added in some future release of
3629** SQLite.</dd>)^
3630**
3631** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3632** <dd>The maximum number of arguments on a function.</dd>)^
3633**
3634** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3635** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3636**
3637** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3638** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3639** <dd>The maximum length of the pattern argument to the [LIKE] or
3640** [GLOB] operators.</dd>)^
3641**
3642** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3643** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3644** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3645**
3646** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3647** <dd>The maximum depth of recursion for triggers.</dd>)^
3648**
3649** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
3650** <dd>The maximum number of auxiliary worker threads that a single
3651** [prepared statement] may start.</dd>)^
3652** </dl>
3653*/
3654#define SQLITE_LIMIT_LENGTH                    0
3655#define SQLITE_LIMIT_SQL_LENGTH                1
3656#define SQLITE_LIMIT_COLUMN                    2
3657#define SQLITE_LIMIT_EXPR_DEPTH                3
3658#define SQLITE_LIMIT_COMPOUND_SELECT           4
3659#define SQLITE_LIMIT_VDBE_OP                   5
3660#define SQLITE_LIMIT_FUNCTION_ARG              6
3661#define SQLITE_LIMIT_ATTACHED                  7
3662#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3663#define SQLITE_LIMIT_VARIABLE_NUMBER           9
3664#define SQLITE_LIMIT_TRIGGER_DEPTH            10
3665#define SQLITE_LIMIT_WORKER_THREADS           11
3666
3667/*
3668** CAPI3REF: Compiling An SQL Statement
3669** KEYWORDS: {SQL statement compiler}
3670** METHOD: sqlite3
3671** CONSTRUCTOR: sqlite3_stmt
3672**
3673** To execute an SQL query, it must first be compiled into a byte-code
3674** program using one of these routines.
3675**
3676** The first argument, "db", is a [database connection] obtained from a
3677** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3678** [sqlite3_open16()].  The database connection must not have been closed.
3679**
3680** The second argument, "zSql", is the statement to be compiled, encoded
3681** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3682** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3683** use UTF-16.
3684**
3685** ^If the nByte argument is negative, then zSql is read up to the
3686** first zero terminator. ^If nByte is positive, then it is the
3687** number of bytes read from zSql.  ^If nByte is zero, then no prepared
3688** statement is generated.
3689** If the caller knows that the supplied string is nul-terminated, then
3690** there is a small performance advantage to passing an nByte parameter that
3691** is the number of bytes in the input string <i>including</i>
3692** the nul-terminator.
3693**
3694** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3695** past the end of the first SQL statement in zSql.  These routines only
3696** compile the first statement in zSql, so *pzTail is left pointing to
3697** what remains uncompiled.
3698**
3699** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3700** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3701** to NULL.  ^If the input text contains no SQL (if the input is an empty
3702** string or a comment) then *ppStmt is set to NULL.
3703** The calling procedure is responsible for deleting the compiled
3704** SQL statement using [sqlite3_finalize()] after it has finished with it.
3705** ppStmt may not be NULL.
3706**
3707** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3708** otherwise an [error code] is returned.
3709**
3710** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3711** recommended for all new programs. The two older interfaces are retained
3712** for backwards compatibility, but their use is discouraged.
3713** ^In the "v2" interfaces, the prepared statement
3714** that is returned (the [sqlite3_stmt] object) contains a copy of the
3715** original SQL text. This causes the [sqlite3_step()] interface to
3716** behave differently in three ways:
3717**
3718** <ol>
3719** <li>
3720** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3721** always used to do, [sqlite3_step()] will automatically recompile the SQL
3722** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
3723** retries will occur before sqlite3_step() gives up and returns an error.
3724** </li>
3725**
3726** <li>
3727** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3728** [error codes] or [extended error codes].  ^The legacy behavior was that
3729** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3730** and the application would have to make a second call to [sqlite3_reset()]
3731** in order to find the underlying cause of the problem. With the "v2" prepare
3732** interfaces, the underlying reason for the error is returned immediately.
3733** </li>
3734**
3735** <li>
3736** ^If the specific value bound to [parameter | host parameter] in the
3737** WHERE clause might influence the choice of query plan for a statement,
3738** then the statement will be automatically recompiled, as if there had been
3739** a schema change, on the first  [sqlite3_step()] call following any change
3740** to the [sqlite3_bind_text | bindings] of that [parameter].
3741** ^The specific value of WHERE-clause [parameter] might influence the
3742** choice of query plan if the parameter is the left-hand side of a [LIKE]
3743** or [GLOB] operator or if the parameter is compared to an indexed column
3744** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3745** </li>
3746** </ol>
3747*/
3748SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
3749  sqlite3 *db,            /* Database handle */
3750  const char *zSql,       /* SQL statement, UTF-8 encoded */
3751  int nByte,              /* Maximum length of zSql in bytes. */
3752  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3753  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3754);
3755SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
3756  sqlite3 *db,            /* Database handle */
3757  const char *zSql,       /* SQL statement, UTF-8 encoded */
3758  int nByte,              /* Maximum length of zSql in bytes. */
3759  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3760  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3761);
3762SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
3763  sqlite3 *db,            /* Database handle */
3764  const void *zSql,       /* SQL statement, UTF-16 encoded */
3765  int nByte,              /* Maximum length of zSql in bytes. */
3766  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3767  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3768);
3769SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
3770  sqlite3 *db,            /* Database handle */
3771  const void *zSql,       /* SQL statement, UTF-16 encoded */
3772  int nByte,              /* Maximum length of zSql in bytes. */
3773  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3774  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3775);
3776
3777/*
3778** CAPI3REF: Retrieving Statement SQL
3779** METHOD: sqlite3_stmt
3780**
3781** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
3782** SQL text used to create [prepared statement] P if P was
3783** created by either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3784** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
3785** string containing the SQL text of prepared statement P with
3786** [bound parameters] expanded.
3787**
3788** ^(For example, if a prepared statement is created using the SQL
3789** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
3790** and parameter :xyz is unbound, then sqlite3_sql() will return
3791** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
3792** will return "SELECT 2345,NULL".)^
3793**
3794** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
3795** is available to hold the result, or if the result would exceed the
3796** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
3797**
3798** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
3799** bound parameter expansions.  ^The [SQLITE_OMIT_TRACE] compile-time
3800** option causes sqlite3_expanded_sql() to always return NULL.
3801**
3802** ^The string returned by sqlite3_sql(P) is managed by SQLite and is
3803** automatically freed when the prepared statement is finalized.
3804** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
3805** is obtained from [sqlite3_malloc()] and must be free by the application
3806** by passing it to [sqlite3_free()].
3807*/
3808SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt);
3809SQLITE_API char *SQLITE_STDCALL sqlite3_expanded_sql(sqlite3_stmt *pStmt);
3810
3811/*
3812** CAPI3REF: Determine If An SQL Statement Writes The Database
3813** METHOD: sqlite3_stmt
3814**
3815** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3816** and only if the [prepared statement] X makes no direct changes to
3817** the content of the database file.
3818**
3819** Note that [application-defined SQL functions] or
3820** [virtual tables] might change the database indirectly as a side effect.
3821** ^(For example, if an application defines a function "eval()" that
3822** calls [sqlite3_exec()], then the following SQL statement would
3823** change the database file through side-effects:
3824**
3825** <blockquote><pre>
3826**    SELECT eval('DELETE FROM t1') FROM t2;
3827** </pre></blockquote>
3828**
3829** But because the [SELECT] statement does not change the database file
3830** directly, sqlite3_stmt_readonly() would still return true.)^
3831**
3832** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3833** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3834** since the statements themselves do not actually modify the database but
3835** rather they control the timing of when other statements modify the
3836** database.  ^The [ATTACH] and [DETACH] statements also cause
3837** sqlite3_stmt_readonly() to return true since, while those statements
3838** change the configuration of a database connection, they do not make
3839** changes to the content of the database files on disk.
3840*/
3841SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3842
3843/*
3844** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3845** METHOD: sqlite3_stmt
3846**
3847** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3848** [prepared statement] S has been stepped at least once using
3849** [sqlite3_step(S)] but has neither run to completion (returned
3850** [SQLITE_DONE] from [sqlite3_step(S)]) nor
3851** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
3852** interface returns false if S is a NULL pointer.  If S is not a
3853** NULL pointer and is not a pointer to a valid [prepared statement]
3854** object, then the behavior is undefined and probably undesirable.
3855**
3856** This interface can be used in combination [sqlite3_next_stmt()]
3857** to locate all prepared statements associated with a database
3858** connection that are in need of being reset.  This can be used,
3859** for example, in diagnostic routines to search for prepared
3860** statements that are holding a transaction open.
3861*/
3862SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt*);
3863
3864/*
3865** CAPI3REF: Dynamically Typed Value Object
3866** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3867**
3868** SQLite uses the sqlite3_value object to represent all values
3869** that can be stored in a database table. SQLite uses dynamic typing
3870** for the values it stores.  ^Values stored in sqlite3_value objects
3871** can be integers, floating point values, strings, BLOBs, or NULL.
3872**
3873** An sqlite3_value object may be either "protected" or "unprotected".
3874** Some interfaces require a protected sqlite3_value.  Other interfaces
3875** will accept either a protected or an unprotected sqlite3_value.
3876** Every interface that accepts sqlite3_value arguments specifies
3877** whether or not it requires a protected sqlite3_value.  The
3878** [sqlite3_value_dup()] interface can be used to construct a new
3879** protected sqlite3_value from an unprotected sqlite3_value.
3880**
3881** The terms "protected" and "unprotected" refer to whether or not
3882** a mutex is held.  An internal mutex is held for a protected
3883** sqlite3_value object but no mutex is held for an unprotected
3884** sqlite3_value object.  If SQLite is compiled to be single-threaded
3885** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3886** or if SQLite is run in one of reduced mutex modes
3887** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3888** then there is no distinction between protected and unprotected
3889** sqlite3_value objects and they can be used interchangeably.  However,
3890** for maximum code portability it is recommended that applications
3891** still make the distinction between protected and unprotected
3892** sqlite3_value objects even when not strictly required.
3893**
3894** ^The sqlite3_value objects that are passed as parameters into the
3895** implementation of [application-defined SQL functions] are protected.
3896** ^The sqlite3_value object returned by
3897** [sqlite3_column_value()] is unprotected.
3898** Unprotected sqlite3_value objects may only be used with
3899** [sqlite3_result_value()] and [sqlite3_bind_value()].
3900** The [sqlite3_value_blob | sqlite3_value_type()] family of
3901** interfaces require protected sqlite3_value objects.
3902*/
3903typedef struct Mem sqlite3_value;
3904
3905/*
3906** CAPI3REF: SQL Function Context Object
3907**
3908** The context in which an SQL function executes is stored in an
3909** sqlite3_context object.  ^A pointer to an sqlite3_context object
3910** is always first parameter to [application-defined SQL functions].
3911** The application-defined SQL function implementation will pass this
3912** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3913** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3914** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3915** and/or [sqlite3_set_auxdata()].
3916*/
3917typedef struct sqlite3_context sqlite3_context;
3918
3919/*
3920** CAPI3REF: Binding Values To Prepared Statements
3921** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3922** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3923** METHOD: sqlite3_stmt
3924**
3925** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3926** literals may be replaced by a [parameter] that matches one of following
3927** templates:
3928**
3929** <ul>
3930** <li>  ?
3931** <li>  ?NNN
3932** <li>  :VVV
3933** <li>  @VVV
3934** <li>  $VVV
3935** </ul>
3936**
3937** In the templates above, NNN represents an integer literal,
3938** and VVV represents an alphanumeric identifier.)^  ^The values of these
3939** parameters (also called "host parameter names" or "SQL parameters")
3940** can be set using the sqlite3_bind_*() routines defined here.
3941**
3942** ^The first argument to the sqlite3_bind_*() routines is always
3943** a pointer to the [sqlite3_stmt] object returned from
3944** [sqlite3_prepare_v2()] or its variants.
3945**
3946** ^The second argument is the index of the SQL parameter to be set.
3947** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3948** SQL parameter is used more than once, second and subsequent
3949** occurrences have the same index as the first occurrence.
3950** ^The index for named parameters can be looked up using the
3951** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3952** for "?NNN" parameters is the value of NNN.
3953** ^The NNN value must be between 1 and the [sqlite3_limit()]
3954** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3955**
3956** ^The third argument is the value to bind to the parameter.
3957** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3958** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
3959** is ignored and the end result is the same as sqlite3_bind_null().
3960**
3961** ^(In those routines that have a fourth argument, its value is the
3962** number of bytes in the parameter.  To be clear: the value is the
3963** number of <u>bytes</u> in the value, not the number of characters.)^
3964** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3965** is negative, then the length of the string is
3966** the number of bytes up to the first zero terminator.
3967** If the fourth parameter to sqlite3_bind_blob() is negative, then
3968** the behavior is undefined.
3969** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3970** or sqlite3_bind_text16() or sqlite3_bind_text64() then
3971** that parameter must be the byte offset
3972** where the NUL terminator would occur assuming the string were NUL
3973** terminated.  If any NUL characters occur at byte offsets less than
3974** the value of the fourth parameter then the resulting string value will
3975** contain embedded NULs.  The result of expressions involving strings
3976** with embedded NULs is undefined.
3977**
3978** ^The fifth argument to the BLOB and string binding interfaces
3979** is a destructor used to dispose of the BLOB or
3980** string after SQLite has finished with it.  ^The destructor is called
3981** to dispose of the BLOB or string even if the call to bind API fails.
3982** ^If the fifth argument is
3983** the special value [SQLITE_STATIC], then SQLite assumes that the
3984** information is in static, unmanaged space and does not need to be freed.
3985** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3986** SQLite makes its own private copy of the data immediately, before
3987** the sqlite3_bind_*() routine returns.
3988**
3989** ^The sixth argument to sqlite3_bind_text64() must be one of
3990** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
3991** to specify the encoding of the text in the third parameter.  If
3992** the sixth argument to sqlite3_bind_text64() is not one of the
3993** allowed values shown above, or if the text encoding is different
3994** from the encoding specified by the sixth parameter, then the behavior
3995** is undefined.
3996**
3997** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3998** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3999** (just an integer to hold its size) while it is being processed.
4000** Zeroblobs are intended to serve as placeholders for BLOBs whose
4001** content is later written using
4002** [sqlite3_blob_open | incremental BLOB I/O] routines.
4003** ^A negative value for the zeroblob results in a zero-length BLOB.
4004**
4005** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
4006** for the [prepared statement] or with a prepared statement for which
4007** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
4008** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
4009** routine is passed a [prepared statement] that has been finalized, the
4010** result is undefined and probably harmful.
4011**
4012** ^Bindings are not cleared by the [sqlite3_reset()] routine.
4013** ^Unbound parameters are interpreted as NULL.
4014**
4015** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
4016** [error code] if anything goes wrong.
4017** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
4018** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
4019** [SQLITE_MAX_LENGTH].
4020** ^[SQLITE_RANGE] is returned if the parameter
4021** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
4022**
4023** See also: [sqlite3_bind_parameter_count()],
4024** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
4025*/
4026SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
4027SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
4028                        void(*)(void*));
4029SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt*, int, double);
4030SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt*, int, int);
4031SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
4032SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt*, int);
4033SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
4034SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
4035SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
4036                         void(*)(void*), unsigned char encoding);
4037SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
4038SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
4039SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
4040
4041/*
4042** CAPI3REF: Number Of SQL Parameters
4043** METHOD: sqlite3_stmt
4044**
4045** ^This routine can be used to find the number of [SQL parameters]
4046** in a [prepared statement].  SQL parameters are tokens of the
4047** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
4048** placeholders for values that are [sqlite3_bind_blob | bound]
4049** to the parameters at a later time.
4050**
4051** ^(This routine actually returns the index of the largest (rightmost)
4052** parameter. For all forms except ?NNN, this will correspond to the
4053** number of unique parameters.  If parameters of the ?NNN form are used,
4054** there may be gaps in the list.)^
4055**
4056** See also: [sqlite3_bind_blob|sqlite3_bind()],
4057** [sqlite3_bind_parameter_name()], and
4058** [sqlite3_bind_parameter_index()].
4059*/
4060SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt*);
4061
4062/*
4063** CAPI3REF: Name Of A Host Parameter
4064** METHOD: sqlite3_stmt
4065**
4066** ^The sqlite3_bind_parameter_name(P,N) interface returns
4067** the name of the N-th [SQL parameter] in the [prepared statement] P.
4068** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
4069** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
4070** respectively.
4071** In other words, the initial ":" or "$" or "@" or "?"
4072** is included as part of the name.)^
4073** ^Parameters of the form "?" without a following integer have no name
4074** and are referred to as "nameless" or "anonymous parameters".
4075**
4076** ^The first host parameter has an index of 1, not 0.
4077**
4078** ^If the value N is out of range or if the N-th parameter is
4079** nameless, then NULL is returned.  ^The returned string is
4080** always in UTF-8 encoding even if the named parameter was
4081** originally specified as UTF-16 in [sqlite3_prepare16()] or
4082** [sqlite3_prepare16_v2()].
4083**
4084** See also: [sqlite3_bind_blob|sqlite3_bind()],
4085** [sqlite3_bind_parameter_count()], and
4086** [sqlite3_bind_parameter_index()].
4087*/
4088SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt*, int);
4089
4090/*
4091** CAPI3REF: Index Of A Parameter With A Given Name
4092** METHOD: sqlite3_stmt
4093**
4094** ^Return the index of an SQL parameter given its name.  ^The
4095** index value returned is suitable for use as the second
4096** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
4097** is returned if no matching parameter is found.  ^The parameter
4098** name must be given in UTF-8 even if the original statement
4099** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
4100**
4101** See also: [sqlite3_bind_blob|sqlite3_bind()],
4102** [sqlite3_bind_parameter_count()], and
4103** [sqlite3_bind_parameter_name()].
4104*/
4105SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
4106
4107/*
4108** CAPI3REF: Reset All Bindings On A Prepared Statement
4109** METHOD: sqlite3_stmt
4110**
4111** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
4112** the [sqlite3_bind_blob | bindings] on a [prepared statement].
4113** ^Use this routine to reset all host parameters to NULL.
4114*/
4115SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt*);
4116
4117/*
4118** CAPI3REF: Number Of Columns In A Result Set
4119** METHOD: sqlite3_stmt
4120**
4121** ^Return the number of columns in the result set returned by the
4122** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
4123** statement that does not return data (for example an [UPDATE]).
4124**
4125** See also: [sqlite3_data_count()]
4126*/
4127SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt);
4128
4129/*
4130** CAPI3REF: Column Names In A Result Set
4131** METHOD: sqlite3_stmt
4132**
4133** ^These routines return the name assigned to a particular column
4134** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
4135** interface returns a pointer to a zero-terminated UTF-8 string
4136** and sqlite3_column_name16() returns a pointer to a zero-terminated
4137** UTF-16 string.  ^The first parameter is the [prepared statement]
4138** that implements the [SELECT] statement. ^The second parameter is the
4139** column number.  ^The leftmost column is number 0.
4140**
4141** ^The returned string pointer is valid until either the [prepared statement]
4142** is destroyed by [sqlite3_finalize()] or until the statement is automatically
4143** reprepared by the first call to [sqlite3_step()] for a particular run
4144** or until the next call to
4145** sqlite3_column_name() or sqlite3_column_name16() on the same column.
4146**
4147** ^If sqlite3_malloc() fails during the processing of either routine
4148** (for example during a conversion from UTF-8 to UTF-16) then a
4149** NULL pointer is returned.
4150**
4151** ^The name of a result column is the value of the "AS" clause for
4152** that column, if there is an AS clause.  If there is no AS clause
4153** then the name of the column is unspecified and may change from
4154** one release of SQLite to the next.
4155*/
4156SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt*, int N);
4157SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt*, int N);
4158
4159/*
4160** CAPI3REF: Source Of Data In A Query Result
4161** METHOD: sqlite3_stmt
4162**
4163** ^These routines provide a means to determine the database, table, and
4164** table column that is the origin of a particular result column in
4165** [SELECT] statement.
4166** ^The name of the database or table or column can be returned as
4167** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
4168** the database name, the _table_ routines return the table name, and
4169** the origin_ routines return the column name.
4170** ^The returned string is valid until the [prepared statement] is destroyed
4171** using [sqlite3_finalize()] or until the statement is automatically
4172** reprepared by the first call to [sqlite3_step()] for a particular run
4173** or until the same information is requested
4174** again in a different encoding.
4175**
4176** ^The names returned are the original un-aliased names of the
4177** database, table, and column.
4178**
4179** ^The first argument to these interfaces is a [prepared statement].
4180** ^These functions return information about the Nth result column returned by
4181** the statement, where N is the second function argument.
4182** ^The left-most column is column 0 for these routines.
4183**
4184** ^If the Nth column returned by the statement is an expression or
4185** subquery and is not a column value, then all of these functions return
4186** NULL.  ^These routine might also return NULL if a memory allocation error
4187** occurs.  ^Otherwise, they return the name of the attached database, table,
4188** or column that query result column was extracted from.
4189**
4190** ^As with all other SQLite APIs, those whose names end with "16" return
4191** UTF-16 encoded strings and the other functions return UTF-8.
4192**
4193** ^These APIs are only available if the library was compiled with the
4194** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
4195**
4196** If two or more threads call one or more of these routines against the same
4197** prepared statement and column at the same time then the results are
4198** undefined.
4199**
4200** If two or more threads call one or more
4201** [sqlite3_column_database_name | column metadata interfaces]
4202** for the same [prepared statement] and result column
4203** at the same time then the results are undefined.
4204*/
4205SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt*,int);
4206SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt*,int);
4207SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt*,int);
4208SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt*,int);
4209SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt*,int);
4210SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt*,int);
4211
4212/*
4213** CAPI3REF: Declared Datatype Of A Query Result
4214** METHOD: sqlite3_stmt
4215**
4216** ^(The first parameter is a [prepared statement].
4217** If this statement is a [SELECT] statement and the Nth column of the
4218** returned result set of that [SELECT] is a table column (not an
4219** expression or subquery) then the declared type of the table
4220** column is returned.)^  ^If the Nth column of the result set is an
4221** expression or subquery, then a NULL pointer is returned.
4222** ^The returned string is always UTF-8 encoded.
4223**
4224** ^(For example, given the database schema:
4225**
4226** CREATE TABLE t1(c1 VARIANT);
4227**
4228** and the following statement to be compiled:
4229**
4230** SELECT c1 + 1, c1 FROM t1;
4231**
4232** this routine would return the string "VARIANT" for the second result
4233** column (i==1), and a NULL pointer for the first result column (i==0).)^
4234**
4235** ^SQLite uses dynamic run-time typing.  ^So just because a column
4236** is declared to contain a particular type does not mean that the
4237** data stored in that column is of the declared type.  SQLite is
4238** strongly typed, but the typing is dynamic not static.  ^Type
4239** is associated with individual values, not with the containers
4240** used to hold those values.
4241*/
4242SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt*,int);
4243SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt*,int);
4244
4245/*
4246** CAPI3REF: Evaluate An SQL Statement
4247** METHOD: sqlite3_stmt
4248**
4249** After a [prepared statement] has been prepared using either
4250** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
4251** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
4252** must be called one or more times to evaluate the statement.
4253**
4254** The details of the behavior of the sqlite3_step() interface depend
4255** on whether the statement was prepared using the newer "v2" interface
4256** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
4257** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
4258** new "v2" interface is recommended for new applications but the legacy
4259** interface will continue to be supported.
4260**
4261** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
4262** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4263** ^With the "v2" interface, any of the other [result codes] or
4264** [extended result codes] might be returned as well.
4265**
4266** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
4267** database locks it needs to do its job.  ^If the statement is a [COMMIT]
4268** or occurs outside of an explicit transaction, then you can retry the
4269** statement.  If the statement is not a [COMMIT] and occurs within an
4270** explicit transaction then you should rollback the transaction before
4271** continuing.
4272**
4273** ^[SQLITE_DONE] means that the statement has finished executing
4274** successfully.  sqlite3_step() should not be called again on this virtual
4275** machine without first calling [sqlite3_reset()] to reset the virtual
4276** machine back to its initial state.
4277**
4278** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
4279** is returned each time a new row of data is ready for processing by the
4280** caller. The values may be accessed using the [column access functions].
4281** sqlite3_step() is called again to retrieve the next row of data.
4282**
4283** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
4284** violation) has occurred.  sqlite3_step() should not be called again on
4285** the VM. More information may be found by calling [sqlite3_errmsg()].
4286** ^With the legacy interface, a more specific error code (for example,
4287** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4288** can be obtained by calling [sqlite3_reset()] on the
4289** [prepared statement].  ^In the "v2" interface,
4290** the more specific error code is returned directly by sqlite3_step().
4291**
4292** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4293** Perhaps it was called on a [prepared statement] that has
4294** already been [sqlite3_finalize | finalized] or on one that had
4295** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
4296** be the case that the same database connection is being used by two or
4297** more threads at the same moment in time.
4298**
4299** For all versions of SQLite up to and including 3.6.23.1, a call to
4300** [sqlite3_reset()] was required after sqlite3_step() returned anything
4301** other than [SQLITE_ROW] before any subsequent invocation of
4302** sqlite3_step().  Failure to reset the prepared statement using
4303** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4304** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
4305** calling [sqlite3_reset()] automatically in this circumstance rather
4306** than returning [SQLITE_MISUSE].  This is not considered a compatibility
4307** break because any application that ever receives an SQLITE_MISUSE error
4308** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
4309** can be used to restore the legacy behavior.
4310**
4311** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4312** API always returns a generic error code, [SQLITE_ERROR], following any
4313** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
4314** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4315** specific [error codes] that better describes the error.
4316** We admit that this is a goofy design.  The problem has been fixed
4317** with the "v2" interface.  If you prepare all of your SQL statements
4318** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4319** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4320** then the more specific [error codes] are returned directly
4321** by sqlite3_step().  The use of the "v2" interface is recommended.
4322*/
4323SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt*);
4324
4325/*
4326** CAPI3REF: Number of columns in a result set
4327** METHOD: sqlite3_stmt
4328**
4329** ^The sqlite3_data_count(P) interface returns the number of columns in the
4330** current row of the result set of [prepared statement] P.
4331** ^If prepared statement P does not have results ready to return
4332** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4333** interfaces) then sqlite3_data_count(P) returns 0.
4334** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4335** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4336** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
4337** will return non-zero if previous call to [sqlite3_step](P) returned
4338** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4339** where it always returns zero since each step of that multi-step
4340** pragma returns 0 columns of data.
4341**
4342** See also: [sqlite3_column_count()]
4343*/
4344SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt);
4345
4346/*
4347** CAPI3REF: Fundamental Datatypes
4348** KEYWORDS: SQLITE_TEXT
4349**
4350** ^(Every value in SQLite has one of five fundamental datatypes:
4351**
4352** <ul>
4353** <li> 64-bit signed integer
4354** <li> 64-bit IEEE floating point number
4355** <li> string
4356** <li> BLOB
4357** <li> NULL
4358** </ul>)^
4359**
4360** These constants are codes for each of those types.
4361**
4362** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4363** for a completely different meaning.  Software that links against both
4364** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4365** SQLITE_TEXT.
4366*/
4367#define SQLITE_INTEGER  1
4368#define SQLITE_FLOAT    2
4369#define SQLITE_BLOB     4
4370#define SQLITE_NULL     5
4371#ifdef SQLITE_TEXT
4372# undef SQLITE_TEXT
4373#else
4374# define SQLITE_TEXT     3
4375#endif
4376#define SQLITE3_TEXT     3
4377
4378/*
4379** CAPI3REF: Result Values From A Query
4380** KEYWORDS: {column access functions}
4381** METHOD: sqlite3_stmt
4382**
4383** ^These routines return information about a single column of the current
4384** result row of a query.  ^In every case the first argument is a pointer
4385** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4386** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4387** and the second argument is the index of the column for which information
4388** should be returned. ^The leftmost column of the result set has the index 0.
4389** ^The number of columns in the result can be determined using
4390** [sqlite3_column_count()].
4391**
4392** If the SQL statement does not currently point to a valid row, or if the
4393** column index is out of range, the result is undefined.
4394** These routines may only be called when the most recent call to
4395** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4396** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4397** If any of these routines are called after [sqlite3_reset()] or
4398** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4399** something other than [SQLITE_ROW], the results are undefined.
4400** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4401** are called from a different thread while any of these routines
4402** are pending, then the results are undefined.
4403**
4404** ^The sqlite3_column_type() routine returns the
4405** [SQLITE_INTEGER | datatype code] for the initial data type
4406** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
4407** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4408** returned by sqlite3_column_type() is only meaningful if no type
4409** conversions have occurred as described below.  After a type conversion,
4410** the value returned by sqlite3_column_type() is undefined.  Future
4411** versions of SQLite may change the behavior of sqlite3_column_type()
4412** following a type conversion.
4413**
4414** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4415** routine returns the number of bytes in that BLOB or string.
4416** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4417** the string to UTF-8 and then returns the number of bytes.
4418** ^If the result is a numeric value then sqlite3_column_bytes() uses
4419** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4420** the number of bytes in that string.
4421** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4422**
4423** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4424** routine returns the number of bytes in that BLOB or string.
4425** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4426** the string to UTF-16 and then returns the number of bytes.
4427** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4428** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4429** the number of bytes in that string.
4430** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4431**
4432** ^The values returned by [sqlite3_column_bytes()] and
4433** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4434** of the string.  ^For clarity: the values returned by
4435** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4436** bytes in the string, not the number of characters.
4437**
4438** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4439** even empty strings, are always zero-terminated.  ^The return
4440** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4441**
4442** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
4443** [unprotected sqlite3_value] object.  In a multithreaded environment,
4444** an unprotected sqlite3_value object may only be used safely with
4445** [sqlite3_bind_value()] and [sqlite3_result_value()].
4446** If the [unprotected sqlite3_value] object returned by
4447** [sqlite3_column_value()] is used in any other way, including calls
4448** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4449** or [sqlite3_value_bytes()], the behavior is not threadsafe.
4450**
4451** These routines attempt to convert the value where appropriate.  ^For
4452** example, if the internal representation is FLOAT and a text result
4453** is requested, [sqlite3_snprintf()] is used internally to perform the
4454** conversion automatically.  ^(The following table details the conversions
4455** that are applied:
4456**
4457** <blockquote>
4458** <table border="1">
4459** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4460**
4461** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4462** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4463** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer
4464** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer
4465** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4466** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4467** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4468** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER
4469** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4470** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
4471** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
4472** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
4473** <tr><td>  TEXT    <td>   BLOB    <td> No change
4474** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
4475** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
4476** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4477** </table>
4478** </blockquote>)^
4479**
4480** Note that when type conversions occur, pointers returned by prior
4481** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4482** sqlite3_column_text16() may be invalidated.
4483** Type conversions and pointer invalidations might occur
4484** in the following cases:
4485**
4486** <ul>
4487** <li> The initial content is a BLOB and sqlite3_column_text() or
4488**      sqlite3_column_text16() is called.  A zero-terminator might
4489**      need to be added to the string.</li>
4490** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4491**      sqlite3_column_text16() is called.  The content must be converted
4492**      to UTF-16.</li>
4493** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4494**      sqlite3_column_text() is called.  The content must be converted
4495**      to UTF-8.</li>
4496** </ul>
4497**
4498** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4499** not invalidate a prior pointer, though of course the content of the buffer
4500** that the prior pointer references will have been modified.  Other kinds
4501** of conversion are done in place when it is possible, but sometimes they
4502** are not possible and in those cases prior pointers are invalidated.
4503**
4504** The safest policy is to invoke these routines
4505** in one of the following ways:
4506**
4507** <ul>
4508**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4509**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4510**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4511** </ul>
4512**
4513** In other words, you should call sqlite3_column_text(),
4514** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4515** into the desired format, then invoke sqlite3_column_bytes() or
4516** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4517** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4518** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4519** with calls to sqlite3_column_bytes().
4520**
4521** ^The pointers returned are valid until a type conversion occurs as
4522** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4523** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4524** and BLOBs is freed automatically.  Do <em>not</em> pass the pointers returned
4525** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4526** [sqlite3_free()].
4527**
4528** ^(If a memory allocation error occurs during the evaluation of any
4529** of these routines, a default value is returned.  The default value
4530** is either the integer 0, the floating point number 0.0, or a NULL
4531** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4532** [SQLITE_NOMEM].)^
4533*/
4534SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt*, int iCol);
4535SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4536SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4537SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt*, int iCol);
4538SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt*, int iCol);
4539SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt*, int iCol);
4540SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt*, int iCol);
4541SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt*, int iCol);
4542SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt*, int iCol);
4543SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt*, int iCol);
4544
4545/*
4546** CAPI3REF: Destroy A Prepared Statement Object
4547** DESTRUCTOR: sqlite3_stmt
4548**
4549** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4550** ^If the most recent evaluation of the statement encountered no errors
4551** or if the statement is never been evaluated, then sqlite3_finalize() returns
4552** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4553** sqlite3_finalize(S) returns the appropriate [error code] or
4554** [extended error code].
4555**
4556** ^The sqlite3_finalize(S) routine can be called at any point during
4557** the life cycle of [prepared statement] S:
4558** before statement S is ever evaluated, after
4559** one or more calls to [sqlite3_reset()], or after any call
4560** to [sqlite3_step()] regardless of whether or not the statement has
4561** completed execution.
4562**
4563** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4564**
4565** The application must finalize every [prepared statement] in order to avoid
4566** resource leaks.  It is a grievous error for the application to try to use
4567** a prepared statement after it has been finalized.  Any use of a prepared
4568** statement after it has been finalized can result in undefined and
4569** undesirable behavior such as segfaults and heap corruption.
4570*/
4571SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt);
4572
4573/*
4574** CAPI3REF: Reset A Prepared Statement Object
4575** METHOD: sqlite3_stmt
4576**
4577** The sqlite3_reset() function is called to reset a [prepared statement]
4578** object back to its initial state, ready to be re-executed.
4579** ^Any SQL statement variables that had values bound to them using
4580** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4581** Use [sqlite3_clear_bindings()] to reset the bindings.
4582**
4583** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4584** back to the beginning of its program.
4585**
4586** ^If the most recent call to [sqlite3_step(S)] for the
4587** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4588** or if [sqlite3_step(S)] has never before been called on S,
4589** then [sqlite3_reset(S)] returns [SQLITE_OK].
4590**
4591** ^If the most recent call to [sqlite3_step(S)] for the
4592** [prepared statement] S indicated an error, then
4593** [sqlite3_reset(S)] returns an appropriate [error code].
4594**
4595** ^The [sqlite3_reset(S)] interface does not change the values
4596** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4597*/
4598SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt);
4599
4600/*
4601** CAPI3REF: Create Or Redefine SQL Functions
4602** KEYWORDS: {function creation routines}
4603** KEYWORDS: {application-defined SQL function}
4604** KEYWORDS: {application-defined SQL functions}
4605** METHOD: sqlite3
4606**
4607** ^These functions (collectively known as "function creation routines")
4608** are used to add SQL functions or aggregates or to redefine the behavior
4609** of existing SQL functions or aggregates.  The only differences between
4610** these routines are the text encoding expected for
4611** the second parameter (the name of the function being created)
4612** and the presence or absence of a destructor callback for
4613** the application data pointer.
4614**
4615** ^The first parameter is the [database connection] to which the SQL
4616** function is to be added.  ^If an application uses more than one database
4617** connection then application-defined SQL functions must be added
4618** to each database connection separately.
4619**
4620** ^The second parameter is the name of the SQL function to be created or
4621** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4622** representation, exclusive of the zero-terminator.  ^Note that the name
4623** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4624** ^Any attempt to create a function with a longer name
4625** will result in [SQLITE_MISUSE] being returned.
4626**
4627** ^The third parameter (nArg)
4628** is the number of arguments that the SQL function or
4629** aggregate takes. ^If this parameter is -1, then the SQL function or
4630** aggregate may take any number of arguments between 0 and the limit
4631** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4632** parameter is less than -1 or greater than 127 then the behavior is
4633** undefined.
4634**
4635** ^The fourth parameter, eTextRep, specifies what
4636** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4637** its parameters.  The application should set this parameter to
4638** [SQLITE_UTF16LE] if the function implementation invokes
4639** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
4640** implementation invokes [sqlite3_value_text16be()] on an input, or
4641** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
4642** otherwise.  ^The same SQL function may be registered multiple times using
4643** different preferred text encodings, with different implementations for
4644** each encoding.
4645** ^When multiple implementations of the same function are available, SQLite
4646** will pick the one that involves the least amount of data conversion.
4647**
4648** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
4649** to signal that the function will always return the same result given
4650** the same inputs within a single SQL statement.  Most SQL functions are
4651** deterministic.  The built-in [random()] SQL function is an example of a
4652** function that is not deterministic.  The SQLite query planner is able to
4653** perform additional optimizations on deterministic functions, so use
4654** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
4655**
4656** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4657** function can gain access to this pointer using [sqlite3_user_data()].)^
4658**
4659** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4660** pointers to C-language functions that implement the SQL function or
4661** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4662** callback only; NULL pointers must be passed as the xStep and xFinal
4663** parameters. ^An aggregate SQL function requires an implementation of xStep
4664** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4665** SQL function or aggregate, pass NULL pointers for all three function
4666** callbacks.
4667**
4668** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4669** then it is destructor for the application data pointer.
4670** The destructor is invoked when the function is deleted, either by being
4671** overloaded or when the database connection closes.)^
4672** ^The destructor is also invoked if the call to
4673** sqlite3_create_function_v2() fails.
4674** ^When the destructor callback of the tenth parameter is invoked, it
4675** is passed a single argument which is a copy of the application data
4676** pointer which was the fifth parameter to sqlite3_create_function_v2().
4677**
4678** ^It is permitted to register multiple implementations of the same
4679** functions with the same name but with either differing numbers of
4680** arguments or differing preferred text encodings.  ^SQLite will use
4681** the implementation that most closely matches the way in which the
4682** SQL function is used.  ^A function implementation with a non-negative
4683** nArg parameter is a better match than a function implementation with
4684** a negative nArg.  ^A function where the preferred text encoding
4685** matches the database encoding is a better
4686** match than a function where the encoding is different.
4687** ^A function where the encoding difference is between UTF16le and UTF16be
4688** is a closer match than a function where the encoding difference is
4689** between UTF8 and UTF16.
4690**
4691** ^Built-in functions may be overloaded by new application-defined functions.
4692**
4693** ^An application-defined function is permitted to call other
4694** SQLite interfaces.  However, such calls must not
4695** close the database connection nor finalize or reset the prepared
4696** statement in which the function is running.
4697*/
4698SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
4699  sqlite3 *db,
4700  const char *zFunctionName,
4701  int nArg,
4702  int eTextRep,
4703  void *pApp,
4704  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4705  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4706  void (*xFinal)(sqlite3_context*)
4707);
4708SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
4709  sqlite3 *db,
4710  const void *zFunctionName,
4711  int nArg,
4712  int eTextRep,
4713  void *pApp,
4714  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4715  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4716  void (*xFinal)(sqlite3_context*)
4717);
4718SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
4719  sqlite3 *db,
4720  const char *zFunctionName,
4721  int nArg,
4722  int eTextRep,
4723  void *pApp,
4724  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4725  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4726  void (*xFinal)(sqlite3_context*),
4727  void(*xDestroy)(void*)
4728);
4729
4730/*
4731** CAPI3REF: Text Encodings
4732**
4733** These constant define integer codes that represent the various
4734** text encodings supported by SQLite.
4735*/
4736#define SQLITE_UTF8           1    /* IMP: R-37514-35566 */
4737#define SQLITE_UTF16LE        2    /* IMP: R-03371-37637 */
4738#define SQLITE_UTF16BE        3    /* IMP: R-51971-34154 */
4739#define SQLITE_UTF16          4    /* Use native byte order */
4740#define SQLITE_ANY            5    /* Deprecated */
4741#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4742
4743/*
4744** CAPI3REF: Function Flags
4745**
4746** These constants may be ORed together with the
4747** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
4748** to [sqlite3_create_function()], [sqlite3_create_function16()], or
4749** [sqlite3_create_function_v2()].
4750*/
4751#define SQLITE_DETERMINISTIC    0x800
4752
4753/*
4754** CAPI3REF: Deprecated Functions
4755** DEPRECATED
4756**
4757** These functions are [deprecated].  In order to maintain
4758** backwards compatibility with older code, these functions continue
4759** to be supported.  However, new applications should avoid
4760** the use of these functions.  To encourage programmers to avoid
4761** these functions, we will not explain what they do.
4762*/
4763#ifndef SQLITE_OMIT_DEPRECATED
4764SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context*);
4765SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt*);
4766SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4767SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_global_recover(void);
4768SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_thread_cleanup(void);
4769SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4770                      void*,sqlite3_int64);
4771#endif
4772
4773/*
4774** CAPI3REF: Obtaining SQL Values
4775** METHOD: sqlite3_value
4776**
4777** The C-language implementation of SQL functions and aggregates uses
4778** this set of interface routines to access the parameter values on
4779** the function or aggregate.
4780**
4781** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4782** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4783** define callbacks that implement the SQL functions and aggregates.
4784** The 3rd parameter to these callbacks is an array of pointers to
4785** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4786** each parameter to the SQL function.  These routines are used to
4787** extract values from the [sqlite3_value] objects.
4788**
4789** These routines work only with [protected sqlite3_value] objects.
4790** Any attempt to use these routines on an [unprotected sqlite3_value]
4791** object results in undefined behavior.
4792**
4793** ^These routines work just like the corresponding [column access functions]
4794** except that these routines take a single [protected sqlite3_value] object
4795** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4796**
4797** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4798** in the native byte-order of the host machine.  ^The
4799** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4800** extract UTF-16 strings as big-endian and little-endian respectively.
4801**
4802** ^(The sqlite3_value_numeric_type() interface attempts to apply
4803** numeric affinity to the value.  This means that an attempt is
4804** made to convert the value to an integer or floating point.  If
4805** such a conversion is possible without loss of information (in other
4806** words, if the value is a string that looks like a number)
4807** then the conversion is performed.  Otherwise no conversion occurs.
4808** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4809**
4810** Please pay particular attention to the fact that the pointer returned
4811** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4812** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4813** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4814** or [sqlite3_value_text16()].
4815**
4816** These routines must be called from the same thread as
4817** the SQL function that supplied the [sqlite3_value*] parameters.
4818*/
4819SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value*);
4820SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value*);
4821SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value*);
4822SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value*);
4823SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value*);
4824SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value*);
4825SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value*);
4826SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value*);
4827SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value*);
4828SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value*);
4829SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value*);
4830SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value*);
4831
4832/*
4833** CAPI3REF: Finding The Subtype Of SQL Values
4834** METHOD: sqlite3_value
4835**
4836** The sqlite3_value_subtype(V) function returns the subtype for
4837** an [application-defined SQL function] argument V.  The subtype
4838** information can be used to pass a limited amount of context from
4839** one SQL function to another.  Use the [sqlite3_result_subtype()]
4840** routine to set the subtype for the return value of an SQL function.
4841**
4842** SQLite makes no use of subtype itself.  It merely passes the subtype
4843** from the result of one [application-defined SQL function] into the
4844** input of another.
4845*/
4846SQLITE_API unsigned int SQLITE_STDCALL sqlite3_value_subtype(sqlite3_value*);
4847
4848/*
4849** CAPI3REF: Copy And Free SQL Values
4850** METHOD: sqlite3_value
4851**
4852** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
4853** object D and returns a pointer to that copy.  ^The [sqlite3_value] returned
4854** is a [protected sqlite3_value] object even if the input is not.
4855** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
4856** memory allocation fails.
4857**
4858** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
4859** previously obtained from [sqlite3_value_dup()].  ^If V is a NULL pointer
4860** then sqlite3_value_free(V) is a harmless no-op.
4861*/
4862SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_value_dup(const sqlite3_value*);
4863SQLITE_API void SQLITE_STDCALL sqlite3_value_free(sqlite3_value*);
4864
4865/*
4866** CAPI3REF: Obtain Aggregate Function Context
4867** METHOD: sqlite3_context
4868**
4869** Implementations of aggregate SQL functions use this
4870** routine to allocate memory for storing their state.
4871**
4872** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4873** for a particular aggregate function, SQLite
4874** allocates N of memory, zeroes out that memory, and returns a pointer
4875** to the new memory. ^On second and subsequent calls to
4876** sqlite3_aggregate_context() for the same aggregate function instance,
4877** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4878** called once for each invocation of the xStep callback and then one
4879** last time when the xFinal callback is invoked.  ^(When no rows match
4880** an aggregate query, the xStep() callback of the aggregate function
4881** implementation is never called and xFinal() is called exactly once.
4882** In those cases, sqlite3_aggregate_context() might be called for the
4883** first time from within xFinal().)^
4884**
4885** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
4886** when first called if N is less than or equal to zero or if a memory
4887** allocate error occurs.
4888**
4889** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4890** determined by the N parameter on first successful call.  Changing the
4891** value of N in subsequent call to sqlite3_aggregate_context() within
4892** the same aggregate function instance will not resize the memory
4893** allocation.)^  Within the xFinal callback, it is customary to set
4894** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
4895** pointless memory allocations occur.
4896**
4897** ^SQLite automatically frees the memory allocated by
4898** sqlite3_aggregate_context() when the aggregate query concludes.
4899**
4900** The first parameter must be a copy of the
4901** [sqlite3_context | SQL function context] that is the first parameter
4902** to the xStep or xFinal callback routine that implements the aggregate
4903** function.
4904**
4905** This routine must be called from the same thread in which
4906** the aggregate SQL function is running.
4907*/
4908SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4909
4910/*
4911** CAPI3REF: User Data For Functions
4912** METHOD: sqlite3_context
4913**
4914** ^The sqlite3_user_data() interface returns a copy of
4915** the pointer that was the pUserData parameter (the 5th parameter)
4916** of the [sqlite3_create_function()]
4917** and [sqlite3_create_function16()] routines that originally
4918** registered the application defined function.
4919**
4920** This routine must be called from the same thread in which
4921** the application-defined function is running.
4922*/
4923SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context*);
4924
4925/*
4926** CAPI3REF: Database Connection For Functions
4927** METHOD: sqlite3_context
4928**
4929** ^The sqlite3_context_db_handle() interface returns a copy of
4930** the pointer to the [database connection] (the 1st parameter)
4931** of the [sqlite3_create_function()]
4932** and [sqlite3_create_function16()] routines that originally
4933** registered the application defined function.
4934*/
4935SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context*);
4936
4937/*
4938** CAPI3REF: Function Auxiliary Data
4939** METHOD: sqlite3_context
4940**
4941** These functions may be used by (non-aggregate) SQL functions to
4942** associate metadata with argument values. If the same value is passed to
4943** multiple invocations of the same SQL function during query execution, under
4944** some circumstances the associated metadata may be preserved.  An example
4945** of where this might be useful is in a regular-expression matching
4946** function. The compiled version of the regular expression can be stored as
4947** metadata associated with the pattern string.
4948** Then as long as the pattern string remains the same,
4949** the compiled regular expression can be reused on multiple
4950** invocations of the same function.
4951**
4952** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4953** associated by the sqlite3_set_auxdata() function with the Nth argument
4954** value to the application-defined function. ^If there is no metadata
4955** associated with the function argument, this sqlite3_get_auxdata() interface
4956** returns a NULL pointer.
4957**
4958** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
4959** argument of the application-defined function.  ^Subsequent
4960** calls to sqlite3_get_auxdata(C,N) return P from the most recent
4961** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
4962** NULL if the metadata has been discarded.
4963** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
4964** SQLite will invoke the destructor function X with parameter P exactly
4965** once, when the metadata is discarded.
4966** SQLite is free to discard the metadata at any time, including: <ul>
4967** <li> ^(when the corresponding function parameter changes)^, or
4968** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
4969**      SQL statement)^, or
4970** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
4971**       parameter)^, or
4972** <li> ^(during the original sqlite3_set_auxdata() call when a memory
4973**      allocation error occurs.)^ </ul>
4974**
4975** Note the last bullet in particular.  The destructor X in
4976** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
4977** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
4978** should be called near the end of the function implementation and the
4979** function implementation should not make any use of P after
4980** sqlite3_set_auxdata() has been called.
4981**
4982** ^(In practice, metadata is preserved between function calls for
4983** function parameters that are compile-time constants, including literal
4984** values and [parameters] and expressions composed from the same.)^
4985**
4986** These routines must be called from the same thread in which
4987** the SQL function is running.
4988*/
4989SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context*, int N);
4990SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4991
4992
4993/*
4994** CAPI3REF: Constants Defining Special Destructor Behavior
4995**
4996** These are special values for the destructor that is passed in as the
4997** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4998** argument is SQLITE_STATIC, it means that the content pointer is constant
4999** and will never change.  It does not need to be destroyed.  ^The
5000** SQLITE_TRANSIENT value means that the content will likely change in
5001** the near future and that SQLite should make its own private copy of
5002** the content before returning.
5003**
5004** The typedef is necessary to work around problems in certain
5005** C++ compilers.
5006*/
5007typedef void (*sqlite3_destructor_type)(void*);
5008#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
5009#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
5010
5011/*
5012** CAPI3REF: Setting The Result Of An SQL Function
5013** METHOD: sqlite3_context
5014**
5015** These routines are used by the xFunc or xFinal callbacks that
5016** implement SQL functions and aggregates.  See
5017** [sqlite3_create_function()] and [sqlite3_create_function16()]
5018** for additional information.
5019**
5020** These functions work very much like the [parameter binding] family of
5021** functions used to bind values to host parameters in prepared statements.
5022** Refer to the [SQL parameter] documentation for additional information.
5023**
5024** ^The sqlite3_result_blob() interface sets the result from
5025** an application-defined function to be the BLOB whose content is pointed
5026** to by the second parameter and which is N bytes long where N is the
5027** third parameter.
5028**
5029** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
5030** interfaces set the result of the application-defined function to be
5031** a BLOB containing all zero bytes and N bytes in size.
5032**
5033** ^The sqlite3_result_double() interface sets the result from
5034** an application-defined function to be a floating point value specified
5035** by its 2nd argument.
5036**
5037** ^The sqlite3_result_error() and sqlite3_result_error16() functions
5038** cause the implemented SQL function to throw an exception.
5039** ^SQLite uses the string pointed to by the
5040** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
5041** as the text of an error message.  ^SQLite interprets the error
5042** message string from sqlite3_result_error() as UTF-8. ^SQLite
5043** interprets the string from sqlite3_result_error16() as UTF-16 in native
5044** byte order.  ^If the third parameter to sqlite3_result_error()
5045** or sqlite3_result_error16() is negative then SQLite takes as the error
5046** message all text up through the first zero character.
5047** ^If the third parameter to sqlite3_result_error() or
5048** sqlite3_result_error16() is non-negative then SQLite takes that many
5049** bytes (not characters) from the 2nd parameter as the error message.
5050** ^The sqlite3_result_error() and sqlite3_result_error16()
5051** routines make a private copy of the error message text before
5052** they return.  Hence, the calling function can deallocate or
5053** modify the text after they return without harm.
5054** ^The sqlite3_result_error_code() function changes the error code
5055** returned by SQLite as a result of an error in a function.  ^By default,
5056** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
5057** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
5058**
5059** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
5060** error indicating that a string or BLOB is too long to represent.
5061**
5062** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
5063** error indicating that a memory allocation failed.
5064**
5065** ^The sqlite3_result_int() interface sets the return value
5066** of the application-defined function to be the 32-bit signed integer
5067** value given in the 2nd argument.
5068** ^The sqlite3_result_int64() interface sets the return value
5069** of the application-defined function to be the 64-bit signed integer
5070** value given in the 2nd argument.
5071**
5072** ^The sqlite3_result_null() interface sets the return value
5073** of the application-defined function to be NULL.
5074**
5075** ^The sqlite3_result_text(), sqlite3_result_text16(),
5076** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
5077** set the return value of the application-defined function to be
5078** a text string which is represented as UTF-8, UTF-16 native byte order,
5079** UTF-16 little endian, or UTF-16 big endian, respectively.
5080** ^The sqlite3_result_text64() interface sets the return value of an
5081** application-defined function to be a text string in an encoding
5082** specified by the fifth (and last) parameter, which must be one
5083** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
5084** ^SQLite takes the text result from the application from
5085** the 2nd parameter of the sqlite3_result_text* interfaces.
5086** ^If the 3rd parameter to the sqlite3_result_text* interfaces
5087** is negative, then SQLite takes result text from the 2nd parameter
5088** through the first zero character.
5089** ^If the 3rd parameter to the sqlite3_result_text* interfaces
5090** is non-negative, then as many bytes (not characters) of the text
5091** pointed to by the 2nd parameter are taken as the application-defined
5092** function result.  If the 3rd parameter is non-negative, then it
5093** must be the byte offset into the string where the NUL terminator would
5094** appear if the string where NUL terminated.  If any NUL characters occur
5095** in the string at a byte offset that is less than the value of the 3rd
5096** parameter, then the resulting string will contain embedded NULs and the
5097** result of expressions operating on strings with embedded NULs is undefined.
5098** ^If the 4th parameter to the sqlite3_result_text* interfaces
5099** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
5100** function as the destructor on the text or BLOB result when it has
5101** finished using that result.
5102** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
5103** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
5104** assumes that the text or BLOB result is in constant space and does not
5105** copy the content of the parameter nor call a destructor on the content
5106** when it has finished using that result.
5107** ^If the 4th parameter to the sqlite3_result_text* interfaces
5108** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
5109** then SQLite makes a copy of the result into space obtained from
5110** from [sqlite3_malloc()] before it returns.
5111**
5112** ^The sqlite3_result_value() interface sets the result of
5113** the application-defined function to be a copy of the
5114** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
5115** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
5116** so that the [sqlite3_value] specified in the parameter may change or
5117** be deallocated after sqlite3_result_value() returns without harm.
5118** ^A [protected sqlite3_value] object may always be used where an
5119** [unprotected sqlite3_value] object is required, so either
5120** kind of [sqlite3_value] object can be used with this interface.
5121**
5122** If these routines are called from within the different thread
5123** than the one containing the application-defined function that received
5124** the [sqlite3_context] pointer, the results are undefined.
5125*/
5126SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
5127SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(sqlite3_context*,const void*,
5128                           sqlite3_uint64,void(*)(void*));
5129SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context*, double);
5130SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context*, const char*, int);
5131SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context*, const void*, int);
5132SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context*);
5133SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context*);
5134SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context*, int);
5135SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context*, int);
5136SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
5137SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context*);
5138SQLITE_API void SQLITE_STDCALL sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
5139SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
5140                           void(*)(void*), unsigned char encoding);
5141SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
5142SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
5143SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
5144SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context*, sqlite3_value*);
5145SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context*, int n);
5146SQLITE_API int SQLITE_STDCALL sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
5147
5148
5149/*
5150** CAPI3REF: Setting The Subtype Of An SQL Function
5151** METHOD: sqlite3_context
5152**
5153** The sqlite3_result_subtype(C,T) function causes the subtype of
5154** the result from the [application-defined SQL function] with
5155** [sqlite3_context] C to be the value T.  Only the lower 8 bits
5156** of the subtype T are preserved in current versions of SQLite;
5157** higher order bits are discarded.
5158** The number of subtype bytes preserved by SQLite might increase
5159** in future releases of SQLite.
5160*/
5161SQLITE_API void SQLITE_STDCALL sqlite3_result_subtype(sqlite3_context*,unsigned int);
5162
5163/*
5164** CAPI3REF: Define New Collating Sequences
5165** METHOD: sqlite3
5166**
5167** ^These functions add, remove, or modify a [collation] associated
5168** with the [database connection] specified as the first argument.
5169**
5170** ^The name of the collation is a UTF-8 string
5171** for sqlite3_create_collation() and sqlite3_create_collation_v2()
5172** and a UTF-16 string in native byte order for sqlite3_create_collation16().
5173** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
5174** considered to be the same name.
5175**
5176** ^(The third argument (eTextRep) must be one of the constants:
5177** <ul>
5178** <li> [SQLITE_UTF8],
5179** <li> [SQLITE_UTF16LE],
5180** <li> [SQLITE_UTF16BE],
5181** <li> [SQLITE_UTF16], or
5182** <li> [SQLITE_UTF16_ALIGNED].
5183** </ul>)^
5184** ^The eTextRep argument determines the encoding of strings passed
5185** to the collating function callback, xCallback.
5186** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
5187** force strings to be UTF16 with native byte order.
5188** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
5189** on an even byte address.
5190**
5191** ^The fourth argument, pArg, is an application data pointer that is passed
5192** through as the first argument to the collating function callback.
5193**
5194** ^The fifth argument, xCallback, is a pointer to the collating function.
5195** ^Multiple collating functions can be registered using the same name but
5196** with different eTextRep parameters and SQLite will use whichever
5197** function requires the least amount of data transformation.
5198** ^If the xCallback argument is NULL then the collating function is
5199** deleted.  ^When all collating functions having the same name are deleted,
5200** that collation is no longer usable.
5201**
5202** ^The collating function callback is invoked with a copy of the pArg
5203** application data pointer and with two strings in the encoding specified
5204** by the eTextRep argument.  The collating function must return an
5205** integer that is negative, zero, or positive
5206** if the first string is less than, equal to, or greater than the second,
5207** respectively.  A collating function must always return the same answer
5208** given the same inputs.  If two or more collating functions are registered
5209** to the same collation name (using different eTextRep values) then all
5210** must give an equivalent answer when invoked with equivalent strings.
5211** The collating function must obey the following properties for all
5212** strings A, B, and C:
5213**
5214** <ol>
5215** <li> If A==B then B==A.
5216** <li> If A==B and B==C then A==C.
5217** <li> If A&lt;B THEN B&gt;A.
5218** <li> If A&lt;B and B&lt;C then A&lt;C.
5219** </ol>
5220**
5221** If a collating function fails any of the above constraints and that
5222** collating function is  registered and used, then the behavior of SQLite
5223** is undefined.
5224**
5225** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
5226** with the addition that the xDestroy callback is invoked on pArg when
5227** the collating function is deleted.
5228** ^Collating functions are deleted when they are overridden by later
5229** calls to the collation creation functions or when the
5230** [database connection] is closed using [sqlite3_close()].
5231**
5232** ^The xDestroy callback is <u>not</u> called if the
5233** sqlite3_create_collation_v2() function fails.  Applications that invoke
5234** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
5235** check the return code and dispose of the application data pointer
5236** themselves rather than expecting SQLite to deal with it for them.
5237** This is different from every other SQLite interface.  The inconsistency
5238** is unfortunate but cannot be changed without breaking backwards
5239** compatibility.
5240**
5241** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
5242*/
5243SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
5244  sqlite3*,
5245  const char *zName,
5246  int eTextRep,
5247  void *pArg,
5248  int(*xCompare)(void*,int,const void*,int,const void*)
5249);
5250SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
5251  sqlite3*,
5252  const char *zName,
5253  int eTextRep,
5254  void *pArg,
5255  int(*xCompare)(void*,int,const void*,int,const void*),
5256  void(*xDestroy)(void*)
5257);
5258SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
5259  sqlite3*,
5260  const void *zName,
5261  int eTextRep,
5262  void *pArg,
5263  int(*xCompare)(void*,int,const void*,int,const void*)
5264);
5265
5266/*
5267** CAPI3REF: Collation Needed Callbacks
5268** METHOD: sqlite3
5269**
5270** ^To avoid having to register all collation sequences before a database
5271** can be used, a single callback function may be registered with the
5272** [database connection] to be invoked whenever an undefined collation
5273** sequence is required.
5274**
5275** ^If the function is registered using the sqlite3_collation_needed() API,
5276** then it is passed the names of undefined collation sequences as strings
5277** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
5278** the names are passed as UTF-16 in machine native byte order.
5279** ^A call to either function replaces the existing collation-needed callback.
5280**
5281** ^(When the callback is invoked, the first argument passed is a copy
5282** of the second argument to sqlite3_collation_needed() or
5283** sqlite3_collation_needed16().  The second argument is the database
5284** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5285** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5286** sequence function required.  The fourth parameter is the name of the
5287** required collation sequence.)^
5288**
5289** The callback function should register the desired collation using
5290** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5291** [sqlite3_create_collation_v2()].
5292*/
5293SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
5294  sqlite3*,
5295  void*,
5296  void(*)(void*,sqlite3*,int eTextRep,const char*)
5297);
5298SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
5299  sqlite3*,
5300  void*,
5301  void(*)(void*,sqlite3*,int eTextRep,const void*)
5302);
5303
5304#ifdef SQLITE_HAS_CODEC
5305/*
5306** Specify the key for an encrypted database.  This routine should be
5307** called right after sqlite3_open().
5308**
5309** The code to implement this API is not available in the public release
5310** of SQLite.
5311*/
5312SQLITE_API int SQLITE_STDCALL sqlite3_key(
5313  sqlite3 *db,                   /* Database to be rekeyed */
5314  const void *pKey, int nKey     /* The key */
5315);
5316SQLITE_API int SQLITE_STDCALL sqlite3_key_v2(
5317  sqlite3 *db,                   /* Database to be rekeyed */
5318  const char *zDbName,           /* Name of the database */
5319  const void *pKey, int nKey     /* The key */
5320);
5321
5322/*
5323** Change the key on an open database.  If the current database is not
5324** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
5325** database is decrypted.
5326**
5327** The code to implement this API is not available in the public release
5328** of SQLite.
5329*/
5330SQLITE_API int SQLITE_STDCALL sqlite3_rekey(
5331  sqlite3 *db,                   /* Database to be rekeyed */
5332  const void *pKey, int nKey     /* The new key */
5333);
5334SQLITE_API int SQLITE_STDCALL sqlite3_rekey_v2(
5335  sqlite3 *db,                   /* Database to be rekeyed */
5336  const char *zDbName,           /* Name of the database */
5337  const void *pKey, int nKey     /* The new key */
5338);
5339
5340/*
5341** Specify the activation key for a SEE database.  Unless
5342** activated, none of the SEE routines will work.
5343*/
5344SQLITE_API void SQLITE_STDCALL sqlite3_activate_see(
5345  const char *zPassPhrase        /* Activation phrase */
5346);
5347#endif
5348
5349#ifdef SQLITE_ENABLE_CEROD
5350/*
5351** Specify the activation key for a CEROD database.  Unless
5352** activated, none of the CEROD routines will work.
5353*/
5354SQLITE_API void SQLITE_STDCALL sqlite3_activate_cerod(
5355  const char *zPassPhrase        /* Activation phrase */
5356);
5357#endif
5358
5359/*
5360** CAPI3REF: Suspend Execution For A Short Time
5361**
5362** The sqlite3_sleep() function causes the current thread to suspend execution
5363** for at least a number of milliseconds specified in its parameter.
5364**
5365** If the operating system does not support sleep requests with
5366** millisecond time resolution, then the time will be rounded up to
5367** the nearest second. The number of milliseconds of sleep actually
5368** requested from the operating system is returned.
5369**
5370** ^SQLite implements this interface by calling the xSleep()
5371** method of the default [sqlite3_vfs] object.  If the xSleep() method
5372** of the default VFS is not implemented correctly, or not implemented at
5373** all, then the behavior of sqlite3_sleep() may deviate from the description
5374** in the previous paragraphs.
5375*/
5376SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int);
5377
5378/*
5379** CAPI3REF: Name Of The Folder Holding Temporary Files
5380**
5381** ^(If this global variable is made to point to a string which is
5382** the name of a folder (a.k.a. directory), then all temporary files
5383** created by SQLite when using a built-in [sqlite3_vfs | VFS]
5384** will be placed in that directory.)^  ^If this variable
5385** is a NULL pointer, then SQLite performs a search for an appropriate
5386** temporary file directory.
5387**
5388** Applications are strongly discouraged from using this global variable.
5389** It is required to set a temporary folder on Windows Runtime (WinRT).
5390** But for all other platforms, it is highly recommended that applications
5391** neither read nor write this variable.  This global variable is a relic
5392** that exists for backwards compatibility of legacy applications and should
5393** be avoided in new projects.
5394**
5395** It is not safe to read or modify this variable in more than one
5396** thread at a time.  It is not safe to read or modify this variable
5397** if a [database connection] is being used at the same time in a separate
5398** thread.
5399** It is intended that this variable be set once
5400** as part of process initialization and before any SQLite interface
5401** routines have been called and that this variable remain unchanged
5402** thereafter.
5403**
5404** ^The [temp_store_directory pragma] may modify this variable and cause
5405** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5406** the [temp_store_directory pragma] always assumes that any string
5407** that this variable points to is held in memory obtained from
5408** [sqlite3_malloc] and the pragma may attempt to free that memory
5409** using [sqlite3_free].
5410** Hence, if this variable is modified directly, either it should be
5411** made NULL or made to point to memory obtained from [sqlite3_malloc]
5412** or else the use of the [temp_store_directory pragma] should be avoided.
5413** Except when requested by the [temp_store_directory pragma], SQLite
5414** does not free the memory that sqlite3_temp_directory points to.  If
5415** the application wants that memory to be freed, it must do
5416** so itself, taking care to only do so after all [database connection]
5417** objects have been destroyed.
5418**
5419** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
5420** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
5421** features that require the use of temporary files may fail.  Here is an
5422** example of how to do this using C++ with the Windows Runtime:
5423**
5424** <blockquote><pre>
5425** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
5426** &nbsp;     TemporaryFolder->Path->Data();
5427** char zPathBuf&#91;MAX_PATH + 1&#93;;
5428** memset(zPathBuf, 0, sizeof(zPathBuf));
5429** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
5430** &nbsp;     NULL, NULL);
5431** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
5432** </pre></blockquote>
5433*/
5434SQLITE_API char *sqlite3_temp_directory;
5435
5436/*
5437** CAPI3REF: Name Of The Folder Holding Database Files
5438**
5439** ^(If this global variable is made to point to a string which is
5440** the name of a folder (a.k.a. directory), then all database files
5441** specified with a relative pathname and created or accessed by
5442** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5443** to be relative to that directory.)^ ^If this variable is a NULL
5444** pointer, then SQLite assumes that all database files specified
5445** with a relative pathname are relative to the current directory
5446** for the process.  Only the windows VFS makes use of this global
5447** variable; it is ignored by the unix VFS.
5448**
5449** Changing the value of this variable while a database connection is
5450** open can result in a corrupt database.
5451**
5452** It is not safe to read or modify this variable in more than one
5453** thread at a time.  It is not safe to read or modify this variable
5454** if a [database connection] is being used at the same time in a separate
5455** thread.
5456** It is intended that this variable be set once
5457** as part of process initialization and before any SQLite interface
5458** routines have been called and that this variable remain unchanged
5459** thereafter.
5460**
5461** ^The [data_store_directory pragma] may modify this variable and cause
5462** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5463** the [data_store_directory pragma] always assumes that any string
5464** that this variable points to is held in memory obtained from
5465** [sqlite3_malloc] and the pragma may attempt to free that memory
5466** using [sqlite3_free].
5467** Hence, if this variable is modified directly, either it should be
5468** made NULL or made to point to memory obtained from [sqlite3_malloc]
5469** or else the use of the [data_store_directory pragma] should be avoided.
5470*/
5471SQLITE_API char *sqlite3_data_directory;
5472
5473/*
5474** CAPI3REF: Test For Auto-Commit Mode
5475** KEYWORDS: {autocommit mode}
5476** METHOD: sqlite3
5477**
5478** ^The sqlite3_get_autocommit() interface returns non-zero or
5479** zero if the given database connection is or is not in autocommit mode,
5480** respectively.  ^Autocommit mode is on by default.
5481** ^Autocommit mode is disabled by a [BEGIN] statement.
5482** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5483**
5484** If certain kinds of errors occur on a statement within a multi-statement
5485** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5486** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5487** transaction might be rolled back automatically.  The only way to
5488** find out whether SQLite automatically rolled back the transaction after
5489** an error is to use this function.
5490**
5491** If another thread changes the autocommit status of the database
5492** connection while this routine is running, then the return value
5493** is undefined.
5494*/
5495SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3*);
5496
5497/*
5498** CAPI3REF: Find The Database Handle Of A Prepared Statement
5499** METHOD: sqlite3_stmt
5500**
5501** ^The sqlite3_db_handle interface returns the [database connection] handle
5502** to which a [prepared statement] belongs.  ^The [database connection]
5503** returned by sqlite3_db_handle is the same [database connection]
5504** that was the first argument
5505** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5506** create the statement in the first place.
5507*/
5508SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt*);
5509
5510/*
5511** CAPI3REF: Return The Filename For A Database Connection
5512** METHOD: sqlite3
5513**
5514** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5515** associated with database N of connection D.  ^The main database file
5516** has the name "main".  If there is no attached database N on the database
5517** connection D, or if database N is a temporary or in-memory database, then
5518** a NULL pointer is returned.
5519**
5520** ^The filename returned by this function is the output of the
5521** xFullPathname method of the [VFS].  ^In other words, the filename
5522** will be an absolute pathname, even if the filename used
5523** to open the database originally was a URI or relative pathname.
5524*/
5525SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5526
5527/*
5528** CAPI3REF: Determine if a database is read-only
5529** METHOD: sqlite3
5530**
5531** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5532** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5533** the name of a database on connection D.
5534*/
5535SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5536
5537/*
5538** CAPI3REF: Find the next prepared statement
5539** METHOD: sqlite3
5540**
5541** ^This interface returns a pointer to the next [prepared statement] after
5542** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
5543** then this interface returns a pointer to the first prepared statement
5544** associated with the database connection pDb.  ^If no prepared statement
5545** satisfies the conditions of this routine, it returns NULL.
5546**
5547** The [database connection] pointer D in a call to
5548** [sqlite3_next_stmt(D,S)] must refer to an open database
5549** connection and in particular must not be a NULL pointer.
5550*/
5551SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5552
5553/*
5554** CAPI3REF: Commit And Rollback Notification Callbacks
5555** METHOD: sqlite3
5556**
5557** ^The sqlite3_commit_hook() interface registers a callback
5558** function to be invoked whenever a transaction is [COMMIT | committed].
5559** ^Any callback set by a previous call to sqlite3_commit_hook()
5560** for the same database connection is overridden.
5561** ^The sqlite3_rollback_hook() interface registers a callback
5562** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5563** ^Any callback set by a previous call to sqlite3_rollback_hook()
5564** for the same database connection is overridden.
5565** ^The pArg argument is passed through to the callback.
5566** ^If the callback on a commit hook function returns non-zero,
5567** then the commit is converted into a rollback.
5568**
5569** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5570** return the P argument from the previous call of the same function
5571** on the same [database connection] D, or NULL for
5572** the first call for each function on D.
5573**
5574** The commit and rollback hook callbacks are not reentrant.
5575** The callback implementation must not do anything that will modify
5576** the database connection that invoked the callback.  Any actions
5577** to modify the database connection must be deferred until after the
5578** completion of the [sqlite3_step()] call that triggered the commit
5579** or rollback hook in the first place.
5580** Note that running any other SQL statements, including SELECT statements,
5581** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5582** the database connections for the meaning of "modify" in this paragraph.
5583**
5584** ^Registering a NULL function disables the callback.
5585**
5586** ^When the commit hook callback routine returns zero, the [COMMIT]
5587** operation is allowed to continue normally.  ^If the commit hook
5588** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5589** ^The rollback hook is invoked on a rollback that results from a commit
5590** hook returning non-zero, just as it would be with any other rollback.
5591**
5592** ^For the purposes of this API, a transaction is said to have been
5593** rolled back if an explicit "ROLLBACK" statement is executed, or
5594** an error or constraint causes an implicit rollback to occur.
5595** ^The rollback callback is not invoked if a transaction is
5596** automatically rolled back because the database connection is closed.
5597**
5598** See also the [sqlite3_update_hook()] interface.
5599*/
5600SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5601SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5602
5603/*
5604** CAPI3REF: Data Change Notification Callbacks
5605** METHOD: sqlite3
5606**
5607** ^The sqlite3_update_hook() interface registers a callback function
5608** with the [database connection] identified by the first argument
5609** to be invoked whenever a row is updated, inserted or deleted in
5610** a [rowid table].
5611** ^Any callback set by a previous call to this function
5612** for the same database connection is overridden.
5613**
5614** ^The second argument is a pointer to the function to invoke when a
5615** row is updated, inserted or deleted in a rowid table.
5616** ^The first argument to the callback is a copy of the third argument
5617** to sqlite3_update_hook().
5618** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5619** or [SQLITE_UPDATE], depending on the operation that caused the callback
5620** to be invoked.
5621** ^The third and fourth arguments to the callback contain pointers to the
5622** database and table name containing the affected row.
5623** ^The final callback parameter is the [rowid] of the row.
5624** ^In the case of an update, this is the [rowid] after the update takes place.
5625**
5626** ^(The update hook is not invoked when internal system tables are
5627** modified (i.e. sqlite_master and sqlite_sequence).)^
5628** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
5629**
5630** ^In the current implementation, the update hook
5631** is not invoked when duplication rows are deleted because of an
5632** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5633** invoked when rows are deleted using the [truncate optimization].
5634** The exceptions defined in this paragraph might change in a future
5635** release of SQLite.
5636**
5637** The update hook implementation must not do anything that will modify
5638** the database connection that invoked the update hook.  Any actions
5639** to modify the database connection must be deferred until after the
5640** completion of the [sqlite3_step()] call that triggered the update hook.
5641** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5642** database connections for the meaning of "modify" in this paragraph.
5643**
5644** ^The sqlite3_update_hook(D,C,P) function
5645** returns the P argument from the previous call
5646** on the same [database connection] D, or NULL for
5647** the first call on D.
5648**
5649** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
5650** and [sqlite3_preupdate_hook()] interfaces.
5651*/
5652SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
5653  sqlite3*,
5654  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5655  void*
5656);
5657
5658/*
5659** CAPI3REF: Enable Or Disable Shared Pager Cache
5660**
5661** ^(This routine enables or disables the sharing of the database cache
5662** and schema data structures between [database connection | connections]
5663** to the same database. Sharing is enabled if the argument is true
5664** and disabled if the argument is false.)^
5665**
5666** ^Cache sharing is enabled and disabled for an entire process.
5667** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5668** sharing was enabled or disabled for each thread separately.
5669**
5670** ^(The cache sharing mode set by this interface effects all subsequent
5671** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5672** Existing database connections continue use the sharing mode
5673** that was in effect at the time they were opened.)^
5674**
5675** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5676** successfully.  An [error code] is returned otherwise.)^
5677**
5678** ^Shared cache is disabled by default. But this might change in
5679** future releases of SQLite.  Applications that care about shared
5680** cache setting should set it explicitly.
5681**
5682** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
5683** and will always return SQLITE_MISUSE. On those systems,
5684** shared cache mode should be enabled per-database connection via
5685** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
5686**
5687** This interface is threadsafe on processors where writing a
5688** 32-bit integer is atomic.
5689**
5690** See Also:  [SQLite Shared-Cache Mode]
5691*/
5692SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int);
5693
5694/*
5695** CAPI3REF: Attempt To Free Heap Memory
5696**
5697** ^The sqlite3_release_memory() interface attempts to free N bytes
5698** of heap memory by deallocating non-essential memory allocations
5699** held by the database library.   Memory used to cache database
5700** pages to improve performance is an example of non-essential memory.
5701** ^sqlite3_release_memory() returns the number of bytes actually freed,
5702** which might be more or less than the amount requested.
5703** ^The sqlite3_release_memory() routine is a no-op returning zero
5704** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5705**
5706** See also: [sqlite3_db_release_memory()]
5707*/
5708SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int);
5709
5710/*
5711** CAPI3REF: Free Memory Used By A Database Connection
5712** METHOD: sqlite3
5713**
5714** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5715** memory as possible from database connection D. Unlike the
5716** [sqlite3_release_memory()] interface, this interface is in effect even
5717** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5718** omitted.
5719**
5720** See also: [sqlite3_release_memory()]
5721*/
5722SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3*);
5723
5724/*
5725** CAPI3REF: Impose A Limit On Heap Size
5726**
5727** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5728** soft limit on the amount of heap memory that may be allocated by SQLite.
5729** ^SQLite strives to keep heap memory utilization below the soft heap
5730** limit by reducing the number of pages held in the page cache
5731** as heap memory usages approaches the limit.
5732** ^The soft heap limit is "soft" because even though SQLite strives to stay
5733** below the limit, it will exceed the limit rather than generate
5734** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
5735** is advisory only.
5736**
5737** ^The return value from sqlite3_soft_heap_limit64() is the size of
5738** the soft heap limit prior to the call, or negative in the case of an
5739** error.  ^If the argument N is negative
5740** then no change is made to the soft heap limit.  Hence, the current
5741** size of the soft heap limit can be determined by invoking
5742** sqlite3_soft_heap_limit64() with a negative argument.
5743**
5744** ^If the argument N is zero then the soft heap limit is disabled.
5745**
5746** ^(The soft heap limit is not enforced in the current implementation
5747** if one or more of following conditions are true:
5748**
5749** <ul>
5750** <li> The soft heap limit is set to zero.
5751** <li> Memory accounting is disabled using a combination of the
5752**      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5753**      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5754** <li> An alternative page cache implementation is specified using
5755**      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5756** <li> The page cache allocates from its own memory pool supplied
5757**      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5758**      from the heap.
5759** </ul>)^
5760**
5761** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5762** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5763** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5764** the soft heap limit is enforced on every memory allocation.  Without
5765** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5766** when memory is allocated by the page cache.  Testing suggests that because
5767** the page cache is the predominate memory user in SQLite, most
5768** applications will achieve adequate soft heap limit enforcement without
5769** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5770**
5771** The circumstances under which SQLite will enforce the soft heap limit may
5772** changes in future releases of SQLite.
5773*/
5774SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 N);
5775
5776/*
5777** CAPI3REF: Deprecated Soft Heap Limit Interface
5778** DEPRECATED
5779**
5780** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5781** interface.  This routine is provided for historical compatibility
5782** only.  All new applications should use the
5783** [sqlite3_soft_heap_limit64()] interface rather than this one.
5784*/
5785SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_soft_heap_limit(int N);
5786
5787
5788/*
5789** CAPI3REF: Extract Metadata About A Column Of A Table
5790** METHOD: sqlite3
5791**
5792** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
5793** information about column C of table T in database D
5794** on [database connection] X.)^  ^The sqlite3_table_column_metadata()
5795** interface returns SQLITE_OK and fills in the non-NULL pointers in
5796** the final five arguments with appropriate values if the specified
5797** column exists.  ^The sqlite3_table_column_metadata() interface returns
5798** SQLITE_ERROR and if the specified column does not exist.
5799** ^If the column-name parameter to sqlite3_table_column_metadata() is a
5800** NULL pointer, then this routine simply checks for the existence of the
5801** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
5802** does not.
5803**
5804** ^The column is identified by the second, third and fourth parameters to
5805** this function. ^(The second parameter is either the name of the database
5806** (i.e. "main", "temp", or an attached database) containing the specified
5807** table or NULL.)^ ^If it is NULL, then all attached databases are searched
5808** for the table using the same algorithm used by the database engine to
5809** resolve unqualified table references.
5810**
5811** ^The third and fourth parameters to this function are the table and column
5812** name of the desired column, respectively.
5813**
5814** ^Metadata is returned by writing to the memory locations passed as the 5th
5815** and subsequent parameters to this function. ^Any of these arguments may be
5816** NULL, in which case the corresponding element of metadata is omitted.
5817**
5818** ^(<blockquote>
5819** <table border="1">
5820** <tr><th> Parameter <th> Output<br>Type <th>  Description
5821**
5822** <tr><td> 5th <td> const char* <td> Data type
5823** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5824** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5825** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5826** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5827** </table>
5828** </blockquote>)^
5829**
5830** ^The memory pointed to by the character pointers returned for the
5831** declaration type and collation sequence is valid until the next
5832** call to any SQLite API function.
5833**
5834** ^If the specified table is actually a view, an [error code] is returned.
5835**
5836** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
5837** is not a [WITHOUT ROWID] table and an
5838** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5839** parameters are set for the explicitly declared column. ^(If there is no
5840** [INTEGER PRIMARY KEY] column, then the outputs
5841** for the [rowid] are set as follows:
5842**
5843** <pre>
5844**     data type: "INTEGER"
5845**     collation sequence: "BINARY"
5846**     not null: 0
5847**     primary key: 1
5848**     auto increment: 0
5849** </pre>)^
5850**
5851** ^This function causes all database schemas to be read from disk and
5852** parsed, if that has not already been done, and returns an error if
5853** any errors are encountered while loading the schema.
5854*/
5855SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
5856  sqlite3 *db,                /* Connection handle */
5857  const char *zDbName,        /* Database name or NULL */
5858  const char *zTableName,     /* Table name */
5859  const char *zColumnName,    /* Column name */
5860  char const **pzDataType,    /* OUTPUT: Declared data type */
5861  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5862  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5863  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5864  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5865);
5866
5867/*
5868** CAPI3REF: Load An Extension
5869** METHOD: sqlite3
5870**
5871** ^This interface loads an SQLite extension library from the named file.
5872**
5873** ^The sqlite3_load_extension() interface attempts to load an
5874** [SQLite extension] library contained in the file zFile.  If
5875** the file cannot be loaded directly, attempts are made to load
5876** with various operating-system specific extensions added.
5877** So for example, if "samplelib" cannot be loaded, then names like
5878** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
5879** be tried also.
5880**
5881** ^The entry point is zProc.
5882** ^(zProc may be 0, in which case SQLite will try to come up with an
5883** entry point name on its own.  It first tries "sqlite3_extension_init".
5884** If that does not work, it constructs a name "sqlite3_X_init" where the
5885** X is consists of the lower-case equivalent of all ASCII alphabetic
5886** characters in the filename from the last "/" to the first following
5887** "." and omitting any initial "lib".)^
5888** ^The sqlite3_load_extension() interface returns
5889** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5890** ^If an error occurs and pzErrMsg is not 0, then the
5891** [sqlite3_load_extension()] interface shall attempt to
5892** fill *pzErrMsg with error message text stored in memory
5893** obtained from [sqlite3_malloc()]. The calling function
5894** should free this memory by calling [sqlite3_free()].
5895**
5896** ^Extension loading must be enabled using
5897** [sqlite3_enable_load_extension()] or
5898** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
5899** prior to calling this API,
5900** otherwise an error will be returned.
5901**
5902** <b>Security warning:</b> It is recommended that the
5903** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
5904** interface.  The use of the [sqlite3_enable_load_extension()] interface
5905** should be avoided.  This will keep the SQL function [load_extension()]
5906** disabled and prevent SQL injections from giving attackers
5907** access to extension loading capabilities.
5908**
5909** See also the [load_extension() SQL function].
5910*/
5911SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
5912  sqlite3 *db,          /* Load the extension into this database connection */
5913  const char *zFile,    /* Name of the shared library containing extension */
5914  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5915  char **pzErrMsg       /* Put error message here if not 0 */
5916);
5917
5918/*
5919** CAPI3REF: Enable Or Disable Extension Loading
5920** METHOD: sqlite3
5921**
5922** ^So as not to open security holes in older applications that are
5923** unprepared to deal with [extension loading], and as a means of disabling
5924** [extension loading] while evaluating user-entered SQL, the following API
5925** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5926**
5927** ^Extension loading is off by default.
5928** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5929** to turn extension loading on and call it with onoff==0 to turn
5930** it back off again.
5931**
5932** ^This interface enables or disables both the C-API
5933** [sqlite3_load_extension()] and the SQL function [load_extension()].
5934** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
5935** to enable or disable only the C-API.)^
5936**
5937** <b>Security warning:</b> It is recommended that extension loading
5938** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
5939** rather than this interface, so the [load_extension()] SQL function
5940** remains disabled. This will prevent SQL injections from giving attackers
5941** access to extension loading capabilities.
5942*/
5943SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5944
5945/*
5946** CAPI3REF: Automatically Load Statically Linked Extensions
5947**
5948** ^This interface causes the xEntryPoint() function to be invoked for
5949** each new [database connection] that is created.  The idea here is that
5950** xEntryPoint() is the entry point for a statically linked [SQLite extension]
5951** that is to be automatically loaded into all new database connections.
5952**
5953** ^(Even though the function prototype shows that xEntryPoint() takes
5954** no arguments and returns void, SQLite invokes xEntryPoint() with three
5955** arguments and expects an integer result as if the signature of the
5956** entry point where as follows:
5957**
5958** <blockquote><pre>
5959** &nbsp;  int xEntryPoint(
5960** &nbsp;    sqlite3 *db,
5961** &nbsp;    const char **pzErrMsg,
5962** &nbsp;    const struct sqlite3_api_routines *pThunk
5963** &nbsp;  );
5964** </pre></blockquote>)^
5965**
5966** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5967** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5968** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5969** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5970** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5971** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5972** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5973**
5974** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5975** on the list of automatic extensions is a harmless no-op. ^No entry point
5976** will be called more than once for each database connection that is opened.
5977**
5978** See also: [sqlite3_reset_auto_extension()]
5979** and [sqlite3_cancel_auto_extension()]
5980*/
5981SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void(*xEntryPoint)(void));
5982
5983/*
5984** CAPI3REF: Cancel Automatic Extension Loading
5985**
5986** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
5987** initialization routine X that was registered using a prior call to
5988** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
5989** routine returns 1 if initialization routine X was successfully
5990** unregistered and it returns 0 if X was not on the list of initialization
5991** routines.
5992*/
5993SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
5994
5995/*
5996** CAPI3REF: Reset Automatic Extension Loading
5997**
5998** ^This interface disables all automatic extensions previously
5999** registered using [sqlite3_auto_extension()].
6000*/
6001SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void);
6002
6003/*
6004** The interface to the virtual-table mechanism is currently considered
6005** to be experimental.  The interface might change in incompatible ways.
6006** If this is a problem for you, do not use the interface at this time.
6007**
6008** When the virtual-table mechanism stabilizes, we will declare the
6009** interface fixed, support it indefinitely, and remove this comment.
6010*/
6011
6012/*
6013** Structures used by the virtual table interface
6014*/
6015typedef struct sqlite3_vtab sqlite3_vtab;
6016typedef struct sqlite3_index_info sqlite3_index_info;
6017typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
6018typedef struct sqlite3_module sqlite3_module;
6019
6020/*
6021** CAPI3REF: Virtual Table Object
6022** KEYWORDS: sqlite3_module {virtual table module}
6023**
6024** This structure, sometimes called a "virtual table module",
6025** defines the implementation of a [virtual tables].
6026** This structure consists mostly of methods for the module.
6027**
6028** ^A virtual table module is created by filling in a persistent
6029** instance of this structure and passing a pointer to that instance
6030** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
6031** ^The registration remains valid until it is replaced by a different
6032** module or until the [database connection] closes.  The content
6033** of this structure must not change while it is registered with
6034** any database connection.
6035*/
6036struct sqlite3_module {
6037  int iVersion;
6038  int (*xCreate)(sqlite3*, void *pAux,
6039               int argc, const char *const*argv,
6040               sqlite3_vtab **ppVTab, char**);
6041  int (*xConnect)(sqlite3*, void *pAux,
6042               int argc, const char *const*argv,
6043               sqlite3_vtab **ppVTab, char**);
6044  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
6045  int (*xDisconnect)(sqlite3_vtab *pVTab);
6046  int (*xDestroy)(sqlite3_vtab *pVTab);
6047  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
6048  int (*xClose)(sqlite3_vtab_cursor*);
6049  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
6050                int argc, sqlite3_value **argv);
6051  int (*xNext)(sqlite3_vtab_cursor*);
6052  int (*xEof)(sqlite3_vtab_cursor*);
6053  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
6054  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
6055  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
6056  int (*xBegin)(sqlite3_vtab *pVTab);
6057  int (*xSync)(sqlite3_vtab *pVTab);
6058  int (*xCommit)(sqlite3_vtab *pVTab);
6059  int (*xRollback)(sqlite3_vtab *pVTab);
6060  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
6061                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
6062                       void **ppArg);
6063  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
6064  /* The methods above are in version 1 of the sqlite_module object. Those
6065  ** below are for version 2 and greater. */
6066  int (*xSavepoint)(sqlite3_vtab *pVTab, int);
6067  int (*xRelease)(sqlite3_vtab *pVTab, int);
6068  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
6069};
6070
6071/*
6072** CAPI3REF: Virtual Table Indexing Information
6073** KEYWORDS: sqlite3_index_info
6074**
6075** The sqlite3_index_info structure and its substructures is used as part
6076** of the [virtual table] interface to
6077** pass information into and receive the reply from the [xBestIndex]
6078** method of a [virtual table module].  The fields under **Inputs** are the
6079** inputs to xBestIndex and are read-only.  xBestIndex inserts its
6080** results into the **Outputs** fields.
6081**
6082** ^(The aConstraint[] array records WHERE clause constraints of the form:
6083**
6084** <blockquote>column OP expr</blockquote>
6085**
6086** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
6087** stored in aConstraint[].op using one of the
6088** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
6089** ^(The index of the column is stored in
6090** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
6091** expr on the right-hand side can be evaluated (and thus the constraint
6092** is usable) and false if it cannot.)^
6093**
6094** ^The optimizer automatically inverts terms of the form "expr OP column"
6095** and makes other simplifications to the WHERE clause in an attempt to
6096** get as many WHERE clause terms into the form shown above as possible.
6097** ^The aConstraint[] array only reports WHERE clause terms that are
6098** relevant to the particular virtual table being queried.
6099**
6100** ^Information about the ORDER BY clause is stored in aOrderBy[].
6101** ^Each term of aOrderBy records a column of the ORDER BY clause.
6102**
6103** The colUsed field indicates which columns of the virtual table may be
6104** required by the current scan. Virtual table columns are numbered from
6105** zero in the order in which they appear within the CREATE TABLE statement
6106** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
6107** the corresponding bit is set within the colUsed mask if the column may be
6108** required by SQLite. If the table has at least 64 columns and any column
6109** to the right of the first 63 is required, then bit 63 of colUsed is also
6110** set. In other words, column iCol may be required if the expression
6111** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
6112** non-zero.
6113**
6114** The [xBestIndex] method must fill aConstraintUsage[] with information
6115** about what parameters to pass to xFilter.  ^If argvIndex>0 then
6116** the right-hand side of the corresponding aConstraint[] is evaluated
6117** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
6118** is true, then the constraint is assumed to be fully handled by the
6119** virtual table and is not checked again by SQLite.)^
6120**
6121** ^The idxNum and idxPtr values are recorded and passed into the
6122** [xFilter] method.
6123** ^[sqlite3_free()] is used to free idxPtr if and only if
6124** needToFreeIdxPtr is true.
6125**
6126** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
6127** the correct order to satisfy the ORDER BY clause so that no separate
6128** sorting step is required.
6129**
6130** ^The estimatedCost value is an estimate of the cost of a particular
6131** strategy. A cost of N indicates that the cost of the strategy is similar
6132** to a linear scan of an SQLite table with N rows. A cost of log(N)
6133** indicates that the expense of the operation is similar to that of a
6134** binary search on a unique indexed field of an SQLite table with N rows.
6135**
6136** ^The estimatedRows value is an estimate of the number of rows that
6137** will be returned by the strategy.
6138**
6139** The xBestIndex method may optionally populate the idxFlags field with a
6140** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
6141** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
6142** assumes that the strategy may visit at most one row.
6143**
6144** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
6145** SQLite also assumes that if a call to the xUpdate() method is made as
6146** part of the same statement to delete or update a virtual table row and the
6147** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
6148** any database changes. In other words, if the xUpdate() returns
6149** SQLITE_CONSTRAINT, the database contents must be exactly as they were
6150** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
6151** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
6152** the xUpdate method are automatically rolled back by SQLite.
6153**
6154** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
6155** structure for SQLite version 3.8.2. If a virtual table extension is
6156** used with an SQLite version earlier than 3.8.2, the results of attempting
6157** to read or write the estimatedRows field are undefined (but are likely
6158** to included crashing the application). The estimatedRows field should
6159** therefore only be used if [sqlite3_libversion_number()] returns a
6160** value greater than or equal to 3008002. Similarly, the idxFlags field
6161** was added for version 3.9.0. It may therefore only be used if
6162** sqlite3_libversion_number() returns a value greater than or equal to
6163** 3009000.
6164*/
6165struct sqlite3_index_info {
6166  /* Inputs */
6167  int nConstraint;           /* Number of entries in aConstraint */
6168  struct sqlite3_index_constraint {
6169     int iColumn;              /* Column constrained.  -1 for ROWID */
6170     unsigned char op;         /* Constraint operator */
6171     unsigned char usable;     /* True if this constraint is usable */
6172     int iTermOffset;          /* Used internally - xBestIndex should ignore */
6173  } *aConstraint;            /* Table of WHERE clause constraints */
6174  int nOrderBy;              /* Number of terms in the ORDER BY clause */
6175  struct sqlite3_index_orderby {
6176     int iColumn;              /* Column number */
6177     unsigned char desc;       /* True for DESC.  False for ASC. */
6178  } *aOrderBy;               /* The ORDER BY clause */
6179  /* Outputs */
6180  struct sqlite3_index_constraint_usage {
6181    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
6182    unsigned char omit;      /* Do not code a test for this constraint */
6183  } *aConstraintUsage;
6184  int idxNum;                /* Number used to identify the index */
6185  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
6186  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
6187  int orderByConsumed;       /* True if output is already ordered */
6188  double estimatedCost;           /* Estimated cost of using this index */
6189  /* Fields below are only available in SQLite 3.8.2 and later */
6190  sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */
6191  /* Fields below are only available in SQLite 3.9.0 and later */
6192  int idxFlags;              /* Mask of SQLITE_INDEX_SCAN_* flags */
6193  /* Fields below are only available in SQLite 3.10.0 and later */
6194  sqlite3_uint64 colUsed;    /* Input: Mask of columns used by statement */
6195};
6196
6197/*
6198** CAPI3REF: Virtual Table Scan Flags
6199*/
6200#define SQLITE_INDEX_SCAN_UNIQUE      1     /* Scan visits at most 1 row */
6201
6202/*
6203** CAPI3REF: Virtual Table Constraint Operator Codes
6204**
6205** These macros defined the allowed values for the
6206** [sqlite3_index_info].aConstraint[].op field.  Each value represents
6207** an operator that is part of a constraint term in the wHERE clause of
6208** a query that uses a [virtual table].
6209*/
6210#define SQLITE_INDEX_CONSTRAINT_EQ      2
6211#define SQLITE_INDEX_CONSTRAINT_GT      4
6212#define SQLITE_INDEX_CONSTRAINT_LE      8
6213#define SQLITE_INDEX_CONSTRAINT_LT     16
6214#define SQLITE_INDEX_CONSTRAINT_GE     32
6215#define SQLITE_INDEX_CONSTRAINT_MATCH  64
6216#define SQLITE_INDEX_CONSTRAINT_LIKE   65
6217#define SQLITE_INDEX_CONSTRAINT_GLOB   66
6218#define SQLITE_INDEX_CONSTRAINT_REGEXP 67
6219
6220/*
6221** CAPI3REF: Register A Virtual Table Implementation
6222** METHOD: sqlite3
6223**
6224** ^These routines are used to register a new [virtual table module] name.
6225** ^Module names must be registered before
6226** creating a new [virtual table] using the module and before using a
6227** preexisting [virtual table] for the module.
6228**
6229** ^The module name is registered on the [database connection] specified
6230** by the first parameter.  ^The name of the module is given by the
6231** second parameter.  ^The third parameter is a pointer to
6232** the implementation of the [virtual table module].   ^The fourth
6233** parameter is an arbitrary client data pointer that is passed through
6234** into the [xCreate] and [xConnect] methods of the virtual table module
6235** when a new virtual table is be being created or reinitialized.
6236**
6237** ^The sqlite3_create_module_v2() interface has a fifth parameter which
6238** is a pointer to a destructor for the pClientData.  ^SQLite will
6239** invoke the destructor function (if it is not NULL) when SQLite
6240** no longer needs the pClientData pointer.  ^The destructor will also
6241** be invoked if the call to sqlite3_create_module_v2() fails.
6242** ^The sqlite3_create_module()
6243** interface is equivalent to sqlite3_create_module_v2() with a NULL
6244** destructor.
6245*/
6246SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
6247  sqlite3 *db,               /* SQLite connection to register module with */
6248  const char *zName,         /* Name of the module */
6249  const sqlite3_module *p,   /* Methods for the module */
6250  void *pClientData          /* Client data for xCreate/xConnect */
6251);
6252SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
6253  sqlite3 *db,               /* SQLite connection to register module with */
6254  const char *zName,         /* Name of the module */
6255  const sqlite3_module *p,   /* Methods for the module */
6256  void *pClientData,         /* Client data for xCreate/xConnect */
6257  void(*xDestroy)(void*)     /* Module destructor function */
6258);
6259
6260/*
6261** CAPI3REF: Virtual Table Instance Object
6262** KEYWORDS: sqlite3_vtab
6263**
6264** Every [virtual table module] implementation uses a subclass
6265** of this object to describe a particular instance
6266** of the [virtual table].  Each subclass will
6267** be tailored to the specific needs of the module implementation.
6268** The purpose of this superclass is to define certain fields that are
6269** common to all module implementations.
6270**
6271** ^Virtual tables methods can set an error message by assigning a
6272** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
6273** take care that any prior string is freed by a call to [sqlite3_free()]
6274** prior to assigning a new string to zErrMsg.  ^After the error message
6275** is delivered up to the client application, the string will be automatically
6276** freed by sqlite3_free() and the zErrMsg field will be zeroed.
6277*/
6278struct sqlite3_vtab {
6279  const sqlite3_module *pModule;  /* The module for this virtual table */
6280  int nRef;                       /* Number of open cursors */
6281  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
6282  /* Virtual table implementations will typically add additional fields */
6283};
6284
6285/*
6286** CAPI3REF: Virtual Table Cursor Object
6287** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
6288**
6289** Every [virtual table module] implementation uses a subclass of the
6290** following structure to describe cursors that point into the
6291** [virtual table] and are used
6292** to loop through the virtual table.  Cursors are created using the
6293** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
6294** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
6295** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
6296** of the module.  Each module implementation will define
6297** the content of a cursor structure to suit its own needs.
6298**
6299** This superclass exists in order to define fields of the cursor that
6300** are common to all implementations.
6301*/
6302struct sqlite3_vtab_cursor {
6303  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
6304  /* Virtual table implementations will typically add additional fields */
6305};
6306
6307/*
6308** CAPI3REF: Declare The Schema Of A Virtual Table
6309**
6310** ^The [xCreate] and [xConnect] methods of a
6311** [virtual table module] call this interface
6312** to declare the format (the names and datatypes of the columns) of
6313** the virtual tables they implement.
6314*/
6315SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3*, const char *zSQL);
6316
6317/*
6318** CAPI3REF: Overload A Function For A Virtual Table
6319** METHOD: sqlite3
6320**
6321** ^(Virtual tables can provide alternative implementations of functions
6322** using the [xFindFunction] method of the [virtual table module].
6323** But global versions of those functions
6324** must exist in order to be overloaded.)^
6325**
6326** ^(This API makes sure a global version of a function with a particular
6327** name and number of parameters exists.  If no such function exists
6328** before this API is called, a new function is created.)^  ^The implementation
6329** of the new function always causes an exception to be thrown.  So
6330** the new function is not good for anything by itself.  Its only
6331** purpose is to be a placeholder function that can be overloaded
6332** by a [virtual table].
6333*/
6334SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
6335
6336/*
6337** The interface to the virtual-table mechanism defined above (back up
6338** to a comment remarkably similar to this one) is currently considered
6339** to be experimental.  The interface might change in incompatible ways.
6340** If this is a problem for you, do not use the interface at this time.
6341**
6342** When the virtual-table mechanism stabilizes, we will declare the
6343** interface fixed, support it indefinitely, and remove this comment.
6344*/
6345
6346/*
6347** CAPI3REF: A Handle To An Open BLOB
6348** KEYWORDS: {BLOB handle} {BLOB handles}
6349**
6350** An instance of this object represents an open BLOB on which
6351** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
6352** ^Objects of this type are created by [sqlite3_blob_open()]
6353** and destroyed by [sqlite3_blob_close()].
6354** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
6355** can be used to read or write small subsections of the BLOB.
6356** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
6357*/
6358typedef struct sqlite3_blob sqlite3_blob;
6359
6360/*
6361** CAPI3REF: Open A BLOB For Incremental I/O
6362** METHOD: sqlite3
6363** CONSTRUCTOR: sqlite3_blob
6364**
6365** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
6366** in row iRow, column zColumn, table zTable in database zDb;
6367** in other words, the same BLOB that would be selected by:
6368**
6369** <pre>
6370**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
6371** </pre>)^
6372**
6373** ^(Parameter zDb is not the filename that contains the database, but
6374** rather the symbolic name of the database. For attached databases, this is
6375** the name that appears after the AS keyword in the [ATTACH] statement.
6376** For the main database file, the database name is "main". For TEMP
6377** tables, the database name is "temp".)^
6378**
6379** ^If the flags parameter is non-zero, then the BLOB is opened for read
6380** and write access. ^If the flags parameter is zero, the BLOB is opened for
6381** read-only access.
6382**
6383** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
6384** in *ppBlob. Otherwise an [error code] is returned and, unless the error
6385** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
6386** the API is not misused, it is always safe to call [sqlite3_blob_close()]
6387** on *ppBlob after this function it returns.
6388**
6389** This function fails with SQLITE_ERROR if any of the following are true:
6390** <ul>
6391**   <li> ^(Database zDb does not exist)^,
6392**   <li> ^(Table zTable does not exist within database zDb)^,
6393**   <li> ^(Table zTable is a WITHOUT ROWID table)^,
6394**   <li> ^(Column zColumn does not exist)^,
6395**   <li> ^(Row iRow is not present in the table)^,
6396**   <li> ^(The specified column of row iRow contains a value that is not
6397**         a TEXT or BLOB value)^,
6398**   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
6399**         constraint and the blob is being opened for read/write access)^,
6400**   <li> ^([foreign key constraints | Foreign key constraints] are enabled,
6401**         column zColumn is part of a [child key] definition and the blob is
6402**         being opened for read/write access)^.
6403** </ul>
6404**
6405** ^Unless it returns SQLITE_MISUSE, this function sets the
6406** [database connection] error code and message accessible via
6407** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6408**
6409**
6410** ^(If the row that a BLOB handle points to is modified by an
6411** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
6412** then the BLOB handle is marked as "expired".
6413** This is true if any column of the row is changed, even a column
6414** other than the one the BLOB handle is open on.)^
6415** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
6416** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
6417** ^(Changes written into a BLOB prior to the BLOB expiring are not
6418** rolled back by the expiration of the BLOB.  Such changes will eventually
6419** commit if the transaction continues to completion.)^
6420**
6421** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
6422** the opened blob.  ^The size of a blob may not be changed by this
6423** interface.  Use the [UPDATE] SQL command to change the size of a
6424** blob.
6425**
6426** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
6427** and the built-in [zeroblob] SQL function may be used to create a
6428** zero-filled blob to read or write using the incremental-blob interface.
6429**
6430** To avoid a resource leak, every open [BLOB handle] should eventually
6431** be released by a call to [sqlite3_blob_close()].
6432*/
6433SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
6434  sqlite3*,
6435  const char *zDb,
6436  const char *zTable,
6437  const char *zColumn,
6438  sqlite3_int64 iRow,
6439  int flags,
6440  sqlite3_blob **ppBlob
6441);
6442
6443/*
6444** CAPI3REF: Move a BLOB Handle to a New Row
6445** METHOD: sqlite3_blob
6446**
6447** ^This function is used to move an existing blob handle so that it points
6448** to a different row of the same database table. ^The new row is identified
6449** by the rowid value passed as the second argument. Only the row can be
6450** changed. ^The database, table and column on which the blob handle is open
6451** remain the same. Moving an existing blob handle to a new row can be
6452** faster than closing the existing handle and opening a new one.
6453**
6454** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
6455** it must exist and there must be either a blob or text value stored in
6456** the nominated column.)^ ^If the new row is not present in the table, or if
6457** it does not contain a blob or text value, or if another error occurs, an
6458** SQLite error code is returned and the blob handle is considered aborted.
6459** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
6460** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
6461** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
6462** always returns zero.
6463**
6464** ^This function sets the database handle error code and message.
6465*/
6466SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
6467
6468/*
6469** CAPI3REF: Close A BLOB Handle
6470** DESTRUCTOR: sqlite3_blob
6471**
6472** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
6473** unconditionally.  Even if this routine returns an error code, the
6474** handle is still closed.)^
6475**
6476** ^If the blob handle being closed was opened for read-write access, and if
6477** the database is in auto-commit mode and there are no other open read-write
6478** blob handles or active write statements, the current transaction is
6479** committed. ^If an error occurs while committing the transaction, an error
6480** code is returned and the transaction rolled back.
6481**
6482** Calling this function with an argument that is not a NULL pointer or an
6483** open blob handle results in undefined behaviour. ^Calling this routine
6484** with a null pointer (such as would be returned by a failed call to
6485** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
6486** is passed a valid open blob handle, the values returned by the
6487** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
6488*/
6489SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *);
6490
6491/*
6492** CAPI3REF: Return The Size Of An Open BLOB
6493** METHOD: sqlite3_blob
6494**
6495** ^Returns the size in bytes of the BLOB accessible via the
6496** successfully opened [BLOB handle] in its only argument.  ^The
6497** incremental blob I/O routines can only read or overwriting existing
6498** blob content; they cannot change the size of a blob.
6499**
6500** This routine only works on a [BLOB handle] which has been created
6501** by a prior successful call to [sqlite3_blob_open()] and which has not
6502** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6503** to this routine results in undefined and probably undesirable behavior.
6504*/
6505SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *);
6506
6507/*
6508** CAPI3REF: Read Data From A BLOB Incrementally
6509** METHOD: sqlite3_blob
6510**
6511** ^(This function is used to read data from an open [BLOB handle] into a
6512** caller-supplied buffer. N bytes of data are copied into buffer Z
6513** from the open BLOB, starting at offset iOffset.)^
6514**
6515** ^If offset iOffset is less than N bytes from the end of the BLOB,
6516** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
6517** less than zero, [SQLITE_ERROR] is returned and no data is read.
6518** ^The size of the blob (and hence the maximum value of N+iOffset)
6519** can be determined using the [sqlite3_blob_bytes()] interface.
6520**
6521** ^An attempt to read from an expired [BLOB handle] fails with an
6522** error code of [SQLITE_ABORT].
6523**
6524** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
6525** Otherwise, an [error code] or an [extended error code] is returned.)^
6526**
6527** This routine only works on a [BLOB handle] which has been created
6528** by a prior successful call to [sqlite3_blob_open()] and which has not
6529** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6530** to this routine results in undefined and probably undesirable behavior.
6531**
6532** See also: [sqlite3_blob_write()].
6533*/
6534SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6535
6536/*
6537** CAPI3REF: Write Data Into A BLOB Incrementally
6538** METHOD: sqlite3_blob
6539**
6540** ^(This function is used to write data into an open [BLOB handle] from a
6541** caller-supplied buffer. N bytes of data are copied from the buffer Z
6542** into the open BLOB, starting at offset iOffset.)^
6543**
6544** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
6545** Otherwise, an  [error code] or an [extended error code] is returned.)^
6546** ^Unless SQLITE_MISUSE is returned, this function sets the
6547** [database connection] error code and message accessible via
6548** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6549**
6550** ^If the [BLOB handle] passed as the first argument was not opened for
6551** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6552** this function returns [SQLITE_READONLY].
6553**
6554** This function may only modify the contents of the BLOB; it is
6555** not possible to increase the size of a BLOB using this API.
6556** ^If offset iOffset is less than N bytes from the end of the BLOB,
6557** [SQLITE_ERROR] is returned and no data is written. The size of the
6558** BLOB (and hence the maximum value of N+iOffset) can be determined
6559** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
6560** than zero [SQLITE_ERROR] is returned and no data is written.
6561**
6562** ^An attempt to write to an expired [BLOB handle] fails with an
6563** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
6564** before the [BLOB handle] expired are not rolled back by the
6565** expiration of the handle, though of course those changes might
6566** have been overwritten by the statement that expired the BLOB handle
6567** or by other independent statements.
6568**
6569** This routine only works on a [BLOB handle] which has been created
6570** by a prior successful call to [sqlite3_blob_open()] and which has not
6571** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6572** to this routine results in undefined and probably undesirable behavior.
6573**
6574** See also: [sqlite3_blob_read()].
6575*/
6576SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6577
6578/*
6579** CAPI3REF: Virtual File System Objects
6580**
6581** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6582** that SQLite uses to interact
6583** with the underlying operating system.  Most SQLite builds come with a
6584** single default VFS that is appropriate for the host computer.
6585** New VFSes can be registered and existing VFSes can be unregistered.
6586** The following interfaces are provided.
6587**
6588** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6589** ^Names are case sensitive.
6590** ^Names are zero-terminated UTF-8 strings.
6591** ^If there is no match, a NULL pointer is returned.
6592** ^If zVfsName is NULL then the default VFS is returned.
6593**
6594** ^New VFSes are registered with sqlite3_vfs_register().
6595** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6596** ^The same VFS can be registered multiple times without injury.
6597** ^To make an existing VFS into the default VFS, register it again
6598** with the makeDflt flag set.  If two different VFSes with the
6599** same name are registered, the behavior is undefined.  If a
6600** VFS is registered with a name that is NULL or an empty string,
6601** then the behavior is undefined.
6602**
6603** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6604** ^(If the default VFS is unregistered, another VFS is chosen as
6605** the default.  The choice for the new VFS is arbitrary.)^
6606*/
6607SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfsName);
6608SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6609SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs*);
6610
6611/*
6612** CAPI3REF: Mutexes
6613**
6614** The SQLite core uses these routines for thread
6615** synchronization. Though they are intended for internal
6616** use by SQLite, code that links against SQLite is
6617** permitted to use any of these routines.
6618**
6619** The SQLite source code contains multiple implementations
6620** of these mutex routines.  An appropriate implementation
6621** is selected automatically at compile-time.  The following
6622** implementations are available in the SQLite core:
6623**
6624** <ul>
6625** <li>   SQLITE_MUTEX_PTHREADS
6626** <li>   SQLITE_MUTEX_W32
6627** <li>   SQLITE_MUTEX_NOOP
6628** </ul>
6629**
6630** The SQLITE_MUTEX_NOOP implementation is a set of routines
6631** that does no real locking and is appropriate for use in
6632** a single-threaded application.  The SQLITE_MUTEX_PTHREADS and
6633** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6634** and Windows.
6635**
6636** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6637** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6638** implementation is included with the library. In this case the
6639** application must supply a custom mutex implementation using the
6640** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6641** before calling sqlite3_initialize() or any other public sqlite3_
6642** function that calls sqlite3_initialize().
6643**
6644** ^The sqlite3_mutex_alloc() routine allocates a new
6645** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
6646** routine returns NULL if it is unable to allocate the requested
6647** mutex.  The argument to sqlite3_mutex_alloc() must one of these
6648** integer constants:
6649**
6650** <ul>
6651** <li>  SQLITE_MUTEX_FAST
6652** <li>  SQLITE_MUTEX_RECURSIVE
6653** <li>  SQLITE_MUTEX_STATIC_MASTER
6654** <li>  SQLITE_MUTEX_STATIC_MEM
6655** <li>  SQLITE_MUTEX_STATIC_OPEN
6656** <li>  SQLITE_MUTEX_STATIC_PRNG
6657** <li>  SQLITE_MUTEX_STATIC_LRU
6658** <li>  SQLITE_MUTEX_STATIC_PMEM
6659** <li>  SQLITE_MUTEX_STATIC_APP1
6660** <li>  SQLITE_MUTEX_STATIC_APP2
6661** <li>  SQLITE_MUTEX_STATIC_APP3
6662** <li>  SQLITE_MUTEX_STATIC_VFS1
6663** <li>  SQLITE_MUTEX_STATIC_VFS2
6664** <li>  SQLITE_MUTEX_STATIC_VFS3
6665** </ul>
6666**
6667** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6668** cause sqlite3_mutex_alloc() to create
6669** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6670** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6671** The mutex implementation does not need to make a distinction
6672** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6673** not want to.  SQLite will only request a recursive mutex in
6674** cases where it really needs one.  If a faster non-recursive mutex
6675** implementation is available on the host platform, the mutex subsystem
6676** might return such a mutex in response to SQLITE_MUTEX_FAST.
6677**
6678** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6679** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6680** a pointer to a static preexisting mutex.  ^Nine static mutexes are
6681** used by the current version of SQLite.  Future versions of SQLite
6682** may add additional static mutexes.  Static mutexes are for internal
6683** use by SQLite only.  Applications that use SQLite mutexes should
6684** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6685** SQLITE_MUTEX_RECURSIVE.
6686**
6687** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6688** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6689** returns a different mutex on every call.  ^For the static
6690** mutex types, the same mutex is returned on every call that has
6691** the same type number.
6692**
6693** ^The sqlite3_mutex_free() routine deallocates a previously
6694** allocated dynamic mutex.  Attempting to deallocate a static
6695** mutex results in undefined behavior.
6696**
6697** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6698** to enter a mutex.  ^If another thread is already within the mutex,
6699** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6700** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6701** upon successful entry.  ^(Mutexes created using
6702** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6703** In such cases, the
6704** mutex must be exited an equal number of times before another thread
6705** can enter.)^  If the same thread tries to enter any mutex other
6706** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
6707**
6708** ^(Some systems (for example, Windows 95) do not support the operation
6709** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6710** will always return SQLITE_BUSY. The SQLite core only ever uses
6711** sqlite3_mutex_try() as an optimization so this is acceptable
6712** behavior.)^
6713**
6714** ^The sqlite3_mutex_leave() routine exits a mutex that was
6715** previously entered by the same thread.   The behavior
6716** is undefined if the mutex is not currently entered by the
6717** calling thread or is not currently allocated.
6718**
6719** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6720** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6721** behave as no-ops.
6722**
6723** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6724*/
6725SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int);
6726SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex*);
6727SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex*);
6728SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex*);
6729SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex*);
6730
6731/*
6732** CAPI3REF: Mutex Methods Object
6733**
6734** An instance of this structure defines the low-level routines
6735** used to allocate and use mutexes.
6736**
6737** Usually, the default mutex implementations provided by SQLite are
6738** sufficient, however the application has the option of substituting a custom
6739** implementation for specialized deployments or systems for which SQLite
6740** does not provide a suitable implementation. In this case, the application
6741** creates and populates an instance of this structure to pass
6742** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6743** Additionally, an instance of this structure can be used as an
6744** output variable when querying the system for the current mutex
6745** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6746**
6747** ^The xMutexInit method defined by this structure is invoked as
6748** part of system initialization by the sqlite3_initialize() function.
6749** ^The xMutexInit routine is called by SQLite exactly once for each
6750** effective call to [sqlite3_initialize()].
6751**
6752** ^The xMutexEnd method defined by this structure is invoked as
6753** part of system shutdown by the sqlite3_shutdown() function. The
6754** implementation of this method is expected to release all outstanding
6755** resources obtained by the mutex methods implementation, especially
6756** those obtained by the xMutexInit method.  ^The xMutexEnd()
6757** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6758**
6759** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6760** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6761** xMutexNotheld) implement the following interfaces (respectively):
6762**
6763** <ul>
6764**   <li>  [sqlite3_mutex_alloc()] </li>
6765**   <li>  [sqlite3_mutex_free()] </li>
6766**   <li>  [sqlite3_mutex_enter()] </li>
6767**   <li>  [sqlite3_mutex_try()] </li>
6768**   <li>  [sqlite3_mutex_leave()] </li>
6769**   <li>  [sqlite3_mutex_held()] </li>
6770**   <li>  [sqlite3_mutex_notheld()] </li>
6771** </ul>)^
6772**
6773** The only difference is that the public sqlite3_XXX functions enumerated
6774** above silently ignore any invocations that pass a NULL pointer instead
6775** of a valid mutex handle. The implementations of the methods defined
6776** by this structure are not required to handle this case, the results
6777** of passing a NULL pointer instead of a valid mutex handle are undefined
6778** (i.e. it is acceptable to provide an implementation that segfaults if
6779** it is passed a NULL pointer).
6780**
6781** The xMutexInit() method must be threadsafe.  It must be harmless to
6782** invoke xMutexInit() multiple times within the same process and without
6783** intervening calls to xMutexEnd().  Second and subsequent calls to
6784** xMutexInit() must be no-ops.
6785**
6786** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6787** and its associates).  Similarly, xMutexAlloc() must not use SQLite memory
6788** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6789** memory allocation for a fast or recursive mutex.
6790**
6791** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6792** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6793** If xMutexInit fails in any way, it is expected to clean up after itself
6794** prior to returning.
6795*/
6796typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6797struct sqlite3_mutex_methods {
6798  int (*xMutexInit)(void);
6799  int (*xMutexEnd)(void);
6800  sqlite3_mutex *(*xMutexAlloc)(int);
6801  void (*xMutexFree)(sqlite3_mutex *);
6802  void (*xMutexEnter)(sqlite3_mutex *);
6803  int (*xMutexTry)(sqlite3_mutex *);
6804  void (*xMutexLeave)(sqlite3_mutex *);
6805  int (*xMutexHeld)(sqlite3_mutex *);
6806  int (*xMutexNotheld)(sqlite3_mutex *);
6807};
6808
6809/*
6810** CAPI3REF: Mutex Verification Routines
6811**
6812** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6813** are intended for use inside assert() statements.  The SQLite core
6814** never uses these routines except inside an assert() and applications
6815** are advised to follow the lead of the core.  The SQLite core only
6816** provides implementations for these routines when it is compiled
6817** with the SQLITE_DEBUG flag.  External mutex implementations
6818** are only required to provide these routines if SQLITE_DEBUG is
6819** defined and if NDEBUG is not defined.
6820**
6821** These routines should return true if the mutex in their argument
6822** is held or not held, respectively, by the calling thread.
6823**
6824** The implementation is not required to provide versions of these
6825** routines that actually work. If the implementation does not provide working
6826** versions of these routines, it should at least provide stubs that always
6827** return true so that one does not get spurious assertion failures.
6828**
6829** If the argument to sqlite3_mutex_held() is a NULL pointer then
6830** the routine should return 1.   This seems counter-intuitive since
6831** clearly the mutex cannot be held if it does not exist.  But
6832** the reason the mutex does not exist is because the build is not
6833** using mutexes.  And we do not want the assert() containing the
6834** call to sqlite3_mutex_held() to fail, so a non-zero return is
6835** the appropriate thing to do.  The sqlite3_mutex_notheld()
6836** interface should also return 1 when given a NULL pointer.
6837*/
6838#ifndef NDEBUG
6839SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex*);
6840SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex*);
6841#endif
6842
6843/*
6844** CAPI3REF: Mutex Types
6845**
6846** The [sqlite3_mutex_alloc()] interface takes a single argument
6847** which is one of these integer constants.
6848**
6849** The set of static mutexes may change from one SQLite release to the
6850** next.  Applications that override the built-in mutex logic must be
6851** prepared to accommodate additional static mutexes.
6852*/
6853#define SQLITE_MUTEX_FAST             0
6854#define SQLITE_MUTEX_RECURSIVE        1
6855#define SQLITE_MUTEX_STATIC_MASTER    2
6856#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6857#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6858#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6859#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6860#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6861#define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6862#define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6863#define SQLITE_MUTEX_STATIC_APP1      8  /* For use by application */
6864#define SQLITE_MUTEX_STATIC_APP2      9  /* For use by application */
6865#define SQLITE_MUTEX_STATIC_APP3     10  /* For use by application */
6866#define SQLITE_MUTEX_STATIC_VFS1     11  /* For use by built-in VFS */
6867#define SQLITE_MUTEX_STATIC_VFS2     12  /* For use by extension VFS */
6868#define SQLITE_MUTEX_STATIC_VFS3     13  /* For use by application VFS */
6869
6870/*
6871** CAPI3REF: Retrieve the mutex for a database connection
6872** METHOD: sqlite3
6873**
6874** ^This interface returns a pointer the [sqlite3_mutex] object that
6875** serializes access to the [database connection] given in the argument
6876** when the [threading mode] is Serialized.
6877** ^If the [threading mode] is Single-thread or Multi-thread then this
6878** routine returns a NULL pointer.
6879*/
6880SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3*);
6881
6882/*
6883** CAPI3REF: Low-Level Control Of Database Files
6884** METHOD: sqlite3
6885**
6886** ^The [sqlite3_file_control()] interface makes a direct call to the
6887** xFileControl method for the [sqlite3_io_methods] object associated
6888** with a particular database identified by the second argument. ^The
6889** name of the database is "main" for the main database or "temp" for the
6890** TEMP database, or the name that appears after the AS keyword for
6891** databases that are added using the [ATTACH] SQL command.
6892** ^A NULL pointer can be used in place of "main" to refer to the
6893** main database file.
6894** ^The third and fourth parameters to this routine
6895** are passed directly through to the second and third parameters of
6896** the xFileControl method.  ^The return value of the xFileControl
6897** method becomes the return value of this routine.
6898**
6899** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6900** a pointer to the underlying [sqlite3_file] object to be written into
6901** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
6902** case is a short-circuit path which does not actually invoke the
6903** underlying sqlite3_io_methods.xFileControl method.
6904**
6905** ^If the second parameter (zDbName) does not match the name of any
6906** open database file, then SQLITE_ERROR is returned.  ^This error
6907** code is not remembered and will not be recalled by [sqlite3_errcode()]
6908** or [sqlite3_errmsg()].  The underlying xFileControl method might
6909** also return SQLITE_ERROR.  There is no way to distinguish between
6910** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6911** xFileControl method.
6912**
6913** See also: [SQLITE_FCNTL_LOCKSTATE]
6914*/
6915SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6916
6917/*
6918** CAPI3REF: Testing Interface
6919**
6920** ^The sqlite3_test_control() interface is used to read out internal
6921** state of SQLite and to inject faults into SQLite for testing
6922** purposes.  ^The first parameter is an operation code that determines
6923** the number, meaning, and operation of all subsequent parameters.
6924**
6925** This interface is not for use by applications.  It exists solely
6926** for verifying the correct operation of the SQLite library.  Depending
6927** on how the SQLite library is compiled, this interface might not exist.
6928**
6929** The details of the operation codes, their meanings, the parameters
6930** they take, and what they do are all subject to change without notice.
6931** Unlike most of the SQLite API, this function is not guaranteed to
6932** operate consistently from one release to the next.
6933*/
6934SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...);
6935
6936/*
6937** CAPI3REF: Testing Interface Operation Codes
6938**
6939** These constants are the valid operation code parameters used
6940** as the first argument to [sqlite3_test_control()].
6941**
6942** These parameters and their meanings are subject to change
6943** without notice.  These values are for testing purposes only.
6944** Applications should not use any of these parameters or the
6945** [sqlite3_test_control()] interface.
6946*/
6947#define SQLITE_TESTCTRL_FIRST                    5
6948#define SQLITE_TESTCTRL_PRNG_SAVE                5
6949#define SQLITE_TESTCTRL_PRNG_RESTORE             6
6950#define SQLITE_TESTCTRL_PRNG_RESET               7
6951#define SQLITE_TESTCTRL_BITVEC_TEST              8
6952#define SQLITE_TESTCTRL_FAULT_INSTALL            9
6953#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6954#define SQLITE_TESTCTRL_PENDING_BYTE            11
6955#define SQLITE_TESTCTRL_ASSERT                  12
6956#define SQLITE_TESTCTRL_ALWAYS                  13
6957#define SQLITE_TESTCTRL_RESERVE                 14
6958#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
6959#define SQLITE_TESTCTRL_ISKEYWORD               16
6960#define SQLITE_TESTCTRL_SCRATCHMALLOC           17
6961#define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
6962#define SQLITE_TESTCTRL_EXPLAIN_STMT            19  /* NOT USED */
6963#define SQLITE_TESTCTRL_NEVER_CORRUPT           20
6964#define SQLITE_TESTCTRL_VDBE_COVERAGE           21
6965#define SQLITE_TESTCTRL_BYTEORDER               22
6966#define SQLITE_TESTCTRL_ISINIT                  23
6967#define SQLITE_TESTCTRL_SORTER_MMAP             24
6968#define SQLITE_TESTCTRL_IMPOSTER                25
6969#define SQLITE_TESTCTRL_LAST                    25
6970
6971/*
6972** CAPI3REF: SQLite Runtime Status
6973**
6974** ^These interfaces are used to retrieve runtime status information
6975** about the performance of SQLite, and optionally to reset various
6976** highwater marks.  ^The first argument is an integer code for
6977** the specific parameter to measure.  ^(Recognized integer codes
6978** are of the form [status parameters | SQLITE_STATUS_...].)^
6979** ^The current value of the parameter is returned into *pCurrent.
6980** ^The highest recorded value is returned in *pHighwater.  ^If the
6981** resetFlag is true, then the highest record value is reset after
6982** *pHighwater is written.  ^(Some parameters do not record the highest
6983** value.  For those parameters
6984** nothing is written into *pHighwater and the resetFlag is ignored.)^
6985** ^(Other parameters record only the highwater mark and not the current
6986** value.  For these latter parameters nothing is written into *pCurrent.)^
6987**
6988** ^The sqlite3_status() and sqlite3_status64() routines return
6989** SQLITE_OK on success and a non-zero [error code] on failure.
6990**
6991** If either the current value or the highwater mark is too large to
6992** be represented by a 32-bit integer, then the values returned by
6993** sqlite3_status() are undefined.
6994**
6995** See also: [sqlite3_db_status()]
6996*/
6997SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6998SQLITE_API int SQLITE_STDCALL sqlite3_status64(
6999  int op,
7000  sqlite3_int64 *pCurrent,
7001  sqlite3_int64 *pHighwater,
7002  int resetFlag
7003);
7004
7005
7006/*
7007** CAPI3REF: Status Parameters
7008** KEYWORDS: {status parameters}
7009**
7010** These integer constants designate various run-time status parameters
7011** that can be returned by [sqlite3_status()].
7012**
7013** <dl>
7014** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
7015** <dd>This parameter is the current amount of memory checked out
7016** using [sqlite3_malloc()], either directly or indirectly.  The
7017** figure includes calls made to [sqlite3_malloc()] by the application
7018** and internal memory usage by the SQLite library.  Scratch memory
7019** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
7020** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
7021** this parameter.  The amount returned is the sum of the allocation
7022** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
7023**
7024** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
7025** <dd>This parameter records the largest memory allocation request
7026** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
7027** internal equivalents).  Only the value returned in the
7028** *pHighwater parameter to [sqlite3_status()] is of interest.
7029** The value written into the *pCurrent parameter is undefined.</dd>)^
7030**
7031** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
7032** <dd>This parameter records the number of separate memory allocations
7033** currently checked out.</dd>)^
7034**
7035** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
7036** <dd>This parameter returns the number of pages used out of the
7037** [pagecache memory allocator] that was configured using
7038** [SQLITE_CONFIG_PAGECACHE].  The
7039** value returned is in pages, not in bytes.</dd>)^
7040**
7041** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
7042** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
7043** <dd>This parameter returns the number of bytes of page cache
7044** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
7045** buffer and where forced to overflow to [sqlite3_malloc()].  The
7046** returned value includes allocations that overflowed because they
7047** where too large (they were larger than the "sz" parameter to
7048** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
7049** no space was left in the page cache.</dd>)^
7050**
7051** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
7052** <dd>This parameter records the largest memory allocation request
7053** handed to [pagecache memory allocator].  Only the value returned in the
7054** *pHighwater parameter to [sqlite3_status()] is of interest.
7055** The value written into the *pCurrent parameter is undefined.</dd>)^
7056**
7057** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
7058** <dd>This parameter returns the number of allocations used out of the
7059** [scratch memory allocator] configured using
7060** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
7061** in bytes.  Since a single thread may only have one scratch allocation
7062** outstanding at time, this parameter also reports the number of threads
7063** using scratch memory at the same time.</dd>)^
7064**
7065** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
7066** <dd>This parameter returns the number of bytes of scratch memory
7067** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
7068** buffer and where forced to overflow to [sqlite3_malloc()].  The values
7069** returned include overflows because the requested allocation was too
7070** larger (that is, because the requested allocation was larger than the
7071** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
7072** slots were available.
7073** </dd>)^
7074**
7075** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
7076** <dd>This parameter records the largest memory allocation request
7077** handed to [scratch memory allocator].  Only the value returned in the
7078** *pHighwater parameter to [sqlite3_status()] is of interest.
7079** The value written into the *pCurrent parameter is undefined.</dd>)^
7080**
7081** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
7082** <dd>The *pHighwater parameter records the deepest parser stack.
7083** The *pCurrent value is undefined.  The *pHighwater value is only
7084** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
7085** </dl>
7086**
7087** New status parameters may be added from time to time.
7088*/
7089#define SQLITE_STATUS_MEMORY_USED          0
7090#define SQLITE_STATUS_PAGECACHE_USED       1
7091#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
7092#define SQLITE_STATUS_SCRATCH_USED         3
7093#define SQLITE_STATUS_SCRATCH_OVERFLOW     4
7094#define SQLITE_STATUS_MALLOC_SIZE          5
7095#define SQLITE_STATUS_PARSER_STACK         6
7096#define SQLITE_STATUS_PAGECACHE_SIZE       7
7097#define SQLITE_STATUS_SCRATCH_SIZE         8
7098#define SQLITE_STATUS_MALLOC_COUNT         9
7099
7100/*
7101** CAPI3REF: Database Connection Status
7102** METHOD: sqlite3
7103**
7104** ^This interface is used to retrieve runtime status information
7105** about a single [database connection].  ^The first argument is the
7106** database connection object to be interrogated.  ^The second argument
7107** is an integer constant, taken from the set of
7108** [SQLITE_DBSTATUS options], that
7109** determines the parameter to interrogate.  The set of
7110** [SQLITE_DBSTATUS options] is likely
7111** to grow in future releases of SQLite.
7112**
7113** ^The current value of the requested parameter is written into *pCur
7114** and the highest instantaneous value is written into *pHiwtr.  ^If
7115** the resetFlg is true, then the highest instantaneous value is
7116** reset back down to the current value.
7117**
7118** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
7119** non-zero [error code] on failure.
7120**
7121** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
7122*/
7123SQLITE_API int SQLITE_STDCALL sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
7124
7125/*
7126** CAPI3REF: Status Parameters for database connections
7127** KEYWORDS: {SQLITE_DBSTATUS options}
7128**
7129** These constants are the available integer "verbs" that can be passed as
7130** the second argument to the [sqlite3_db_status()] interface.
7131**
7132** New verbs may be added in future releases of SQLite. Existing verbs
7133** might be discontinued. Applications should check the return code from
7134** [sqlite3_db_status()] to make sure that the call worked.
7135** The [sqlite3_db_status()] interface will return a non-zero error code
7136** if a discontinued or unsupported verb is invoked.
7137**
7138** <dl>
7139** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
7140** <dd>This parameter returns the number of lookaside memory slots currently
7141** checked out.</dd>)^
7142**
7143** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
7144** <dd>This parameter returns the number malloc attempts that were
7145** satisfied using lookaside memory. Only the high-water value is meaningful;
7146** the current value is always zero.)^
7147**
7148** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
7149** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
7150** <dd>This parameter returns the number malloc attempts that might have
7151** been satisfied using lookaside memory but failed due to the amount of
7152** memory requested being larger than the lookaside slot size.
7153** Only the high-water value is meaningful;
7154** the current value is always zero.)^
7155**
7156** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
7157** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
7158** <dd>This parameter returns the number malloc attempts that might have
7159** been satisfied using lookaside memory but failed due to all lookaside
7160** memory already being in use.
7161** Only the high-water value is meaningful;
7162** the current value is always zero.)^
7163**
7164** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
7165** <dd>This parameter returns the approximate number of bytes of heap
7166** memory used by all pager caches associated with the database connection.)^
7167** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
7168**
7169** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
7170** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
7171** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
7172** pager cache is shared between two or more connections the bytes of heap
7173** memory used by that pager cache is divided evenly between the attached
7174** connections.)^  In other words, if none of the pager caches associated
7175** with the database connection are shared, this request returns the same
7176** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
7177** shared, the value returned by this call will be smaller than that returned
7178** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
7179** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
7180**
7181** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
7182** <dd>This parameter returns the approximate number of bytes of heap
7183** memory used to store the schema for all databases associated
7184** with the connection - main, temp, and any [ATTACH]-ed databases.)^
7185** ^The full amount of memory used by the schemas is reported, even if the
7186** schema memory is shared with other database connections due to
7187** [shared cache mode] being enabled.
7188** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
7189**
7190** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
7191** <dd>This parameter returns the approximate number of bytes of heap
7192** and lookaside memory used by all prepared statements associated with
7193** the database connection.)^
7194** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
7195** </dd>
7196**
7197** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
7198** <dd>This parameter returns the number of pager cache hits that have
7199** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
7200** is always 0.
7201** </dd>
7202**
7203** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
7204** <dd>This parameter returns the number of pager cache misses that have
7205** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
7206** is always 0.
7207** </dd>
7208**
7209** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
7210** <dd>This parameter returns the number of dirty cache entries that have
7211** been written to disk. Specifically, the number of pages written to the
7212** wal file in wal mode databases, or the number of pages written to the
7213** database file in rollback mode databases. Any pages written as part of
7214** transaction rollback or database recovery operations are not included.
7215** If an IO or other error occurs while writing a page to disk, the effect
7216** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
7217** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
7218** </dd>
7219**
7220** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
7221** <dd>This parameter returns zero for the current value if and only if
7222** all foreign key constraints (deferred or immediate) have been
7223** resolved.)^  ^The highwater mark is always 0.
7224** </dd>
7225** </dl>
7226*/
7227#define SQLITE_DBSTATUS_LOOKASIDE_USED       0
7228#define SQLITE_DBSTATUS_CACHE_USED           1
7229#define SQLITE_DBSTATUS_SCHEMA_USED          2
7230#define SQLITE_DBSTATUS_STMT_USED            3
7231#define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
7232#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
7233#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
7234#define SQLITE_DBSTATUS_CACHE_HIT            7
7235#define SQLITE_DBSTATUS_CACHE_MISS           8
7236#define SQLITE_DBSTATUS_CACHE_WRITE          9
7237#define SQLITE_DBSTATUS_DEFERRED_FKS        10
7238#define SQLITE_DBSTATUS_CACHE_USED_SHARED   11
7239#define SQLITE_DBSTATUS_MAX                 11   /* Largest defined DBSTATUS */
7240
7241
7242/*
7243** CAPI3REF: Prepared Statement Status
7244** METHOD: sqlite3_stmt
7245**
7246** ^(Each prepared statement maintains various
7247** [SQLITE_STMTSTATUS counters] that measure the number
7248** of times it has performed specific operations.)^  These counters can
7249** be used to monitor the performance characteristics of the prepared
7250** statements.  For example, if the number of table steps greatly exceeds
7251** the number of table searches or result rows, that would tend to indicate
7252** that the prepared statement is using a full table scan rather than
7253** an index.
7254**
7255** ^(This interface is used to retrieve and reset counter values from
7256** a [prepared statement].  The first argument is the prepared statement
7257** object to be interrogated.  The second argument
7258** is an integer code for a specific [SQLITE_STMTSTATUS counter]
7259** to be interrogated.)^
7260** ^The current value of the requested counter is returned.
7261** ^If the resetFlg is true, then the counter is reset to zero after this
7262** interface call returns.
7263**
7264** See also: [sqlite3_status()] and [sqlite3_db_status()].
7265*/
7266SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
7267
7268/*
7269** CAPI3REF: Status Parameters for prepared statements
7270** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
7271**
7272** These preprocessor macros define integer codes that name counter
7273** values associated with the [sqlite3_stmt_status()] interface.
7274** The meanings of the various counters are as follows:
7275**
7276** <dl>
7277** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
7278** <dd>^This is the number of times that SQLite has stepped forward in
7279** a table as part of a full table scan.  Large numbers for this counter
7280** may indicate opportunities for performance improvement through
7281** careful use of indices.</dd>
7282**
7283** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
7284** <dd>^This is the number of sort operations that have occurred.
7285** A non-zero value in this counter may indicate an opportunity to
7286** improvement performance through careful use of indices.</dd>
7287**
7288** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
7289** <dd>^This is the number of rows inserted into transient indices that
7290** were created automatically in order to help joins run faster.
7291** A non-zero value in this counter may indicate an opportunity to
7292** improvement performance by adding permanent indices that do not
7293** need to be reinitialized each time the statement is run.</dd>
7294**
7295** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
7296** <dd>^This is the number of virtual machine operations executed
7297** by the prepared statement if that number is less than or equal
7298** to 2147483647.  The number of virtual machine operations can be
7299** used as a proxy for the total work done by the prepared statement.
7300** If the number of virtual machine operations exceeds 2147483647
7301** then the value returned by this statement status code is undefined.
7302** </dd>
7303** </dl>
7304*/
7305#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
7306#define SQLITE_STMTSTATUS_SORT              2
7307#define SQLITE_STMTSTATUS_AUTOINDEX         3
7308#define SQLITE_STMTSTATUS_VM_STEP           4
7309
7310/*
7311** CAPI3REF: Custom Page Cache Object
7312**
7313** The sqlite3_pcache type is opaque.  It is implemented by
7314** the pluggable module.  The SQLite core has no knowledge of
7315** its size or internal structure and never deals with the
7316** sqlite3_pcache object except by holding and passing pointers
7317** to the object.
7318**
7319** See [sqlite3_pcache_methods2] for additional information.
7320*/
7321typedef struct sqlite3_pcache sqlite3_pcache;
7322
7323/*
7324** CAPI3REF: Custom Page Cache Object
7325**
7326** The sqlite3_pcache_page object represents a single page in the
7327** page cache.  The page cache will allocate instances of this
7328** object.  Various methods of the page cache use pointers to instances
7329** of this object as parameters or as their return value.
7330**
7331** See [sqlite3_pcache_methods2] for additional information.
7332*/
7333typedef struct sqlite3_pcache_page sqlite3_pcache_page;
7334struct sqlite3_pcache_page {
7335  void *pBuf;        /* The content of the page */
7336  void *pExtra;      /* Extra information associated with the page */
7337};
7338
7339/*
7340** CAPI3REF: Application Defined Page Cache.
7341** KEYWORDS: {page cache}
7342**
7343** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
7344** register an alternative page cache implementation by passing in an
7345** instance of the sqlite3_pcache_methods2 structure.)^
7346** In many applications, most of the heap memory allocated by
7347** SQLite is used for the page cache.
7348** By implementing a
7349** custom page cache using this API, an application can better control
7350** the amount of memory consumed by SQLite, the way in which
7351** that memory is allocated and released, and the policies used to
7352** determine exactly which parts of a database file are cached and for
7353** how long.
7354**
7355** The alternative page cache mechanism is an
7356** extreme measure that is only needed by the most demanding applications.
7357** The built-in page cache is recommended for most uses.
7358**
7359** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
7360** internal buffer by SQLite within the call to [sqlite3_config].  Hence
7361** the application may discard the parameter after the call to
7362** [sqlite3_config()] returns.)^
7363**
7364** [[the xInit() page cache method]]
7365** ^(The xInit() method is called once for each effective
7366** call to [sqlite3_initialize()])^
7367** (usually only once during the lifetime of the process). ^(The xInit()
7368** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
7369** The intent of the xInit() method is to set up global data structures
7370** required by the custom page cache implementation.
7371** ^(If the xInit() method is NULL, then the
7372** built-in default page cache is used instead of the application defined
7373** page cache.)^
7374**
7375** [[the xShutdown() page cache method]]
7376** ^The xShutdown() method is called by [sqlite3_shutdown()].
7377** It can be used to clean up
7378** any outstanding resources before process shutdown, if required.
7379** ^The xShutdown() method may be NULL.
7380**
7381** ^SQLite automatically serializes calls to the xInit method,
7382** so the xInit method need not be threadsafe.  ^The
7383** xShutdown method is only called from [sqlite3_shutdown()] so it does
7384** not need to be threadsafe either.  All other methods must be threadsafe
7385** in multithreaded applications.
7386**
7387** ^SQLite will never invoke xInit() more than once without an intervening
7388** call to xShutdown().
7389**
7390** [[the xCreate() page cache methods]]
7391** ^SQLite invokes the xCreate() method to construct a new cache instance.
7392** SQLite will typically create one cache instance for each open database file,
7393** though this is not guaranteed. ^The
7394** first parameter, szPage, is the size in bytes of the pages that must
7395** be allocated by the cache.  ^szPage will always a power of two.  ^The
7396** second parameter szExtra is a number of bytes of extra storage
7397** associated with each page cache entry.  ^The szExtra parameter will
7398** a number less than 250.  SQLite will use the
7399** extra szExtra bytes on each page to store metadata about the underlying
7400** database page on disk.  The value passed into szExtra depends
7401** on the SQLite version, the target platform, and how SQLite was compiled.
7402** ^The third argument to xCreate(), bPurgeable, is true if the cache being
7403** created will be used to cache database pages of a file stored on disk, or
7404** false if it is used for an in-memory database. The cache implementation
7405** does not have to do anything special based with the value of bPurgeable;
7406** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
7407** never invoke xUnpin() except to deliberately delete a page.
7408** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
7409** false will always have the "discard" flag set to true.
7410** ^Hence, a cache created with bPurgeable false will
7411** never contain any unpinned pages.
7412**
7413** [[the xCachesize() page cache method]]
7414** ^(The xCachesize() method may be called at any time by SQLite to set the
7415** suggested maximum cache-size (number of pages stored by) the cache
7416** instance passed as the first argument. This is the value configured using
7417** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
7418** parameter, the implementation is not required to do anything with this
7419** value; it is advisory only.
7420**
7421** [[the xPagecount() page cache methods]]
7422** The xPagecount() method must return the number of pages currently
7423** stored in the cache, both pinned and unpinned.
7424**
7425** [[the xFetch() page cache methods]]
7426** The xFetch() method locates a page in the cache and returns a pointer to
7427** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
7428** The pBuf element of the returned sqlite3_pcache_page object will be a
7429** pointer to a buffer of szPage bytes used to store the content of a
7430** single database page.  The pExtra element of sqlite3_pcache_page will be
7431** a pointer to the szExtra bytes of extra storage that SQLite has requested
7432** for each entry in the page cache.
7433**
7434** The page to be fetched is determined by the key. ^The minimum key value
7435** is 1.  After it has been retrieved using xFetch, the page is considered
7436** to be "pinned".
7437**
7438** If the requested page is already in the page cache, then the page cache
7439** implementation must return a pointer to the page buffer with its content
7440** intact.  If the requested page is not already in the cache, then the
7441** cache implementation should use the value of the createFlag
7442** parameter to help it determined what action to take:
7443**
7444** <table border=1 width=85% align=center>
7445** <tr><th> createFlag <th> Behavior when page is not already in cache
7446** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
7447** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
7448**                 Otherwise return NULL.
7449** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
7450**                 NULL if allocating a new page is effectively impossible.
7451** </table>
7452**
7453** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
7454** will only use a createFlag of 2 after a prior call with a createFlag of 1
7455** failed.)^  In between the to xFetch() calls, SQLite may
7456** attempt to unpin one or more cache pages by spilling the content of
7457** pinned pages to disk and synching the operating system disk cache.
7458**
7459** [[the xUnpin() page cache method]]
7460** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
7461** as its second argument.  If the third parameter, discard, is non-zero,
7462** then the page must be evicted from the cache.
7463** ^If the discard parameter is
7464** zero, then the page may be discarded or retained at the discretion of
7465** page cache implementation. ^The page cache implementation
7466** may choose to evict unpinned pages at any time.
7467**
7468** The cache must not perform any reference counting. A single
7469** call to xUnpin() unpins the page regardless of the number of prior calls
7470** to xFetch().
7471**
7472** [[the xRekey() page cache methods]]
7473** The xRekey() method is used to change the key value associated with the
7474** page passed as the second argument. If the cache
7475** previously contains an entry associated with newKey, it must be
7476** discarded. ^Any prior cache entry associated with newKey is guaranteed not
7477** to be pinned.
7478**
7479** When SQLite calls the xTruncate() method, the cache must discard all
7480** existing cache entries with page numbers (keys) greater than or equal
7481** to the value of the iLimit parameter passed to xTruncate(). If any
7482** of these pages are pinned, they are implicitly unpinned, meaning that
7483** they can be safely discarded.
7484**
7485** [[the xDestroy() page cache method]]
7486** ^The xDestroy() method is used to delete a cache allocated by xCreate().
7487** All resources associated with the specified cache should be freed. ^After
7488** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
7489** handle invalid, and will not use it with any other sqlite3_pcache_methods2
7490** functions.
7491**
7492** [[the xShrink() page cache method]]
7493** ^SQLite invokes the xShrink() method when it wants the page cache to
7494** free up as much of heap memory as possible.  The page cache implementation
7495** is not obligated to free any memory, but well-behaved implementations should
7496** do their best.
7497*/
7498typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
7499struct sqlite3_pcache_methods2 {
7500  int iVersion;
7501  void *pArg;
7502  int (*xInit)(void*);
7503  void (*xShutdown)(void*);
7504  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
7505  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7506  int (*xPagecount)(sqlite3_pcache*);
7507  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7508  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
7509  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
7510      unsigned oldKey, unsigned newKey);
7511  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7512  void (*xDestroy)(sqlite3_pcache*);
7513  void (*xShrink)(sqlite3_pcache*);
7514};
7515
7516/*
7517** This is the obsolete pcache_methods object that has now been replaced
7518** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
7519** retained in the header file for backwards compatibility only.
7520*/
7521typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
7522struct sqlite3_pcache_methods {
7523  void *pArg;
7524  int (*xInit)(void*);
7525  void (*xShutdown)(void*);
7526  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7527  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7528  int (*xPagecount)(sqlite3_pcache*);
7529  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7530  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7531  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7532  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7533  void (*xDestroy)(sqlite3_pcache*);
7534};
7535
7536
7537/*
7538** CAPI3REF: Online Backup Object
7539**
7540** The sqlite3_backup object records state information about an ongoing
7541** online backup operation.  ^The sqlite3_backup object is created by
7542** a call to [sqlite3_backup_init()] and is destroyed by a call to
7543** [sqlite3_backup_finish()].
7544**
7545** See Also: [Using the SQLite Online Backup API]
7546*/
7547typedef struct sqlite3_backup sqlite3_backup;
7548
7549/*
7550** CAPI3REF: Online Backup API.
7551**
7552** The backup API copies the content of one database into another.
7553** It is useful either for creating backups of databases or
7554** for copying in-memory databases to or from persistent files.
7555**
7556** See Also: [Using the SQLite Online Backup API]
7557**
7558** ^SQLite holds a write transaction open on the destination database file
7559** for the duration of the backup operation.
7560** ^The source database is read-locked only while it is being read;
7561** it is not locked continuously for the entire backup operation.
7562** ^Thus, the backup may be performed on a live source database without
7563** preventing other database connections from
7564** reading or writing to the source database while the backup is underway.
7565**
7566** ^(To perform a backup operation:
7567**   <ol>
7568**     <li><b>sqlite3_backup_init()</b> is called once to initialize the
7569**         backup,
7570**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
7571**         the data between the two databases, and finally
7572**     <li><b>sqlite3_backup_finish()</b> is called to release all resources
7573**         associated with the backup operation.
7574**   </ol>)^
7575** There should be exactly one call to sqlite3_backup_finish() for each
7576** successful call to sqlite3_backup_init().
7577**
7578** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
7579**
7580** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
7581** [database connection] associated with the destination database
7582** and the database name, respectively.
7583** ^The database name is "main" for the main database, "temp" for the
7584** temporary database, or the name specified after the AS keyword in
7585** an [ATTACH] statement for an attached database.
7586** ^The S and M arguments passed to
7587** sqlite3_backup_init(D,N,S,M) identify the [database connection]
7588** and database name of the source database, respectively.
7589** ^The source and destination [database connections] (parameters S and D)
7590** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7591** an error.
7592**
7593** ^A call to sqlite3_backup_init() will fail, returning NULL, if
7594** there is already a read or read-write transaction open on the
7595** destination database.
7596**
7597** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7598** returned and an error code and error message are stored in the
7599** destination [database connection] D.
7600** ^The error code and message for the failed call to sqlite3_backup_init()
7601** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
7602** [sqlite3_errmsg16()] functions.
7603** ^A successful call to sqlite3_backup_init() returns a pointer to an
7604** [sqlite3_backup] object.
7605** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
7606** sqlite3_backup_finish() functions to perform the specified backup
7607** operation.
7608**
7609** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
7610**
7611** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
7612** the source and destination databases specified by [sqlite3_backup] object B.
7613** ^If N is negative, all remaining source pages are copied.
7614** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
7615** are still more pages to be copied, then the function returns [SQLITE_OK].
7616** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
7617** from source to destination, then it returns [SQLITE_DONE].
7618** ^If an error occurs while running sqlite3_backup_step(B,N),
7619** then an [error code] is returned. ^As well as [SQLITE_OK] and
7620** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7621** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7622** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7623**
7624** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7625** <ol>
7626** <li> the destination database was opened read-only, or
7627** <li> the destination database is using write-ahead-log journaling
7628** and the destination and source page sizes differ, or
7629** <li> the destination database is an in-memory database and the
7630** destination and source page sizes differ.
7631** </ol>)^
7632**
7633** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7634** the [sqlite3_busy_handler | busy-handler function]
7635** is invoked (if one is specified). ^If the
7636** busy-handler returns non-zero before the lock is available, then
7637** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7638** sqlite3_backup_step() can be retried later. ^If the source
7639** [database connection]
7640** is being used to write to the source database when sqlite3_backup_step()
7641** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7642** case the call to sqlite3_backup_step() can be retried later on. ^(If
7643** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7644** [SQLITE_READONLY] is returned, then
7645** there is no point in retrying the call to sqlite3_backup_step(). These
7646** errors are considered fatal.)^  The application must accept
7647** that the backup operation has failed and pass the backup operation handle
7648** to the sqlite3_backup_finish() to release associated resources.
7649**
7650** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7651** on the destination file. ^The exclusive lock is not released until either
7652** sqlite3_backup_finish() is called or the backup operation is complete
7653** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
7654** sqlite3_backup_step() obtains a [shared lock] on the source database that
7655** lasts for the duration of the sqlite3_backup_step() call.
7656** ^Because the source database is not locked between calls to
7657** sqlite3_backup_step(), the source database may be modified mid-way
7658** through the backup process.  ^If the source database is modified by an
7659** external process or via a database connection other than the one being
7660** used by the backup operation, then the backup will be automatically
7661** restarted by the next call to sqlite3_backup_step(). ^If the source
7662** database is modified by the using the same database connection as is used
7663** by the backup operation, then the backup database is automatically
7664** updated at the same time.
7665**
7666** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7667**
7668** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
7669** application wishes to abandon the backup operation, the application
7670** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7671** ^The sqlite3_backup_finish() interfaces releases all
7672** resources associated with the [sqlite3_backup] object.
7673** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7674** active write-transaction on the destination database is rolled back.
7675** The [sqlite3_backup] object is invalid
7676** and may not be used following a call to sqlite3_backup_finish().
7677**
7678** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7679** sqlite3_backup_step() errors occurred, regardless or whether or not
7680** sqlite3_backup_step() completed.
7681** ^If an out-of-memory condition or IO error occurred during any prior
7682** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7683** sqlite3_backup_finish() returns the corresponding [error code].
7684**
7685** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7686** is not a permanent error and does not affect the return value of
7687** sqlite3_backup_finish().
7688**
7689** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
7690** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7691**
7692** ^The sqlite3_backup_remaining() routine returns the number of pages still
7693** to be backed up at the conclusion of the most recent sqlite3_backup_step().
7694** ^The sqlite3_backup_pagecount() routine returns the total number of pages
7695** in the source database at the conclusion of the most recent
7696** sqlite3_backup_step().
7697** ^(The values returned by these functions are only updated by
7698** sqlite3_backup_step(). If the source database is modified in a way that
7699** changes the size of the source database or the number of pages remaining,
7700** those changes are not reflected in the output of sqlite3_backup_pagecount()
7701** and sqlite3_backup_remaining() until after the next
7702** sqlite3_backup_step().)^
7703**
7704** <b>Concurrent Usage of Database Handles</b>
7705**
7706** ^The source [database connection] may be used by the application for other
7707** purposes while a backup operation is underway or being initialized.
7708** ^If SQLite is compiled and configured to support threadsafe database
7709** connections, then the source database connection may be used concurrently
7710** from within other threads.
7711**
7712** However, the application must guarantee that the destination
7713** [database connection] is not passed to any other API (by any thread) after
7714** sqlite3_backup_init() is called and before the corresponding call to
7715** sqlite3_backup_finish().  SQLite does not currently check to see
7716** if the application incorrectly accesses the destination [database connection]
7717** and so no error code is reported, but the operations may malfunction
7718** nevertheless.  Use of the destination database connection while a
7719** backup is in progress might also also cause a mutex deadlock.
7720**
7721** If running in [shared cache mode], the application must
7722** guarantee that the shared cache used by the destination database
7723** is not accessed while the backup is running. In practice this means
7724** that the application must guarantee that the disk file being
7725** backed up to is not accessed by any connection within the process,
7726** not just the specific connection that was passed to sqlite3_backup_init().
7727**
7728** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7729** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7730** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7731** APIs are not strictly speaking threadsafe. If they are invoked at the
7732** same time as another thread is invoking sqlite3_backup_step() it is
7733** possible that they return invalid values.
7734*/
7735SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
7736  sqlite3 *pDest,                        /* Destination database handle */
7737  const char *zDestName,                 /* Destination database name */
7738  sqlite3 *pSource,                      /* Source database handle */
7739  const char *zSourceName                /* Source database name */
7740);
7741SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage);
7742SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p);
7743SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p);
7744SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p);
7745
7746/*
7747** CAPI3REF: Unlock Notification
7748** METHOD: sqlite3
7749**
7750** ^When running in shared-cache mode, a database operation may fail with
7751** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7752** individual tables within the shared-cache cannot be obtained. See
7753** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7754** ^This API may be used to register a callback that SQLite will invoke
7755** when the connection currently holding the required lock relinquishes it.
7756** ^This API is only available if the library was compiled with the
7757** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7758**
7759** See Also: [Using the SQLite Unlock Notification Feature].
7760**
7761** ^Shared-cache locks are released when a database connection concludes
7762** its current transaction, either by committing it or rolling it back.
7763**
7764** ^When a connection (known as the blocked connection) fails to obtain a
7765** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7766** identity of the database connection (the blocking connection) that
7767** has locked the required resource is stored internally. ^After an
7768** application receives an SQLITE_LOCKED error, it may call the
7769** sqlite3_unlock_notify() method with the blocked connection handle as
7770** the first argument to register for a callback that will be invoked
7771** when the blocking connections current transaction is concluded. ^The
7772** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7773** call that concludes the blocking connections transaction.
7774**
7775** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7776** there is a chance that the blocking connection will have already
7777** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7778** If this happens, then the specified callback is invoked immediately,
7779** from within the call to sqlite3_unlock_notify().)^
7780**
7781** ^If the blocked connection is attempting to obtain a write-lock on a
7782** shared-cache table, and more than one other connection currently holds
7783** a read-lock on the same table, then SQLite arbitrarily selects one of
7784** the other connections to use as the blocking connection.
7785**
7786** ^(There may be at most one unlock-notify callback registered by a
7787** blocked connection. If sqlite3_unlock_notify() is called when the
7788** blocked connection already has a registered unlock-notify callback,
7789** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7790** called with a NULL pointer as its second argument, then any existing
7791** unlock-notify callback is canceled. ^The blocked connections
7792** unlock-notify callback may also be canceled by closing the blocked
7793** connection using [sqlite3_close()].
7794**
7795** The unlock-notify callback is not reentrant. If an application invokes
7796** any sqlite3_xxx API functions from within an unlock-notify callback, a
7797** crash or deadlock may be the result.
7798**
7799** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7800** returns SQLITE_OK.
7801**
7802** <b>Callback Invocation Details</b>
7803**
7804** When an unlock-notify callback is registered, the application provides a
7805** single void* pointer that is passed to the callback when it is invoked.
7806** However, the signature of the callback function allows SQLite to pass
7807** it an array of void* context pointers. The first argument passed to
7808** an unlock-notify callback is a pointer to an array of void* pointers,
7809** and the second is the number of entries in the array.
7810**
7811** When a blocking connections transaction is concluded, there may be
7812** more than one blocked connection that has registered for an unlock-notify
7813** callback. ^If two or more such blocked connections have specified the
7814** same callback function, then instead of invoking the callback function
7815** multiple times, it is invoked once with the set of void* context pointers
7816** specified by the blocked connections bundled together into an array.
7817** This gives the application an opportunity to prioritize any actions
7818** related to the set of unblocked database connections.
7819**
7820** <b>Deadlock Detection</b>
7821**
7822** Assuming that after registering for an unlock-notify callback a
7823** database waits for the callback to be issued before taking any further
7824** action (a reasonable assumption), then using this API may cause the
7825** application to deadlock. For example, if connection X is waiting for
7826** connection Y's transaction to be concluded, and similarly connection
7827** Y is waiting on connection X's transaction, then neither connection
7828** will proceed and the system may remain deadlocked indefinitely.
7829**
7830** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7831** detection. ^If a given call to sqlite3_unlock_notify() would put the
7832** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7833** unlock-notify callback is registered. The system is said to be in
7834** a deadlocked state if connection A has registered for an unlock-notify
7835** callback on the conclusion of connection B's transaction, and connection
7836** B has itself registered for an unlock-notify callback when connection
7837** A's transaction is concluded. ^Indirect deadlock is also detected, so
7838** the system is also considered to be deadlocked if connection B has
7839** registered for an unlock-notify callback on the conclusion of connection
7840** C's transaction, where connection C is waiting on connection A. ^Any
7841** number of levels of indirection are allowed.
7842**
7843** <b>The "DROP TABLE" Exception</b>
7844**
7845** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7846** always appropriate to call sqlite3_unlock_notify(). There is however,
7847** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7848** SQLite checks if there are any currently executing SELECT statements
7849** that belong to the same connection. If there are, SQLITE_LOCKED is
7850** returned. In this case there is no "blocking connection", so invoking
7851** sqlite3_unlock_notify() results in the unlock-notify callback being
7852** invoked immediately. If the application then re-attempts the "DROP TABLE"
7853** or "DROP INDEX" query, an infinite loop might be the result.
7854**
7855** One way around this problem is to check the extended error code returned
7856** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7857** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7858** the special "DROP TABLE/INDEX" case, the extended error code is just
7859** SQLITE_LOCKED.)^
7860*/
7861SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
7862  sqlite3 *pBlocked,                          /* Waiting connection */
7863  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
7864  void *pNotifyArg                            /* Argument to pass to xNotify */
7865);
7866
7867
7868/*
7869** CAPI3REF: String Comparison
7870**
7871** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7872** and extensions to compare the contents of two buffers containing UTF-8
7873** strings in a case-independent fashion, using the same definition of "case
7874** independence" that SQLite uses internally when comparing identifiers.
7875*/
7876SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *, const char *);
7877SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *, const char *, int);
7878
7879/*
7880** CAPI3REF: String Globbing
7881*
7882** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
7883** string X matches the [GLOB] pattern P.
7884** ^The definition of [GLOB] pattern matching used in
7885** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
7886** SQL dialect understood by SQLite.  ^The [sqlite3_strglob(P,X)] function
7887** is case sensitive.
7888**
7889** Note that this routine returns zero on a match and non-zero if the strings
7890** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7891**
7892** See also: [sqlite3_strlike()].
7893*/
7894SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlob, const char *zStr);
7895
7896/*
7897** CAPI3REF: String LIKE Matching
7898*
7899** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
7900** string X matches the [LIKE] pattern P with escape character E.
7901** ^The definition of [LIKE] pattern matching used in
7902** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
7903** operator in the SQL dialect understood by SQLite.  ^For "X LIKE P" without
7904** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
7905** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
7906** insensitive - equivalent upper and lower case ASCII characters match
7907** one another.
7908**
7909** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
7910** only ASCII characters are case folded.
7911**
7912** Note that this routine returns zero on a match and non-zero if the strings
7913** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7914**
7915** See also: [sqlite3_strglob()].
7916*/
7917SQLITE_API int SQLITE_STDCALL sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
7918
7919/*
7920** CAPI3REF: Error Logging Interface
7921**
7922** ^The [sqlite3_log()] interface writes a message into the [error log]
7923** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7924** ^If logging is enabled, the zFormat string and subsequent arguments are
7925** used with [sqlite3_snprintf()] to generate the final output string.
7926**
7927** The sqlite3_log() interface is intended for use by extensions such as
7928** virtual tables, collating functions, and SQL functions.  While there is
7929** nothing to prevent an application from calling sqlite3_log(), doing so
7930** is considered bad form.
7931**
7932** The zFormat string must not be NULL.
7933**
7934** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7935** will not use dynamically allocated memory.  The log message is stored in
7936** a fixed-length buffer on the stack.  If the log message is longer than
7937** a few hundred characters, it will be truncated to the length of the
7938** buffer.
7939*/
7940SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...);
7941
7942/*
7943** CAPI3REF: Write-Ahead Log Commit Hook
7944** METHOD: sqlite3
7945**
7946** ^The [sqlite3_wal_hook()] function is used to register a callback that
7947** is invoked each time data is committed to a database in wal mode.
7948**
7949** ^(The callback is invoked by SQLite after the commit has taken place and
7950** the associated write-lock on the database released)^, so the implementation
7951** may read, write or [checkpoint] the database as required.
7952**
7953** ^The first parameter passed to the callback function when it is invoked
7954** is a copy of the third parameter passed to sqlite3_wal_hook() when
7955** registering the callback. ^The second is a copy of the database handle.
7956** ^The third parameter is the name of the database that was written to -
7957** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7958** is the number of pages currently in the write-ahead log file,
7959** including those that were just committed.
7960**
7961** The callback function should normally return [SQLITE_OK].  ^If an error
7962** code is returned, that error will propagate back up through the
7963** SQLite code base to cause the statement that provoked the callback
7964** to report an error, though the commit will have still occurred. If the
7965** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7966** that does not correspond to any valid SQLite error code, the results
7967** are undefined.
7968**
7969** A single database handle may have at most a single write-ahead log callback
7970** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7971** previously registered write-ahead log callback. ^Note that the
7972** [sqlite3_wal_autocheckpoint()] interface and the
7973** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7974** overwrite any prior [sqlite3_wal_hook()] settings.
7975*/
7976SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
7977  sqlite3*,
7978  int(*)(void *,sqlite3*,const char*,int),
7979  void*
7980);
7981
7982/*
7983** CAPI3REF: Configure an auto-checkpoint
7984** METHOD: sqlite3
7985**
7986** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7987** [sqlite3_wal_hook()] that causes any database on [database connection] D
7988** to automatically [checkpoint]
7989** after committing a transaction if there are N or
7990** more frames in the [write-ahead log] file.  ^Passing zero or
7991** a negative value as the nFrame parameter disables automatic
7992** checkpoints entirely.
7993**
7994** ^The callback registered by this function replaces any existing callback
7995** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
7996** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7997** configured by this function.
7998**
7999** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
8000** from SQL.
8001**
8002** ^Checkpoints initiated by this mechanism are
8003** [sqlite3_wal_checkpoint_v2|PASSIVE].
8004**
8005** ^Every new [database connection] defaults to having the auto-checkpoint
8006** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
8007** pages.  The use of this interface
8008** is only necessary if the default setting is found to be suboptimal
8009** for a particular application.
8010*/
8011SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
8012
8013/*
8014** CAPI3REF: Checkpoint a database
8015** METHOD: sqlite3
8016**
8017** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
8018** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
8019**
8020** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
8021** [write-ahead log] for database X on [database connection] D to be
8022** transferred into the database file and for the write-ahead log to
8023** be reset.  See the [checkpointing] documentation for addition
8024** information.
8025**
8026** This interface used to be the only way to cause a checkpoint to
8027** occur.  But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
8028** interface was added.  This interface is retained for backwards
8029** compatibility and as a convenience for applications that need to manually
8030** start a callback but which do not need the full power (and corresponding
8031** complication) of [sqlite3_wal_checkpoint_v2()].
8032*/
8033SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
8034
8035/*
8036** CAPI3REF: Checkpoint a database
8037** METHOD: sqlite3
8038**
8039** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
8040** operation on database X of [database connection] D in mode M.  Status
8041** information is written back into integers pointed to by L and C.)^
8042** ^(The M parameter must be a valid [checkpoint mode]:)^
8043**
8044** <dl>
8045** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
8046**   ^Checkpoint as many frames as possible without waiting for any database
8047**   readers or writers to finish, then sync the database file if all frames
8048**   in the log were checkpointed. ^The [busy-handler callback]
8049**   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
8050**   ^On the other hand, passive mode might leave the checkpoint unfinished
8051**   if there are concurrent readers or writers.
8052**
8053** <dt>SQLITE_CHECKPOINT_FULL<dd>
8054**   ^This mode blocks (it invokes the
8055**   [sqlite3_busy_handler|busy-handler callback]) until there is no
8056**   database writer and all readers are reading from the most recent database
8057**   snapshot. ^It then checkpoints all frames in the log file and syncs the
8058**   database file. ^This mode blocks new database writers while it is pending,
8059**   but new database readers are allowed to continue unimpeded.
8060**
8061** <dt>SQLITE_CHECKPOINT_RESTART<dd>
8062**   ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
8063**   that after checkpointing the log file it blocks (calls the
8064**   [busy-handler callback])
8065**   until all readers are reading from the database file only. ^This ensures
8066**   that the next writer will restart the log file from the beginning.
8067**   ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
8068**   database writer attempts while it is pending, but does not impede readers.
8069**
8070** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
8071**   ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
8072**   addition that it also truncates the log file to zero bytes just prior
8073**   to a successful return.
8074** </dl>
8075**
8076** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
8077** the log file or to -1 if the checkpoint could not run because
8078** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
8079** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
8080** log file (including any that were already checkpointed before the function
8081** was called) or to -1 if the checkpoint could not run due to an error or
8082** because the database is not in WAL mode. ^Note that upon successful
8083** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
8084** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
8085**
8086** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
8087** any other process is running a checkpoint operation at the same time, the
8088** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
8089** busy-handler configured, it will not be invoked in this case.
8090**
8091** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
8092** exclusive "writer" lock on the database file. ^If the writer lock cannot be
8093** obtained immediately, and a busy-handler is configured, it is invoked and
8094** the writer lock retried until either the busy-handler returns 0 or the lock
8095** is successfully obtained. ^The busy-handler is also invoked while waiting for
8096** database readers as described above. ^If the busy-handler returns 0 before
8097** the writer lock is obtained or while waiting for database readers, the
8098** checkpoint operation proceeds from that point in the same way as
8099** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
8100** without blocking any further. ^SQLITE_BUSY is returned in this case.
8101**
8102** ^If parameter zDb is NULL or points to a zero length string, then the
8103** specified operation is attempted on all WAL databases [attached] to
8104** [database connection] db.  In this case the
8105** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
8106** an SQLITE_BUSY error is encountered when processing one or more of the
8107** attached WAL databases, the operation is still attempted on any remaining
8108** attached databases and SQLITE_BUSY is returned at the end. ^If any other
8109** error occurs while processing an attached database, processing is abandoned
8110** and the error code is returned to the caller immediately. ^If no error
8111** (SQLITE_BUSY or otherwise) is encountered while processing the attached
8112** databases, SQLITE_OK is returned.
8113**
8114** ^If database zDb is the name of an attached database that is not in WAL
8115** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
8116** zDb is not NULL (or a zero length string) and is not the name of any
8117** attached database, SQLITE_ERROR is returned to the caller.
8118**
8119** ^Unless it returns SQLITE_MISUSE,
8120** the sqlite3_wal_checkpoint_v2() interface
8121** sets the error information that is queried by
8122** [sqlite3_errcode()] and [sqlite3_errmsg()].
8123**
8124** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
8125** from SQL.
8126*/
8127SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
8128  sqlite3 *db,                    /* Database handle */
8129  const char *zDb,                /* Name of attached database (or NULL) */
8130  int eMode,                      /* SQLITE_CHECKPOINT_* value */
8131  int *pnLog,                     /* OUT: Size of WAL log in frames */
8132  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
8133);
8134
8135/*
8136** CAPI3REF: Checkpoint Mode Values
8137** KEYWORDS: {checkpoint mode}
8138**
8139** These constants define all valid values for the "checkpoint mode" passed
8140** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
8141** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
8142** meaning of each of these checkpoint modes.
8143*/
8144#define SQLITE_CHECKPOINT_PASSIVE  0  /* Do as much as possible w/o blocking */
8145#define SQLITE_CHECKPOINT_FULL     1  /* Wait for writers, then checkpoint */
8146#define SQLITE_CHECKPOINT_RESTART  2  /* Like FULL but wait for for readers */
8147#define SQLITE_CHECKPOINT_TRUNCATE 3  /* Like RESTART but also truncate WAL */
8148
8149/*
8150** CAPI3REF: Virtual Table Interface Configuration
8151**
8152** This function may be called by either the [xConnect] or [xCreate] method
8153** of a [virtual table] implementation to configure
8154** various facets of the virtual table interface.
8155**
8156** If this interface is invoked outside the context of an xConnect or
8157** xCreate virtual table method then the behavior is undefined.
8158**
8159** At present, there is only one option that may be configured using
8160** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
8161** may be added in the future.
8162*/
8163SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3*, int op, ...);
8164
8165/*
8166** CAPI3REF: Virtual Table Configuration Options
8167**
8168** These macros define the various options to the
8169** [sqlite3_vtab_config()] interface that [virtual table] implementations
8170** can use to customize and optimize their behavior.
8171**
8172** <dl>
8173** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
8174** <dd>Calls of the form
8175** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
8176** where X is an integer.  If X is zero, then the [virtual table] whose
8177** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
8178** support constraints.  In this configuration (which is the default) if
8179** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
8180** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
8181** specified as part of the users SQL statement, regardless of the actual
8182** ON CONFLICT mode specified.
8183**
8184** If X is non-zero, then the virtual table implementation guarantees
8185** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
8186** any modifications to internal or persistent data structures have been made.
8187** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
8188** is able to roll back a statement or database transaction, and abandon
8189** or continue processing the current SQL statement as appropriate.
8190** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
8191** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
8192** had been ABORT.
8193**
8194** Virtual table implementations that are required to handle OR REPLACE
8195** must do so within the [xUpdate] method. If a call to the
8196** [sqlite3_vtab_on_conflict()] function indicates that the current ON
8197** CONFLICT policy is REPLACE, the virtual table implementation should
8198** silently replace the appropriate rows within the xUpdate callback and
8199** return SQLITE_OK. Or, if this is not possible, it may return
8200** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
8201** constraint handling.
8202** </dl>
8203*/
8204#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
8205
8206/*
8207** CAPI3REF: Determine The Virtual Table Conflict Policy
8208**
8209** This function may only be called from within a call to the [xUpdate] method
8210** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
8211** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
8212** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
8213** of the SQL statement that triggered the call to the [xUpdate] method of the
8214** [virtual table].
8215*/
8216SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *);
8217
8218/*
8219** CAPI3REF: Conflict resolution modes
8220** KEYWORDS: {conflict resolution mode}
8221**
8222** These constants are returned by [sqlite3_vtab_on_conflict()] to
8223** inform a [virtual table] implementation what the [ON CONFLICT] mode
8224** is for the SQL statement being evaluated.
8225**
8226** Note that the [SQLITE_IGNORE] constant is also used as a potential
8227** return value from the [sqlite3_set_authorizer()] callback and that
8228** [SQLITE_ABORT] is also a [result code].
8229*/
8230#define SQLITE_ROLLBACK 1
8231/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
8232#define SQLITE_FAIL     3
8233/* #define SQLITE_ABORT 4  // Also an error code */
8234#define SQLITE_REPLACE  5
8235
8236/*
8237** CAPI3REF: Prepared Statement Scan Status Opcodes
8238** KEYWORDS: {scanstatus options}
8239**
8240** The following constants can be used for the T parameter to the
8241** [sqlite3_stmt_scanstatus(S,X,T,V)] interface.  Each constant designates a
8242** different metric for sqlite3_stmt_scanstatus() to return.
8243**
8244** When the value returned to V is a string, space to hold that string is
8245** managed by the prepared statement S and will be automatically freed when
8246** S is finalized.
8247**
8248** <dl>
8249** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
8250** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
8251** set to the total number of times that the X-th loop has run.</dd>
8252**
8253** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
8254** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
8255** to the total number of rows examined by all iterations of the X-th loop.</dd>
8256**
8257** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
8258** <dd>^The "double" variable pointed to by the T parameter will be set to the
8259** query planner's estimate for the average number of rows output from each
8260** iteration of the X-th loop.  If the query planner's estimates was accurate,
8261** then this value will approximate the quotient NVISIT/NLOOP and the
8262** product of this value for all prior loops with the same SELECTID will
8263** be the NLOOP value for the current loop.
8264**
8265** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
8266** <dd>^The "const char *" variable pointed to by the T parameter will be set
8267** to a zero-terminated UTF-8 string containing the name of the index or table
8268** used for the X-th loop.
8269**
8270** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
8271** <dd>^The "const char *" variable pointed to by the T parameter will be set
8272** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
8273** description for the X-th loop.
8274**
8275** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
8276** <dd>^The "int" variable pointed to by the T parameter will be set to the
8277** "select-id" for the X-th loop.  The select-id identifies which query or
8278** subquery the loop is part of.  The main query has a select-id of zero.
8279** The select-id is the same value as is output in the first column
8280** of an [EXPLAIN QUERY PLAN] query.
8281** </dl>
8282*/
8283#define SQLITE_SCANSTAT_NLOOP    0
8284#define SQLITE_SCANSTAT_NVISIT   1
8285#define SQLITE_SCANSTAT_EST      2
8286#define SQLITE_SCANSTAT_NAME     3
8287#define SQLITE_SCANSTAT_EXPLAIN  4
8288#define SQLITE_SCANSTAT_SELECTID 5
8289
8290/*
8291** CAPI3REF: Prepared Statement Scan Status
8292** METHOD: sqlite3_stmt
8293**
8294** This interface returns information about the predicted and measured
8295** performance for pStmt.  Advanced applications can use this
8296** interface to compare the predicted and the measured performance and
8297** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
8298**
8299** Since this interface is expected to be rarely used, it is only
8300** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
8301** compile-time option.
8302**
8303** The "iScanStatusOp" parameter determines which status information to return.
8304** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
8305** of this interface is undefined.
8306** ^The requested measurement is written into a variable pointed to by
8307** the "pOut" parameter.
8308** Parameter "idx" identifies the specific loop to retrieve statistics for.
8309** Loops are numbered starting from zero. ^If idx is out of range - less than
8310** zero or greater than or equal to the total number of loops used to implement
8311** the statement - a non-zero value is returned and the variable that pOut
8312** points to is unchanged.
8313**
8314** ^Statistics might not be available for all loops in all statements. ^In cases
8315** where there exist loops with no available statistics, this function behaves
8316** as if the loop did not exist - it returns non-zero and leave the variable
8317** that pOut points to unchanged.
8318**
8319** See also: [sqlite3_stmt_scanstatus_reset()]
8320*/
8321SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
8322  sqlite3_stmt *pStmt,      /* Prepared statement for which info desired */
8323  int idx,                  /* Index of loop to report on */
8324  int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */
8325  void *pOut                /* Result written here */
8326);
8327
8328/*
8329** CAPI3REF: Zero Scan-Status Counters
8330** METHOD: sqlite3_stmt
8331**
8332** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
8333**
8334** This API is only available if the library is built with pre-processor
8335** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
8336*/
8337SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
8338
8339/*
8340** CAPI3REF: Flush caches to disk mid-transaction
8341**
8342** ^If a write-transaction is open on [database connection] D when the
8343** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
8344** pages in the pager-cache that are not currently in use are written out
8345** to disk. A dirty page may be in use if a database cursor created by an
8346** active SQL statement is reading from it, or if it is page 1 of a database
8347** file (page 1 is always "in use").  ^The [sqlite3_db_cacheflush(D)]
8348** interface flushes caches for all schemas - "main", "temp", and
8349** any [attached] databases.
8350**
8351** ^If this function needs to obtain extra database locks before dirty pages
8352** can be flushed to disk, it does so. ^If those locks cannot be obtained
8353** immediately and there is a busy-handler callback configured, it is invoked
8354** in the usual manner. ^If the required lock still cannot be obtained, then
8355** the database is skipped and an attempt made to flush any dirty pages
8356** belonging to the next (if any) database. ^If any databases are skipped
8357** because locks cannot be obtained, but no other error occurs, this
8358** function returns SQLITE_BUSY.
8359**
8360** ^If any other error occurs while flushing dirty pages to disk (for
8361** example an IO error or out-of-memory condition), then processing is
8362** abandoned and an SQLite [error code] is returned to the caller immediately.
8363**
8364** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
8365**
8366** ^This function does not set the database handle error code or message
8367** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
8368*/
8369SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3*);
8370
8371/*
8372** CAPI3REF: The pre-update hook.
8373**
8374** ^These interfaces are only available if SQLite is compiled using the
8375** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
8376**
8377** ^The [sqlite3_preupdate_hook()] interface registers a callback function
8378** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
8379** on a [rowid table].
8380** ^At most one preupdate hook may be registered at a time on a single
8381** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
8382** the previous setting.
8383** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
8384** with a NULL pointer as the second parameter.
8385** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
8386** the first parameter to callbacks.
8387**
8388** ^The preupdate hook only fires for changes to [rowid tables]; the preupdate
8389** hook is not invoked for changes to [virtual tables] or [WITHOUT ROWID]
8390** tables.
8391**
8392** ^The second parameter to the preupdate callback is a pointer to
8393** the [database connection] that registered the preupdate hook.
8394** ^The third parameter to the preupdate callback is one of the constants
8395** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
8396** kind of update operation that is about to occur.
8397** ^(The fourth parameter to the preupdate callback is the name of the
8398** database within the database connection that is being modified.  This
8399** will be "main" for the main database or "temp" for TEMP tables or
8400** the name given after the AS keyword in the [ATTACH] statement for attached
8401** databases.)^
8402** ^The fifth parameter to the preupdate callback is the name of the
8403** table that is being modified.
8404** ^The sixth parameter to the preupdate callback is the initial [rowid] of the
8405** row being changes for SQLITE_UPDATE and SQLITE_DELETE changes and is
8406** undefined for SQLITE_INSERT changes.
8407** ^The seventh parameter to the preupdate callback is the final [rowid] of
8408** the row being changed for SQLITE_UPDATE and SQLITE_INSERT changes and is
8409** undefined for SQLITE_DELETE changes.
8410**
8411** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
8412** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
8413** provide additional information about a preupdate event. These routines
8414** may only be called from within a preupdate callback.  Invoking any of
8415** these routines from outside of a preupdate callback or with a
8416** [database connection] pointer that is different from the one supplied
8417** to the preupdate callback results in undefined and probably undesirable
8418** behavior.
8419**
8420** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
8421** in the row that is being inserted, updated, or deleted.
8422**
8423** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
8424** a [protected sqlite3_value] that contains the value of the Nth column of
8425** the table row before it is updated.  The N parameter must be between 0
8426** and one less than the number of columns or the behavior will be
8427** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
8428** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
8429** behavior is undefined.  The [sqlite3_value] that P points to
8430** will be destroyed when the preupdate callback returns.
8431**
8432** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
8433** a [protected sqlite3_value] that contains the value of the Nth column of
8434** the table row after it is updated.  The N parameter must be between 0
8435** and one less than the number of columns or the behavior will be
8436** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
8437** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
8438** behavior is undefined.  The [sqlite3_value] that P points to
8439** will be destroyed when the preupdate callback returns.
8440**
8441** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
8442** callback was invoked as a result of a direct insert, update, or delete
8443** operation; or 1 for inserts, updates, or deletes invoked by top-level
8444** triggers; or 2 for changes resulting from triggers called by top-level
8445** triggers; and so forth.
8446**
8447** See also:  [sqlite3_update_hook()]
8448*/
8449SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL sqlite3_preupdate_hook(
8450  sqlite3 *db,
8451  void(*xPreUpdate)(
8452    void *pCtx,                   /* Copy of third arg to preupdate_hook() */
8453    sqlite3 *db,                  /* Database handle */
8454    int op,                       /* SQLITE_UPDATE, DELETE or INSERT */
8455    char const *zDb,              /* Database name */
8456    char const *zName,            /* Table name */
8457    sqlite3_int64 iKey1,          /* Rowid of row about to be deleted/updated */
8458    sqlite3_int64 iKey2           /* New rowid value (for a rowid UPDATE) */
8459  ),
8460  void*
8461);
8462SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
8463SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_count(sqlite3 *);
8464SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_depth(sqlite3 *);
8465SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
8466
8467/*
8468** CAPI3REF: Low-level system error code
8469**
8470** ^Attempt to return the underlying operating system error code or error
8471** number that caused the most recent I/O error or failure to open a file.
8472** The return value is OS-dependent.  For example, on unix systems, after
8473** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
8474** called to get back the underlying "errno" that caused the problem, such
8475** as ENOSPC, EAUTH, EISDIR, and so forth.
8476*/
8477SQLITE_API int SQLITE_STDCALL sqlite3_system_errno(sqlite3*);
8478
8479/*
8480** CAPI3REF: Database Snapshot
8481** KEYWORDS: {snapshot}
8482** EXPERIMENTAL
8483**
8484** An instance of the snapshot object records the state of a [WAL mode]
8485** database for some specific point in history.
8486**
8487** In [WAL mode], multiple [database connections] that are open on the
8488** same database file can each be reading a different historical version
8489** of the database file.  When a [database connection] begins a read
8490** transaction, that connection sees an unchanging copy of the database
8491** as it existed for the point in time when the transaction first started.
8492** Subsequent changes to the database from other connections are not seen
8493** by the reader until a new read transaction is started.
8494**
8495** The sqlite3_snapshot object records state information about an historical
8496** version of the database file so that it is possible to later open a new read
8497** transaction that sees that historical version of the database rather than
8498** the most recent version.
8499**
8500** The constructor for this object is [sqlite3_snapshot_get()].  The
8501** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
8502** to an historical snapshot (if possible).  The destructor for
8503** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
8504*/
8505typedef struct sqlite3_snapshot sqlite3_snapshot;
8506
8507/*
8508** CAPI3REF: Record A Database Snapshot
8509** EXPERIMENTAL
8510**
8511** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
8512** new [sqlite3_snapshot] object that records the current state of
8513** schema S in database connection D.  ^On success, the
8514** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
8515** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
8516** ^If schema S of [database connection] D is not a [WAL mode] database
8517** that is in a read transaction, then [sqlite3_snapshot_get(D,S,P)]
8518** leaves the *P value unchanged and returns an appropriate [error code].
8519**
8520** The [sqlite3_snapshot] object returned from a successful call to
8521** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
8522** to avoid a memory leak.
8523**
8524** The [sqlite3_snapshot_get()] interface is only available when the
8525** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8526*/
8527SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_get(
8528  sqlite3 *db,
8529  const char *zSchema,
8530  sqlite3_snapshot **ppSnapshot
8531);
8532
8533/*
8534** CAPI3REF: Start a read transaction on an historical snapshot
8535** EXPERIMENTAL
8536**
8537** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
8538** read transaction for schema S of
8539** [database connection] D such that the read transaction
8540** refers to historical [snapshot] P, rather than the most
8541** recent change to the database.
8542** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
8543** or an appropriate [error code] if it fails.
8544**
8545** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
8546** the first operation following the [BEGIN] that takes the schema S
8547** out of [autocommit mode].
8548** ^In other words, schema S must not currently be in
8549** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
8550** database connection D must be out of [autocommit mode].
8551** ^A [snapshot] will fail to open if it has been overwritten by a
8552** [checkpoint].
8553** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
8554** database connection D does not know that the database file for
8555** schema S is in [WAL mode].  A database connection might not know
8556** that the database file is in [WAL mode] if there has been no prior
8557** I/O on that database connection, or if the database entered [WAL mode]
8558** after the most recent I/O on the database connection.)^
8559** (Hint: Run "[PRAGMA application_id]" against a newly opened
8560** database connection in order to make it ready to use snapshots.)
8561**
8562** The [sqlite3_snapshot_open()] interface is only available when the
8563** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8564*/
8565SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_open(
8566  sqlite3 *db,
8567  const char *zSchema,
8568  sqlite3_snapshot *pSnapshot
8569);
8570
8571/*
8572** CAPI3REF: Destroy a snapshot
8573** EXPERIMENTAL
8574**
8575** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
8576** The application must eventually free every [sqlite3_snapshot] object
8577** using this routine to avoid a memory leak.
8578**
8579** The [sqlite3_snapshot_free()] interface is only available when the
8580** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8581*/
8582SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_snapshot_free(sqlite3_snapshot*);
8583
8584/*
8585** CAPI3REF: Compare the ages of two snapshot handles.
8586** EXPERIMENTAL
8587**
8588** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
8589** of two valid snapshot handles.
8590**
8591** If the two snapshot handles are not associated with the same database
8592** file, the result of the comparison is undefined.
8593**
8594** Additionally, the result of the comparison is only valid if both of the
8595** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
8596** last time the wal file was deleted. The wal file is deleted when the
8597** database is changed back to rollback mode or when the number of database
8598** clients drops to zero. If either snapshot handle was obtained before the
8599** wal file was last deleted, the value returned by this function
8600** is undefined.
8601**
8602** Otherwise, this API returns a negative value if P1 refers to an older
8603** snapshot than P2, zero if the two handles refer to the same database
8604** snapshot, and a positive value if P1 is a newer snapshot than P2.
8605*/
8606SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_cmp(
8607  sqlite3_snapshot *p1,
8608  sqlite3_snapshot *p2
8609);
8610
8611/*
8612** Undo the hack that converts floating point types to integer for
8613** builds on processors without floating point support.
8614*/
8615#ifdef SQLITE_OMIT_FLOATING_POINT
8616# undef double
8617#endif
8618
8619#if 0
8620}  /* End of the 'extern "C"' block */
8621#endif
8622#endif /* SQLITE3_H */
8623
8624/******** Begin file sqlite3rtree.h *********/
8625/*
8626** 2010 August 30
8627**
8628** The author disclaims copyright to this source code.  In place of
8629** a legal notice, here is a blessing:
8630**
8631**    May you do good and not evil.
8632**    May you find forgiveness for yourself and forgive others.
8633**    May you share freely, never taking more than you give.
8634**
8635*************************************************************************
8636*/
8637
8638#ifndef _SQLITE3RTREE_H_
8639#define _SQLITE3RTREE_H_
8640
8641
8642#if 0
8643extern "C" {
8644#endif
8645
8646typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
8647typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
8648
8649/* The double-precision datatype used by RTree depends on the
8650** SQLITE_RTREE_INT_ONLY compile-time option.
8651*/
8652#ifdef SQLITE_RTREE_INT_ONLY
8653  typedef sqlite3_int64 sqlite3_rtree_dbl;
8654#else
8655  typedef double sqlite3_rtree_dbl;
8656#endif
8657
8658/*
8659** Register a geometry callback named zGeom that can be used as part of an
8660** R-Tree geometry query as follows:
8661**
8662**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
8663*/
8664SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
8665  sqlite3 *db,
8666  const char *zGeom,
8667  int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
8668  void *pContext
8669);
8670
8671
8672/*
8673** A pointer to a structure of the following type is passed as the first
8674** argument to callbacks registered using rtree_geometry_callback().
8675*/
8676struct sqlite3_rtree_geometry {
8677  void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
8678  int nParam;                     /* Size of array aParam[] */
8679  sqlite3_rtree_dbl *aParam;      /* Parameters passed to SQL geom function */
8680  void *pUser;                    /* Callback implementation user data */
8681  void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
8682};
8683
8684/*
8685** Register a 2nd-generation geometry callback named zScore that can be
8686** used as part of an R-Tree geometry query as follows:
8687**
8688**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
8689*/
8690SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
8691  sqlite3 *db,
8692  const char *zQueryFunc,
8693  int (*xQueryFunc)(sqlite3_rtree_query_info*),
8694  void *pContext,
8695  void (*xDestructor)(void*)
8696);
8697
8698
8699/*
8700** A pointer to a structure of the following type is passed as the
8701** argument to scored geometry callback registered using
8702** sqlite3_rtree_query_callback().
8703**
8704** Note that the first 5 fields of this structure are identical to
8705** sqlite3_rtree_geometry.  This structure is a subclass of
8706** sqlite3_rtree_geometry.
8707*/
8708struct sqlite3_rtree_query_info {
8709  void *pContext;                   /* pContext from when function registered */
8710  int nParam;                       /* Number of function parameters */
8711  sqlite3_rtree_dbl *aParam;        /* value of function parameters */
8712  void *pUser;                      /* callback can use this, if desired */
8713  void (*xDelUser)(void*);          /* function to free pUser */
8714  sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */
8715  unsigned int *anQueue;            /* Number of pending entries in the queue */
8716  int nCoord;                       /* Number of coordinates */
8717  int iLevel;                       /* Level of current node or entry */
8718  int mxLevel;                      /* The largest iLevel value in the tree */
8719  sqlite3_int64 iRowid;             /* Rowid for current entry */
8720  sqlite3_rtree_dbl rParentScore;   /* Score of parent node */
8721  int eParentWithin;                /* Visibility of parent node */
8722  int eWithin;                      /* OUT: Visiblity */
8723  sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */
8724  /* The following fields are only available in 3.8.11 and later */
8725  sqlite3_value **apSqlParam;       /* Original SQL values of parameters */
8726};
8727
8728/*
8729** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
8730*/
8731#define NOT_WITHIN       0   /* Object completely outside of query region */
8732#define PARTLY_WITHIN    1   /* Object partially overlaps query region */
8733#define FULLY_WITHIN     2   /* Object fully contained within query region */
8734
8735
8736#if 0
8737}  /* end of the 'extern "C"' block */
8738#endif
8739
8740#endif  /* ifndef _SQLITE3RTREE_H_ */
8741
8742/******** End of sqlite3rtree.h *********/
8743/******** Begin file sqlite3session.h *********/
8744
8745#if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
8746#define __SQLITESESSION_H_ 1
8747
8748/*
8749** Make sure we can call this stuff from C++.
8750*/
8751#if 0
8752extern "C" {
8753#endif
8754
8755
8756/*
8757** CAPI3REF: Session Object Handle
8758*/
8759typedef struct sqlite3_session sqlite3_session;
8760
8761/*
8762** CAPI3REF: Changeset Iterator Handle
8763*/
8764typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
8765
8766/*
8767** CAPI3REF: Create A New Session Object
8768**
8769** Create a new session object attached to database handle db. If successful,
8770** a pointer to the new object is written to *ppSession and SQLITE_OK is
8771** returned. If an error occurs, *ppSession is set to NULL and an SQLite
8772** error code (e.g. SQLITE_NOMEM) is returned.
8773**
8774** It is possible to create multiple session objects attached to a single
8775** database handle.
8776**
8777** Session objects created using this function should be deleted using the
8778** [sqlite3session_delete()] function before the database handle that they
8779** are attached to is itself closed. If the database handle is closed before
8780** the session object is deleted, then the results of calling any session
8781** module function, including [sqlite3session_delete()] on the session object
8782** are undefined.
8783**
8784** Because the session module uses the [sqlite3_preupdate_hook()] API, it
8785** is not possible for an application to register a pre-update hook on a
8786** database handle that has one or more session objects attached. Nor is
8787** it possible to create a session object attached to a database handle for
8788** which a pre-update hook is already defined. The results of attempting
8789** either of these things are undefined.
8790**
8791** The session object will be used to create changesets for tables in
8792** database zDb, where zDb is either "main", or "temp", or the name of an
8793** attached database. It is not an error if database zDb is not attached
8794** to the database when the session object is created.
8795*/
8796int sqlite3session_create(
8797  sqlite3 *db,                    /* Database handle */
8798  const char *zDb,                /* Name of db (e.g. "main") */
8799  sqlite3_session **ppSession     /* OUT: New session object */
8800);
8801
8802/*
8803** CAPI3REF: Delete A Session Object
8804**
8805** Delete a session object previously allocated using
8806** [sqlite3session_create()]. Once a session object has been deleted, the
8807** results of attempting to use pSession with any other session module
8808** function are undefined.
8809**
8810** Session objects must be deleted before the database handle to which they
8811** are attached is closed. Refer to the documentation for
8812** [sqlite3session_create()] for details.
8813*/
8814void sqlite3session_delete(sqlite3_session *pSession);
8815
8816
8817/*
8818** CAPI3REF: Enable Or Disable A Session Object
8819**
8820** Enable or disable the recording of changes by a session object. When
8821** enabled, a session object records changes made to the database. When
8822** disabled - it does not. A newly created session object is enabled.
8823** Refer to the documentation for [sqlite3session_changeset()] for further
8824** details regarding how enabling and disabling a session object affects
8825** the eventual changesets.
8826**
8827** Passing zero to this function disables the session. Passing a value
8828** greater than zero enables it. Passing a value less than zero is a
8829** no-op, and may be used to query the current state of the session.
8830**
8831** The return value indicates the final state of the session object: 0 if
8832** the session is disabled, or 1 if it is enabled.
8833*/
8834int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
8835
8836/*
8837** CAPI3REF: Set Or Clear the Indirect Change Flag
8838**
8839** Each change recorded by a session object is marked as either direct or
8840** indirect. A change is marked as indirect if either:
8841**
8842** <ul>
8843**   <li> The session object "indirect" flag is set when the change is
8844**        made, or
8845**   <li> The change is made by an SQL trigger or foreign key action
8846**        instead of directly as a result of a users SQL statement.
8847** </ul>
8848**
8849** If a single row is affected by more than one operation within a session,
8850** then the change is considered indirect if all operations meet the criteria
8851** for an indirect change above, or direct otherwise.
8852**
8853** This function is used to set, clear or query the session object indirect
8854** flag.  If the second argument passed to this function is zero, then the
8855** indirect flag is cleared. If it is greater than zero, the indirect flag
8856** is set. Passing a value less than zero does not modify the current value
8857** of the indirect flag, and may be used to query the current state of the
8858** indirect flag for the specified session object.
8859**
8860** The return value indicates the final state of the indirect flag: 0 if
8861** it is clear, or 1 if it is set.
8862*/
8863int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
8864
8865/*
8866** CAPI3REF: Attach A Table To A Session Object
8867**
8868** If argument zTab is not NULL, then it is the name of a table to attach
8869** to the session object passed as the first argument. All subsequent changes
8870** made to the table while the session object is enabled will be recorded. See
8871** documentation for [sqlite3session_changeset()] for further details.
8872**
8873** Or, if argument zTab is NULL, then changes are recorded for all tables
8874** in the database. If additional tables are added to the database (by
8875** executing "CREATE TABLE" statements) after this call is made, changes for
8876** the new tables are also recorded.
8877**
8878** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
8879** defined as part of their CREATE TABLE statement. It does not matter if the
8880** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
8881** KEY may consist of a single column, or may be a composite key.
8882**
8883** It is not an error if the named table does not exist in the database. Nor
8884** is it an error if the named table does not have a PRIMARY KEY. However,
8885** no changes will be recorded in either of these scenarios.
8886**
8887** Changes are not recorded for individual rows that have NULL values stored
8888** in one or more of their PRIMARY KEY columns.
8889**
8890** SQLITE_OK is returned if the call completes without error. Or, if an error
8891** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
8892*/
8893int sqlite3session_attach(
8894  sqlite3_session *pSession,      /* Session object */
8895  const char *zTab                /* Table name */
8896);
8897
8898/*
8899** CAPI3REF: Set a table filter on a Session Object.
8900**
8901** The second argument (xFilter) is the "filter callback". For changes to rows
8902** in tables that are not attached to the Session oject, the filter is called
8903** to determine whether changes to the table's rows should be tracked or not.
8904** If xFilter returns 0, changes is not tracked. Note that once a table is
8905** attached, xFilter will not be called again.
8906*/
8907void sqlite3session_table_filter(
8908  sqlite3_session *pSession,      /* Session object */
8909  int(*xFilter)(
8910    void *pCtx,                   /* Copy of third arg to _filter_table() */
8911    const char *zTab              /* Table name */
8912  ),
8913  void *pCtx                      /* First argument passed to xFilter */
8914);
8915
8916/*
8917** CAPI3REF: Generate A Changeset From A Session Object
8918**
8919** Obtain a changeset containing changes to the tables attached to the
8920** session object passed as the first argument. If successful,
8921** set *ppChangeset to point to a buffer containing the changeset
8922** and *pnChangeset to the size of the changeset in bytes before returning
8923** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
8924** zero and return an SQLite error code.
8925**
8926** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
8927** each representing a change to a single row of an attached table. An INSERT
8928** change contains the values of each field of a new database row. A DELETE
8929** contains the original values of each field of a deleted database row. An
8930** UPDATE change contains the original values of each field of an updated
8931** database row along with the updated values for each updated non-primary-key
8932** column. It is not possible for an UPDATE change to represent a change that
8933** modifies the values of primary key columns. If such a change is made, it
8934** is represented in a changeset as a DELETE followed by an INSERT.
8935**
8936** Changes are not recorded for rows that have NULL values stored in one or
8937** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
8938** no corresponding change is present in the changesets returned by this
8939** function. If an existing row with one or more NULL values stored in
8940** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
8941** only an INSERT is appears in the changeset. Similarly, if an existing row
8942** with non-NULL PRIMARY KEY values is updated so that one or more of its
8943** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
8944** DELETE change only.
8945**
8946** The contents of a changeset may be traversed using an iterator created
8947** using the [sqlite3changeset_start()] API. A changeset may be applied to
8948** a database with a compatible schema using the [sqlite3changeset_apply()]
8949** API.
8950**
8951** Within a changeset generated by this function, all changes related to a
8952** single table are grouped together. In other words, when iterating through
8953** a changeset or when applying a changeset to a database, all changes related
8954** to a single table are processed before moving on to the next table. Tables
8955** are sorted in the same order in which they were attached (or auto-attached)
8956** to the sqlite3_session object. The order in which the changes related to
8957** a single table are stored is undefined.
8958**
8959** Following a successful call to this function, it is the responsibility of
8960** the caller to eventually free the buffer that *ppChangeset points to using
8961** [sqlite3_free()].
8962**
8963** <h3>Changeset Generation</h3>
8964**
8965** Once a table has been attached to a session object, the session object
8966** records the primary key values of all new rows inserted into the table.
8967** It also records the original primary key and other column values of any
8968** deleted or updated rows. For each unique primary key value, data is only
8969** recorded once - the first time a row with said primary key is inserted,
8970** updated or deleted in the lifetime of the session.
8971**
8972** There is one exception to the previous paragraph: when a row is inserted,
8973** updated or deleted, if one or more of its primary key columns contain a
8974** NULL value, no record of the change is made.
8975**
8976** The session object therefore accumulates two types of records - those
8977** that consist of primary key values only (created when the user inserts
8978** a new record) and those that consist of the primary key values and the
8979** original values of other table columns (created when the users deletes
8980** or updates a record).
8981**
8982** When this function is called, the requested changeset is created using
8983** both the accumulated records and the current contents of the database
8984** file. Specifically:
8985**
8986** <ul>
8987**   <li> For each record generated by an insert, the database is queried
8988**        for a row with a matching primary key. If one is found, an INSERT
8989**        change is added to the changeset. If no such row is found, no change
8990**        is added to the changeset.
8991**
8992**   <li> For each record generated by an update or delete, the database is
8993**        queried for a row with a matching primary key. If such a row is
8994**        found and one or more of the non-primary key fields have been
8995**        modified from their original values, an UPDATE change is added to
8996**        the changeset. Or, if no such row is found in the table, a DELETE
8997**        change is added to the changeset. If there is a row with a matching
8998**        primary key in the database, but all fields contain their original
8999**        values, no change is added to the changeset.
9000** </ul>
9001**
9002** This means, amongst other things, that if a row is inserted and then later
9003** deleted while a session object is active, neither the insert nor the delete
9004** will be present in the changeset. Or if a row is deleted and then later a
9005** row with the same primary key values inserted while a session object is
9006** active, the resulting changeset will contain an UPDATE change instead of
9007** a DELETE and an INSERT.
9008**
9009** When a session object is disabled (see the [sqlite3session_enable()] API),
9010** it does not accumulate records when rows are inserted, updated or deleted.
9011** This may appear to have some counter-intuitive effects if a single row
9012** is written to more than once during a session. For example, if a row
9013** is inserted while a session object is enabled, then later deleted while
9014** the same session object is disabled, no INSERT record will appear in the
9015** changeset, even though the delete took place while the session was disabled.
9016** Or, if one field of a row is updated while a session is disabled, and
9017** another field of the same row is updated while the session is enabled, the
9018** resulting changeset will contain an UPDATE change that updates both fields.
9019*/
9020int sqlite3session_changeset(
9021  sqlite3_session *pSession,      /* Session object */
9022  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
9023  void **ppChangeset              /* OUT: Buffer containing changeset */
9024);
9025
9026/*
9027** CAPI3REF: Load The Difference Between Tables Into A Session
9028**
9029** If it is not already attached to the session object passed as the first
9030** argument, this function attaches table zTbl in the same manner as the
9031** [sqlite3session_attach()] function. If zTbl does not exist, or if it
9032** does not have a primary key, this function is a no-op (but does not return
9033** an error).
9034**
9035** Argument zFromDb must be the name of a database ("main", "temp" etc.)
9036** attached to the same database handle as the session object that contains
9037** a table compatible with the table attached to the session by this function.
9038** A table is considered compatible if it:
9039**
9040** <ul>
9041**   <li> Has the same name,
9042**   <li> Has the same set of columns declared in the same order, and
9043**   <li> Has the same PRIMARY KEY definition.
9044** </ul>
9045**
9046** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
9047** are compatible but do not have any PRIMARY KEY columns, it is not an error
9048** but no changes are added to the session object. As with other session
9049** APIs, tables without PRIMARY KEYs are simply ignored.
9050**
9051** This function adds a set of changes to the session object that could be
9052** used to update the table in database zFrom (call this the "from-table")
9053** so that its content is the same as the table attached to the session
9054** object (call this the "to-table"). Specifically:
9055**
9056** <ul>
9057**   <li> For each row (primary key) that exists in the to-table but not in
9058**     the from-table, an INSERT record is added to the session object.
9059**
9060**   <li> For each row (primary key) that exists in the to-table but not in
9061**     the from-table, a DELETE record is added to the session object.
9062**
9063**   <li> For each row (primary key) that exists in both tables, but features
9064**     different in each, an UPDATE record is added to the session.
9065** </ul>
9066**
9067** To clarify, if this function is called and then a changeset constructed
9068** using [sqlite3session_changeset()], then after applying that changeset to
9069** database zFrom the contents of the two compatible tables would be
9070** identical.
9071**
9072** It an error if database zFrom does not exist or does not contain the
9073** required compatible table.
9074**
9075** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
9076** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
9077** may be set to point to a buffer containing an English language error
9078** message. It is the responsibility of the caller to free this buffer using
9079** sqlite3_free().
9080*/
9081int sqlite3session_diff(
9082  sqlite3_session *pSession,
9083  const char *zFromDb,
9084  const char *zTbl,
9085  char **pzErrMsg
9086);
9087
9088
9089/*
9090** CAPI3REF: Generate A Patchset From A Session Object
9091**
9092** The differences between a patchset and a changeset are that:
9093**
9094** <ul>
9095**   <li> DELETE records consist of the primary key fields only. The
9096**        original values of other fields are omitted.
9097**   <li> The original values of any modified fields are omitted from
9098**        UPDATE records.
9099** </ul>
9100**
9101** A patchset blob may be used with up to date versions of all
9102** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
9103** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
9104** attempting to use a patchset blob with old versions of the
9105** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
9106**
9107** Because the non-primary key "old.*" fields are omitted, no
9108** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
9109** is passed to the sqlite3changeset_apply() API. Other conflict types work
9110** in the same way as for changesets.
9111**
9112** Changes within a patchset are ordered in the same way as for changesets
9113** generated by the sqlite3session_changeset() function (i.e. all changes for
9114** a single table are grouped together, tables appear in the order in which
9115** they were attached to the session object).
9116*/
9117int sqlite3session_patchset(
9118  sqlite3_session *pSession,      /* Session object */
9119  int *pnPatchset,                /* OUT: Size of buffer at *ppChangeset */
9120  void **ppPatchset               /* OUT: Buffer containing changeset */
9121);
9122
9123/*
9124** CAPI3REF: Test if a changeset has recorded any changes.
9125**
9126** Return non-zero if no changes to attached tables have been recorded by
9127** the session object passed as the first argument. Otherwise, if one or
9128** more changes have been recorded, return zero.
9129**
9130** Even if this function returns zero, it is possible that calling
9131** [sqlite3session_changeset()] on the session handle may still return a
9132** changeset that contains no changes. This can happen when a row in
9133** an attached table is modified and then later on the original values
9134** are restored. However, if this function returns non-zero, then it is
9135** guaranteed that a call to sqlite3session_changeset() will return a
9136** changeset containing zero changes.
9137*/
9138int sqlite3session_isempty(sqlite3_session *pSession);
9139
9140/*
9141** CAPI3REF: Create An Iterator To Traverse A Changeset
9142**
9143** Create an iterator used to iterate through the contents of a changeset.
9144** If successful, *pp is set to point to the iterator handle and SQLITE_OK
9145** is returned. Otherwise, if an error occurs, *pp is set to zero and an
9146** SQLite error code is returned.
9147**
9148** The following functions can be used to advance and query a changeset
9149** iterator created by this function:
9150**
9151** <ul>
9152**   <li> [sqlite3changeset_next()]
9153**   <li> [sqlite3changeset_op()]
9154**   <li> [sqlite3changeset_new()]
9155**   <li> [sqlite3changeset_old()]
9156** </ul>
9157**
9158** It is the responsibility of the caller to eventually destroy the iterator
9159** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
9160** changeset (pChangeset) must remain valid until after the iterator is
9161** destroyed.
9162**
9163** Assuming the changeset blob was created by one of the
9164** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
9165** [sqlite3changeset_invert()] functions, all changes within the changeset
9166** that apply to a single table are grouped together. This means that when
9167** an application iterates through a changeset using an iterator created by
9168** this function, all changes that relate to a single table are visted
9169** consecutively. There is no chance that the iterator will visit a change
9170** the applies to table X, then one for table Y, and then later on visit
9171** another change for table X.
9172*/
9173int sqlite3changeset_start(
9174  sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */
9175  int nChangeset,                 /* Size of changeset blob in bytes */
9176  void *pChangeset                /* Pointer to blob containing changeset */
9177);
9178
9179
9180/*
9181** CAPI3REF: Advance A Changeset Iterator
9182**
9183** This function may only be used with iterators created by function
9184** [sqlite3changeset_start()]. If it is called on an iterator passed to
9185** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
9186** is returned and the call has no effect.
9187**
9188** Immediately after an iterator is created by sqlite3changeset_start(), it
9189** does not point to any change in the changeset. Assuming the changeset
9190** is not empty, the first call to this function advances the iterator to
9191** point to the first change in the changeset. Each subsequent call advances
9192** the iterator to point to the next change in the changeset (if any). If
9193** no error occurs and the iterator points to a valid change after a call
9194** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
9195** Otherwise, if all changes in the changeset have already been visited,
9196** SQLITE_DONE is returned.
9197**
9198** If an error occurs, an SQLite error code is returned. Possible error
9199** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
9200** SQLITE_NOMEM.
9201*/
9202int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
9203
9204/*
9205** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
9206**
9207** The pIter argument passed to this function may either be an iterator
9208** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9209** created by [sqlite3changeset_start()]. In the latter case, the most recent
9210** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
9211** is not the case, this function returns [SQLITE_MISUSE].
9212**
9213** If argument pzTab is not NULL, then *pzTab is set to point to a
9214** nul-terminated utf-8 encoded string containing the name of the table
9215** affected by the current change. The buffer remains valid until either
9216** sqlite3changeset_next() is called on the iterator or until the
9217** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
9218** set to the number of columns in the table affected by the change. If
9219** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
9220** is an indirect change, or false (0) otherwise. See the documentation for
9221** [sqlite3session_indirect()] for a description of direct and indirect
9222** changes. Finally, if pOp is not NULL, then *pOp is set to one of
9223** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
9224** type of change that the iterator currently points to.
9225**
9226** If no error occurs, SQLITE_OK is returned. If an error does occur, an
9227** SQLite error code is returned. The values of the output variables may not
9228** be trusted in this case.
9229*/
9230int sqlite3changeset_op(
9231  sqlite3_changeset_iter *pIter,  /* Iterator object */
9232  const char **pzTab,             /* OUT: Pointer to table name */
9233  int *pnCol,                     /* OUT: Number of columns in table */
9234  int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
9235  int *pbIndirect                 /* OUT: True for an 'indirect' change */
9236);
9237
9238/*
9239** CAPI3REF: Obtain The Primary Key Definition Of A Table
9240**
9241** For each modified table, a changeset includes the following:
9242**
9243** <ul>
9244**   <li> The number of columns in the table, and
9245**   <li> Which of those columns make up the tables PRIMARY KEY.
9246** </ul>
9247**
9248** This function is used to find which columns comprise the PRIMARY KEY of
9249** the table modified by the change that iterator pIter currently points to.
9250** If successful, *pabPK is set to point to an array of nCol entries, where
9251** nCol is the number of columns in the table. Elements of *pabPK are set to
9252** 0x01 if the corresponding column is part of the tables primary key, or
9253** 0x00 if it is not.
9254**
9255** If argumet pnCol is not NULL, then *pnCol is set to the number of columns
9256** in the table.
9257**
9258** If this function is called when the iterator does not point to a valid
9259** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
9260** SQLITE_OK is returned and the output variables populated as described
9261** above.
9262*/
9263int sqlite3changeset_pk(
9264  sqlite3_changeset_iter *pIter,  /* Iterator object */
9265  unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
9266  int *pnCol                      /* OUT: Number of entries in output array */
9267);
9268
9269/*
9270** CAPI3REF: Obtain old.* Values From A Changeset Iterator
9271**
9272** The pIter argument passed to this function may either be an iterator
9273** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9274** created by [sqlite3changeset_start()]. In the latter case, the most recent
9275** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
9276** Furthermore, it may only be called if the type of change that the iterator
9277** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
9278** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
9279**
9280** Argument iVal must be greater than or equal to 0, and less than the number
9281** of columns in the table affected by the current change. Otherwise,
9282** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9283**
9284** If successful, this function sets *ppValue to point to a protected
9285** sqlite3_value object containing the iVal'th value from the vector of
9286** original row values stored as part of the UPDATE or DELETE change and
9287** returns SQLITE_OK. The name of the function comes from the fact that this
9288** is similar to the "old.*" columns available to update or delete triggers.
9289**
9290** If some other error occurs (e.g. an OOM condition), an SQLite error code
9291** is returned and *ppValue is set to NULL.
9292*/
9293int sqlite3changeset_old(
9294  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
9295  int iVal,                       /* Column number */
9296  sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
9297);
9298
9299/*
9300** CAPI3REF: Obtain new.* Values From A Changeset Iterator
9301**
9302** The pIter argument passed to this function may either be an iterator
9303** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9304** created by [sqlite3changeset_start()]. In the latter case, the most recent
9305** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
9306** Furthermore, it may only be called if the type of change that the iterator
9307** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
9308** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
9309**
9310** Argument iVal must be greater than or equal to 0, and less than the number
9311** of columns in the table affected by the current change. Otherwise,
9312** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9313**
9314** If successful, this function sets *ppValue to point to a protected
9315** sqlite3_value object containing the iVal'th value from the vector of
9316** new row values stored as part of the UPDATE or INSERT change and
9317** returns SQLITE_OK. If the change is an UPDATE and does not include
9318** a new value for the requested column, *ppValue is set to NULL and
9319** SQLITE_OK returned. The name of the function comes from the fact that
9320** this is similar to the "new.*" columns available to update or delete
9321** triggers.
9322**
9323** If some other error occurs (e.g. an OOM condition), an SQLite error code
9324** is returned and *ppValue is set to NULL.
9325*/
9326int sqlite3changeset_new(
9327  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
9328  int iVal,                       /* Column number */
9329  sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
9330);
9331
9332/*
9333** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
9334**
9335** This function should only be used with iterator objects passed to a
9336** conflict-handler callback by [sqlite3changeset_apply()] with either
9337** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
9338** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
9339** is set to NULL.
9340**
9341** Argument iVal must be greater than or equal to 0, and less than the number
9342** of columns in the table affected by the current change. Otherwise,
9343** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9344**
9345** If successful, this function sets *ppValue to point to a protected
9346** sqlite3_value object containing the iVal'th value from the
9347** "conflicting row" associated with the current conflict-handler callback
9348** and returns SQLITE_OK.
9349**
9350** If some other error occurs (e.g. an OOM condition), an SQLite error code
9351** is returned and *ppValue is set to NULL.
9352*/
9353int sqlite3changeset_conflict(
9354  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
9355  int iVal,                       /* Column number */
9356  sqlite3_value **ppValue         /* OUT: Value from conflicting row */
9357);
9358
9359/*
9360** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
9361**
9362** This function may only be called with an iterator passed to an
9363** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
9364** it sets the output variable to the total number of known foreign key
9365** violations in the destination database and returns SQLITE_OK.
9366**
9367** In all other cases this function returns SQLITE_MISUSE.
9368*/
9369int sqlite3changeset_fk_conflicts(
9370  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
9371  int *pnOut                      /* OUT: Number of FK violations */
9372);
9373
9374
9375/*
9376** CAPI3REF: Finalize A Changeset Iterator
9377**
9378** This function is used to finalize an iterator allocated with
9379** [sqlite3changeset_start()].
9380**
9381** This function should only be called on iterators created using the
9382** [sqlite3changeset_start()] function. If an application calls this
9383** function with an iterator passed to a conflict-handler by
9384** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
9385** call has no effect.
9386**
9387** If an error was encountered within a call to an sqlite3changeset_xxx()
9388** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
9389** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
9390** to that error is returned by this function. Otherwise, SQLITE_OK is
9391** returned. This is to allow the following pattern (pseudo-code):
9392**
9393**   sqlite3changeset_start();
9394**   while( SQLITE_ROW==sqlite3changeset_next() ){
9395**     // Do something with change.
9396**   }
9397**   rc = sqlite3changeset_finalize();
9398**   if( rc!=SQLITE_OK ){
9399**     // An error has occurred
9400**   }
9401*/
9402int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
9403
9404/*
9405** CAPI3REF: Invert A Changeset
9406**
9407** This function is used to "invert" a changeset object. Applying an inverted
9408** changeset to a database reverses the effects of applying the uninverted
9409** changeset. Specifically:
9410**
9411** <ul>
9412**   <li> Each DELETE change is changed to an INSERT, and
9413**   <li> Each INSERT change is changed to a DELETE, and
9414**   <li> For each UPDATE change, the old.* and new.* values are exchanged.
9415** </ul>
9416**
9417** This function does not change the order in which changes appear within
9418** the changeset. It merely reverses the sense of each individual change.
9419**
9420** If successful, a pointer to a buffer containing the inverted changeset
9421** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
9422** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
9423** zeroed and an SQLite error code returned.
9424**
9425** It is the responsibility of the caller to eventually call sqlite3_free()
9426** on the *ppOut pointer to free the buffer allocation following a successful
9427** call to this function.
9428**
9429** WARNING/TODO: This function currently assumes that the input is a valid
9430** changeset. If it is not, the results are undefined.
9431*/
9432int sqlite3changeset_invert(
9433  int nIn, const void *pIn,       /* Input changeset */
9434  int *pnOut, void **ppOut        /* OUT: Inverse of input */
9435);
9436
9437/*
9438** CAPI3REF: Concatenate Two Changeset Objects
9439**
9440** This function is used to concatenate two changesets, A and B, into a
9441** single changeset. The result is a changeset equivalent to applying
9442** changeset A followed by changeset B.
9443**
9444** This function combines the two input changesets using an
9445** sqlite3_changegroup object. Calling it produces similar results as the
9446** following code fragment:
9447**
9448**   sqlite3_changegroup *pGrp;
9449**   rc = sqlite3_changegroup_new(&pGrp);
9450**   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
9451**   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
9452**   if( rc==SQLITE_OK ){
9453**     rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
9454**   }else{
9455**     *ppOut = 0;
9456**     *pnOut = 0;
9457**   }
9458**
9459** Refer to the sqlite3_changegroup documentation below for details.
9460*/
9461int sqlite3changeset_concat(
9462  int nA,                         /* Number of bytes in buffer pA */
9463  void *pA,                       /* Pointer to buffer containing changeset A */
9464  int nB,                         /* Number of bytes in buffer pB */
9465  void *pB,                       /* Pointer to buffer containing changeset B */
9466  int *pnOut,                     /* OUT: Number of bytes in output changeset */
9467  void **ppOut                    /* OUT: Buffer containing output changeset */
9468);
9469
9470
9471/*
9472** Changegroup handle.
9473*/
9474typedef struct sqlite3_changegroup sqlite3_changegroup;
9475
9476/*
9477** CAPI3REF: Combine two or more changesets into a single changeset.
9478**
9479** An sqlite3_changegroup object is used to combine two or more changesets
9480** (or patchsets) into a single changeset (or patchset). A single changegroup
9481** object may combine changesets or patchsets, but not both. The output is
9482** always in the same format as the input.
9483**
9484** If successful, this function returns SQLITE_OK and populates (*pp) with
9485** a pointer to a new sqlite3_changegroup object before returning. The caller
9486** should eventually free the returned object using a call to
9487** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
9488** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
9489**
9490** The usual usage pattern for an sqlite3_changegroup object is as follows:
9491**
9492** <ul>
9493**   <li> It is created using a call to sqlite3changegroup_new().
9494**
9495**   <li> Zero or more changesets (or patchsets) are added to the object
9496**        by calling sqlite3changegroup_add().
9497**
9498**   <li> The result of combining all input changesets together is obtained
9499**        by the application via a call to sqlite3changegroup_output().
9500**
9501**   <li> The object is deleted using a call to sqlite3changegroup_delete().
9502** </ul>
9503**
9504** Any number of calls to add() and output() may be made between the calls to
9505** new() and delete(), and in any order.
9506**
9507** As well as the regular sqlite3changegroup_add() and
9508** sqlite3changegroup_output() functions, also available are the streaming
9509** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
9510*/
9511int sqlite3changegroup_new(sqlite3_changegroup **pp);
9512
9513/*
9514** Add all changes within the changeset (or patchset) in buffer pData (size
9515** nData bytes) to the changegroup.
9516**
9517** If the buffer contains a patchset, then all prior calls to this function
9518** on the same changegroup object must also have specified patchsets. Or, if
9519** the buffer contains a changeset, so must have the earlier calls to this
9520** function. Otherwise, SQLITE_ERROR is returned and no changes are added
9521** to the changegroup.
9522**
9523** Rows within the changeset and changegroup are identified by the values in
9524** their PRIMARY KEY columns. A change in the changeset is considered to
9525** apply to the same row as a change already present in the changegroup if
9526** the two rows have the same primary key.
9527**
9528** Changes to rows that that do not already appear in the changegroup are
9529** simply copied into it. Or, if both the new changeset and the changegroup
9530** contain changes that apply to a single row, the final contents of the
9531** changegroup depends on the type of each change, as follows:
9532**
9533** <table border=1 style="margin-left:8ex;margin-right:8ex">
9534**   <tr><th style="white-space:pre">Existing Change  </th>
9535**       <th style="white-space:pre">New Change       </th>
9536**       <th>Output Change
9537**   <tr><td>INSERT <td>INSERT <td>
9538**       The new change is ignored. This case does not occur if the new
9539**       changeset was recorded immediately after the changesets already
9540**       added to the changegroup.
9541**   <tr><td>INSERT <td>UPDATE <td>
9542**       The INSERT change remains in the changegroup. The values in the
9543**       INSERT change are modified as if the row was inserted by the
9544**       existing change and then updated according to the new change.
9545**   <tr><td>INSERT <td>DELETE <td>
9546**       The existing INSERT is removed from the changegroup. The DELETE is
9547**       not added.
9548**   <tr><td>UPDATE <td>INSERT <td>
9549**       The new change is ignored. This case does not occur if the new
9550**       changeset was recorded immediately after the changesets already
9551**       added to the changegroup.
9552**   <tr><td>UPDATE <td>UPDATE <td>
9553**       The existing UPDATE remains within the changegroup. It is amended
9554**       so that the accompanying values are as if the row was updated once
9555**       by the existing change and then again by the new change.
9556**   <tr><td>UPDATE <td>DELETE <td>
9557**       The existing UPDATE is replaced by the new DELETE within the
9558**       changegroup.
9559**   <tr><td>DELETE <td>INSERT <td>
9560**       If one or more of the column values in the row inserted by the
9561**       new change differ from those in the row deleted by the existing
9562**       change, the existing DELETE is replaced by an UPDATE within the
9563**       changegroup. Otherwise, if the inserted row is exactly the same
9564**       as the deleted row, the existing DELETE is simply discarded.
9565**   <tr><td>DELETE <td>UPDATE <td>
9566**       The new change is ignored. This case does not occur if the new
9567**       changeset was recorded immediately after the changesets already
9568**       added to the changegroup.
9569**   <tr><td>DELETE <td>DELETE <td>
9570**       The new change is ignored. This case does not occur if the new
9571**       changeset was recorded immediately after the changesets already
9572**       added to the changegroup.
9573** </table>
9574**
9575** If the new changeset contains changes to a table that is already present
9576** in the changegroup, then the number of columns and the position of the
9577** primary key columns for the table must be consistent. If this is not the
9578** case, this function fails with SQLITE_SCHEMA. If the input changeset
9579** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
9580** returned. Or, if an out-of-memory condition occurs during processing, this
9581** function returns SQLITE_NOMEM. In all cases, if an error occurs the
9582** final contents of the changegroup is undefined.
9583**
9584** If no error occurs, SQLITE_OK is returned.
9585*/
9586int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
9587
9588/*
9589** Obtain a buffer containing a changeset (or patchset) representing the
9590** current contents of the changegroup. If the inputs to the changegroup
9591** were themselves changesets, the output is a changeset. Or, if the
9592** inputs were patchsets, the output is also a patchset.
9593**
9594** As with the output of the sqlite3session_changeset() and
9595** sqlite3session_patchset() functions, all changes related to a single
9596** table are grouped together in the output of this function. Tables appear
9597** in the same order as for the very first changeset added to the changegroup.
9598** If the second or subsequent changesets added to the changegroup contain
9599** changes for tables that do not appear in the first changeset, they are
9600** appended onto the end of the output changeset, again in the order in
9601** which they are first encountered.
9602**
9603** If an error occurs, an SQLite error code is returned and the output
9604** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
9605** is returned and the output variables are set to the size of and a
9606** pointer to the output buffer, respectively. In this case it is the
9607** responsibility of the caller to eventually free the buffer using a
9608** call to sqlite3_free().
9609*/
9610int sqlite3changegroup_output(
9611  sqlite3_changegroup*,
9612  int *pnData,                    /* OUT: Size of output buffer in bytes */
9613  void **ppData                   /* OUT: Pointer to output buffer */
9614);
9615
9616/*
9617** Delete a changegroup object.
9618*/
9619void sqlite3changegroup_delete(sqlite3_changegroup*);
9620
9621/*
9622** CAPI3REF: Apply A Changeset To A Database
9623**
9624** Apply a changeset to a database. This function attempts to update the
9625** "main" database attached to handle db with the changes found in the
9626** changeset passed via the second and third arguments.
9627**
9628** The fourth argument (xFilter) passed to this function is the "filter
9629** callback". If it is not NULL, then for each table affected by at least one
9630** change in the changeset, the filter callback is invoked with
9631** the table name as the second argument, and a copy of the context pointer
9632** passed as the sixth argument to this function as the first. If the "filter
9633** callback" returns zero, then no attempt is made to apply any changes to
9634** the table. Otherwise, if the return value is non-zero or the xFilter
9635** argument to this function is NULL, all changes related to the table are
9636** attempted.
9637**
9638** For each table that is not excluded by the filter callback, this function
9639** tests that the target database contains a compatible table. A table is
9640** considered compatible if all of the following are true:
9641**
9642** <ul>
9643**   <li> The table has the same name as the name recorded in the
9644**        changeset, and
9645**   <li> The table has the same number of columns as recorded in the
9646**        changeset, and
9647**   <li> The table has primary key columns in the same position as
9648**        recorded in the changeset.
9649** </ul>
9650**
9651** If there is no compatible table, it is not an error, but none of the
9652** changes associated with the table are applied. A warning message is issued
9653** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
9654** one such warning is issued for each table in the changeset.
9655**
9656** For each change for which there is a compatible table, an attempt is made
9657** to modify the table contents according to the UPDATE, INSERT or DELETE
9658** change. If a change cannot be applied cleanly, the conflict handler
9659** function passed as the fifth argument to sqlite3changeset_apply() may be
9660** invoked. A description of exactly when the conflict handler is invoked for
9661** each type of change is below.
9662**
9663** Unlike the xFilter argument, xConflict may not be passed NULL. The results
9664** of passing anything other than a valid function pointer as the xConflict
9665** argument are undefined.
9666**
9667** Each time the conflict handler function is invoked, it must return one
9668** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
9669** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
9670** if the second argument passed to the conflict handler is either
9671** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
9672** returns an illegal value, any changes already made are rolled back and
9673** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
9674** actions are taken by sqlite3changeset_apply() depending on the value
9675** returned by each invocation of the conflict-handler function. Refer to
9676** the documentation for the three
9677** [SQLITE_CHANGESET_OMIT|available return values] for details.
9678**
9679** <dl>
9680** <dt>DELETE Changes<dd>
9681**   For each DELETE change, this function checks if the target database
9682**   contains a row with the same primary key value (or values) as the
9683**   original row values stored in the changeset. If it does, and the values
9684**   stored in all non-primary key columns also match the values stored in
9685**   the changeset the row is deleted from the target database.
9686**
9687**   If a row with matching primary key values is found, but one or more of
9688**   the non-primary key fields contains a value different from the original
9689**   row value stored in the changeset, the conflict-handler function is
9690**   invoked with [SQLITE_CHANGESET_DATA] as the second argument.
9691**
9692**   If no row with matching primary key values is found in the database,
9693**   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9694**   passed as the second argument.
9695**
9696**   If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
9697**   (which can only happen if a foreign key constraint is violated), the
9698**   conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
9699**   passed as the second argument. This includes the case where the DELETE
9700**   operation is attempted because an earlier call to the conflict handler
9701**   function returned [SQLITE_CHANGESET_REPLACE].
9702**
9703** <dt>INSERT Changes<dd>
9704**   For each INSERT change, an attempt is made to insert the new row into
9705**   the database.
9706**
9707**   If the attempt to insert the row fails because the database already
9708**   contains a row with the same primary key values, the conflict handler
9709**   function is invoked with the second argument set to
9710**   [SQLITE_CHANGESET_CONFLICT].
9711**
9712**   If the attempt to insert the row fails because of some other constraint
9713**   violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
9714**   invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
9715**   This includes the case where the INSERT operation is re-attempted because
9716**   an earlier call to the conflict handler function returned
9717**   [SQLITE_CHANGESET_REPLACE].
9718**
9719** <dt>UPDATE Changes<dd>
9720**   For each UPDATE change, this function checks if the target database
9721**   contains a row with the same primary key value (or values) as the
9722**   original row values stored in the changeset. If it does, and the values
9723**   stored in all non-primary key columns also match the values stored in
9724**   the changeset the row is updated within the target database.
9725**
9726**   If a row with matching primary key values is found, but one or more of
9727**   the non-primary key fields contains a value different from an original
9728**   row value stored in the changeset, the conflict-handler function is
9729**   invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
9730**   UPDATE changes only contain values for non-primary key fields that are
9731**   to be modified, only those fields need to match the original values to
9732**   avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
9733**
9734**   If no row with matching primary key values is found in the database,
9735**   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9736**   passed as the second argument.
9737**
9738**   If the UPDATE operation is attempted, but SQLite returns
9739**   SQLITE_CONSTRAINT, the conflict-handler function is invoked with
9740**   [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
9741**   This includes the case where the UPDATE operation is attempted after
9742**   an earlier call to the conflict handler function returned
9743**   [SQLITE_CHANGESET_REPLACE].
9744** </dl>
9745**
9746** It is safe to execute SQL statements, including those that write to the
9747** table that the callback related to, from within the xConflict callback.
9748** This can be used to further customize the applications conflict
9749** resolution strategy.
9750**
9751** All changes made by this function are enclosed in a savepoint transaction.
9752** If any other error (aside from a constraint failure when attempting to
9753** write to the target database) occurs, then the savepoint transaction is
9754** rolled back, restoring the target database to its original state, and an
9755** SQLite error code returned.
9756*/
9757int sqlite3changeset_apply(
9758  sqlite3 *db,                    /* Apply change to "main" db of this handle */
9759  int nChangeset,                 /* Size of changeset in bytes */
9760  void *pChangeset,               /* Changeset blob */
9761  int(*xFilter)(
9762    void *pCtx,                   /* Copy of sixth arg to _apply() */
9763    const char *zTab              /* Table name */
9764  ),
9765  int(*xConflict)(
9766    void *pCtx,                   /* Copy of sixth arg to _apply() */
9767    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
9768    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
9769  ),
9770  void *pCtx                      /* First argument passed to xConflict */
9771);
9772
9773/*
9774** CAPI3REF: Constants Passed To The Conflict Handler
9775**
9776** Values that may be passed as the second argument to a conflict-handler.
9777**
9778** <dl>
9779** <dt>SQLITE_CHANGESET_DATA<dd>
9780**   The conflict handler is invoked with CHANGESET_DATA as the second argument
9781**   when processing a DELETE or UPDATE change if a row with the required
9782**   PRIMARY KEY fields is present in the database, but one or more other
9783**   (non primary-key) fields modified by the update do not contain the
9784**   expected "before" values.
9785**
9786**   The conflicting row, in this case, is the database row with the matching
9787**   primary key.
9788**
9789** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
9790**   The conflict handler is invoked with CHANGESET_NOTFOUND as the second
9791**   argument when processing a DELETE or UPDATE change if a row with the
9792**   required PRIMARY KEY fields is not present in the database.
9793**
9794**   There is no conflicting row in this case. The results of invoking the
9795**   sqlite3changeset_conflict() API are undefined.
9796**
9797** <dt>SQLITE_CHANGESET_CONFLICT<dd>
9798**   CHANGESET_CONFLICT is passed as the second argument to the conflict
9799**   handler while processing an INSERT change if the operation would result
9800**   in duplicate primary key values.
9801**
9802**   The conflicting row in this case is the database row with the matching
9803**   primary key.
9804**
9805** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
9806**   If foreign key handling is enabled, and applying a changeset leaves the
9807**   database in a state containing foreign key violations, the conflict
9808**   handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
9809**   exactly once before the changeset is committed. If the conflict handler
9810**   returns CHANGESET_OMIT, the changes, including those that caused the
9811**   foreign key constraint violation, are committed. Or, if it returns
9812**   CHANGESET_ABORT, the changeset is rolled back.
9813**
9814**   No current or conflicting row information is provided. The only function
9815**   it is possible to call on the supplied sqlite3_changeset_iter handle
9816**   is sqlite3changeset_fk_conflicts().
9817**
9818** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
9819**   If any other constraint violation occurs while applying a change (i.e.
9820**   a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
9821**   invoked with CHANGESET_CONSTRAINT as the second argument.
9822**
9823**   There is no conflicting row in this case. The results of invoking the
9824**   sqlite3changeset_conflict() API are undefined.
9825**
9826** </dl>
9827*/
9828#define SQLITE_CHANGESET_DATA        1
9829#define SQLITE_CHANGESET_NOTFOUND    2
9830#define SQLITE_CHANGESET_CONFLICT    3
9831#define SQLITE_CHANGESET_CONSTRAINT  4
9832#define SQLITE_CHANGESET_FOREIGN_KEY 5
9833
9834/*
9835** CAPI3REF: Constants Returned By The Conflict Handler
9836**
9837** A conflict handler callback must return one of the following three values.
9838**
9839** <dl>
9840** <dt>SQLITE_CHANGESET_OMIT<dd>
9841**   If a conflict handler returns this value no special action is taken. The
9842**   change that caused the conflict is not applied. The session module
9843**   continues to the next change in the changeset.
9844**
9845** <dt>SQLITE_CHANGESET_REPLACE<dd>
9846**   This value may only be returned if the second argument to the conflict
9847**   handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
9848**   is not the case, any changes applied so far are rolled back and the
9849**   call to sqlite3changeset_apply() returns SQLITE_MISUSE.
9850**
9851**   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
9852**   handler, then the conflicting row is either updated or deleted, depending
9853**   on the type of change.
9854**
9855**   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
9856**   handler, then the conflicting row is removed from the database and a
9857**   second attempt to apply the change is made. If this second attempt fails,
9858**   the original row is restored to the database before continuing.
9859**
9860** <dt>SQLITE_CHANGESET_ABORT<dd>
9861**   If this value is returned, any changes applied so far are rolled back
9862**   and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
9863** </dl>
9864*/
9865#define SQLITE_CHANGESET_OMIT       0
9866#define SQLITE_CHANGESET_REPLACE    1
9867#define SQLITE_CHANGESET_ABORT      2
9868
9869/*
9870** CAPI3REF: Streaming Versions of API functions.
9871**
9872** The six streaming API xxx_strm() functions serve similar purposes to the
9873** corresponding non-streaming API functions:
9874**
9875** <table border=1 style="margin-left:8ex;margin-right:8ex">
9876**   <tr><th>Streaming function<th>Non-streaming equivalent</th>
9877**   <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply]
9878**   <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat]
9879**   <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert]
9880**   <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start]
9881**   <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset]
9882**   <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset]
9883** </table>
9884**
9885** Non-streaming functions that accept changesets (or patchsets) as input
9886** require that the entire changeset be stored in a single buffer in memory.
9887** Similarly, those that return a changeset or patchset do so by returning
9888** a pointer to a single large buffer allocated using sqlite3_malloc().
9889** Normally this is convenient. However, if an application running in a
9890** low-memory environment is required to handle very large changesets, the
9891** large contiguous memory allocations required can become onerous.
9892**
9893** In order to avoid this problem, instead of a single large buffer, input
9894** is passed to a streaming API functions by way of a callback function that
9895** the sessions module invokes to incrementally request input data as it is
9896** required. In all cases, a pair of API function parameters such as
9897**
9898**  <pre>
9899**  &nbsp;     int nChangeset,
9900**  &nbsp;     void *pChangeset,
9901**  </pre>
9902**
9903** Is replaced by:
9904**
9905**  <pre>
9906**  &nbsp;     int (*xInput)(void *pIn, void *pData, int *pnData),
9907**  &nbsp;     void *pIn,
9908**  </pre>
9909**
9910** Each time the xInput callback is invoked by the sessions module, the first
9911** argument passed is a copy of the supplied pIn context pointer. The second
9912** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
9913** error occurs the xInput method should copy up to (*pnData) bytes of data
9914** into the buffer and set (*pnData) to the actual number of bytes copied
9915** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
9916** should be set to zero to indicate this. Or, if an error occurs, an SQLite
9917** error code should be returned. In all cases, if an xInput callback returns
9918** an error, all processing is abandoned and the streaming API function
9919** returns a copy of the error code to the caller.
9920**
9921** In the case of sqlite3changeset_start_strm(), the xInput callback may be
9922** invoked by the sessions module at any point during the lifetime of the
9923** iterator. If such an xInput callback returns an error, the iterator enters
9924** an error state, whereby all subsequent calls to iterator functions
9925** immediately fail with the same error code as returned by xInput.
9926**
9927** Similarly, streaming API functions that return changesets (or patchsets)
9928** return them in chunks by way of a callback function instead of via a
9929** pointer to a single large buffer. In this case, a pair of parameters such
9930** as:
9931**
9932**  <pre>
9933**  &nbsp;     int *pnChangeset,
9934**  &nbsp;     void **ppChangeset,
9935**  </pre>
9936**
9937** Is replaced by:
9938**
9939**  <pre>
9940**  &nbsp;     int (*xOutput)(void *pOut, const void *pData, int nData),
9941**  &nbsp;     void *pOut
9942**  </pre>
9943**
9944** The xOutput callback is invoked zero or more times to return data to
9945** the application. The first parameter passed to each call is a copy of the
9946** pOut pointer supplied by the application. The second parameter, pData,
9947** points to a buffer nData bytes in size containing the chunk of output
9948** data being returned. If the xOutput callback successfully processes the
9949** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
9950** it should return some other SQLite error code. In this case processing
9951** is immediately abandoned and the streaming API function returns a copy
9952** of the xOutput error code to the application.
9953**
9954** The sessions module never invokes an xOutput callback with the third
9955** parameter set to a value less than or equal to zero. Other than this,
9956** no guarantees are made as to the size of the chunks of data returned.
9957*/
9958int sqlite3changeset_apply_strm(
9959  sqlite3 *db,                    /* Apply change to "main" db of this handle */
9960  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
9961  void *pIn,                                          /* First arg for xInput */
9962  int(*xFilter)(
9963    void *pCtx,                   /* Copy of sixth arg to _apply() */
9964    const char *zTab              /* Table name */
9965  ),
9966  int(*xConflict)(
9967    void *pCtx,                   /* Copy of sixth arg to _apply() */
9968    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
9969    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
9970  ),
9971  void *pCtx                      /* First argument passed to xConflict */
9972);
9973int sqlite3changeset_concat_strm(
9974  int (*xInputA)(void *pIn, void *pData, int *pnData),
9975  void *pInA,
9976  int (*xInputB)(void *pIn, void *pData, int *pnData),
9977  void *pInB,
9978  int (*xOutput)(void *pOut, const void *pData, int nData),
9979  void *pOut
9980);
9981int sqlite3changeset_invert_strm(
9982  int (*xInput)(void *pIn, void *pData, int *pnData),
9983  void *pIn,
9984  int (*xOutput)(void *pOut, const void *pData, int nData),
9985  void *pOut
9986);
9987int sqlite3changeset_start_strm(
9988  sqlite3_changeset_iter **pp,
9989  int (*xInput)(void *pIn, void *pData, int *pnData),
9990  void *pIn
9991);
9992int sqlite3session_changeset_strm(
9993  sqlite3_session *pSession,
9994  int (*xOutput)(void *pOut, const void *pData, int nData),
9995  void *pOut
9996);
9997int sqlite3session_patchset_strm(
9998  sqlite3_session *pSession,
9999  int (*xOutput)(void *pOut, const void *pData, int nData),
10000  void *pOut
10001);
10002int sqlite3changegroup_add_strm(sqlite3_changegroup*,
10003    int (*xInput)(void *pIn, void *pData, int *pnData),
10004    void *pIn
10005);
10006int sqlite3changegroup_output_strm(sqlite3_changegroup*,
10007    int (*xOutput)(void *pOut, const void *pData, int nData),
10008    void *pOut
10009);
10010
10011
10012/*
10013** Make sure we can call this stuff from C++.
10014*/
10015#if 0
10016}
10017#endif
10018
10019#endif  /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
10020
10021/******** End of sqlite3session.h *********/
10022/******** Begin file fts5.h *********/
10023/*
10024** 2014 May 31
10025**
10026** The author disclaims copyright to this source code.  In place of
10027** a legal notice, here is a blessing:
10028**
10029**    May you do good and not evil.
10030**    May you find forgiveness for yourself and forgive others.
10031**    May you share freely, never taking more than you give.
10032**
10033******************************************************************************
10034**
10035** Interfaces to extend FTS5. Using the interfaces defined in this file,
10036** FTS5 may be extended with:
10037**
10038**     * custom tokenizers, and
10039**     * custom auxiliary functions.
10040*/
10041
10042
10043#ifndef _FTS5_H
10044#define _FTS5_H
10045
10046
10047#if 0
10048extern "C" {
10049#endif
10050
10051/*************************************************************************
10052** CUSTOM AUXILIARY FUNCTIONS
10053**
10054** Virtual table implementations may overload SQL functions by implementing
10055** the sqlite3_module.xFindFunction() method.
10056*/
10057
10058typedef struct Fts5ExtensionApi Fts5ExtensionApi;
10059typedef struct Fts5Context Fts5Context;
10060typedef struct Fts5PhraseIter Fts5PhraseIter;
10061
10062typedef void (*fts5_extension_function)(
10063  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
10064  Fts5Context *pFts,              /* First arg to pass to pApi functions */
10065  sqlite3_context *pCtx,          /* Context for returning result/error */
10066  int nVal,                       /* Number of values in apVal[] array */
10067  sqlite3_value **apVal           /* Array of trailing arguments */
10068);
10069
10070struct Fts5PhraseIter {
10071  const unsigned char *a;
10072  const unsigned char *b;
10073};
10074
10075/*
10076** EXTENSION API FUNCTIONS
10077**
10078** xUserData(pFts):
10079**   Return a copy of the context pointer the extension function was
10080**   registered with.
10081**
10082** xColumnTotalSize(pFts, iCol, pnToken):
10083**   If parameter iCol is less than zero, set output variable *pnToken
10084**   to the total number of tokens in the FTS5 table. Or, if iCol is
10085**   non-negative but less than the number of columns in the table, return
10086**   the total number of tokens in column iCol, considering all rows in
10087**   the FTS5 table.
10088**
10089**   If parameter iCol is greater than or equal to the number of columns
10090**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
10091**   an OOM condition or IO error), an appropriate SQLite error code is
10092**   returned.
10093**
10094** xColumnCount(pFts):
10095**   Return the number of columns in the table.
10096**
10097** xColumnSize(pFts, iCol, pnToken):
10098**   If parameter iCol is less than zero, set output variable *pnToken
10099**   to the total number of tokens in the current row. Or, if iCol is
10100**   non-negative but less than the number of columns in the table, set
10101**   *pnToken to the number of tokens in column iCol of the current row.
10102**
10103**   If parameter iCol is greater than or equal to the number of columns
10104**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
10105**   an OOM condition or IO error), an appropriate SQLite error code is
10106**   returned.
10107**
10108**   This function may be quite inefficient if used with an FTS5 table
10109**   created with the "columnsize=0" option.
10110**
10111** xColumnText:
10112**   This function attempts to retrieve the text of column iCol of the
10113**   current document. If successful, (*pz) is set to point to a buffer
10114**   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
10115**   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
10116**   if an error occurs, an SQLite error code is returned and the final values
10117**   of (*pz) and (*pn) are undefined.
10118**
10119** xPhraseCount:
10120**   Returns the number of phrases in the current query expression.
10121**
10122** xPhraseSize:
10123**   Returns the number of tokens in phrase iPhrase of the query. Phrases
10124**   are numbered starting from zero.
10125**
10126** xInstCount:
10127**   Set *pnInst to the total number of occurrences of all phrases within
10128**   the query within the current row. Return SQLITE_OK if successful, or
10129**   an error code (i.e. SQLITE_NOMEM) if an error occurs.
10130**
10131**   This API can be quite slow if used with an FTS5 table created with the
10132**   "detail=none" or "detail=column" option. If the FTS5 table is created
10133**   with either "detail=none" or "detail=column" and "content=" option
10134**   (i.e. if it is a contentless table), then this API always returns 0.
10135**
10136** xInst:
10137**   Query for the details of phrase match iIdx within the current row.
10138**   Phrase matches are numbered starting from zero, so the iIdx argument
10139**   should be greater than or equal to zero and smaller than the value
10140**   output by xInstCount().
10141**
10142**   Usually, output parameter *piPhrase is set to the phrase number, *piCol
10143**   to the column in which it occurs and *piOff the token offset of the
10144**   first token of the phrase. The exception is if the table was created
10145**   with the offsets=0 option specified. In this case *piOff is always
10146**   set to -1.
10147**
10148**   Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
10149**   if an error occurs.
10150**
10151**   This API can be quite slow if used with an FTS5 table created with the
10152**   "detail=none" or "detail=column" option.
10153**
10154** xRowid:
10155**   Returns the rowid of the current row.
10156**
10157** xTokenize:
10158**   Tokenize text using the tokenizer belonging to the FTS5 table.
10159**
10160** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
10161**   This API function is used to query the FTS table for phrase iPhrase
10162**   of the current query. Specifically, a query equivalent to:
10163**
10164**       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
10165**
10166**   with $p set to a phrase equivalent to the phrase iPhrase of the
10167**   current query is executed. Any column filter that applies to
10168**   phrase iPhrase of the current query is included in $p. For each
10169**   row visited, the callback function passed as the fourth argument
10170**   is invoked. The context and API objects passed to the callback
10171**   function may be used to access the properties of each matched row.
10172**   Invoking Api.xUserData() returns a copy of the pointer passed as
10173**   the third argument to pUserData.
10174**
10175**   If the callback function returns any value other than SQLITE_OK, the
10176**   query is abandoned and the xQueryPhrase function returns immediately.
10177**   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
10178**   Otherwise, the error code is propagated upwards.
10179**
10180**   If the query runs to completion without incident, SQLITE_OK is returned.
10181**   Or, if some error occurs before the query completes or is aborted by
10182**   the callback, an SQLite error code is returned.
10183**
10184**
10185** xSetAuxdata(pFts5, pAux, xDelete)
10186**
10187**   Save the pointer passed as the second argument as the extension functions
10188**   "auxiliary data". The pointer may then be retrieved by the current or any
10189**   future invocation of the same fts5 extension function made as part of
10190**   of the same MATCH query using the xGetAuxdata() API.
10191**
10192**   Each extension function is allocated a single auxiliary data slot for
10193**   each FTS query (MATCH expression). If the extension function is invoked
10194**   more than once for a single FTS query, then all invocations share a
10195**   single auxiliary data context.
10196**
10197**   If there is already an auxiliary data pointer when this function is
10198**   invoked, then it is replaced by the new pointer. If an xDelete callback
10199**   was specified along with the original pointer, it is invoked at this
10200**   point.
10201**
10202**   The xDelete callback, if one is specified, is also invoked on the
10203**   auxiliary data pointer after the FTS5 query has finished.
10204**
10205**   If an error (e.g. an OOM condition) occurs within this function, an
10206**   the auxiliary data is set to NULL and an error code returned. If the
10207**   xDelete parameter was not NULL, it is invoked on the auxiliary data
10208**   pointer before returning.
10209**
10210**
10211** xGetAuxdata(pFts5, bClear)
10212**
10213**   Returns the current auxiliary data pointer for the fts5 extension
10214**   function. See the xSetAuxdata() method for details.
10215**
10216**   If the bClear argument is non-zero, then the auxiliary data is cleared
10217**   (set to NULL) before this function returns. In this case the xDelete,
10218**   if any, is not invoked.
10219**
10220**
10221** xRowCount(pFts5, pnRow)
10222**
10223**   This function is used to retrieve the total number of rows in the table.
10224**   In other words, the same value that would be returned by:
10225**
10226**        SELECT count(*) FROM ftstable;
10227**
10228** xPhraseFirst()
10229**   This function is used, along with type Fts5PhraseIter and the xPhraseNext
10230**   method, to iterate through all instances of a single query phrase within
10231**   the current row. This is the same information as is accessible via the
10232**   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
10233**   to use, this API may be faster under some circumstances. To iterate
10234**   through instances of phrase iPhrase, use the following code:
10235**
10236**       Fts5PhraseIter iter;
10237**       int iCol, iOff;
10238**       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
10239**           iCol>=0;
10240**           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
10241**       ){
10242**         // An instance of phrase iPhrase at offset iOff of column iCol
10243**       }
10244**
10245**   The Fts5PhraseIter structure is defined above. Applications should not
10246**   modify this structure directly - it should only be used as shown above
10247**   with the xPhraseFirst() and xPhraseNext() API methods (and by
10248**   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
10249**
10250**   This API can be quite slow if used with an FTS5 table created with the
10251**   "detail=none" or "detail=column" option. If the FTS5 table is created
10252**   with either "detail=none" or "detail=column" and "content=" option
10253**   (i.e. if it is a contentless table), then this API always iterates
10254**   through an empty set (all calls to xPhraseFirst() set iCol to -1).
10255**
10256** xPhraseNext()
10257**   See xPhraseFirst above.
10258**
10259** xPhraseFirstColumn()
10260**   This function and xPhraseNextColumn() are similar to the xPhraseFirst()
10261**   and xPhraseNext() APIs described above. The difference is that instead
10262**   of iterating through all instances of a phrase in the current row, these
10263**   APIs are used to iterate through the set of columns in the current row
10264**   that contain one or more instances of a specified phrase. For example:
10265**
10266**       Fts5PhraseIter iter;
10267**       int iCol;
10268**       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
10269**           iCol>=0;
10270**           pApi->xPhraseNextColumn(pFts, &iter, &iCol)
10271**       ){
10272**         // Column iCol contains at least one instance of phrase iPhrase
10273**       }
10274**
10275**   This API can be quite slow if used with an FTS5 table created with the
10276**   "detail=none" option. If the FTS5 table is created with either
10277**   "detail=none" "content=" option (i.e. if it is a contentless table),
10278**   then this API always iterates through an empty set (all calls to
10279**   xPhraseFirstColumn() set iCol to -1).
10280**
10281**   The information accessed using this API and its companion
10282**   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
10283**   (or xInst/xInstCount). The chief advantage of this API is that it is
10284**   significantly more efficient than those alternatives when used with
10285**   "detail=column" tables.
10286**
10287** xPhraseNextColumn()
10288**   See xPhraseFirstColumn above.
10289*/
10290struct Fts5ExtensionApi {
10291  int iVersion;                   /* Currently always set to 3 */
10292
10293  void *(*xUserData)(Fts5Context*);
10294
10295  int (*xColumnCount)(Fts5Context*);
10296  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
10297  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
10298
10299  int (*xTokenize)(Fts5Context*,
10300    const char *pText, int nText, /* Text to tokenize */
10301    void *pCtx,                   /* Context passed to xToken() */
10302    int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
10303  );
10304
10305  int (*xPhraseCount)(Fts5Context*);
10306  int (*xPhraseSize)(Fts5Context*, int iPhrase);
10307
10308  int (*xInstCount)(Fts5Context*, int *pnInst);
10309  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
10310
10311  sqlite3_int64 (*xRowid)(Fts5Context*);
10312  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
10313  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
10314
10315  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
10316    int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
10317  );
10318  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
10319  void *(*xGetAuxdata)(Fts5Context*, int bClear);
10320
10321  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
10322  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
10323
10324  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
10325  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
10326};
10327
10328/*
10329** CUSTOM AUXILIARY FUNCTIONS
10330*************************************************************************/
10331
10332/*************************************************************************
10333** CUSTOM TOKENIZERS
10334**
10335** Applications may also register custom tokenizer types. A tokenizer
10336** is registered by providing fts5 with a populated instance of the
10337** following structure. All structure methods must be defined, setting
10338** any member of the fts5_tokenizer struct to NULL leads to undefined
10339** behaviour. The structure methods are expected to function as follows:
10340**
10341** xCreate:
10342**   This function is used to allocate and initialize a tokenizer instance.
10343**   A tokenizer instance is required to actually tokenize text.
10344**
10345**   The first argument passed to this function is a copy of the (void*)
10346**   pointer provided by the application when the fts5_tokenizer object
10347**   was registered with FTS5 (the third argument to xCreateTokenizer()).
10348**   The second and third arguments are an array of nul-terminated strings
10349**   containing the tokenizer arguments, if any, specified following the
10350**   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
10351**   to create the FTS5 table.
10352**
10353**   The final argument is an output variable. If successful, (*ppOut)
10354**   should be set to point to the new tokenizer handle and SQLITE_OK
10355**   returned. If an error occurs, some value other than SQLITE_OK should
10356**   be returned. In this case, fts5 assumes that the final value of *ppOut
10357**   is undefined.
10358**
10359** xDelete:
10360**   This function is invoked to delete a tokenizer handle previously
10361**   allocated using xCreate(). Fts5 guarantees that this function will
10362**   be invoked exactly once for each successful call to xCreate().
10363**
10364** xTokenize:
10365**   This function is expected to tokenize the nText byte string indicated
10366**   by argument pText. pText may or may not be nul-terminated. The first
10367**   argument passed to this function is a pointer to an Fts5Tokenizer object
10368**   returned by an earlier call to xCreate().
10369**
10370**   The second argument indicates the reason that FTS5 is requesting
10371**   tokenization of the supplied text. This is always one of the following
10372**   four values:
10373**
10374**   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
10375**            or removed from the FTS table. The tokenizer is being invoked to
10376**            determine the set of tokens to add to (or delete from) the
10377**            FTS index.
10378**
10379**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
10380**            against the FTS index. The tokenizer is being called to tokenize
10381**            a bareword or quoted string specified as part of the query.
10382**
10383**       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
10384**            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
10385**            followed by a "*" character, indicating that the last token
10386**            returned by the tokenizer will be treated as a token prefix.
10387**
10388**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
10389**            satisfy an fts5_api.xTokenize() request made by an auxiliary
10390**            function. Or an fts5_api.xColumnSize() request made by the same
10391**            on a columnsize=0 database.
10392**   </ul>
10393**
10394**   For each token in the input string, the supplied callback xToken() must
10395**   be invoked. The first argument to it should be a copy of the pointer
10396**   passed as the second argument to xTokenize(). The third and fourth
10397**   arguments are a pointer to a buffer containing the token text, and the
10398**   size of the token in bytes. The 4th and 5th arguments are the byte offsets
10399**   of the first byte of and first byte immediately following the text from
10400**   which the token is derived within the input.
10401**
10402**   The second argument passed to the xToken() callback ("tflags") should
10403**   normally be set to 0. The exception is if the tokenizer supports
10404**   synonyms. In this case see the discussion below for details.
10405**
10406**   FTS5 assumes the xToken() callback is invoked for each token in the
10407**   order that they occur within the input text.
10408**
10409**   If an xToken() callback returns any value other than SQLITE_OK, then
10410**   the tokenization should be abandoned and the xTokenize() method should
10411**   immediately return a copy of the xToken() return value. Or, if the
10412**   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
10413**   if an error occurs with the xTokenize() implementation itself, it
10414**   may abandon the tokenization and return any error code other than
10415**   SQLITE_OK or SQLITE_DONE.
10416**
10417** SYNONYM SUPPORT
10418**
10419**   Custom tokenizers may also support synonyms. Consider a case in which a
10420**   user wishes to query for a phrase such as "first place". Using the
10421**   built-in tokenizers, the FTS5 query 'first + place' will match instances
10422**   of "first place" within the document set, but not alternative forms
10423**   such as "1st place". In some applications, it would be better to match
10424**   all instances of "first place" or "1st place" regardless of which form
10425**   the user specified in the MATCH query text.
10426**
10427**   There are several ways to approach this in FTS5:
10428**
10429**   <ol><li> By mapping all synonyms to a single token. In this case, the
10430**            In the above example, this means that the tokenizer returns the
10431**            same token for inputs "first" and "1st". Say that token is in
10432**            fact "first", so that when the user inserts the document "I won
10433**            1st place" entries are added to the index for tokens "i", "won",
10434**            "first" and "place". If the user then queries for '1st + place',
10435**            the tokenizer substitutes "first" for "1st" and the query works
10436**            as expected.
10437**
10438**       <li> By adding multiple synonyms for a single term to the FTS index.
10439**            In this case, when tokenizing query text, the tokenizer may
10440**            provide multiple synonyms for a single term within the document.
10441**            FTS5 then queries the index for each synonym individually. For
10442**            example, faced with the query:
10443**
10444**   <codeblock>
10445**     ... MATCH 'first place'</codeblock>
10446**
10447**            the tokenizer offers both "1st" and "first" as synonyms for the
10448**            first token in the MATCH query and FTS5 effectively runs a query
10449**            similar to:
10450**
10451**   <codeblock>
10452**     ... MATCH '(first OR 1st) place'</codeblock>
10453**
10454**            except that, for the purposes of auxiliary functions, the query
10455**            still appears to contain just two phrases - "(first OR 1st)"
10456**            being treated as a single phrase.
10457**
10458**       <li> By adding multiple synonyms for a single term to the FTS index.
10459**            Using this method, when tokenizing document text, the tokenizer
10460**            provides multiple synonyms for each token. So that when a
10461**            document such as "I won first place" is tokenized, entries are
10462**            added to the FTS index for "i", "won", "first", "1st" and
10463**            "place".
10464**
10465**            This way, even if the tokenizer does not provide synonyms
10466**            when tokenizing query text (it should not - to do would be
10467**            inefficient), it doesn't matter if the user queries for
10468**            'first + place' or '1st + place', as there are entires in the
10469**            FTS index corresponding to both forms of the first token.
10470**   </ol>
10471**
10472**   Whether it is parsing document or query text, any call to xToken that
10473**   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
10474**   is considered to supply a synonym for the previous token. For example,
10475**   when parsing the document "I won first place", a tokenizer that supports
10476**   synonyms would call xToken() 5 times, as follows:
10477**
10478**   <codeblock>
10479**       xToken(pCtx, 0, "i",                      1,  0,  1);
10480**       xToken(pCtx, 0, "won",                    3,  2,  5);
10481**       xToken(pCtx, 0, "first",                  5,  6, 11);
10482**       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
10483**       xToken(pCtx, 0, "place",                  5, 12, 17);
10484**</codeblock>
10485**
10486**   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
10487**   xToken() is called. Multiple synonyms may be specified for a single token
10488**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
10489**   There is no limit to the number of synonyms that may be provided for a
10490**   single token.
10491**
10492**   In many cases, method (1) above is the best approach. It does not add
10493**   extra data to the FTS index or require FTS5 to query for multiple terms,
10494**   so it is efficient in terms of disk space and query speed. However, it
10495**   does not support prefix queries very well. If, as suggested above, the
10496**   token "first" is subsituted for "1st" by the tokenizer, then the query:
10497**
10498**   <codeblock>
10499**     ... MATCH '1s*'</codeblock>
10500**
10501**   will not match documents that contain the token "1st" (as the tokenizer
10502**   will probably not map "1s" to any prefix of "first").
10503**
10504**   For full prefix support, method (3) may be preferred. In this case,
10505**   because the index contains entries for both "first" and "1st", prefix
10506**   queries such as 'fi*' or '1s*' will match correctly. However, because
10507**   extra entries are added to the FTS index, this method uses more space
10508**   within the database.
10509**
10510**   Method (2) offers a midpoint between (1) and (3). Using this method,
10511**   a query such as '1s*' will match documents that contain the literal
10512**   token "1st", but not "first" (assuming the tokenizer is not able to
10513**   provide synonyms for prefixes). However, a non-prefix query like '1st'
10514**   will match against "1st" and "first". This method does not require
10515**   extra disk space, as no extra entries are added to the FTS index.
10516**   On the other hand, it may require more CPU cycles to run MATCH queries,
10517**   as separate queries of the FTS index are required for each synonym.
10518**
10519**   When using methods (2) or (3), it is important that the tokenizer only
10520**   provide synonyms when tokenizing document text (method (2)) or query
10521**   text (method (3)), not both. Doing so will not cause any errors, but is
10522**   inefficient.
10523*/
10524typedef struct Fts5Tokenizer Fts5Tokenizer;
10525typedef struct fts5_tokenizer fts5_tokenizer;
10526struct fts5_tokenizer {
10527  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
10528  void (*xDelete)(Fts5Tokenizer*);
10529  int (*xTokenize)(Fts5Tokenizer*,
10530      void *pCtx,
10531      int flags,            /* Mask of FTS5_TOKENIZE_* flags */
10532      const char *pText, int nText,
10533      int (*xToken)(
10534        void *pCtx,         /* Copy of 2nd argument to xTokenize() */
10535        int tflags,         /* Mask of FTS5_TOKEN_* flags */
10536        const char *pToken, /* Pointer to buffer containing token */
10537        int nToken,         /* Size of token in bytes */
10538        int iStart,         /* Byte offset of token within input text */
10539        int iEnd            /* Byte offset of end of token within input text */
10540      )
10541  );
10542};
10543
10544/* Flags that may be passed as the third argument to xTokenize() */
10545#define FTS5_TOKENIZE_QUERY     0x0001
10546#define FTS5_TOKENIZE_PREFIX    0x0002
10547#define FTS5_TOKENIZE_DOCUMENT  0x0004
10548#define FTS5_TOKENIZE_AUX       0x0008
10549
10550/* Flags that may be passed by the tokenizer implementation back to FTS5
10551** as the third argument to the supplied xToken callback. */
10552#define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
10553
10554/*
10555** END OF CUSTOM TOKENIZERS
10556*************************************************************************/
10557
10558/*************************************************************************
10559** FTS5 EXTENSION REGISTRATION API
10560*/
10561typedef struct fts5_api fts5_api;
10562struct fts5_api {
10563  int iVersion;                   /* Currently always set to 2 */
10564
10565  /* Create a new tokenizer */
10566  int (*xCreateTokenizer)(
10567    fts5_api *pApi,
10568    const char *zName,
10569    void *pContext,
10570    fts5_tokenizer *pTokenizer,
10571    void (*xDestroy)(void*)
10572  );
10573
10574  /* Find an existing tokenizer */
10575  int (*xFindTokenizer)(
10576    fts5_api *pApi,
10577    const char *zName,
10578    void **ppContext,
10579    fts5_tokenizer *pTokenizer
10580  );
10581
10582  /* Create a new auxiliary function */
10583  int (*xCreateFunction)(
10584    fts5_api *pApi,
10585    const char *zName,
10586    void *pContext,
10587    fts5_extension_function xFunction,
10588    void (*xDestroy)(void*)
10589  );
10590};
10591
10592/*
10593** END OF REGISTRATION API
10594*************************************************************************/
10595
10596#if 0
10597}  /* end of the 'extern "C"' block */
10598#endif
10599
10600#endif /* _FTS5_H */
10601
10602/******** End of fts5.h *********/
10603
10604/************** End of sqlite3.h *********************************************/
10605/************** Continuing where we left off in sqliteInt.h ******************/
10606
10607/*
10608** Include the configuration header output by 'configure' if we're using the
10609** autoconf-based build
10610*/
10611#ifdef _HAVE_SQLITE_CONFIG_H
10612#include "config.h"
10613#endif
10614
10615/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
10616/************** Begin file sqliteLimit.h *************************************/
10617/*
10618** 2007 May 7
10619**
10620** The author disclaims copyright to this source code.  In place of
10621** a legal notice, here is a blessing:
10622**
10623**    May you do good and not evil.
10624**    May you find forgiveness for yourself and forgive others.
10625**    May you share freely, never taking more than you give.
10626**
10627*************************************************************************
10628**
10629** This file defines various limits of what SQLite can process.
10630*/
10631
10632/*
10633** The maximum length of a TEXT or BLOB in bytes.   This also
10634** limits the size of a row in a table or index.
10635**
10636** The hard limit is the ability of a 32-bit signed integer
10637** to count the size: 2^31-1 or 2147483647.
10638*/
10639#ifndef SQLITE_MAX_LENGTH
10640# define SQLITE_MAX_LENGTH 1000000000
10641#endif
10642
10643/*
10644** This is the maximum number of
10645**
10646**    * Columns in a table
10647**    * Columns in an index
10648**    * Columns in a view
10649**    * Terms in the SET clause of an UPDATE statement
10650**    * Terms in the result set of a SELECT statement
10651**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
10652**    * Terms in the VALUES clause of an INSERT statement
10653**
10654** The hard upper limit here is 32676.  Most database people will
10655** tell you that in a well-normalized database, you usually should
10656** not have more than a dozen or so columns in any table.  And if
10657** that is the case, there is no point in having more than a few
10658** dozen values in any of the other situations described above.
10659*/
10660#ifndef SQLITE_MAX_COLUMN
10661# define SQLITE_MAX_COLUMN 2000
10662#endif
10663
10664/*
10665** The maximum length of a single SQL statement in bytes.
10666**
10667** It used to be the case that setting this value to zero would
10668** turn the limit off.  That is no longer true.  It is not possible
10669** to turn this limit off.
10670*/
10671#ifndef SQLITE_MAX_SQL_LENGTH
10672# define SQLITE_MAX_SQL_LENGTH 1000000000
10673#endif
10674
10675/*
10676** The maximum depth of an expression tree. This is limited to
10677** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
10678** want to place more severe limits on the complexity of an
10679** expression.
10680**
10681** A value of 0 used to mean that the limit was not enforced.
10682** But that is no longer true.  The limit is now strictly enforced
10683** at all times.
10684*/
10685#ifndef SQLITE_MAX_EXPR_DEPTH
10686# define SQLITE_MAX_EXPR_DEPTH 1000
10687#endif
10688
10689/*
10690** The maximum number of terms in a compound SELECT statement.
10691** The code generator for compound SELECT statements does one
10692** level of recursion for each term.  A stack overflow can result
10693** if the number of terms is too large.  In practice, most SQL
10694** never has more than 3 or 4 terms.  Use a value of 0 to disable
10695** any limit on the number of terms in a compount SELECT.
10696*/
10697#ifndef SQLITE_MAX_COMPOUND_SELECT
10698# define SQLITE_MAX_COMPOUND_SELECT 500
10699#endif
10700
10701/*
10702** The maximum number of opcodes in a VDBE program.
10703** Not currently enforced.
10704*/
10705#ifndef SQLITE_MAX_VDBE_OP
10706# define SQLITE_MAX_VDBE_OP 25000
10707#endif
10708
10709/*
10710** The maximum number of arguments to an SQL function.
10711*/
10712#ifndef SQLITE_MAX_FUNCTION_ARG
10713# define SQLITE_MAX_FUNCTION_ARG 127
10714#endif
10715
10716/*
10717** The suggested maximum number of in-memory pages to use for
10718** the main database table and for temporary tables.
10719**
10720** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
10721** which means the cache size is limited to 2048000 bytes of memory.
10722** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
10723** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
10724*/
10725#ifndef SQLITE_DEFAULT_CACHE_SIZE
10726# define SQLITE_DEFAULT_CACHE_SIZE  -2000
10727#endif
10728
10729/*
10730** The default number of frames to accumulate in the log file before
10731** checkpointing the database in WAL mode.
10732*/
10733#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
10734# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
10735#endif
10736
10737/*
10738** The maximum number of attached databases.  This must be between 0
10739** and 125.  The upper bound of 125 is because the attached databases are
10740** counted using a signed 8-bit integer which has a maximum value of 127
10741** and we have to allow 2 extra counts for the "main" and "temp" databases.
10742*/
10743#ifndef SQLITE_MAX_ATTACHED
10744# define SQLITE_MAX_ATTACHED 10
10745#endif
10746
10747
10748/*
10749** The maximum value of a ?nnn wildcard that the parser will accept.
10750*/
10751#ifndef SQLITE_MAX_VARIABLE_NUMBER
10752# define SQLITE_MAX_VARIABLE_NUMBER 999
10753#endif
10754
10755/* Maximum page size.  The upper bound on this value is 65536.  This a limit
10756** imposed by the use of 16-bit offsets within each page.
10757**
10758** Earlier versions of SQLite allowed the user to change this value at
10759** compile time. This is no longer permitted, on the grounds that it creates
10760** a library that is technically incompatible with an SQLite library
10761** compiled with a different limit. If a process operating on a database
10762** with a page-size of 65536 bytes crashes, then an instance of SQLite
10763** compiled with the default page-size limit will not be able to rollback
10764** the aborted transaction. This could lead to database corruption.
10765*/
10766#ifdef SQLITE_MAX_PAGE_SIZE
10767# undef SQLITE_MAX_PAGE_SIZE
10768#endif
10769#define SQLITE_MAX_PAGE_SIZE 65536
10770
10771
10772/*
10773** The default size of a database page.
10774*/
10775#ifndef SQLITE_DEFAULT_PAGE_SIZE
10776# define SQLITE_DEFAULT_PAGE_SIZE 4096
10777#endif
10778#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
10779# undef SQLITE_DEFAULT_PAGE_SIZE
10780# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
10781#endif
10782
10783/*
10784** Ordinarily, if no value is explicitly provided, SQLite creates databases
10785** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
10786** device characteristics (sector-size and atomic write() support),
10787** SQLite may choose a larger value. This constant is the maximum value
10788** SQLite will choose on its own.
10789*/
10790#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
10791# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
10792#endif
10793#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
10794# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
10795# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
10796#endif
10797
10798
10799/*
10800** Maximum number of pages in one database file.
10801**
10802** This is really just the default value for the max_page_count pragma.
10803** This value can be lowered (or raised) at run-time using that the
10804** max_page_count macro.
10805*/
10806#ifndef SQLITE_MAX_PAGE_COUNT
10807# define SQLITE_MAX_PAGE_COUNT 1073741823
10808#endif
10809
10810/*
10811** Maximum length (in bytes) of the pattern in a LIKE or GLOB
10812** operator.
10813*/
10814#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
10815# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
10816#endif
10817
10818/*
10819** Maximum depth of recursion for triggers.
10820**
10821** A value of 1 means that a trigger program will not be able to itself
10822** fire any triggers. A value of 0 means that no trigger programs at all
10823** may be executed.
10824*/
10825#ifndef SQLITE_MAX_TRIGGER_DEPTH
10826# define SQLITE_MAX_TRIGGER_DEPTH 1000
10827#endif
10828
10829/************** End of sqliteLimit.h *****************************************/
10830/************** Continuing where we left off in sqliteInt.h ******************/
10831
10832/* Disable nuisance warnings on Borland compilers */
10833#if defined(__BORLANDC__)
10834#pragma warn -rch /* unreachable code */
10835#pragma warn -ccc /* Condition is always true or false */
10836#pragma warn -aus /* Assigned value is never used */
10837#pragma warn -csu /* Comparing signed and unsigned */
10838#pragma warn -spa /* Suspicious pointer arithmetic */
10839#endif
10840
10841/*
10842** Include standard header files as necessary
10843*/
10844#ifdef HAVE_STDINT_H
10845#include <stdint.h>
10846#endif
10847#ifdef HAVE_INTTYPES_H
10848#include <inttypes.h>
10849#endif
10850
10851/*
10852** The following macros are used to cast pointers to integers and
10853** integers to pointers.  The way you do this varies from one compiler
10854** to the next, so we have developed the following set of #if statements
10855** to generate appropriate macros for a wide range of compilers.
10856**
10857** The correct "ANSI" way to do this is to use the intptr_t type.
10858** Unfortunately, that typedef is not available on all compilers, or
10859** if it is available, it requires an #include of specific headers
10860** that vary from one machine to the next.
10861**
10862** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
10863** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
10864** So we have to define the macros in different ways depending on the
10865** compiler.
10866*/
10867#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
10868# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
10869# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
10870#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
10871# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
10872# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
10873#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
10874# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
10875# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
10876#else                          /* Generates a warning - but it always works */
10877# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
10878# define SQLITE_PTR_TO_INT(X)  ((int)(X))
10879#endif
10880
10881/*
10882** A macro to hint to the compiler that a function should not be
10883** inlined.
10884*/
10885#if defined(__GNUC__)
10886#  define SQLITE_NOINLINE  __attribute__((noinline))
10887#elif defined(_MSC_VER) && _MSC_VER>=1310
10888#  define SQLITE_NOINLINE  __declspec(noinline)
10889#else
10890#  define SQLITE_NOINLINE
10891#endif
10892
10893/*
10894** Make sure that the compiler intrinsics we desire are enabled when
10895** compiling with an appropriate version of MSVC unless prevented by
10896** the SQLITE_DISABLE_INTRINSIC define.
10897*/
10898#if !defined(SQLITE_DISABLE_INTRINSIC)
10899#  if defined(_MSC_VER) && _MSC_VER>=1400
10900#    if !defined(_WIN32_WCE)
10901#      include <intrin.h>
10902#      pragma intrinsic(_byteswap_ushort)
10903#      pragma intrinsic(_byteswap_ulong)
10904#      pragma intrinsic(_ReadWriteBarrier)
10905#    else
10906#      include <cmnintrin.h>
10907#    endif
10908#  endif
10909#endif
10910
10911/*
10912** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
10913** 0 means mutexes are permanently disable and the library is never
10914** threadsafe.  1 means the library is serialized which is the highest
10915** level of threadsafety.  2 means the library is multithreaded - multiple
10916** threads can use SQLite as long as no two threads try to use the same
10917** database connection at the same time.
10918**
10919** Older versions of SQLite used an optional THREADSAFE macro.
10920** We support that for legacy.
10921*/
10922#if !defined(SQLITE_THREADSAFE)
10923# if defined(THREADSAFE)
10924#   define SQLITE_THREADSAFE THREADSAFE
10925# else
10926#   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
10927# endif
10928#endif
10929
10930/*
10931** Powersafe overwrite is on by default.  But can be turned off using
10932** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
10933*/
10934#ifndef SQLITE_POWERSAFE_OVERWRITE
10935# define SQLITE_POWERSAFE_OVERWRITE 1
10936#endif
10937
10938/*
10939** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
10940** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
10941** which case memory allocation statistics are disabled by default.
10942*/
10943#if !defined(SQLITE_DEFAULT_MEMSTATUS)
10944# define SQLITE_DEFAULT_MEMSTATUS 1
10945#endif
10946
10947/*
10948** Exactly one of the following macros must be defined in order to
10949** specify which memory allocation subsystem to use.
10950**
10951**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
10952**     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
10953**     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
10954**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
10955**
10956** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
10957** assert() macro is enabled, each call into the Win32 native heap subsystem
10958** will cause HeapValidate to be called.  If heap validation should fail, an
10959** assertion will be triggered.
10960**
10961** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
10962** the default.
10963*/
10964#if defined(SQLITE_SYSTEM_MALLOC) \
10965  + defined(SQLITE_WIN32_MALLOC) \
10966  + defined(SQLITE_ZERO_MALLOC) \
10967  + defined(SQLITE_MEMDEBUG)>1
10968# error "Two or more of the following compile-time configuration options\
10969 are defined but at most one is allowed:\
10970 SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
10971 SQLITE_ZERO_MALLOC"
10972#endif
10973#if defined(SQLITE_SYSTEM_MALLOC) \
10974  + defined(SQLITE_WIN32_MALLOC) \
10975  + defined(SQLITE_ZERO_MALLOC) \
10976  + defined(SQLITE_MEMDEBUG)==0
10977# define SQLITE_SYSTEM_MALLOC 1
10978#endif
10979
10980/*
10981** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
10982** sizes of memory allocations below this value where possible.
10983*/
10984#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
10985# define SQLITE_MALLOC_SOFT_LIMIT 1024
10986#endif
10987
10988/*
10989** We need to define _XOPEN_SOURCE as follows in order to enable
10990** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
10991** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
10992** it.
10993*/
10994#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
10995#  define _XOPEN_SOURCE 600
10996#endif
10997
10998/*
10999** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
11000** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
11001** make it true by defining or undefining NDEBUG.
11002**
11003** Setting NDEBUG makes the code smaller and faster by disabling the
11004** assert() statements in the code.  So we want the default action
11005** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
11006** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
11007** feature.
11008*/
11009#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
11010# define NDEBUG 1
11011#endif
11012#if defined(NDEBUG) && defined(SQLITE_DEBUG)
11013# undef NDEBUG
11014#endif
11015
11016/*
11017** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
11018*/
11019#if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
11020# define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
11021#endif
11022
11023/*
11024** The testcase() macro is used to aid in coverage testing.  When
11025** doing coverage testing, the condition inside the argument to
11026** testcase() must be evaluated both true and false in order to
11027** get full branch coverage.  The testcase() macro is inserted
11028** to help ensure adequate test coverage in places where simple
11029** condition/decision coverage is inadequate.  For example, testcase()
11030** can be used to make sure boundary values are tested.  For
11031** bitmask tests, testcase() can be used to make sure each bit
11032** is significant and used at least once.  On switch statements
11033** where multiple cases go to the same block of code, testcase()
11034** can insure that all cases are evaluated.
11035**
11036*/
11037#ifdef SQLITE_COVERAGE_TEST
11038SQLITE_PRIVATE   void sqlite3Coverage(int);
11039# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
11040#else
11041# define testcase(X)
11042#endif
11043
11044/*
11045** The TESTONLY macro is used to enclose variable declarations or
11046** other bits of code that are needed to support the arguments
11047** within testcase() and assert() macros.
11048*/
11049#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
11050# define TESTONLY(X)  X
11051#else
11052# define TESTONLY(X)
11053#endif
11054
11055/*
11056** Sometimes we need a small amount of code such as a variable initialization
11057** to setup for a later assert() statement.  We do not want this code to
11058** appear when assert() is disabled.  The following macro is therefore
11059** used to contain that setup code.  The "VVA" acronym stands for
11060** "Verification, Validation, and Accreditation".  In other words, the
11061** code within VVA_ONLY() will only run during verification processes.
11062*/
11063#ifndef NDEBUG
11064# define VVA_ONLY(X)  X
11065#else
11066# define VVA_ONLY(X)
11067#endif
11068
11069/*
11070** The ALWAYS and NEVER macros surround boolean expressions which
11071** are intended to always be true or false, respectively.  Such
11072** expressions could be omitted from the code completely.  But they
11073** are included in a few cases in order to enhance the resilience
11074** of SQLite to unexpected behavior - to make the code "self-healing"
11075** or "ductile" rather than being "brittle" and crashing at the first
11076** hint of unplanned behavior.
11077**
11078** In other words, ALWAYS and NEVER are added for defensive code.
11079**
11080** When doing coverage testing ALWAYS and NEVER are hard-coded to
11081** be true and false so that the unreachable code they specify will
11082** not be counted as untested code.
11083*/
11084#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
11085# define ALWAYS(X)      (1)
11086# define NEVER(X)       (0)
11087#elif !defined(NDEBUG)
11088# define ALWAYS(X)      ((X)?1:(assert(0),0))
11089# define NEVER(X)       ((X)?(assert(0),1):0)
11090#else
11091# define ALWAYS(X)      (X)
11092# define NEVER(X)       (X)
11093#endif
11094
11095/*
11096** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
11097** defined.  We need to defend against those failures when testing with
11098** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
11099** during a normal build.  The following macro can be used to disable tests
11100** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
11101*/
11102#if defined(SQLITE_TEST_REALLOC_STRESS)
11103# define ONLY_IF_REALLOC_STRESS(X)  (X)
11104#elif !defined(NDEBUG)
11105# define ONLY_IF_REALLOC_STRESS(X)  ((X)?(assert(0),1):0)
11106#else
11107# define ONLY_IF_REALLOC_STRESS(X)  (0)
11108#endif
11109
11110/*
11111** Declarations used for tracing the operating system interfaces.
11112*/
11113#if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
11114    (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
11115  extern int sqlite3OSTrace;
11116# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
11117# define SQLITE_HAVE_OS_TRACE
11118#else
11119# define OSTRACE(X)
11120# undef  SQLITE_HAVE_OS_TRACE
11121#endif
11122
11123/*
11124** Is the sqlite3ErrName() function needed in the build?  Currently,
11125** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
11126** OSTRACE is enabled), and by several "test*.c" files (which are
11127** compiled using SQLITE_TEST).
11128*/
11129#if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
11130    (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
11131# define SQLITE_NEED_ERR_NAME
11132#else
11133# undef  SQLITE_NEED_ERR_NAME
11134#endif
11135
11136/*
11137** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
11138*/
11139#ifdef SQLITE_OMIT_EXPLAIN
11140# undef SQLITE_ENABLE_EXPLAIN_COMMENTS
11141#endif
11142
11143/*
11144** Return true (non-zero) if the input is an integer that is too large
11145** to fit in 32-bits.  This macro is used inside of various testcase()
11146** macros to verify that we have tested SQLite for large-file support.
11147*/
11148#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
11149
11150/*
11151** The macro unlikely() is a hint that surrounds a boolean
11152** expression that is usually false.  Macro likely() surrounds
11153** a boolean expression that is usually true.  These hints could,
11154** in theory, be used by the compiler to generate better code, but
11155** currently they are just comments for human readers.
11156*/
11157#define likely(X)    (X)
11158#define unlikely(X)  (X)
11159
11160/************** Include hash.h in the middle of sqliteInt.h ******************/
11161/************** Begin file hash.h ********************************************/
11162/*
11163** 2001 September 22
11164**
11165** The author disclaims copyright to this source code.  In place of
11166** a legal notice, here is a blessing:
11167**
11168**    May you do good and not evil.
11169**    May you find forgiveness for yourself and forgive others.
11170**    May you share freely, never taking more than you give.
11171**
11172*************************************************************************
11173** This is the header file for the generic hash-table implementation
11174** used in SQLite.
11175*/
11176#ifndef SQLITE_HASH_H
11177#define SQLITE_HASH_H
11178
11179/* Forward declarations of structures. */
11180typedef struct Hash Hash;
11181typedef struct HashElem HashElem;
11182
11183/* A complete hash table is an instance of the following structure.
11184** The internals of this structure are intended to be opaque -- client
11185** code should not attempt to access or modify the fields of this structure
11186** directly.  Change this structure only by using the routines below.
11187** However, some of the "procedures" and "functions" for modifying and
11188** accessing this structure are really macros, so we can't really make
11189** this structure opaque.
11190**
11191** All elements of the hash table are on a single doubly-linked list.
11192** Hash.first points to the head of this list.
11193**
11194** There are Hash.htsize buckets.  Each bucket points to a spot in
11195** the global doubly-linked list.  The contents of the bucket are the
11196** element pointed to plus the next _ht.count-1 elements in the list.
11197**
11198** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
11199** by a linear search of the global list.  For small tables, the
11200** Hash.ht table is never allocated because if there are few elements
11201** in the table, it is faster to do a linear search than to manage
11202** the hash table.
11203*/
11204struct Hash {
11205  unsigned int htsize;      /* Number of buckets in the hash table */
11206  unsigned int count;       /* Number of entries in this table */
11207  HashElem *first;          /* The first element of the array */
11208  struct _ht {              /* the hash table */
11209    int count;                 /* Number of entries with this hash */
11210    HashElem *chain;           /* Pointer to first entry with this hash */
11211  } *ht;
11212};
11213
11214/* Each element in the hash table is an instance of the following
11215** structure.  All elements are stored on a single doubly-linked list.
11216**
11217** Again, this structure is intended to be opaque, but it can't really
11218** be opaque because it is used by macros.
11219*/
11220struct HashElem {
11221  HashElem *next, *prev;       /* Next and previous elements in the table */
11222  void *data;                  /* Data associated with this element */
11223  const char *pKey;            /* Key associated with this element */
11224};
11225
11226/*
11227** Access routines.  To delete, insert a NULL pointer.
11228*/
11229SQLITE_PRIVATE void sqlite3HashInit(Hash*);
11230SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
11231SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
11232SQLITE_PRIVATE void sqlite3HashClear(Hash*);
11233
11234/*
11235** Macros for looping over all elements of a hash table.  The idiom is
11236** like this:
11237**
11238**   Hash h;
11239**   HashElem *p;
11240**   ...
11241**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
11242**     SomeStructure *pData = sqliteHashData(p);
11243**     // do something with pData
11244**   }
11245*/
11246#define sqliteHashFirst(H)  ((H)->first)
11247#define sqliteHashNext(E)   ((E)->next)
11248#define sqliteHashData(E)   ((E)->data)
11249/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
11250/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
11251
11252/*
11253** Number of entries in a hash table
11254*/
11255/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
11256
11257#endif /* SQLITE_HASH_H */
11258
11259/************** End of hash.h ************************************************/
11260/************** Continuing where we left off in sqliteInt.h ******************/
11261/************** Include parse.h in the middle of sqliteInt.h *****************/
11262/************** Begin file parse.h *******************************************/
11263#define TK_SEMI                             1
11264#define TK_EXPLAIN                          2
11265#define TK_QUERY                            3
11266#define TK_PLAN                             4
11267#define TK_BEGIN                            5
11268#define TK_TRANSACTION                      6
11269#define TK_DEFERRED                         7
11270#define TK_IMMEDIATE                        8
11271#define TK_EXCLUSIVE                        9
11272#define TK_COMMIT                          10
11273#define TK_END                             11
11274#define TK_ROLLBACK                        12
11275#define TK_SAVEPOINT                       13
11276#define TK_RELEASE                         14
11277#define TK_TO                              15
11278#define TK_TABLE                           16
11279#define TK_CREATE                          17
11280#define TK_IF                              18
11281#define TK_NOT                             19
11282#define TK_EXISTS                          20
11283#define TK_TEMP                            21
11284#define TK_LP                              22
11285#define TK_RP                              23
11286#define TK_AS                              24
11287#define TK_WITHOUT                         25
11288#define TK_COMMA                           26
11289#define TK_OR                              27
11290#define TK_AND                             28
11291#define TK_IS                              29
11292#define TK_MATCH                           30
11293#define TK_LIKE_KW                         31
11294#define TK_BETWEEN                         32
11295#define TK_IN                              33
11296#define TK_ISNULL                          34
11297#define TK_NOTNULL                         35
11298#define TK_NE                              36
11299#define TK_EQ                              37
11300#define TK_GT                              38
11301#define TK_LE                              39
11302#define TK_LT                              40
11303#define TK_GE                              41
11304#define TK_ESCAPE                          42
11305#define TK_BITAND                          43
11306#define TK_BITOR                           44
11307#define TK_LSHIFT                          45
11308#define TK_RSHIFT                          46
11309#define TK_PLUS                            47
11310#define TK_MINUS                           48
11311#define TK_STAR                            49
11312#define TK_SLASH                           50
11313#define TK_REM                             51
11314#define TK_CONCAT                          52
11315#define TK_COLLATE                         53
11316#define TK_BITNOT                          54
11317#define TK_ID                              55
11318#define TK_INDEXED                         56
11319#define TK_ABORT                           57
11320#define TK_ACTION                          58
11321#define TK_AFTER                           59
11322#define TK_ANALYZE                         60
11323#define TK_ASC                             61
11324#define TK_ATTACH                          62
11325#define TK_BEFORE                          63
11326#define TK_BY                              64
11327#define TK_CASCADE                         65
11328#define TK_CAST                            66
11329#define TK_COLUMNKW                        67
11330#define TK_CONFLICT                        68
11331#define TK_DATABASE                        69
11332#define TK_DESC                            70
11333#define TK_DETACH                          71
11334#define TK_EACH                            72
11335#define TK_FAIL                            73
11336#define TK_FOR                             74
11337#define TK_IGNORE                          75
11338#define TK_INITIALLY                       76
11339#define TK_INSTEAD                         77
11340#define TK_NO                              78
11341#define TK_KEY                             79
11342#define TK_OF                              80
11343#define TK_OFFSET                          81
11344#define TK_PRAGMA                          82
11345#define TK_RAISE                           83
11346#define TK_RECURSIVE                       84
11347#define TK_REPLACE                         85
11348#define TK_RESTRICT                        86
11349#define TK_ROW                             87
11350#define TK_TRIGGER                         88
11351#define TK_VACUUM                          89
11352#define TK_VIEW                            90
11353#define TK_VIRTUAL                         91
11354#define TK_WITH                            92
11355#define TK_REINDEX                         93
11356#define TK_RENAME                          94
11357#define TK_CTIME_KW                        95
11358#define TK_ANY                             96
11359#define TK_STRING                          97
11360#define TK_JOIN_KW                         98
11361#define TK_CONSTRAINT                      99
11362#define TK_DEFAULT                        100
11363#define TK_NULL                           101
11364#define TK_PRIMARY                        102
11365#define TK_UNIQUE                         103
11366#define TK_CHECK                          104
11367#define TK_REFERENCES                     105
11368#define TK_AUTOINCR                       106
11369#define TK_ON                             107
11370#define TK_INSERT                         108
11371#define TK_DELETE                         109
11372#define TK_UPDATE                         110
11373#define TK_SET                            111
11374#define TK_DEFERRABLE                     112
11375#define TK_FOREIGN                        113
11376#define TK_DROP                           114
11377#define TK_UNION                          115
11378#define TK_ALL                            116
11379#define TK_EXCEPT                         117
11380#define TK_INTERSECT                      118
11381#define TK_SELECT                         119
11382#define TK_VALUES                         120
11383#define TK_DISTINCT                       121
11384#define TK_DOT                            122
11385#define TK_FROM                           123
11386#define TK_JOIN                           124
11387#define TK_USING                          125
11388#define TK_ORDER                          126
11389#define TK_GROUP                          127
11390#define TK_HAVING                         128
11391#define TK_LIMIT                          129
11392#define TK_WHERE                          130
11393#define TK_INTO                           131
11394#define TK_INTEGER                        132
11395#define TK_FLOAT                          133
11396#define TK_BLOB                           134
11397#define TK_VARIABLE                       135
11398#define TK_CASE                           136
11399#define TK_WHEN                           137
11400#define TK_THEN                           138
11401#define TK_ELSE                           139
11402#define TK_INDEX                          140
11403#define TK_ALTER                          141
11404#define TK_ADD                            142
11405#define TK_TO_TEXT                        143
11406#define TK_TO_BLOB                        144
11407#define TK_TO_NUMERIC                     145
11408#define TK_TO_INT                         146
11409#define TK_TO_REAL                        147
11410#define TK_ISNOT                          148
11411#define TK_END_OF_FILE                    149
11412#define TK_UNCLOSED_STRING                150
11413#define TK_FUNCTION                       151
11414#define TK_COLUMN                         152
11415#define TK_AGG_FUNCTION                   153
11416#define TK_AGG_COLUMN                     154
11417#define TK_UMINUS                         155
11418#define TK_UPLUS                          156
11419#define TK_REGISTER                       157
11420#define TK_ASTERISK                       158
11421#define TK_SPAN                           159
11422#define TK_SPACE                          160
11423#define TK_ILLEGAL                        161
11424
11425/* The token codes above must all fit in 8 bits */
11426#define TKFLG_MASK           0xff
11427
11428/* Flags that can be added to a token code when it is not
11429** being stored in a u8: */
11430#define TKFLG_DONTFOLD       0x100  /* Omit constant folding optimizations */
11431
11432/************** End of parse.h ***********************************************/
11433/************** Continuing where we left off in sqliteInt.h ******************/
11434#include <stdio.h>
11435#include <stdlib.h>
11436#include <string.h>
11437#include <assert.h>
11438#include <stddef.h>
11439
11440/*
11441** If compiling for a processor that lacks floating point support,
11442** substitute integer for floating-point
11443*/
11444#ifdef SQLITE_OMIT_FLOATING_POINT
11445# define double sqlite_int64
11446# define float sqlite_int64
11447# define LONGDOUBLE_TYPE sqlite_int64
11448# ifndef SQLITE_BIG_DBL
11449#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
11450# endif
11451# define SQLITE_OMIT_DATETIME_FUNCS 1
11452# define SQLITE_OMIT_TRACE 1
11453# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11454# undef SQLITE_HAVE_ISNAN
11455#endif
11456#ifndef SQLITE_BIG_DBL
11457# define SQLITE_BIG_DBL (1e99)
11458#endif
11459
11460/*
11461** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
11462** afterward. Having this macro allows us to cause the C compiler
11463** to omit code used by TEMP tables without messy #ifndef statements.
11464*/
11465#ifdef SQLITE_OMIT_TEMPDB
11466#define OMIT_TEMPDB 1
11467#else
11468#define OMIT_TEMPDB 0
11469#endif
11470
11471/*
11472** The "file format" number is an integer that is incremented whenever
11473** the VDBE-level file format changes.  The following macros define the
11474** the default file format for new databases and the maximum file format
11475** that the library can read.
11476*/
11477#define SQLITE_MAX_FILE_FORMAT 4
11478#ifndef SQLITE_DEFAULT_FILE_FORMAT
11479# define SQLITE_DEFAULT_FILE_FORMAT 4
11480#endif
11481
11482/*
11483** Determine whether triggers are recursive by default.  This can be
11484** changed at run-time using a pragma.
11485*/
11486#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
11487# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
11488#endif
11489
11490/*
11491** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
11492** on the command-line
11493*/
11494#ifndef SQLITE_TEMP_STORE
11495# define SQLITE_TEMP_STORE 1
11496# define SQLITE_TEMP_STORE_xc 1  /* Exclude from ctime.c */
11497#endif
11498
11499/*
11500** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
11501** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
11502** to zero.
11503*/
11504#if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
11505# undef SQLITE_MAX_WORKER_THREADS
11506# define SQLITE_MAX_WORKER_THREADS 0
11507#endif
11508#ifndef SQLITE_MAX_WORKER_THREADS
11509# define SQLITE_MAX_WORKER_THREADS 8
11510#endif
11511#ifndef SQLITE_DEFAULT_WORKER_THREADS
11512# define SQLITE_DEFAULT_WORKER_THREADS 0
11513#endif
11514#if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
11515# undef SQLITE_MAX_WORKER_THREADS
11516# define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
11517#endif
11518
11519/*
11520** The default initial allocation for the pagecache when using separate
11521** pagecaches for each database connection.  A positive number is the
11522** number of pages.  A negative number N translations means that a buffer
11523** of -1024*N bytes is allocated and used for as many pages as it will hold.
11524*/
11525#ifndef SQLITE_DEFAULT_PCACHE_INITSZ
11526# define SQLITE_DEFAULT_PCACHE_INITSZ 100
11527#endif
11528
11529/*
11530** GCC does not define the offsetof() macro so we'll have to do it
11531** ourselves.
11532*/
11533#ifndef offsetof
11534#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
11535#endif
11536
11537/*
11538** Macros to compute minimum and maximum of two numbers.
11539*/
11540#ifndef MIN
11541# define MIN(A,B) ((A)<(B)?(A):(B))
11542#endif
11543#ifndef MAX
11544# define MAX(A,B) ((A)>(B)?(A):(B))
11545#endif
11546
11547/*
11548** Swap two objects of type TYPE.
11549*/
11550#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
11551
11552/*
11553** Check to see if this machine uses EBCDIC.  (Yes, believe it or
11554** not, there are still machines out there that use EBCDIC.)
11555*/
11556#if 'A' == '\301'
11557# define SQLITE_EBCDIC 1
11558#else
11559# define SQLITE_ASCII 1
11560#endif
11561
11562/*
11563** Integers of known sizes.  These typedefs might change for architectures
11564** where the sizes very.  Preprocessor macros are available so that the
11565** types can be conveniently redefined at compile-type.  Like this:
11566**
11567**         cc '-DUINTPTR_TYPE=long long int' ...
11568*/
11569#ifndef UINT32_TYPE
11570# ifdef HAVE_UINT32_T
11571#  define UINT32_TYPE uint32_t
11572# else
11573#  define UINT32_TYPE unsigned int
11574# endif
11575#endif
11576#ifndef UINT16_TYPE
11577# ifdef HAVE_UINT16_T
11578#  define UINT16_TYPE uint16_t
11579# else
11580#  define UINT16_TYPE unsigned short int
11581# endif
11582#endif
11583#ifndef INT16_TYPE
11584# ifdef HAVE_INT16_T
11585#  define INT16_TYPE int16_t
11586# else
11587#  define INT16_TYPE short int
11588# endif
11589#endif
11590#ifndef UINT8_TYPE
11591# ifdef HAVE_UINT8_T
11592#  define UINT8_TYPE uint8_t
11593# else
11594#  define UINT8_TYPE unsigned char
11595# endif
11596#endif
11597#ifndef INT8_TYPE
11598# ifdef HAVE_INT8_T
11599#  define INT8_TYPE int8_t
11600# else
11601#  define INT8_TYPE signed char
11602# endif
11603#endif
11604#ifndef LONGDOUBLE_TYPE
11605# define LONGDOUBLE_TYPE long double
11606#endif
11607typedef sqlite_int64 i64;          /* 8-byte signed integer */
11608typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
11609typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
11610typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
11611typedef INT16_TYPE i16;            /* 2-byte signed integer */
11612typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
11613typedef INT8_TYPE i8;              /* 1-byte signed integer */
11614
11615/*
11616** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
11617** that can be stored in a u32 without loss of data.  The value
11618** is 0x00000000ffffffff.  But because of quirks of some compilers, we
11619** have to specify the value in the less intuitive manner shown:
11620*/
11621#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
11622
11623/*
11624** The datatype used to store estimates of the number of rows in a
11625** table or index.  This is an unsigned integer type.  For 99.9% of
11626** the world, a 32-bit integer is sufficient.  But a 64-bit integer
11627** can be used at compile-time if desired.
11628*/
11629#ifdef SQLITE_64BIT_STATS
11630 typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
11631#else
11632 typedef u32 tRowcnt;    /* 32-bit is the default */
11633#endif
11634
11635/*
11636** Estimated quantities used for query planning are stored as 16-bit
11637** logarithms.  For quantity X, the value stored is 10*log2(X).  This
11638** gives a possible range of values of approximately 1.0e986 to 1e-986.
11639** But the allowed values are "grainy".  Not every value is representable.
11640** For example, quantities 16 and 17 are both represented by a LogEst
11641** of 40.  However, since LogEst quantities are suppose to be estimates,
11642** not exact values, this imprecision is not a problem.
11643**
11644** "LogEst" is short for "Logarithmic Estimate".
11645**
11646** Examples:
11647**      1 -> 0              20 -> 43          10000 -> 132
11648**      2 -> 10             25 -> 46          25000 -> 146
11649**      3 -> 16            100 -> 66        1000000 -> 199
11650**      4 -> 20           1000 -> 99        1048576 -> 200
11651**     10 -> 33           1024 -> 100    4294967296 -> 320
11652**
11653** The LogEst can be negative to indicate fractional values.
11654** Examples:
11655**
11656**    0.5 -> -10           0.1 -> -33        0.0625 -> -40
11657*/
11658typedef INT16_TYPE LogEst;
11659
11660/*
11661** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
11662*/
11663#ifndef SQLITE_PTRSIZE
11664# if defined(__SIZEOF_POINTER__)
11665#   define SQLITE_PTRSIZE __SIZEOF_POINTER__
11666# elif defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
11667       defined(_M_ARM)   || defined(__arm__)    || defined(__x86)
11668#   define SQLITE_PTRSIZE 4
11669# else
11670#   define SQLITE_PTRSIZE 8
11671# endif
11672#endif
11673
11674/* The uptr type is an unsigned integer large enough to hold a pointer
11675*/
11676#if defined(HAVE_STDINT_H)
11677  typedef uintptr_t uptr;
11678#elif SQLITE_PTRSIZE==4
11679  typedef u32 uptr;
11680#else
11681  typedef u64 uptr;
11682#endif
11683
11684/*
11685** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
11686** something between S (inclusive) and E (exclusive).
11687**
11688** In other words, S is a buffer and E is a pointer to the first byte after
11689** the end of buffer S.  This macro returns true if P points to something
11690** contained within the buffer S.
11691*/
11692#define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
11693
11694
11695/*
11696** Macros to determine whether the machine is big or little endian,
11697** and whether or not that determination is run-time or compile-time.
11698**
11699** For best performance, an attempt is made to guess at the byte-order
11700** using C-preprocessor macros.  If that is unsuccessful, or if
11701** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
11702** at run-time.
11703*/
11704#if (defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
11705     defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
11706     defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
11707     defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
11708# define SQLITE_BYTEORDER    1234
11709# define SQLITE_BIGENDIAN    0
11710# define SQLITE_LITTLEENDIAN 1
11711# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
11712#endif
11713#if (defined(sparc)    || defined(__ppc__))  \
11714    && !defined(SQLITE_RUNTIME_BYTEORDER)
11715# define SQLITE_BYTEORDER    4321
11716# define SQLITE_BIGENDIAN    1
11717# define SQLITE_LITTLEENDIAN 0
11718# define SQLITE_UTF16NATIVE  SQLITE_UTF16BE
11719#endif
11720#if !defined(SQLITE_BYTEORDER)
11721# ifdef SQLITE_AMALGAMATION
11722  const int sqlite3one = 1;
11723# else
11724  extern const int sqlite3one;
11725# endif
11726# define SQLITE_BYTEORDER    0     /* 0 means "unknown at compile-time" */
11727# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
11728# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
11729# define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
11730#endif
11731
11732/*
11733** Constants for the largest and smallest possible 64-bit signed integers.
11734** These macros are designed to work correctly on both 32-bit and 64-bit
11735** compilers.
11736*/
11737#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
11738#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
11739
11740/*
11741** Round up a number to the next larger multiple of 8.  This is used
11742** to force 8-byte alignment on 64-bit architectures.
11743*/
11744#define ROUND8(x)     (((x)+7)&~7)
11745
11746/*
11747** Round down to the nearest multiple of 8
11748*/
11749#define ROUNDDOWN8(x) ((x)&~7)
11750
11751/*
11752** Assert that the pointer X is aligned to an 8-byte boundary.  This
11753** macro is used only within assert() to verify that the code gets
11754** all alignment restrictions correct.
11755**
11756** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
11757** underlying malloc() implementation might return us 4-byte aligned
11758** pointers.  In that case, only verify 4-byte alignment.
11759*/
11760#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11761# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
11762#else
11763# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
11764#endif
11765
11766/*
11767** Disable MMAP on platforms where it is known to not work
11768*/
11769#if defined(__OpenBSD__) || defined(__QNXNTO__)
11770# undef SQLITE_MAX_MMAP_SIZE
11771# define SQLITE_MAX_MMAP_SIZE 0
11772#endif
11773
11774/*
11775** Default maximum size of memory used by memory-mapped I/O in the VFS
11776*/
11777#ifdef __APPLE__
11778# include <TargetConditionals.h>
11779#endif
11780#ifndef SQLITE_MAX_MMAP_SIZE
11781# if defined(__linux__) \
11782  || defined(_WIN32) \
11783  || (defined(__APPLE__) && defined(__MACH__)) \
11784  || defined(__sun) \
11785  || defined(__FreeBSD__) \
11786  || defined(__DragonFly__)
11787#   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
11788# else
11789#   define SQLITE_MAX_MMAP_SIZE 0
11790# endif
11791# define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
11792#endif
11793
11794/*
11795** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
11796** default MMAP_SIZE is specified at compile-time, make sure that it does
11797** not exceed the maximum mmap size.
11798*/
11799#ifndef SQLITE_DEFAULT_MMAP_SIZE
11800# define SQLITE_DEFAULT_MMAP_SIZE 0
11801# define SQLITE_DEFAULT_MMAP_SIZE_xc 1  /* Exclude from ctime.c */
11802#endif
11803#if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
11804# undef SQLITE_DEFAULT_MMAP_SIZE
11805# define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
11806#endif
11807
11808/*
11809** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
11810** Priority is given to SQLITE_ENABLE_STAT4.  If either are defined, also
11811** define SQLITE_ENABLE_STAT3_OR_STAT4
11812*/
11813#ifdef SQLITE_ENABLE_STAT4
11814# undef SQLITE_ENABLE_STAT3
11815# define SQLITE_ENABLE_STAT3_OR_STAT4 1
11816#elif SQLITE_ENABLE_STAT3
11817# define SQLITE_ENABLE_STAT3_OR_STAT4 1
11818#elif SQLITE_ENABLE_STAT3_OR_STAT4
11819# undef SQLITE_ENABLE_STAT3_OR_STAT4
11820#endif
11821
11822/*
11823** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
11824** the Select query generator tracing logic is turned on.
11825*/
11826#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
11827# define SELECTTRACE_ENABLED 1
11828#else
11829# define SELECTTRACE_ENABLED 0
11830#endif
11831
11832/*
11833** An instance of the following structure is used to store the busy-handler
11834** callback for a given sqlite handle.
11835**
11836** The sqlite.busyHandler member of the sqlite struct contains the busy
11837** callback for the database handle. Each pager opened via the sqlite
11838** handle is passed a pointer to sqlite.busyHandler. The busy-handler
11839** callback is currently invoked only from within pager.c.
11840*/
11841typedef struct BusyHandler BusyHandler;
11842struct BusyHandler {
11843  int (*xFunc)(void *,int);  /* The busy callback */
11844  void *pArg;                /* First arg to busy callback */
11845  int nBusy;                 /* Incremented with each busy call */
11846};
11847
11848/*
11849** Name of the master database table.  The master database table
11850** is a special table that holds the names and attributes of all
11851** user tables and indices.
11852*/
11853#define MASTER_NAME       "sqlite_master"
11854#define TEMP_MASTER_NAME  "sqlite_temp_master"
11855
11856/*
11857** The root-page of the master database table.
11858*/
11859#define MASTER_ROOT       1
11860
11861/*
11862** The name of the schema table.
11863*/
11864#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
11865
11866/*
11867** A convenience macro that returns the number of elements in
11868** an array.
11869*/
11870#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
11871
11872/*
11873** Determine if the argument is a power of two
11874*/
11875#define IsPowerOfTwo(X) (((X)&((X)-1))==0)
11876
11877/*
11878** The following value as a destructor means to use sqlite3DbFree().
11879** The sqlite3DbFree() routine requires two parameters instead of the
11880** one parameter that destructors normally want.  So we have to introduce
11881** this magic value that the code knows to handle differently.  Any
11882** pointer will work here as long as it is distinct from SQLITE_STATIC
11883** and SQLITE_TRANSIENT.
11884*/
11885#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
11886
11887/*
11888** When SQLITE_OMIT_WSD is defined, it means that the target platform does
11889** not support Writable Static Data (WSD) such as global and static variables.
11890** All variables must either be on the stack or dynamically allocated from
11891** the heap.  When WSD is unsupported, the variable declarations scattered
11892** throughout the SQLite code must become constants instead.  The SQLITE_WSD
11893** macro is used for this purpose.  And instead of referencing the variable
11894** directly, we use its constant as a key to lookup the run-time allocated
11895** buffer that holds real variable.  The constant is also the initializer
11896** for the run-time allocated buffer.
11897**
11898** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
11899** macros become no-ops and have zero performance impact.
11900*/
11901#ifdef SQLITE_OMIT_WSD
11902  #define SQLITE_WSD const
11903  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
11904  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
11905SQLITE_API int SQLITE_STDCALL sqlite3_wsd_init(int N, int J);
11906SQLITE_API void *SQLITE_STDCALL sqlite3_wsd_find(void *K, int L);
11907#else
11908  #define SQLITE_WSD
11909  #define GLOBAL(t,v) v
11910  #define sqlite3GlobalConfig sqlite3Config
11911#endif
11912
11913/*
11914** The following macros are used to suppress compiler warnings and to
11915** make it clear to human readers when a function parameter is deliberately
11916** left unused within the body of a function. This usually happens when
11917** a function is called via a function pointer. For example the
11918** implementation of an SQL aggregate step callback may not use the
11919** parameter indicating the number of arguments passed to the aggregate,
11920** if it knows that this is enforced elsewhere.
11921**
11922** When a function parameter is not used at all within the body of a function,
11923** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
11924** However, these macros may also be used to suppress warnings related to
11925** parameters that may or may not be used depending on compilation options.
11926** For example those parameters only used in assert() statements. In these
11927** cases the parameters are named as per the usual conventions.
11928*/
11929#define UNUSED_PARAMETER(x) (void)(x)
11930#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
11931
11932/*
11933** Forward references to structures
11934*/
11935typedef struct AggInfo AggInfo;
11936typedef struct AuthContext AuthContext;
11937typedef struct AutoincInfo AutoincInfo;
11938typedef struct Bitvec Bitvec;
11939typedef struct CollSeq CollSeq;
11940typedef struct Column Column;
11941typedef struct Db Db;
11942typedef struct Schema Schema;
11943typedef struct Expr Expr;
11944typedef struct ExprList ExprList;
11945typedef struct ExprSpan ExprSpan;
11946typedef struct FKey FKey;
11947typedef struct FuncDestructor FuncDestructor;
11948typedef struct FuncDef FuncDef;
11949typedef struct FuncDefHash FuncDefHash;
11950typedef struct IdList IdList;
11951typedef struct Index Index;
11952typedef struct IndexSample IndexSample;
11953typedef struct KeyClass KeyClass;
11954typedef struct KeyInfo KeyInfo;
11955typedef struct Lookaside Lookaside;
11956typedef struct LookasideSlot LookasideSlot;
11957typedef struct Module Module;
11958typedef struct NameContext NameContext;
11959typedef struct Parse Parse;
11960typedef struct PreUpdate PreUpdate;
11961typedef struct PrintfArguments PrintfArguments;
11962typedef struct RowSet RowSet;
11963typedef struct Savepoint Savepoint;
11964typedef struct Select Select;
11965typedef struct SQLiteThread SQLiteThread;
11966typedef struct SelectDest SelectDest;
11967typedef struct SrcList SrcList;
11968typedef struct StrAccum StrAccum;
11969typedef struct Table Table;
11970typedef struct TableLock TableLock;
11971typedef struct Token Token;
11972typedef struct TreeView TreeView;
11973typedef struct Trigger Trigger;
11974typedef struct TriggerPrg TriggerPrg;
11975typedef struct TriggerStep TriggerStep;
11976typedef struct UnpackedRecord UnpackedRecord;
11977typedef struct VTable VTable;
11978typedef struct VtabCtx VtabCtx;
11979typedef struct Walker Walker;
11980typedef struct WhereInfo WhereInfo;
11981typedef struct With With;
11982
11983/*
11984** Defer sourcing vdbe.h and btree.h until after the "u8" and
11985** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
11986** pointer types (i.e. FuncDef) defined above.
11987*/
11988/************** Include btree.h in the middle of sqliteInt.h *****************/
11989/************** Begin file btree.h *******************************************/
11990/*
11991** 2001 September 15
11992**
11993** The author disclaims copyright to this source code.  In place of
11994** a legal notice, here is a blessing:
11995**
11996**    May you do good and not evil.
11997**    May you find forgiveness for yourself and forgive others.
11998**    May you share freely, never taking more than you give.
11999**
12000*************************************************************************
12001** This header file defines the interface that the sqlite B-Tree file
12002** subsystem.  See comments in the source code for a detailed description
12003** of what each interface routine does.
12004*/
12005#ifndef SQLITE_BTREE_H
12006#define SQLITE_BTREE_H
12007
12008/* TODO: This definition is just included so other modules compile. It
12009** needs to be revisited.
12010*/
12011#define SQLITE_N_BTREE_META 16
12012
12013/*
12014** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
12015** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
12016*/
12017#ifndef SQLITE_DEFAULT_AUTOVACUUM
12018  #define SQLITE_DEFAULT_AUTOVACUUM 0
12019#endif
12020
12021#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
12022#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
12023#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
12024
12025/*
12026** Forward declarations of structure
12027*/
12028typedef struct Btree Btree;
12029typedef struct BtCursor BtCursor;
12030typedef struct BtShared BtShared;
12031typedef struct BtreePayload BtreePayload;
12032
12033
12034SQLITE_PRIVATE int sqlite3BtreeOpen(
12035  sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
12036  const char *zFilename,   /* Name of database file to open */
12037  sqlite3 *db,             /* Associated database connection */
12038  Btree **ppBtree,         /* Return open Btree* here */
12039  int flags,               /* Flags */
12040  int vfsFlags             /* Flags passed through to VFS open */
12041);
12042
12043/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
12044** following values.
12045**
12046** NOTE:  These values must match the corresponding PAGER_ values in
12047** pager.h.
12048*/
12049#define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
12050#define BTREE_MEMORY        2  /* This is an in-memory DB */
12051#define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
12052#define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
12053
12054SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
12055SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
12056SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
12057#if SQLITE_MAX_MMAP_SIZE>0
12058SQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
12059#endif
12060SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
12061SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
12062SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
12063SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
12064SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
12065SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
12066SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
12067SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
12068SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
12069SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
12070SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
12071SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
12072SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
12073SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
12074SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
12075SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
12076SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
12077SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
12078SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
12079SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
12080SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
12081SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
12082SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
12083SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
12084
12085SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
12086SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
12087SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
12088
12089SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
12090
12091/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
12092** of the flags shown below.
12093**
12094** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
12095** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
12096** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
12097** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
12098** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
12099** indices.)
12100*/
12101#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
12102#define BTREE_BLOBKEY    2    /* Table has keys only - no data */
12103
12104SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
12105SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
12106SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
12107SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
12108
12109SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
12110SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
12111
12112SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
12113
12114/*
12115** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
12116** should be one of the following values. The integer values are assigned
12117** to constants so that the offset of the corresponding field in an
12118** SQLite database header may be found using the following formula:
12119**
12120**   offset = 36 + (idx * 4)
12121**
12122** For example, the free-page-count field is located at byte offset 36 of
12123** the database file header. The incr-vacuum-flag field is located at
12124** byte offset 64 (== 36+4*7).
12125**
12126** The BTREE_DATA_VERSION value is not really a value stored in the header.
12127** It is a read-only number computed by the pager.  But we merge it with
12128** the header value access routines since its access pattern is the same.
12129** Call it a "virtual meta value".
12130*/
12131#define BTREE_FREE_PAGE_COUNT     0
12132#define BTREE_SCHEMA_VERSION      1
12133#define BTREE_FILE_FORMAT         2
12134#define BTREE_DEFAULT_CACHE_SIZE  3
12135#define BTREE_LARGEST_ROOT_PAGE   4
12136#define BTREE_TEXT_ENCODING       5
12137#define BTREE_USER_VERSION        6
12138#define BTREE_INCR_VACUUM         7
12139#define BTREE_APPLICATION_ID      8
12140#define BTREE_DATA_VERSION        15  /* A virtual meta-value */
12141
12142/*
12143** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
12144** interface.
12145**
12146** BTREE_HINT_RANGE  (arguments: Expr*, Mem*)
12147**
12148**     The first argument is an Expr* (which is guaranteed to be constant for
12149**     the lifetime of the cursor) that defines constraints on which rows
12150**     might be fetched with this cursor.  The Expr* tree may contain
12151**     TK_REGISTER nodes that refer to values stored in the array of registers
12152**     passed as the second parameter.  In other words, if Expr.op==TK_REGISTER
12153**     then the value of the node is the value in Mem[pExpr.iTable].  Any
12154**     TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
12155**     column of the b-tree of the cursor.  The Expr tree will not contain
12156**     any function calls nor subqueries nor references to b-trees other than
12157**     the cursor being hinted.
12158**
12159**     The design of the _RANGE hint is aid b-tree implementations that try
12160**     to prefetch content from remote machines - to provide those
12161**     implementations with limits on what needs to be prefetched and thereby
12162**     reduce network bandwidth.
12163**
12164** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
12165** standard SQLite.  The other hints are provided for extentions that use
12166** the SQLite parser and code generator but substitute their own storage
12167** engine.
12168*/
12169#define BTREE_HINT_RANGE 0       /* Range constraints on queries */
12170
12171/*
12172** Values that may be OR'd together to form the argument to the
12173** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
12174**
12175** The BTREE_BULKLOAD flag is set on index cursors when the index is going
12176** to be filled with content that is already in sorted order.
12177**
12178** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
12179** OP_SeekLE opcodes for a range search, but where the range of entries
12180** selected will all have the same key.  In other words, the cursor will
12181** be used only for equality key searches.
12182**
12183*/
12184#define BTREE_BULKLOAD 0x00000001  /* Used to full index in sorted order */
12185#define BTREE_SEEK_EQ  0x00000002  /* EQ seeks only - no range seeks */
12186
12187/*
12188** Flags passed as the third argument to sqlite3BtreeCursor().
12189**
12190** For read-only cursors the wrFlag argument is always zero. For read-write
12191** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
12192** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
12193** only be used by SQLite for the following:
12194**
12195**   * to seek to and then delete specific entries, and/or
12196**
12197**   * to read values that will be used to create keys that other
12198**     BTREE_FORDELETE cursors will seek to and delete.
12199**
12200** The BTREE_FORDELETE flag is an optimization hint.  It is not used by
12201** by this, the native b-tree engine of SQLite, but it is available to
12202** alternative storage engines that might be substituted in place of this
12203** b-tree system.  For alternative storage engines in which a delete of
12204** the main table row automatically deletes corresponding index rows,
12205** the FORDELETE flag hint allows those alternative storage engines to
12206** skip a lot of work.  Namely:  FORDELETE cursors may treat all SEEK
12207** and DELETE operations as no-ops, and any READ operation against a
12208** FORDELETE cursor may return a null row: 0x01 0x00.
12209*/
12210#define BTREE_WRCSR     0x00000004     /* read-write cursor */
12211#define BTREE_FORDELETE 0x00000008     /* Cursor is for seek/delete only */
12212
12213SQLITE_PRIVATE int sqlite3BtreeCursor(
12214  Btree*,                              /* BTree containing table to open */
12215  int iTable,                          /* Index of root page */
12216  int wrFlag,                          /* 1 for writing.  0 for read-only */
12217  struct KeyInfo*,                     /* First argument to compare function */
12218  BtCursor *pCursor                    /* Space to write cursor structure */
12219);
12220SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
12221SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
12222SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
12223#ifdef SQLITE_ENABLE_CURSOR_HINTS
12224SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
12225#endif
12226
12227SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
12228SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
12229  BtCursor*,
12230  UnpackedRecord *pUnKey,
12231  i64 intKey,
12232  int bias,
12233  int *pRes
12234);
12235SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
12236SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
12237SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
12238
12239/* Allowed flags for the 2nd argument to sqlite3BtreeDelete() */
12240#define BTREE_SAVEPOSITION 0x02  /* Leave cursor pointing at NEXT or PREV */
12241#define BTREE_AUXDELETE    0x04  /* not the primary delete operation */
12242
12243/* An instance of the BtreePayload object describes the content of a single
12244** entry in either an index or table btree.
12245**
12246** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
12247** an arbitrary key and no data.  These btrees have pKey,nKey set to their
12248** key and pData,nData,nZero set to zero.
12249**
12250** Table btrees (used for rowid tables) contain an integer rowid used as
12251** the key and passed in the nKey field.  The pKey field is zero.
12252** pData,nData hold the content of the new entry.  nZero extra zero bytes
12253** are appended to the end of the content when constructing the entry.
12254**
12255** This object is used to pass information into sqlite3BtreeInsert().  The
12256** same information used to be passed as five separate parameters.  But placing
12257** the information into this object helps to keep the interface more
12258** organized and understandable, and it also helps the resulting code to
12259** run a little faster by using fewer registers for parameter passing.
12260*/
12261struct BtreePayload {
12262  const void *pKey;       /* Key content for indexes.  NULL for tables */
12263  sqlite3_int64 nKey;     /* Size of pKey for indexes.  PRIMARY KEY for tabs */
12264  const void *pData;      /* Data for tables.  NULL for indexes */
12265  int nData;              /* Size of pData.  0 if none. */
12266  int nZero;              /* Extra zero data appended after pData,nData */
12267};
12268
12269SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
12270                       int bias, int seekResult);
12271SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
12272SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
12273SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
12274SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
12275SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
12276SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
12277SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
12278SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
12279SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
12280SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
12281
12282SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
12283SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
12284
12285SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
12286SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
12287SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
12288SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
12289SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
12290SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
12291SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
12292
12293#ifndef NDEBUG
12294SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
12295#endif
12296
12297#ifndef SQLITE_OMIT_BTREECOUNT
12298SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
12299#endif
12300
12301#ifdef SQLITE_TEST
12302SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
12303SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
12304#endif
12305
12306#ifndef SQLITE_OMIT_WAL
12307SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
12308#endif
12309
12310/*
12311** If we are not using shared cache, then there is no need to
12312** use mutexes to access the BtShared structures.  So make the
12313** Enter and Leave procedures no-ops.
12314*/
12315#ifndef SQLITE_OMIT_SHARED_CACHE
12316SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
12317SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
12318SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
12319SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
12320SQLITE_PRIVATE   int sqlite3BtreeConnectionCount(Btree*);
12321#else
12322# define sqlite3BtreeEnter(X)
12323# define sqlite3BtreeEnterAll(X)
12324# define sqlite3BtreeSharable(X) 0
12325# define sqlite3BtreeEnterCursor(X)
12326# define sqlite3BtreeConnectionCount(X) 1
12327#endif
12328
12329#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
12330SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
12331SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
12332SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
12333#ifndef NDEBUG
12334  /* These routines are used inside assert() statements only. */
12335SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
12336SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
12337SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
12338#endif
12339#else
12340
12341# define sqlite3BtreeLeave(X)
12342# define sqlite3BtreeLeaveCursor(X)
12343# define sqlite3BtreeLeaveAll(X)
12344
12345# define sqlite3BtreeHoldsMutex(X) 1
12346# define sqlite3BtreeHoldsAllMutexes(X) 1
12347# define sqlite3SchemaMutexHeld(X,Y,Z) 1
12348#endif
12349
12350
12351#endif /* SQLITE_BTREE_H */
12352
12353/************** End of btree.h ***********************************************/
12354/************** Continuing where we left off in sqliteInt.h ******************/
12355/************** Include vdbe.h in the middle of sqliteInt.h ******************/
12356/************** Begin file vdbe.h ********************************************/
12357/*
12358** 2001 September 15
12359**
12360** The author disclaims copyright to this source code.  In place of
12361** a legal notice, here is a blessing:
12362**
12363**    May you do good and not evil.
12364**    May you find forgiveness for yourself and forgive others.
12365**    May you share freely, never taking more than you give.
12366**
12367*************************************************************************
12368** Header file for the Virtual DataBase Engine (VDBE)
12369**
12370** This header defines the interface to the virtual database engine
12371** or VDBE.  The VDBE implements an abstract machine that runs a
12372** simple program to access and modify the underlying database.
12373*/
12374#ifndef SQLITE_VDBE_H
12375#define SQLITE_VDBE_H
12376/* #include <stdio.h> */
12377
12378/*
12379** A single VDBE is an opaque structure named "Vdbe".  Only routines
12380** in the source file sqliteVdbe.c are allowed to see the insides
12381** of this structure.
12382*/
12383typedef struct Vdbe Vdbe;
12384
12385/*
12386** The names of the following types declared in vdbeInt.h are required
12387** for the VdbeOp definition.
12388*/
12389typedef struct Mem Mem;
12390typedef struct SubProgram SubProgram;
12391
12392/*
12393** A single instruction of the virtual machine has an opcode
12394** and as many as three operands.  The instruction is recorded
12395** as an instance of the following structure:
12396*/
12397struct VdbeOp {
12398  u8 opcode;          /* What operation to perform */
12399  signed char p4type; /* One of the P4_xxx constants for p4 */
12400  u8 notUsed1;
12401  u8 p5;              /* Fifth parameter is an unsigned character */
12402  int p1;             /* First operand */
12403  int p2;             /* Second parameter (often the jump destination) */
12404  int p3;             /* The third parameter */
12405  union p4union {     /* fourth parameter */
12406    int i;                 /* Integer value if p4type==P4_INT32 */
12407    void *p;               /* Generic pointer */
12408    char *z;               /* Pointer to data for string (char array) types */
12409    i64 *pI64;             /* Used when p4type is P4_INT64 */
12410    double *pReal;         /* Used when p4type is P4_REAL */
12411    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
12412    sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
12413    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
12414    Mem *pMem;             /* Used when p4type is P4_MEM */
12415    VTable *pVtab;         /* Used when p4type is P4_VTAB */
12416    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
12417    int *ai;               /* Used when p4type is P4_INTARRAY */
12418    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
12419    Table *pTab;           /* Used when p4type is P4_TABLE */
12420#ifdef SQLITE_ENABLE_CURSOR_HINTS
12421    Expr *pExpr;           /* Used when p4type is P4_EXPR */
12422#endif
12423    int (*xAdvance)(BtCursor *, int *);
12424  } p4;
12425#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
12426  char *zComment;          /* Comment to improve readability */
12427#endif
12428#ifdef VDBE_PROFILE
12429  u32 cnt;                 /* Number of times this instruction was executed */
12430  u64 cycles;              /* Total time spent executing this instruction */
12431#endif
12432#ifdef SQLITE_VDBE_COVERAGE
12433  int iSrcLine;            /* Source-code line that generated this opcode */
12434#endif
12435};
12436typedef struct VdbeOp VdbeOp;
12437
12438
12439/*
12440** A sub-routine used to implement a trigger program.
12441*/
12442struct SubProgram {
12443  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
12444  int nOp;                      /* Elements in aOp[] */
12445  int nMem;                     /* Number of memory cells required */
12446  int nCsr;                     /* Number of cursors required */
12447  int nOnce;                    /* Number of OP_Once instructions */
12448  void *token;                  /* id that may be used to recursive triggers */
12449  SubProgram *pNext;            /* Next sub-program already visited */
12450};
12451
12452/*
12453** A smaller version of VdbeOp used for the VdbeAddOpList() function because
12454** it takes up less space.
12455*/
12456struct VdbeOpList {
12457  u8 opcode;          /* What operation to perform */
12458  signed char p1;     /* First operand */
12459  signed char p2;     /* Second parameter (often the jump destination) */
12460  signed char p3;     /* Third parameter */
12461};
12462typedef struct VdbeOpList VdbeOpList;
12463
12464/*
12465** Allowed values of VdbeOp.p4type
12466*/
12467#define P4_NOTUSED    0   /* The P4 parameter is not used */
12468#define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
12469#define P4_STATIC   (-2)  /* Pointer to a static string */
12470#define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
12471#define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
12472#define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
12473#define P4_EXPR     (-7)  /* P4 is a pointer to an Expr tree */
12474#define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
12475#define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
12476#define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
12477#define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
12478#define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
12479#define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
12480#define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
12481#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
12482#define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
12483#define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
12484#define P4_TABLE    (-20) /* P4 is a pointer to a Table structure */
12485#define P4_FUNCCTX  (-21) /* P4 is a pointer to an sqlite3_context object */
12486
12487/* Error message codes for OP_Halt */
12488#define P5_ConstraintNotNull 1
12489#define P5_ConstraintUnique  2
12490#define P5_ConstraintCheck   3
12491#define P5_ConstraintFK      4
12492
12493/*
12494** The Vdbe.aColName array contains 5n Mem structures, where n is the
12495** number of columns of data returned by the statement.
12496*/
12497#define COLNAME_NAME     0
12498#define COLNAME_DECLTYPE 1
12499#define COLNAME_DATABASE 2
12500#define COLNAME_TABLE    3
12501#define COLNAME_COLUMN   4
12502#ifdef SQLITE_ENABLE_COLUMN_METADATA
12503# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
12504#else
12505# ifdef SQLITE_OMIT_DECLTYPE
12506#   define COLNAME_N      1      /* Store only the name */
12507# else
12508#   define COLNAME_N      2      /* Store the name and decltype */
12509# endif
12510#endif
12511
12512/*
12513** The following macro converts a relative address in the p2 field
12514** of a VdbeOp structure into a negative number so that
12515** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
12516** the macro again restores the address.
12517*/
12518#define ADDR(X)  (-1-(X))
12519
12520/*
12521** The makefile scans the vdbe.c source file and creates the "opcodes.h"
12522** header file that defines a number for each opcode used by the VDBE.
12523*/
12524/************** Include opcodes.h in the middle of vdbe.h ********************/
12525/************** Begin file opcodes.h *****************************************/
12526/* Automatically generated.  Do not edit */
12527/* See the tool/mkopcodeh.tcl script for details */
12528#define OP_Savepoint       0
12529#define OP_AutoCommit      1
12530#define OP_Transaction     2
12531#define OP_SorterNext      3
12532#define OP_PrevIfOpen      4
12533#define OP_NextIfOpen      5
12534#define OP_Prev            6
12535#define OP_Next            7
12536#define OP_Checkpoint      8
12537#define OP_JournalMode     9
12538#define OP_Vacuum         10
12539#define OP_VFilter        11 /* synopsis: iplan=r[P3] zplan='P4'           */
12540#define OP_VUpdate        12 /* synopsis: data=r[P3@P2]                    */
12541#define OP_Goto           13
12542#define OP_Gosub          14
12543#define OP_InitCoroutine  15
12544#define OP_Yield          16
12545#define OP_MustBeInt      17
12546#define OP_Jump           18
12547#define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */
12548#define OP_Once           20
12549#define OP_If             21
12550#define OP_IfNot          22
12551#define OP_SeekLT         23 /* synopsis: key=r[P3@P4]                     */
12552#define OP_SeekLE         24 /* synopsis: key=r[P3@P4]                     */
12553#define OP_SeekGE         25 /* synopsis: key=r[P3@P4]                     */
12554#define OP_SeekGT         26 /* synopsis: key=r[P3@P4]                     */
12555#define OP_Or             27 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
12556#define OP_And            28 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
12557#define OP_NoConflict     29 /* synopsis: key=r[P3@P4]                     */
12558#define OP_NotFound       30 /* synopsis: key=r[P3@P4]                     */
12559#define OP_Found          31 /* synopsis: key=r[P3@P4]                     */
12560#define OP_SeekRowid      32 /* synopsis: intkey=r[P3]                     */
12561#define OP_NotExists      33 /* synopsis: intkey=r[P3]                     */
12562#define OP_IsNull         34 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
12563#define OP_NotNull        35 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
12564#define OP_Ne             36 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
12565#define OP_Eq             37 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
12566#define OP_Gt             38 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
12567#define OP_Le             39 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
12568#define OP_Lt             40 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
12569#define OP_Ge             41 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
12570#define OP_Last           42
12571#define OP_BitAnd         43 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
12572#define OP_BitOr          44 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
12573#define OP_ShiftLeft      45 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
12574#define OP_ShiftRight     46 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
12575#define OP_Add            47 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
12576#define OP_Subtract       48 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
12577#define OP_Multiply       49 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
12578#define OP_Divide         50 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
12579#define OP_Remainder      51 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
12580#define OP_Concat         52 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
12581#define OP_SorterSort     53
12582#define OP_BitNot         54 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
12583#define OP_Sort           55
12584#define OP_Rewind         56
12585#define OP_IdxLE          57 /* synopsis: key=r[P3@P4]                     */
12586#define OP_IdxGT          58 /* synopsis: key=r[P3@P4]                     */
12587#define OP_IdxLT          59 /* synopsis: key=r[P3@P4]                     */
12588#define OP_IdxGE          60 /* synopsis: key=r[P3@P4]                     */
12589#define OP_RowSetRead     61 /* synopsis: r[P3]=rowset(P1)                 */
12590#define OP_RowSetTest     62 /* synopsis: if r[P3] in rowset(P1) goto P2   */
12591#define OP_Program        63
12592#define OP_FkIfZero       64 /* synopsis: if fkctr[P1]==0 goto P2          */
12593#define OP_IfPos          65 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
12594#define OP_IfNotZero      66 /* synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 */
12595#define OP_DecrJumpZero   67 /* synopsis: if (--r[P1])==0 goto P2          */
12596#define OP_IncrVacuum     68
12597#define OP_VNext          69
12598#define OP_Init           70 /* synopsis: Start at P2                      */
12599#define OP_Return         71
12600#define OP_EndCoroutine   72
12601#define OP_HaltIfNull     73 /* synopsis: if r[P3]=null halt               */
12602#define OP_Halt           74
12603#define OP_Integer        75 /* synopsis: r[P2]=P1                         */
12604#define OP_Int64          76 /* synopsis: r[P2]=P4                         */
12605#define OP_String         77 /* synopsis: r[P2]='P4' (len=P1)              */
12606#define OP_Null           78 /* synopsis: r[P2..P3]=NULL                   */
12607#define OP_SoftNull       79 /* synopsis: r[P1]=NULL                       */
12608#define OP_Blob           80 /* synopsis: r[P2]=P4 (len=P1)                */
12609#define OP_Variable       81 /* synopsis: r[P2]=parameter(P1,P4)           */
12610#define OP_Move           82 /* synopsis: r[P2@P3]=r[P1@P3]                */
12611#define OP_Copy           83 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
12612#define OP_SCopy          84 /* synopsis: r[P2]=r[P1]                      */
12613#define OP_IntCopy        85 /* synopsis: r[P2]=r[P1]                      */
12614#define OP_ResultRow      86 /* synopsis: output=r[P1@P2]                  */
12615#define OP_CollSeq        87
12616#define OP_Function0      88 /* synopsis: r[P3]=func(r[P2@P5])             */
12617#define OP_Function       89 /* synopsis: r[P3]=func(r[P2@P5])             */
12618#define OP_AddImm         90 /* synopsis: r[P1]=r[P1]+P2                   */
12619#define OP_RealAffinity   91
12620#define OP_Cast           92 /* synopsis: affinity(r[P1])                  */
12621#define OP_Permutation    93
12622#define OP_Compare        94 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
12623#define OP_Column         95 /* synopsis: r[P3]=PX                         */
12624#define OP_Affinity       96 /* synopsis: affinity(r[P1@P2])               */
12625#define OP_String8        97 /* same as TK_STRING, synopsis: r[P2]='P4'    */
12626#define OP_MakeRecord     98 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
12627#define OP_Count          99 /* synopsis: r[P2]=count()                    */
12628#define OP_ReadCookie    100
12629#define OP_SetCookie     101
12630#define OP_ReopenIdx     102 /* synopsis: root=P2 iDb=P3                   */
12631#define OP_OpenRead      103 /* synopsis: root=P2 iDb=P3                   */
12632#define OP_OpenWrite     104 /* synopsis: root=P2 iDb=P3                   */
12633#define OP_OpenAutoindex 105 /* synopsis: nColumn=P2                       */
12634#define OP_OpenEphemeral 106 /* synopsis: nColumn=P2                       */
12635#define OP_SorterOpen    107
12636#define OP_SequenceTest  108 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
12637#define OP_OpenPseudo    109 /* synopsis: P3 columns in r[P2]              */
12638#define OP_Close         110
12639#define OP_ColumnsUsed   111
12640#define OP_Sequence      112 /* synopsis: r[P2]=cursor[P1].ctr++           */
12641#define OP_NewRowid      113 /* synopsis: r[P2]=rowid                      */
12642#define OP_Insert        114 /* synopsis: intkey=r[P3] data=r[P2]          */
12643#define OP_InsertInt     115 /* synopsis: intkey=P3 data=r[P2]             */
12644#define OP_Delete        116
12645#define OP_ResetCount    117
12646#define OP_SorterCompare 118 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
12647#define OP_SorterData    119 /* synopsis: r[P2]=data                       */
12648#define OP_RowKey        120 /* synopsis: r[P2]=key                        */
12649#define OP_RowData       121 /* synopsis: r[P2]=data                       */
12650#define OP_Rowid         122 /* synopsis: r[P2]=rowid                      */
12651#define OP_NullRow       123
12652#define OP_SorterInsert  124
12653#define OP_IdxInsert     125 /* synopsis: key=r[P2]                        */
12654#define OP_IdxDelete     126 /* synopsis: key=r[P2@P3]                     */
12655#define OP_Seek          127 /* synopsis: Move P3 to P1.rowid              */
12656#define OP_IdxRowid      128 /* synopsis: r[P2]=rowid                      */
12657#define OP_Destroy       129
12658#define OP_Clear         130
12659#define OP_ResetSorter   131
12660#define OP_CreateIndex   132 /* synopsis: r[P2]=root iDb=P1                */
12661#define OP_Real          133 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
12662#define OP_CreateTable   134 /* synopsis: r[P2]=root iDb=P1                */
12663#define OP_ParseSchema   135
12664#define OP_LoadAnalysis  136
12665#define OP_DropTable     137
12666#define OP_DropIndex     138
12667#define OP_DropTrigger   139
12668#define OP_IntegrityCk   140
12669#define OP_RowSetAdd     141 /* synopsis: rowset(P1)=r[P2]                 */
12670#define OP_Param         142
12671#define OP_FkCounter     143 /* synopsis: fkctr[P1]+=P2                    */
12672#define OP_MemMax        144 /* synopsis: r[P1]=max(r[P1],r[P2])           */
12673#define OP_OffsetLimit   145 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
12674#define OP_AggStep0      146 /* synopsis: accum=r[P3] step(r[P2@P5])       */
12675#define OP_AggStep       147 /* synopsis: accum=r[P3] step(r[P2@P5])       */
12676#define OP_AggFinal      148 /* synopsis: accum=r[P1] N=P2                 */
12677#define OP_Expire        149
12678#define OP_TableLock     150 /* synopsis: iDb=P1 root=P2 write=P3          */
12679#define OP_VBegin        151
12680#define OP_VCreate       152
12681#define OP_VDestroy      153
12682#define OP_VOpen         154
12683#define OP_VColumn       155 /* synopsis: r[P3]=vcolumn(P2)                */
12684#define OP_VRename       156
12685#define OP_Pagecount     157
12686#define OP_MaxPgcnt      158
12687#define OP_CursorHint    159
12688#define OP_Noop          160
12689#define OP_Explain       161
12690
12691/* Properties such as "out2" or "jump" that are specified in
12692** comments following the "case" for each opcode in the vdbe.c
12693** are encoded into bitvectors as follows:
12694*/
12695#define OPFLG_JUMP        0x01  /* jump:  P2 holds jmp target */
12696#define OPFLG_IN1         0x02  /* in1:   P1 is an input */
12697#define OPFLG_IN2         0x04  /* in2:   P2 is an input */
12698#define OPFLG_IN3         0x08  /* in3:   P3 is an input */
12699#define OPFLG_OUT2        0x10  /* out2:  P2 is an output */
12700#define OPFLG_OUT3        0x20  /* out3:  P3 is an output */
12701#define OPFLG_INITIALIZER {\
12702/*   0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
12703/*   8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
12704/*  16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x09,\
12705/*  24 */ 0x09, 0x09, 0x09, 0x26, 0x26, 0x09, 0x09, 0x09,\
12706/*  32 */ 0x09, 0x09, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
12707/*  40 */ 0x0b, 0x0b, 0x01, 0x26, 0x26, 0x26, 0x26, 0x26,\
12708/*  48 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x01, 0x12, 0x01,\
12709/*  56 */ 0x01, 0x01, 0x01, 0x01, 0x01, 0x23, 0x0b, 0x01,\
12710/*  64 */ 0x01, 0x03, 0x03, 0x03, 0x01, 0x01, 0x01, 0x02,\
12711/*  72 */ 0x02, 0x08, 0x00, 0x10, 0x10, 0x10, 0x10, 0x00,\
12712/*  80 */ 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
12713/*  88 */ 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x00,\
12714/*  96 */ 0x00, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00,\
12715/* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12716/* 112 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12717/* 120 */ 0x00, 0x00, 0x10, 0x00, 0x04, 0x04, 0x00, 0x00,\
12718/* 128 */ 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x10, 0x00,\
12719/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x10, 0x00,\
12720/* 144 */ 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12721/* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00,\
12722/* 160 */ 0x00, 0x00,}
12723
12724/* The sqlite3P2Values() routine is able to run faster if it knows
12725** the value of the largest JUMP opcode.  The smaller the maximum
12726** JUMP opcode the better, so the mkopcodeh.tcl script that
12727** generated this include file strives to group all JUMP opcodes
12728** together near the beginning of the list.
12729*/
12730#define SQLITE_MX_JUMP_OPCODE  70  /* Maximum JUMP opcode */
12731
12732/************** End of opcodes.h *********************************************/
12733/************** Continuing where we left off in vdbe.h ***********************/
12734
12735/*
12736** Prototypes for the VDBE interface.  See comments on the implementation
12737** for a description of what each of these routines does.
12738*/
12739SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
12740SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
12741SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
12742SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
12743SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
12744SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
12745SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
12746SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
12747SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
12748SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
12749SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
12750SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
12751#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
12752SQLITE_PRIVATE   void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
12753#else
12754# define sqlite3VdbeVerifyNoMallocRequired(A,B)
12755#endif
12756SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
12757SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
12758SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
12759SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
12760SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
12761SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
12762SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
12763SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
12764SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
12765SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
12766SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
12767SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
12768SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
12769SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
12770SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
12771SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
12772SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
12773SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
12774SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
12775SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
12776SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
12777SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
12778SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
12779#ifdef SQLITE_DEBUG
12780SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
12781#endif
12782SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
12783SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
12784SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
12785SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
12786SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
12787SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
12788SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
12789SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
12790SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
12791SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
12792SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
12793SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
12794#ifndef SQLITE_OMIT_TRACE
12795SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
12796#endif
12797SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12798
12799SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
12800SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
12801SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
12802SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
12803
12804typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
12805SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
12806
12807#ifndef SQLITE_OMIT_TRIGGER
12808SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
12809#endif
12810
12811/* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
12812** each VDBE opcode.
12813**
12814** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
12815** comments in VDBE programs that show key decision points in the code
12816** generator.
12817*/
12818#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
12819SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
12820# define VdbeComment(X)  sqlite3VdbeComment X
12821SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
12822# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
12823# ifdef SQLITE_ENABLE_MODULE_COMMENTS
12824#   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X
12825# else
12826#   define VdbeModuleComment(X)
12827# endif
12828#else
12829# define VdbeComment(X)
12830# define VdbeNoopComment(X)
12831# define VdbeModuleComment(X)
12832#endif
12833
12834/*
12835** The VdbeCoverage macros are used to set a coverage testing point
12836** for VDBE branch instructions.  The coverage testing points are line
12837** numbers in the sqlite3.c source file.  VDBE branch coverage testing
12838** only works with an amalagmation build.  That's ok since a VDBE branch
12839** coverage build designed for testing the test suite only.  No application
12840** should ever ship with VDBE branch coverage measuring turned on.
12841**
12842**    VdbeCoverage(v)                  // Mark the previously coded instruction
12843**                                     // as a branch
12844**
12845**    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true
12846**
12847**    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken
12848**
12849**    VdbeCoverageNeverTaken(v)        // Previous branch is never taken
12850**
12851** Every VDBE branch operation must be tagged with one of the macros above.
12852** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
12853** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
12854** routine in vdbe.c, alerting the developer to the missed tag.
12855*/
12856#ifdef SQLITE_VDBE_COVERAGE
12857SQLITE_PRIVATE   void sqlite3VdbeSetLineNumber(Vdbe*,int);
12858# define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
12859# define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
12860# define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
12861# define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
12862# define VDBE_OFFSET_LINENO(x) (__LINE__+x)
12863#else
12864# define VdbeCoverage(v)
12865# define VdbeCoverageIf(v,x)
12866# define VdbeCoverageAlwaysTaken(v)
12867# define VdbeCoverageNeverTaken(v)
12868# define VDBE_OFFSET_LINENO(x) 0
12869#endif
12870
12871#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
12872SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
12873#else
12874# define sqlite3VdbeScanStatus(a,b,c,d,e)
12875#endif
12876
12877#endif /* SQLITE_VDBE_H */
12878
12879/************** End of vdbe.h ************************************************/
12880/************** Continuing where we left off in sqliteInt.h ******************/
12881/************** Include pager.h in the middle of sqliteInt.h *****************/
12882/************** Begin file pager.h *******************************************/
12883/*
12884** 2001 September 15
12885**
12886** The author disclaims copyright to this source code.  In place of
12887** a legal notice, here is a blessing:
12888**
12889**    May you do good and not evil.
12890**    May you find forgiveness for yourself and forgive others.
12891**    May you share freely, never taking more than you give.
12892**
12893*************************************************************************
12894** This header file defines the interface that the sqlite page cache
12895** subsystem.  The page cache subsystem reads and writes a file a page
12896** at a time and provides a journal for rollback.
12897*/
12898
12899#ifndef SQLITE_PAGER_H
12900#define SQLITE_PAGER_H
12901
12902/*
12903** Default maximum size for persistent journal files. A negative
12904** value means no limit. This value may be overridden using the
12905** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
12906*/
12907#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
12908  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
12909#endif
12910
12911/*
12912** The type used to represent a page number.  The first page in a file
12913** is called page 1.  0 is used to represent "not a page".
12914*/
12915typedef u32 Pgno;
12916
12917/*
12918** Each open file is managed by a separate instance of the "Pager" structure.
12919*/
12920typedef struct Pager Pager;
12921
12922/*
12923** Handle type for pages.
12924*/
12925typedef struct PgHdr DbPage;
12926
12927/*
12928** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
12929** reserved for working around a windows/posix incompatibility). It is
12930** used in the journal to signify that the remainder of the journal file
12931** is devoted to storing a master journal name - there are no more pages to
12932** roll back. See comments for function writeMasterJournal() in pager.c
12933** for details.
12934*/
12935#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
12936
12937/*
12938** Allowed values for the flags parameter to sqlite3PagerOpen().
12939**
12940** NOTE: These values must match the corresponding BTREE_ values in btree.h.
12941*/
12942#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
12943#define PAGER_MEMORY        0x0002    /* In-memory database */
12944
12945/*
12946** Valid values for the second argument to sqlite3PagerLockingMode().
12947*/
12948#define PAGER_LOCKINGMODE_QUERY      -1
12949#define PAGER_LOCKINGMODE_NORMAL      0
12950#define PAGER_LOCKINGMODE_EXCLUSIVE   1
12951
12952/*
12953** Numeric constants that encode the journalmode.
12954**
12955** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
12956** are exposed in the API via the "PRAGMA journal_mode" command and
12957** therefore cannot be changed without a compatibility break.
12958*/
12959#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
12960#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
12961#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
12962#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
12963#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
12964#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
12965#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
12966
12967/*
12968** Flags that make up the mask passed to sqlite3PagerGet().
12969*/
12970#define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
12971#define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
12972
12973/*
12974** Flags for sqlite3PagerSetFlags()
12975**
12976** Value constraints (enforced via assert()):
12977**    PAGER_FULLFSYNC      == SQLITE_FullFSync
12978**    PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
12979**    PAGER_CACHE_SPILL    == SQLITE_CacheSpill
12980*/
12981#define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
12982#define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
12983#define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
12984#define PAGER_SYNCHRONOUS_EXTRA     0x04  /* PRAGMA synchronous=EXTRA */
12985#define PAGER_SYNCHRONOUS_MASK      0x07  /* Mask for four values above */
12986#define PAGER_FULLFSYNC             0x08  /* PRAGMA fullfsync=ON */
12987#define PAGER_CKPT_FULLFSYNC        0x10  /* PRAGMA checkpoint_fullfsync=ON */
12988#define PAGER_CACHESPILL            0x20  /* PRAGMA cache_spill=ON */
12989#define PAGER_FLAGS_MASK            0x38  /* All above except SYNCHRONOUS */
12990
12991/*
12992** The remainder of this file contains the declarations of the functions
12993** that make up the Pager sub-system API. See source code comments for
12994** a detailed description of each routine.
12995*/
12996
12997/* Open and close a Pager connection. */
12998SQLITE_PRIVATE int sqlite3PagerOpen(
12999  sqlite3_vfs*,
13000  Pager **ppPager,
13001  const char*,
13002  int,
13003  int,
13004  int,
13005  void(*)(DbPage*)
13006);
13007SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
13008SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
13009
13010/* Functions used to configure a Pager object. */
13011SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
13012SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
13013#ifdef SQLITE_HAS_CODEC
13014SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
13015#endif
13016SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
13017SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
13018SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
13019SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
13020SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
13021SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
13022SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
13023SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
13024SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
13025SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
13026SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
13027SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
13028SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
13029
13030/* Functions used to obtain and release page references. */
13031SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
13032SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
13033SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
13034SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
13035SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
13036
13037/* Operations on page references. */
13038SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
13039SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
13040SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
13041SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
13042SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
13043SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
13044
13045/* Functions used to manage pager transactions and savepoints. */
13046SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
13047SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
13048SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
13049SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
13050SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
13051SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
13052SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
13053SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
13054SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
13055SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
13056
13057#ifndef SQLITE_OMIT_WAL
13058SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
13059SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
13060SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
13061SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
13062SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager);
13063# ifdef SQLITE_ENABLE_SNAPSHOT
13064SQLITE_PRIVATE   int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
13065SQLITE_PRIVATE   int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
13066# endif
13067#endif
13068
13069#ifdef SQLITE_ENABLE_ZIPVFS
13070SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
13071#endif
13072
13073/* Functions used to query pager state and configuration. */
13074SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
13075SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
13076#ifdef SQLITE_DEBUG
13077SQLITE_PRIVATE   int sqlite3PagerRefcount(Pager*);
13078#endif
13079SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
13080SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
13081SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
13082SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
13083SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
13084SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
13085SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
13086SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
13087SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
13088SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
13089SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
13090
13091/* Functions used to truncate the database file. */
13092SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
13093
13094SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
13095
13096#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
13097SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
13098#endif
13099
13100/* Functions to support testing and debugging. */
13101#if !defined(NDEBUG) || defined(SQLITE_TEST)
13102SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
13103SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
13104#endif
13105#ifdef SQLITE_TEST
13106SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
13107SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
13108  void disable_simulated_io_errors(void);
13109  void enable_simulated_io_errors(void);
13110#else
13111# define disable_simulated_io_errors()
13112# define enable_simulated_io_errors()
13113#endif
13114
13115#endif /* SQLITE_PAGER_H */
13116
13117/************** End of pager.h ***********************************************/
13118/************** Continuing where we left off in sqliteInt.h ******************/
13119/************** Include pcache.h in the middle of sqliteInt.h ****************/
13120/************** Begin file pcache.h ******************************************/
13121/*
13122** 2008 August 05
13123**
13124** The author disclaims copyright to this source code.  In place of
13125** a legal notice, here is a blessing:
13126**
13127**    May you do good and not evil.
13128**    May you find forgiveness for yourself and forgive others.
13129**    May you share freely, never taking more than you give.
13130**
13131*************************************************************************
13132** This header file defines the interface that the sqlite page cache
13133** subsystem.
13134*/
13135
13136#ifndef _PCACHE_H_
13137
13138typedef struct PgHdr PgHdr;
13139typedef struct PCache PCache;
13140
13141/*
13142** Every page in the cache is controlled by an instance of the following
13143** structure.
13144*/
13145struct PgHdr {
13146  sqlite3_pcache_page *pPage;    /* Pcache object page handle */
13147  void *pData;                   /* Page data */
13148  void *pExtra;                  /* Extra content */
13149  PgHdr *pDirty;                 /* Transient list of dirty sorted by pgno */
13150  Pager *pPager;                 /* The pager this page is part of */
13151  Pgno pgno;                     /* Page number for this page */
13152#ifdef SQLITE_CHECK_PAGES
13153  u32 pageHash;                  /* Hash of page content */
13154#endif
13155  u16 flags;                     /* PGHDR flags defined below */
13156
13157  /**********************************************************************
13158  ** Elements above are public.  All that follows is private to pcache.c
13159  ** and should not be accessed by other modules.
13160  */
13161  i16 nRef;                      /* Number of users of this page */
13162  PCache *pCache;                /* Cache that owns this page */
13163
13164  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
13165  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
13166};
13167
13168/* Bit values for PgHdr.flags */
13169#define PGHDR_CLEAN           0x001  /* Page not on the PCache.pDirty list */
13170#define PGHDR_DIRTY           0x002  /* Page is on the PCache.pDirty list */
13171#define PGHDR_WRITEABLE       0x004  /* Journaled and ready to modify */
13172#define PGHDR_NEED_SYNC       0x008  /* Fsync the rollback journal before
13173                                     ** writing this page to the database */
13174#define PGHDR_DONT_WRITE      0x010  /* Do not write content to disk */
13175#define PGHDR_MMAP            0x020  /* This is an mmap page object */
13176
13177#define PGHDR_WAL_APPEND      0x040  /* Appended to wal file */
13178
13179/* Initialize and shutdown the page cache subsystem */
13180SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
13181SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
13182
13183/* Page cache buffer management:
13184** These routines implement SQLITE_CONFIG_PAGECACHE.
13185*/
13186SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
13187
13188/* Create a new pager cache.
13189** Under memory stress, invoke xStress to try to make pages clean.
13190** Only clean and unpinned pages can be reclaimed.
13191*/
13192SQLITE_PRIVATE int sqlite3PcacheOpen(
13193  int szPage,                    /* Size of every page */
13194  int szExtra,                   /* Extra space associated with each page */
13195  int bPurgeable,                /* True if pages are on backing store */
13196  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
13197  void *pStress,                 /* Argument to xStress */
13198  PCache *pToInit                /* Preallocated space for the PCache */
13199);
13200
13201/* Modify the page-size after the cache has been created. */
13202SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
13203
13204/* Return the size in bytes of a PCache object.  Used to preallocate
13205** storage space.
13206*/
13207SQLITE_PRIVATE int sqlite3PcacheSize(void);
13208
13209/* One release per successful fetch.  Page is pinned until released.
13210** Reference counted.
13211*/
13212SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
13213SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
13214SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
13215SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
13216
13217SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
13218SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
13219SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
13220SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
13221SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
13222
13223/* Change a page number.  Used by incr-vacuum. */
13224SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
13225
13226/* Remove all pages with pgno>x.  Reset the cache if x==0 */
13227SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
13228
13229/* Get a list of all dirty pages in the cache, sorted by page number */
13230SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
13231
13232/* Reset and close the cache object */
13233SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
13234
13235/* Clear flags from pages of the page cache */
13236SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
13237
13238/* Discard the contents of the cache */
13239SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
13240
13241/* Return the total number of outstanding page references */
13242SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
13243
13244/* Increment the reference count of an existing page */
13245SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
13246
13247SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
13248
13249/* Return the total number of pages stored in the cache */
13250SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
13251
13252#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
13253/* Iterate through all dirty pages currently stored in the cache. This
13254** interface is only available if SQLITE_CHECK_PAGES is defined when the
13255** library is built.
13256*/
13257SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
13258#endif
13259
13260#if defined(SQLITE_DEBUG)
13261/* Check invariants on a PgHdr object */
13262SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
13263#endif
13264
13265/* Set and get the suggested cache-size for the specified pager-cache.
13266**
13267** If no global maximum is configured, then the system attempts to limit
13268** the total number of pages cached by purgeable pager-caches to the sum
13269** of the suggested cache-sizes.
13270*/
13271SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
13272#ifdef SQLITE_TEST
13273SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
13274#endif
13275
13276/* Set or get the suggested spill-size for the specified pager-cache.
13277**
13278** The spill-size is the minimum number of pages in cache before the cache
13279** will attempt to spill dirty pages by calling xStress.
13280*/
13281SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
13282
13283/* Free up as much memory as possible from the page cache */
13284SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
13285
13286#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
13287/* Try to return memory used by the pcache module to the main memory heap */
13288SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
13289#endif
13290
13291#ifdef SQLITE_TEST
13292SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
13293#endif
13294
13295SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
13296
13297/* Return the header size */
13298SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
13299SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
13300
13301/* Number of dirty pages as a percentage of the configured cache size */
13302SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
13303
13304#endif /* _PCACHE_H_ */
13305
13306/************** End of pcache.h **********************************************/
13307/************** Continuing where we left off in sqliteInt.h ******************/
13308/************** Include os.h in the middle of sqliteInt.h ********************/
13309/************** Begin file os.h **********************************************/
13310/*
13311** 2001 September 16
13312**
13313** The author disclaims copyright to this source code.  In place of
13314** a legal notice, here is a blessing:
13315**
13316**    May you do good and not evil.
13317**    May you find forgiveness for yourself and forgive others.
13318**    May you share freely, never taking more than you give.
13319**
13320******************************************************************************
13321**
13322** This header file (together with is companion C source-code file
13323** "os.c") attempt to abstract the underlying operating system so that
13324** the SQLite library will work on both POSIX and windows systems.
13325**
13326** This header file is #include-ed by sqliteInt.h and thus ends up
13327** being included by every source file.
13328*/
13329#ifndef _SQLITE_OS_H_
13330#define _SQLITE_OS_H_
13331
13332/*
13333** Attempt to automatically detect the operating system and setup the
13334** necessary pre-processor macros for it.
13335*/
13336/************** Include os_setup.h in the middle of os.h *********************/
13337/************** Begin file os_setup.h ****************************************/
13338/*
13339** 2013 November 25
13340**
13341** The author disclaims copyright to this source code.  In place of
13342** a legal notice, here is a blessing:
13343**
13344**    May you do good and not evil.
13345**    May you find forgiveness for yourself and forgive others.
13346**    May you share freely, never taking more than you give.
13347**
13348******************************************************************************
13349**
13350** This file contains pre-processor directives related to operating system
13351** detection and/or setup.
13352*/
13353#ifndef SQLITE_OS_SETUP_H
13354#define SQLITE_OS_SETUP_H
13355
13356/*
13357** Figure out if we are dealing with Unix, Windows, or some other operating
13358** system.
13359**
13360** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
13361** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0.  One of
13362** the three will be 1.  The other two will be 0.
13363*/
13364#if defined(SQLITE_OS_OTHER)
13365#  if SQLITE_OS_OTHER==1
13366#    undef SQLITE_OS_UNIX
13367#    define SQLITE_OS_UNIX 0
13368#    undef SQLITE_OS_WIN
13369#    define SQLITE_OS_WIN 0
13370#  else
13371#    undef SQLITE_OS_OTHER
13372#  endif
13373#endif
13374#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
13375#  define SQLITE_OS_OTHER 0
13376#  ifndef SQLITE_OS_WIN
13377#    if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
13378        defined(__MINGW32__) || defined(__BORLANDC__)
13379#      define SQLITE_OS_WIN 1
13380#      define SQLITE_OS_UNIX 0
13381#    else
13382#      define SQLITE_OS_WIN 0
13383#      define SQLITE_OS_UNIX 1
13384#    endif
13385#  else
13386#    define SQLITE_OS_UNIX 0
13387#  endif
13388#else
13389#  ifndef SQLITE_OS_WIN
13390#    define SQLITE_OS_WIN 0
13391#  endif
13392#endif
13393
13394#endif /* SQLITE_OS_SETUP_H */
13395
13396/************** End of os_setup.h ********************************************/
13397/************** Continuing where we left off in os.h *************************/
13398
13399/* If the SET_FULLSYNC macro is not defined above, then make it
13400** a no-op
13401*/
13402#ifndef SET_FULLSYNC
13403# define SET_FULLSYNC(x,y)
13404#endif
13405
13406/*
13407** The default size of a disk sector
13408*/
13409#ifndef SQLITE_DEFAULT_SECTOR_SIZE
13410# define SQLITE_DEFAULT_SECTOR_SIZE 4096
13411#endif
13412
13413/*
13414** Temporary files are named starting with this prefix followed by 16 random
13415** alphanumeric characters, and no file extension. They are stored in the
13416** OS's standard temporary file directory, and are deleted prior to exit.
13417** If sqlite is being embedded in another program, you may wish to change the
13418** prefix to reflect your program's name, so that if your program exits
13419** prematurely, old temporary files can be easily identified. This can be done
13420** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
13421**
13422** 2006-10-31:  The default prefix used to be "sqlite_".  But then
13423** Mcafee started using SQLite in their anti-virus product and it
13424** started putting files with the "sqlite" name in the c:/temp folder.
13425** This annoyed many windows users.  Those users would then do a
13426** Google search for "sqlite", find the telephone numbers of the
13427** developers and call to wake them up at night and complain.
13428** For this reason, the default name prefix is changed to be "sqlite"
13429** spelled backwards.  So the temp files are still identified, but
13430** anybody smart enough to figure out the code is also likely smart
13431** enough to know that calling the developer will not help get rid
13432** of the file.
13433*/
13434#ifndef SQLITE_TEMP_FILE_PREFIX
13435# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
13436#endif
13437
13438/*
13439** The following values may be passed as the second argument to
13440** sqlite3OsLock(). The various locks exhibit the following semantics:
13441**
13442** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
13443** RESERVED:  A single process may hold a RESERVED lock on a file at
13444**            any time. Other processes may hold and obtain new SHARED locks.
13445** PENDING:   A single process may hold a PENDING lock on a file at
13446**            any one time. Existing SHARED locks may persist, but no new
13447**            SHARED locks may be obtained by other processes.
13448** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
13449**
13450** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
13451** process that requests an EXCLUSIVE lock may actually obtain a PENDING
13452** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
13453** sqlite3OsLock().
13454*/
13455#define NO_LOCK         0
13456#define SHARED_LOCK     1
13457#define RESERVED_LOCK   2
13458#define PENDING_LOCK    3
13459#define EXCLUSIVE_LOCK  4
13460
13461/*
13462** File Locking Notes:  (Mostly about windows but also some info for Unix)
13463**
13464** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
13465** those functions are not available.  So we use only LockFile() and
13466** UnlockFile().
13467**
13468** LockFile() prevents not just writing but also reading by other processes.
13469** A SHARED_LOCK is obtained by locking a single randomly-chosen
13470** byte out of a specific range of bytes. The lock byte is obtained at
13471** random so two separate readers can probably access the file at the
13472** same time, unless they are unlucky and choose the same lock byte.
13473** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
13474** There can only be one writer.  A RESERVED_LOCK is obtained by locking
13475** a single byte of the file that is designated as the reserved lock byte.
13476** A PENDING_LOCK is obtained by locking a designated byte different from
13477** the RESERVED_LOCK byte.
13478**
13479** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
13480** which means we can use reader/writer locks.  When reader/writer locks
13481** are used, the lock is placed on the same range of bytes that is used
13482** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
13483** will support two or more Win95 readers or two or more WinNT readers.
13484** But a single Win95 reader will lock out all WinNT readers and a single
13485** WinNT reader will lock out all other Win95 readers.
13486**
13487** The following #defines specify the range of bytes used for locking.
13488** SHARED_SIZE is the number of bytes available in the pool from which
13489** a random byte is selected for a shared lock.  The pool of bytes for
13490** shared locks begins at SHARED_FIRST.
13491**
13492** The same locking strategy and
13493** byte ranges are used for Unix.  This leaves open the possibility of having
13494** clients on win95, winNT, and unix all talking to the same shared file
13495** and all locking correctly.  To do so would require that samba (or whatever
13496** tool is being used for file sharing) implements locks correctly between
13497** windows and unix.  I'm guessing that isn't likely to happen, but by
13498** using the same locking range we are at least open to the possibility.
13499**
13500** Locking in windows is manditory.  For this reason, we cannot store
13501** actual data in the bytes used for locking.  The pager never allocates
13502** the pages involved in locking therefore.  SHARED_SIZE is selected so
13503** that all locks will fit on a single page even at the minimum page size.
13504** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
13505** is set high so that we don't have to allocate an unused page except
13506** for very large databases.  But one should test the page skipping logic
13507** by setting PENDING_BYTE low and running the entire regression suite.
13508**
13509** Changing the value of PENDING_BYTE results in a subtly incompatible
13510** file format.  Depending on how it is changed, you might not notice
13511** the incompatibility right away, even running a full regression test.
13512** The default location of PENDING_BYTE is the first byte past the
13513** 1GB boundary.
13514**
13515*/
13516#ifdef SQLITE_OMIT_WSD
13517# define PENDING_BYTE     (0x40000000)
13518#else
13519# define PENDING_BYTE      sqlite3PendingByte
13520#endif
13521#define RESERVED_BYTE     (PENDING_BYTE+1)
13522#define SHARED_FIRST      (PENDING_BYTE+2)
13523#define SHARED_SIZE       510
13524
13525/*
13526** Wrapper around OS specific sqlite3_os_init() function.
13527*/
13528SQLITE_PRIVATE int sqlite3OsInit(void);
13529
13530/*
13531** Functions for accessing sqlite3_file methods
13532*/
13533SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
13534SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
13535SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
13536SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
13537SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
13538SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
13539SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
13540SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
13541SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
13542SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
13543SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
13544#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
13545SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
13546SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
13547SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
13548SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
13549SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
13550SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
13551SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
13552SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
13553
13554
13555/*
13556** Functions for accessing sqlite3_vfs methods
13557*/
13558SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
13559SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
13560SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
13561SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
13562#ifndef SQLITE_OMIT_LOAD_EXTENSION
13563SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
13564SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
13565SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
13566SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
13567#endif /* SQLITE_OMIT_LOAD_EXTENSION */
13568SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
13569SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
13570SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
13571SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
13572
13573/*
13574** Convenience functions for opening and closing files using
13575** sqlite3_malloc() to obtain space for the file-handle structure.
13576*/
13577SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
13578SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
13579
13580#endif /* _SQLITE_OS_H_ */
13581
13582/************** End of os.h **************************************************/
13583/************** Continuing where we left off in sqliteInt.h ******************/
13584/************** Include mutex.h in the middle of sqliteInt.h *****************/
13585/************** Begin file mutex.h *******************************************/
13586/*
13587** 2007 August 28
13588**
13589** The author disclaims copyright to this source code.  In place of
13590** a legal notice, here is a blessing:
13591**
13592**    May you do good and not evil.
13593**    May you find forgiveness for yourself and forgive others.
13594**    May you share freely, never taking more than you give.
13595**
13596*************************************************************************
13597**
13598** This file contains the common header for all mutex implementations.
13599** The sqliteInt.h header #includes this file so that it is available
13600** to all source files.  We break it out in an effort to keep the code
13601** better organized.
13602**
13603** NOTE:  source files should *not* #include this header file directly.
13604** Source files should #include the sqliteInt.h file and let that file
13605** include this one indirectly.
13606*/
13607
13608
13609/*
13610** Figure out what version of the code to use.  The choices are
13611**
13612**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
13613**                             mutexes implementation cannot be overridden
13614**                             at start-time.
13615**
13616**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
13617**                             mutual exclusion is provided.  But this
13618**                             implementation can be overridden at
13619**                             start-time.
13620**
13621**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
13622**
13623**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
13624*/
13625#if !SQLITE_THREADSAFE
13626# define SQLITE_MUTEX_OMIT
13627#endif
13628#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
13629#  if SQLITE_OS_UNIX
13630#    define SQLITE_MUTEX_PTHREADS
13631#  elif SQLITE_OS_WIN
13632#    define SQLITE_MUTEX_W32
13633#  else
13634#    define SQLITE_MUTEX_NOOP
13635#  endif
13636#endif
13637
13638#ifdef SQLITE_MUTEX_OMIT
13639/*
13640** If this is a no-op implementation, implement everything as macros.
13641*/
13642#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
13643#define sqlite3_mutex_free(X)
13644#define sqlite3_mutex_enter(X)
13645#define sqlite3_mutex_try(X)      SQLITE_OK
13646#define sqlite3_mutex_leave(X)
13647#define sqlite3_mutex_held(X)     ((void)(X),1)
13648#define sqlite3_mutex_notheld(X)  ((void)(X),1)
13649#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
13650#define sqlite3MutexInit()        SQLITE_OK
13651#define sqlite3MutexEnd()
13652#define MUTEX_LOGIC(X)
13653#else
13654#define MUTEX_LOGIC(X)            X
13655#endif /* defined(SQLITE_MUTEX_OMIT) */
13656
13657/************** End of mutex.h ***********************************************/
13658/************** Continuing where we left off in sqliteInt.h ******************/
13659
13660/* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
13661** synchronous setting to EXTRA.  It is no longer supported.
13662*/
13663#ifdef SQLITE_EXTRA_DURABLE
13664# warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
13665# define SQLITE_DEFAULT_SYNCHRONOUS 3
13666#endif
13667
13668/*
13669** Default synchronous levels.
13670**
13671** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
13672** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
13673**
13674**           PAGER_SYNCHRONOUS       DEFAULT_SYNCHRONOUS
13675**   OFF           1                         0
13676**   NORMAL        2                         1
13677**   FULL          3                         2
13678**   EXTRA         4                         3
13679**
13680** The "PRAGMA synchronous" statement also uses the zero-based numbers.
13681** In other words, the zero-based numbers are used for all external interfaces
13682** and the one-based values are used internally.
13683*/
13684#ifndef SQLITE_DEFAULT_SYNCHRONOUS
13685# define SQLITE_DEFAULT_SYNCHRONOUS (PAGER_SYNCHRONOUS_FULL-1)
13686#endif
13687#ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
13688# define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
13689#endif
13690
13691/*
13692** Each database file to be accessed by the system is an instance
13693** of the following structure.  There are normally two of these structures
13694** in the sqlite.aDb[] array.  aDb[0] is the main database file and
13695** aDb[1] is the database file used to hold temporary tables.  Additional
13696** databases may be attached.
13697*/
13698struct Db {
13699  char *zName;         /* Name of this database */
13700  Btree *pBt;          /* The B*Tree structure for this database file */
13701  u8 safety_level;     /* How aggressive at syncing data to disk */
13702  u8 bSyncSet;         /* True if "PRAGMA synchronous=N" has been run */
13703  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
13704};
13705
13706/*
13707** An instance of the following structure stores a database schema.
13708**
13709** Most Schema objects are associated with a Btree.  The exception is
13710** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
13711** In shared cache mode, a single Schema object can be shared by multiple
13712** Btrees that refer to the same underlying BtShared object.
13713**
13714** Schema objects are automatically deallocated when the last Btree that
13715** references them is destroyed.   The TEMP Schema is manually freed by
13716** sqlite3_close().
13717*
13718** A thread must be holding a mutex on the corresponding Btree in order
13719** to access Schema content.  This implies that the thread must also be
13720** holding a mutex on the sqlite3 connection pointer that owns the Btree.
13721** For a TEMP Schema, only the connection mutex is required.
13722*/
13723struct Schema {
13724  int schema_cookie;   /* Database schema version number for this file */
13725  int iGeneration;     /* Generation counter.  Incremented with each change */
13726  Hash tblHash;        /* All tables indexed by name */
13727  Hash idxHash;        /* All (named) indices indexed by name */
13728  Hash trigHash;       /* All triggers indexed by name */
13729  Hash fkeyHash;       /* All foreign keys by referenced table name */
13730  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
13731  u8 file_format;      /* Schema format version for this file */
13732  u8 enc;              /* Text encoding used by this database */
13733  u16 schemaFlags;     /* Flags associated with this schema */
13734  int cache_size;      /* Number of pages to use in the cache */
13735};
13736
13737/*
13738** These macros can be used to test, set, or clear bits in the
13739** Db.pSchema->flags field.
13740*/
13741#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
13742#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
13743#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)
13744#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)
13745
13746/*
13747** Allowed values for the DB.pSchema->flags field.
13748**
13749** The DB_SchemaLoaded flag is set after the database schema has been
13750** read into internal hash tables.
13751**
13752** DB_UnresetViews means that one or more views have column names that
13753** have been filled out.  If the schema changes, these column names might
13754** changes and so the view will need to be reset.
13755*/
13756#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
13757#define DB_UnresetViews    0x0002  /* Some views have defined column names */
13758#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
13759
13760/*
13761** The number of different kinds of things that can be limited
13762** using the sqlite3_limit() interface.
13763*/
13764#define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
13765
13766/*
13767** Lookaside malloc is a set of fixed-size buffers that can be used
13768** to satisfy small transient memory allocation requests for objects
13769** associated with a particular database connection.  The use of
13770** lookaside malloc provides a significant performance enhancement
13771** (approx 10%) by avoiding numerous malloc/free requests while parsing
13772** SQL statements.
13773**
13774** The Lookaside structure holds configuration information about the
13775** lookaside malloc subsystem.  Each available memory allocation in
13776** the lookaside subsystem is stored on a linked list of LookasideSlot
13777** objects.
13778**
13779** Lookaside allocations are only allowed for objects that are associated
13780** with a particular database connection.  Hence, schema information cannot
13781** be stored in lookaside because in shared cache mode the schema information
13782** is shared by multiple database connections.  Therefore, while parsing
13783** schema information, the Lookaside.bEnabled flag is cleared so that
13784** lookaside allocations are not used to construct the schema objects.
13785*/
13786struct Lookaside {
13787  u32 bDisable;           /* Only operate the lookaside when zero */
13788  u16 sz;                 /* Size of each buffer in bytes */
13789  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
13790  int nOut;               /* Number of buffers currently checked out */
13791  int mxOut;              /* Highwater mark for nOut */
13792  int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
13793  LookasideSlot *pFree;   /* List of available buffers */
13794  void *pStart;           /* First byte of available memory space */
13795  void *pEnd;             /* First byte past end of available space */
13796};
13797struct LookasideSlot {
13798  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
13799};
13800
13801/*
13802** A hash table for built-in function definitions.  (Application-defined
13803** functions use a regular table table from hash.h.)
13804**
13805** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
13806** Collisions are on the FuncDef.u.pHash chain.
13807*/
13808#define SQLITE_FUNC_HASH_SZ 23
13809struct FuncDefHash {
13810  FuncDef *a[SQLITE_FUNC_HASH_SZ];       /* Hash table for functions */
13811};
13812
13813#ifdef SQLITE_USER_AUTHENTICATION
13814/*
13815** Information held in the "sqlite3" database connection object and used
13816** to manage user authentication.
13817*/
13818typedef struct sqlite3_userauth sqlite3_userauth;
13819struct sqlite3_userauth {
13820  u8 authLevel;                 /* Current authentication level */
13821  int nAuthPW;                  /* Size of the zAuthPW in bytes */
13822  char *zAuthPW;                /* Password used to authenticate */
13823  char *zAuthUser;              /* User name used to authenticate */
13824};
13825
13826/* Allowed values for sqlite3_userauth.authLevel */
13827#define UAUTH_Unknown     0     /* Authentication not yet checked */
13828#define UAUTH_Fail        1     /* User authentication failed */
13829#define UAUTH_User        2     /* Authenticated as a normal user */
13830#define UAUTH_Admin       3     /* Authenticated as an administrator */
13831
13832/* Functions used only by user authorization logic */
13833SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
13834SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
13835SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
13836SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
13837
13838#endif /* SQLITE_USER_AUTHENTICATION */
13839
13840/*
13841** typedef for the authorization callback function.
13842*/
13843#ifdef SQLITE_USER_AUTHENTICATION
13844  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
13845                               const char*, const char*);
13846#else
13847  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
13848                               const char*);
13849#endif
13850
13851#ifndef SQLITE_OMIT_DEPRECATED
13852/* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
13853** in the style of sqlite3_trace()
13854*/
13855#define SQLITE_TRACE_LEGACY  0x80
13856#else
13857#define SQLITE_TRACE_LEGACY  0
13858#endif /* SQLITE_OMIT_DEPRECATED */
13859
13860
13861/*
13862** Each database connection is an instance of the following structure.
13863*/
13864struct sqlite3 {
13865  sqlite3_vfs *pVfs;            /* OS Interface */
13866  struct Vdbe *pVdbe;           /* List of active virtual machines */
13867  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
13868  sqlite3_mutex *mutex;         /* Connection mutex */
13869  Db *aDb;                      /* All backends */
13870  int nDb;                      /* Number of backends currently in use */
13871  int flags;                    /* Miscellaneous flags. See below */
13872  i64 lastRowid;                /* ROWID of most recent insert (see above) */
13873  i64 szMmap;                   /* Default mmap_size setting */
13874  unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
13875  int errCode;                  /* Most recent error code (SQLITE_*) */
13876  int errMask;                  /* & result codes with this before returning */
13877  int iSysErrno;                /* Errno value from last system error */
13878  u16 dbOptFlags;               /* Flags to enable/disable optimizations */
13879  u8 enc;                       /* Text encoding */
13880  u8 autoCommit;                /* The auto-commit flag. */
13881  u8 temp_store;                /* 1: file 2: memory 0: default */
13882  u8 mallocFailed;              /* True if we have seen a malloc failure */
13883  u8 bBenignMalloc;             /* Do not require OOMs if true */
13884  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
13885  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
13886  u8 suppressErr;               /* Do not issue error messages if true */
13887  u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
13888  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
13889  u8 mTrace;                    /* zero or more SQLITE_TRACE flags */
13890  int nextPagesize;             /* Pagesize after VACUUM if >0 */
13891  u32 magic;                    /* Magic number for detect library misuse */
13892  int nChange;                  /* Value returned by sqlite3_changes() */
13893  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
13894  int aLimit[SQLITE_N_LIMIT];   /* Limits */
13895  int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */
13896  struct sqlite3InitInfo {      /* Information used during initialization */
13897    int newTnum;                /* Rootpage of table being initialized */
13898    u8 iDb;                     /* Which db file is being initialized */
13899    u8 busy;                    /* TRUE if currently initializing */
13900    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
13901    u8 imposterTable;           /* Building an imposter table */
13902  } init;
13903  int nVdbeActive;              /* Number of VDBEs currently running */
13904  int nVdbeRead;                /* Number of active VDBEs that read or write */
13905  int nVdbeWrite;               /* Number of active VDBEs that read and write */
13906  int nVdbeExec;                /* Number of nested calls to VdbeExec() */
13907  int nVDestroy;                /* Number of active OP_VDestroy operations */
13908  int nExtension;               /* Number of loaded extensions */
13909  void **aExtension;            /* Array of shared library handles */
13910  int (*xTrace)(u32,void*,void*,void*);     /* Trace function */
13911  void *pTraceArg;                          /* Argument to the trace function */
13912  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
13913  void *pProfileArg;                        /* Argument to profile function */
13914  void *pCommitArg;                 /* Argument to xCommitCallback() */
13915  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
13916  void *pRollbackArg;               /* Argument to xRollbackCallback() */
13917  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
13918  void *pUpdateArg;
13919  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
13920#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
13921  void *pPreUpdateArg;          /* First argument to xPreUpdateCallback */
13922  void (*xPreUpdateCallback)(   /* Registered using sqlite3_preupdate_hook() */
13923    void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
13924  );
13925  PreUpdate *pPreUpdate;        /* Context for active pre-update callback */
13926#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
13927#ifndef SQLITE_OMIT_WAL
13928  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
13929  void *pWalArg;
13930#endif
13931  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
13932  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
13933  void *pCollNeededArg;
13934  sqlite3_value *pErr;          /* Most recent error message */
13935  union {
13936    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
13937    double notUsed1;            /* Spacer */
13938  } u1;
13939  Lookaside lookaside;          /* Lookaside malloc configuration */
13940#ifndef SQLITE_OMIT_AUTHORIZATION
13941  sqlite3_xauth xAuth;          /* Access authorization function */
13942  void *pAuthArg;               /* 1st argument to the access auth function */
13943#endif
13944#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
13945  int (*xProgress)(void *);     /* The progress callback */
13946  void *pProgressArg;           /* Argument to the progress callback */
13947  unsigned nProgressOps;        /* Number of opcodes for progress callback */
13948#endif
13949#ifndef SQLITE_OMIT_VIRTUALTABLE
13950  int nVTrans;                  /* Allocated size of aVTrans */
13951  Hash aModule;                 /* populated by sqlite3_create_module() */
13952  VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
13953  VTable **aVTrans;             /* Virtual tables with open transactions */
13954  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
13955#endif
13956  Hash aFunc;                   /* Hash table of connection functions */
13957  Hash aCollSeq;                /* All collating sequences */
13958  BusyHandler busyHandler;      /* Busy callback */
13959  Db aDbStatic[2];              /* Static space for the 2 default backends */
13960  Savepoint *pSavepoint;        /* List of active savepoints */
13961  int busyTimeout;              /* Busy handler timeout, in msec */
13962  int nSavepoint;               /* Number of non-transaction savepoints */
13963  int nStatement;               /* Number of nested statement-transactions  */
13964  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
13965  i64 nDeferredImmCons;         /* Net deferred immediate constraints */
13966  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
13967#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
13968  /* The following variables are all protected by the STATIC_MASTER
13969  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
13970  **
13971  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
13972  ** unlock so that it can proceed.
13973  **
13974  ** When X.pBlockingConnection==Y, that means that something that X tried
13975  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
13976  ** held by Y.
13977  */
13978  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
13979  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
13980  void *pUnlockArg;                     /* Argument to xUnlockNotify */
13981  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
13982  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
13983#endif
13984#ifdef SQLITE_USER_AUTHENTICATION
13985  sqlite3_userauth auth;        /* User authentication information */
13986#endif
13987};
13988
13989/*
13990** A macro to discover the encoding of a database.
13991*/
13992#define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
13993#define ENC(db)        ((db)->enc)
13994
13995/*
13996** Possible values for the sqlite3.flags.
13997**
13998** Value constraints (enforced via assert()):
13999**      SQLITE_FullFSync     == PAGER_FULLFSYNC
14000**      SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
14001**      SQLITE_CacheSpill    == PAGER_CACHE_SPILL
14002*/
14003#define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
14004#define SQLITE_InternChanges  0x00000002  /* Uncommitted Hash table changes */
14005#define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */
14006#define SQLITE_FullFSync      0x00000008  /* Use full fsync on the backend */
14007#define SQLITE_CkptFullFSync  0x00000010  /* Use full fsync for checkpoint */
14008#define SQLITE_CacheSpill     0x00000020  /* OK to spill pager cache */
14009#define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
14010#define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
14011                                          /*   DELETE, or UPDATE and return */
14012                                          /*   the count using a callback. */
14013#define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
14014                                          /*   result set is empty */
14015#define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
14016#define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
14017#define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
14018#define SQLITE_VdbeAddopTrace 0x00001000  /* Trace sqlite3VdbeAddOp() calls */
14019#define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
14020#define SQLITE_ReadUncommitted 0x0004000  /* For shared-cache mode */
14021#define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
14022#define SQLITE_RecoveryMode   0x00010000  /* Ignore schema errors */
14023#define SQLITE_ReverseOrder   0x00020000  /* Reverse unordered SELECTs */
14024#define SQLITE_RecTriggers    0x00040000  /* Enable recursive triggers */
14025#define SQLITE_ForeignKeys    0x00080000  /* Enforce foreign key constraints  */
14026#define SQLITE_AutoIndex      0x00100000  /* Enable automatic indexes */
14027#define SQLITE_PreferBuiltin  0x00200000  /* Preference to built-in funcs */
14028#define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
14029#define SQLITE_LoadExtFunc    0x00800000  /* Enable load_extension() SQL func */
14030#define SQLITE_EnableTrigger  0x01000000  /* True to enable triggers */
14031#define SQLITE_DeferFKs       0x02000000  /* Defer all FK constraints */
14032#define SQLITE_QueryOnly      0x04000000  /* Disable database changes */
14033#define SQLITE_VdbeEQP        0x08000000  /* Debug EXPLAIN QUERY PLAN */
14034#define SQLITE_Vacuum         0x10000000  /* Currently in a VACUUM */
14035#define SQLITE_CellSizeCk     0x20000000  /* Check btree cell sizes on load */
14036#define SQLITE_Fts3Tokenizer  0x40000000  /* Enable fts3_tokenizer(2) */
14037
14038
14039/*
14040** Bits of the sqlite3.dbOptFlags field that are used by the
14041** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
14042** selectively disable various optimizations.
14043*/
14044#define SQLITE_QueryFlattener 0x0001   /* Query flattening */
14045#define SQLITE_ColumnCache    0x0002   /* Column cache */
14046#define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
14047#define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
14048/*                not used    0x0010   // Was: SQLITE_IdxRealAsInt */
14049#define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
14050#define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
14051#define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
14052#define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
14053#define SQLITE_Transitive     0x0200   /* Transitive constraints */
14054#define SQLITE_OmitNoopJoin   0x0400   /* Omit unused tables in joins */
14055#define SQLITE_Stat34         0x0800   /* Use STAT3 or STAT4 data */
14056#define SQLITE_CursorHints    0x2000   /* Add OP_CursorHint opcodes */
14057#define SQLITE_AllOpts        0xffff   /* All optimizations */
14058
14059/*
14060** Macros for testing whether or not optimizations are enabled or disabled.
14061*/
14062#ifndef SQLITE_OMIT_BUILTIN_TEST
14063#define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
14064#define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
14065#else
14066#define OptimizationDisabled(db, mask)  0
14067#define OptimizationEnabled(db, mask)   1
14068#endif
14069
14070/*
14071** Return true if it OK to factor constant expressions into the initialization
14072** code. The argument is a Parse object for the code generator.
14073*/
14074#define ConstFactorOk(P) ((P)->okConstFactor)
14075
14076/*
14077** Possible values for the sqlite.magic field.
14078** The numbers are obtained at random and have no special meaning, other
14079** than being distinct from one another.
14080*/
14081#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
14082#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
14083#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
14084#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
14085#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
14086#define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
14087
14088/*
14089** Each SQL function is defined by an instance of the following
14090** structure.  For global built-in functions (ex: substr(), max(), count())
14091** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
14092** For per-connection application-defined functions, a pointer to this
14093** structure is held in the db->aHash hash table.
14094**
14095** The u.pHash field is used by the global built-ins.  The u.pDestructor
14096** field is used by per-connection app-def functions.
14097*/
14098struct FuncDef {
14099  i8 nArg;             /* Number of arguments.  -1 means unlimited */
14100  u16 funcFlags;       /* Some combination of SQLITE_FUNC_* */
14101  void *pUserData;     /* User data parameter */
14102  FuncDef *pNext;      /* Next function with same name */
14103  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
14104  void (*xFinalize)(sqlite3_context*);                  /* Agg finalizer */
14105  const char *zName;   /* SQL name of the function. */
14106  union {
14107    FuncDef *pHash;      /* Next with a different name but the same hash */
14108    FuncDestructor *pDestructor;   /* Reference counted destructor function */
14109  } u;
14110};
14111
14112/*
14113** This structure encapsulates a user-function destructor callback (as
14114** configured using create_function_v2()) and a reference counter. When
14115** create_function_v2() is called to create a function with a destructor,
14116** a single object of this type is allocated. FuncDestructor.nRef is set to
14117** the number of FuncDef objects created (either 1 or 3, depending on whether
14118** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
14119** member of each of the new FuncDef objects is set to point to the allocated
14120** FuncDestructor.
14121**
14122** Thereafter, when one of the FuncDef objects is deleted, the reference
14123** count on this object is decremented. When it reaches 0, the destructor
14124** is invoked and the FuncDestructor structure freed.
14125*/
14126struct FuncDestructor {
14127  int nRef;
14128  void (*xDestroy)(void *);
14129  void *pUserData;
14130};
14131
14132/*
14133** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
14134** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  And
14135** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC.  There
14136** are assert() statements in the code to verify this.
14137**
14138** Value constraints (enforced via assert()):
14139**     SQLITE_FUNC_MINMAX    ==  NC_MinMaxAgg      == SF_MinMaxAgg
14140**     SQLITE_FUNC_LENGTH    ==  OPFLAG_LENGTHARG
14141**     SQLITE_FUNC_TYPEOF    ==  OPFLAG_TYPEOFARG
14142**     SQLITE_FUNC_CONSTANT  ==  SQLITE_DETERMINISTIC from the API
14143**     SQLITE_FUNC_ENCMASK   depends on SQLITE_UTF* macros in the API
14144*/
14145#define SQLITE_FUNC_ENCMASK  0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
14146#define SQLITE_FUNC_LIKE     0x0004 /* Candidate for the LIKE optimization */
14147#define SQLITE_FUNC_CASE     0x0008 /* Case-sensitive LIKE-type function */
14148#define SQLITE_FUNC_EPHEM    0x0010 /* Ephemeral.  Delete with VDBE */
14149#define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
14150#define SQLITE_FUNC_LENGTH   0x0040 /* Built-in length() function */
14151#define SQLITE_FUNC_TYPEOF   0x0080 /* Built-in typeof() function */
14152#define SQLITE_FUNC_COUNT    0x0100 /* Built-in count(*) aggregate */
14153#define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
14154#define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
14155#define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
14156#define SQLITE_FUNC_MINMAX   0x1000 /* True for min() and max() aggregates */
14157#define SQLITE_FUNC_SLOCHNG  0x2000 /* "Slow Change". Value constant during a
14158                                    ** single query - might change over time */
14159
14160/*
14161** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
14162** used to create the initializers for the FuncDef structures.
14163**
14164**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
14165**     Used to create a scalar function definition of a function zName
14166**     implemented by C function xFunc that accepts nArg arguments. The
14167**     value passed as iArg is cast to a (void*) and made available
14168**     as the user-data (sqlite3_user_data()) for the function. If
14169**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
14170**
14171**   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
14172**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
14173**
14174**   DFUNCTION(zName, nArg, iArg, bNC, xFunc)
14175**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
14176**     adds the SQLITE_FUNC_SLOCHNG flag.  Used for date & time functions
14177**     and functions like sqlite_version() that can change, but not during
14178**     a single query.
14179**
14180**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
14181**     Used to create an aggregate function definition implemented by
14182**     the C functions xStep and xFinal. The first four parameters
14183**     are interpreted in the same way as the first 4 parameters to
14184**     FUNCTION().
14185**
14186**   LIKEFUNC(zName, nArg, pArg, flags)
14187**     Used to create a scalar function definition of a function zName
14188**     that accepts nArg arguments and is implemented by a call to C
14189**     function likeFunc. Argument pArg is cast to a (void *) and made
14190**     available as the function user-data (sqlite3_user_data()). The
14191**     FuncDef.flags variable is set to the value passed as the flags
14192**     parameter.
14193*/
14194#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
14195  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14196   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14197#define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
14198  {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14199   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14200#define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
14201  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14202   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14203#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
14204  {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
14205   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14206#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
14207  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14208   pArg, 0, xFunc, 0, #zName, }
14209#define LIKEFUNC(zName, nArg, arg, flags) \
14210  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
14211   (void *)arg, 0, likeFunc, 0, #zName, {0} }
14212#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
14213  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
14214   SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
14215#define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
14216  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
14217   SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
14218
14219/*
14220** All current savepoints are stored in a linked list starting at
14221** sqlite3.pSavepoint. The first element in the list is the most recently
14222** opened savepoint. Savepoints are added to the list by the vdbe
14223** OP_Savepoint instruction.
14224*/
14225struct Savepoint {
14226  char *zName;                        /* Savepoint name (nul-terminated) */
14227  i64 nDeferredCons;                  /* Number of deferred fk violations */
14228  i64 nDeferredImmCons;               /* Number of deferred imm fk. */
14229  Savepoint *pNext;                   /* Parent savepoint (if any) */
14230};
14231
14232/*
14233** The following are used as the second parameter to sqlite3Savepoint(),
14234** and as the P1 argument to the OP_Savepoint instruction.
14235*/
14236#define SAVEPOINT_BEGIN      0
14237#define SAVEPOINT_RELEASE    1
14238#define SAVEPOINT_ROLLBACK   2
14239
14240
14241/*
14242** Each SQLite module (virtual table definition) is defined by an
14243** instance of the following structure, stored in the sqlite3.aModule
14244** hash table.
14245*/
14246struct Module {
14247  const sqlite3_module *pModule;       /* Callback pointers */
14248  const char *zName;                   /* Name passed to create_module() */
14249  void *pAux;                          /* pAux passed to create_module() */
14250  void (*xDestroy)(void *);            /* Module destructor function */
14251  Table *pEpoTab;                      /* Eponymous table for this module */
14252};
14253
14254/*
14255** information about each column of an SQL table is held in an instance
14256** of this structure.
14257*/
14258struct Column {
14259  char *zName;     /* Name of this column, \000, then the type */
14260  Expr *pDflt;     /* Default value of this column */
14261  char *zColl;     /* Collating sequence.  If NULL, use the default */
14262  u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
14263  char affinity;   /* One of the SQLITE_AFF_... values */
14264  u8 szEst;        /* Estimated size of value in this column. sizeof(INT)==1 */
14265  u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
14266};
14267
14268/* Allowed values for Column.colFlags:
14269*/
14270#define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
14271#define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
14272#define COLFLAG_HASTYPE  0x0004    /* Type name follows column name */
14273
14274/*
14275** A "Collating Sequence" is defined by an instance of the following
14276** structure. Conceptually, a collating sequence consists of a name and
14277** a comparison routine that defines the order of that sequence.
14278**
14279** If CollSeq.xCmp is NULL, it means that the
14280** collating sequence is undefined.  Indices built on an undefined
14281** collating sequence may not be read or written.
14282*/
14283struct CollSeq {
14284  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
14285  u8 enc;               /* Text encoding handled by xCmp() */
14286  void *pUser;          /* First argument to xCmp() */
14287  int (*xCmp)(void*,int, const void*, int, const void*);
14288  void (*xDel)(void*);  /* Destructor for pUser */
14289};
14290
14291/*
14292** A sort order can be either ASC or DESC.
14293*/
14294#define SQLITE_SO_ASC       0  /* Sort in ascending order */
14295#define SQLITE_SO_DESC      1  /* Sort in ascending order */
14296#define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
14297
14298/*
14299** Column affinity types.
14300**
14301** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
14302** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
14303** the speed a little by numbering the values consecutively.
14304**
14305** But rather than start with 0 or 1, we begin with 'A'.  That way,
14306** when multiple affinity types are concatenated into a string and
14307** used as the P4 operand, they will be more readable.
14308**
14309** Note also that the numeric types are grouped together so that testing
14310** for a numeric type is a single comparison.  And the BLOB type is first.
14311*/
14312#define SQLITE_AFF_BLOB     'A'
14313#define SQLITE_AFF_TEXT     'B'
14314#define SQLITE_AFF_NUMERIC  'C'
14315#define SQLITE_AFF_INTEGER  'D'
14316#define SQLITE_AFF_REAL     'E'
14317
14318#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
14319
14320/*
14321** The SQLITE_AFF_MASK values masks off the significant bits of an
14322** affinity value.
14323*/
14324#define SQLITE_AFF_MASK     0x47
14325
14326/*
14327** Additional bit values that can be ORed with an affinity without
14328** changing the affinity.
14329**
14330** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
14331** It causes an assert() to fire if either operand to a comparison
14332** operator is NULL.  It is added to certain comparison operators to
14333** prove that the operands are always NOT NULL.
14334*/
14335#define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */
14336#define SQLITE_STOREP2      0x20  /* Store result in reg[P2] rather than jump */
14337#define SQLITE_NULLEQ       0x80  /* NULL=NULL */
14338#define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */
14339
14340/*
14341** An object of this type is created for each virtual table present in
14342** the database schema.
14343**
14344** If the database schema is shared, then there is one instance of this
14345** structure for each database connection (sqlite3*) that uses the shared
14346** schema. This is because each database connection requires its own unique
14347** instance of the sqlite3_vtab* handle used to access the virtual table
14348** implementation. sqlite3_vtab* handles can not be shared between
14349** database connections, even when the rest of the in-memory database
14350** schema is shared, as the implementation often stores the database
14351** connection handle passed to it via the xConnect() or xCreate() method
14352** during initialization internally. This database connection handle may
14353** then be used by the virtual table implementation to access real tables
14354** within the database. So that they appear as part of the callers
14355** transaction, these accesses need to be made via the same database
14356** connection as that used to execute SQL operations on the virtual table.
14357**
14358** All VTable objects that correspond to a single table in a shared
14359** database schema are initially stored in a linked-list pointed to by
14360** the Table.pVTable member variable of the corresponding Table object.
14361** When an sqlite3_prepare() operation is required to access the virtual
14362** table, it searches the list for the VTable that corresponds to the
14363** database connection doing the preparing so as to use the correct
14364** sqlite3_vtab* handle in the compiled query.
14365**
14366** When an in-memory Table object is deleted (for example when the
14367** schema is being reloaded for some reason), the VTable objects are not
14368** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
14369** immediately. Instead, they are moved from the Table.pVTable list to
14370** another linked list headed by the sqlite3.pDisconnect member of the
14371** corresponding sqlite3 structure. They are then deleted/xDisconnected
14372** next time a statement is prepared using said sqlite3*. This is done
14373** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
14374** Refer to comments above function sqlite3VtabUnlockList() for an
14375** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
14376** list without holding the corresponding sqlite3.mutex mutex.
14377**
14378** The memory for objects of this type is always allocated by
14379** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
14380** the first argument.
14381*/
14382struct VTable {
14383  sqlite3 *db;              /* Database connection associated with this table */
14384  Module *pMod;             /* Pointer to module implementation */
14385  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
14386  int nRef;                 /* Number of pointers to this structure */
14387  u8 bConstraint;           /* True if constraints are supported */
14388  int iSavepoint;           /* Depth of the SAVEPOINT stack */
14389  VTable *pNext;            /* Next in linked list (see above) */
14390};
14391
14392/*
14393** The schema for each SQL table and view is represented in memory
14394** by an instance of the following structure.
14395*/
14396struct Table {
14397  char *zName;         /* Name of the table or view */
14398  Column *aCol;        /* Information about each column */
14399  Index *pIndex;       /* List of SQL indexes on this table. */
14400  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
14401  FKey *pFKey;         /* Linked list of all foreign keys in this table */
14402  char *zColAff;       /* String defining the affinity of each column */
14403  ExprList *pCheck;    /* All CHECK constraints */
14404                       /*   ... also used as column name list in a VIEW */
14405  int tnum;            /* Root BTree page for this table */
14406  i16 iPKey;           /* If not negative, use aCol[iPKey] as the rowid */
14407  i16 nCol;            /* Number of columns in this table */
14408  u16 nRef;            /* Number of pointers to this Table */
14409  LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */
14410  LogEst szTabRow;     /* Estimated size of each table row in bytes */
14411#ifdef SQLITE_ENABLE_COSTMULT
14412  LogEst costMult;     /* Cost multiplier for using this table */
14413#endif
14414  u8 tabFlags;         /* Mask of TF_* values */
14415  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
14416#ifndef SQLITE_OMIT_ALTERTABLE
14417  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
14418#endif
14419#ifndef SQLITE_OMIT_VIRTUALTABLE
14420  int nModuleArg;      /* Number of arguments to the module */
14421  char **azModuleArg;  /* 0: module 1: schema 2: vtab name 3...: args */
14422  VTable *pVTable;     /* List of VTable objects. */
14423#endif
14424  Trigger *pTrigger;   /* List of triggers stored in pSchema */
14425  Schema *pSchema;     /* Schema that contains this table */
14426  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
14427};
14428
14429/*
14430** Allowed values for Table.tabFlags.
14431**
14432** TF_OOOHidden applies to tables or view that have hidden columns that are
14433** followed by non-hidden columns.  Example:  "CREATE VIRTUAL TABLE x USING
14434** vtab1(a HIDDEN, b);".  Since "b" is a non-hidden column but "a" is hidden,
14435** the TF_OOOHidden attribute would apply in this case.  Such tables require
14436** special handling during INSERT processing.
14437*/
14438#define TF_Readonly        0x01    /* Read-only system table */
14439#define TF_Ephemeral       0x02    /* An ephemeral table */
14440#define TF_HasPrimaryKey   0x04    /* Table has a primary key */
14441#define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
14442#define TF_Virtual         0x10    /* Is a virtual table */
14443#define TF_WithoutRowid    0x20    /* No rowid.  PRIMARY KEY is the key */
14444#define TF_NoVisibleRowid  0x40    /* No user-visible "rowid" column */
14445#define TF_OOOHidden       0x80    /* Out-of-Order hidden columns */
14446
14447
14448/*
14449** Test to see whether or not a table is a virtual table.  This is
14450** done as a macro so that it will be optimized out when virtual
14451** table support is omitted from the build.
14452*/
14453#ifndef SQLITE_OMIT_VIRTUALTABLE
14454#  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
14455#else
14456#  define IsVirtual(X)      0
14457#endif
14458
14459/*
14460** Macros to determine if a column is hidden.  IsOrdinaryHiddenColumn()
14461** only works for non-virtual tables (ordinary tables and views) and is
14462** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined.  The
14463** IsHiddenColumn() macro is general purpose.
14464*/
14465#if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
14466#  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14467#  define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14468#elif !defined(SQLITE_OMIT_VIRTUALTABLE)
14469#  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14470#  define IsOrdinaryHiddenColumn(X) 0
14471#else
14472#  define IsHiddenColumn(X)         0
14473#  define IsOrdinaryHiddenColumn(X) 0
14474#endif
14475
14476
14477/* Does the table have a rowid */
14478#define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
14479#define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
14480
14481/*
14482** Each foreign key constraint is an instance of the following structure.
14483**
14484** A foreign key is associated with two tables.  The "from" table is
14485** the table that contains the REFERENCES clause that creates the foreign
14486** key.  The "to" table is the table that is named in the REFERENCES clause.
14487** Consider this example:
14488**
14489**     CREATE TABLE ex1(
14490**       a INTEGER PRIMARY KEY,
14491**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
14492**     );
14493**
14494** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
14495** Equivalent names:
14496**
14497**     from-table == child-table
14498**       to-table == parent-table
14499**
14500** Each REFERENCES clause generates an instance of the following structure
14501** which is attached to the from-table.  The to-table need not exist when
14502** the from-table is created.  The existence of the to-table is not checked.
14503**
14504** The list of all parents for child Table X is held at X.pFKey.
14505**
14506** A list of all children for a table named Z (which might not even exist)
14507** is held in Schema.fkeyHash with a hash key of Z.
14508*/
14509struct FKey {
14510  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
14511  FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
14512  char *zTo;        /* Name of table that the key points to (aka: Parent) */
14513  FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
14514  FKey *pPrevTo;    /* Previous with the same zTo */
14515  int nCol;         /* Number of columns in this key */
14516  /* EV: R-30323-21917 */
14517  u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
14518  u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
14519  Trigger *apTrigger[2];/* Triggers for aAction[] actions */
14520  struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
14521    int iFrom;            /* Index of column in pFrom */
14522    char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
14523  } aCol[1];            /* One entry for each of nCol columns */
14524};
14525
14526/*
14527** SQLite supports many different ways to resolve a constraint
14528** error.  ROLLBACK processing means that a constraint violation
14529** causes the operation in process to fail and for the current transaction
14530** to be rolled back.  ABORT processing means the operation in process
14531** fails and any prior changes from that one operation are backed out,
14532** but the transaction is not rolled back.  FAIL processing means that
14533** the operation in progress stops and returns an error code.  But prior
14534** changes due to the same operation are not backed out and no rollback
14535** occurs.  IGNORE means that the particular row that caused the constraint
14536** error is not inserted or updated.  Processing continues and no error
14537** is returned.  REPLACE means that preexisting database rows that caused
14538** a UNIQUE constraint violation are removed so that the new insert or
14539** update can proceed.  Processing continues and no error is reported.
14540**
14541** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
14542** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
14543** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
14544** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
14545** referenced table row is propagated into the row that holds the
14546** foreign key.
14547**
14548** The following symbolic values are used to record which type
14549** of action to take.
14550*/
14551#define OE_None     0   /* There is no constraint to check */
14552#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
14553#define OE_Abort    2   /* Back out changes but do no rollback transaction */
14554#define OE_Fail     3   /* Stop the operation but leave all prior changes */
14555#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
14556#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
14557
14558#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
14559#define OE_SetNull  7   /* Set the foreign key value to NULL */
14560#define OE_SetDflt  8   /* Set the foreign key value to its default */
14561#define OE_Cascade  9   /* Cascade the changes */
14562
14563#define OE_Default  10  /* Do whatever the default action is */
14564
14565
14566/*
14567** An instance of the following structure is passed as the first
14568** argument to sqlite3VdbeKeyCompare and is used to control the
14569** comparison of the two index keys.
14570**
14571** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
14572** are nField slots for the columns of an index then one extra slot
14573** for the rowid at the end.
14574*/
14575struct KeyInfo {
14576  u32 nRef;           /* Number of references to this KeyInfo object */
14577  u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
14578  u16 nField;         /* Number of key columns in the index */
14579  u16 nXField;        /* Number of columns beyond the key columns */
14580  sqlite3 *db;        /* The database connection */
14581  u8 *aSortOrder;     /* Sort order for each column. */
14582  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
14583};
14584
14585/*
14586** This object holds a record which has been parsed out into individual
14587** fields, for the purposes of doing a comparison.
14588**
14589** A record is an object that contains one or more fields of data.
14590** Records are used to store the content of a table row and to store
14591** the key of an index.  A blob encoding of a record is created by
14592** the OP_MakeRecord opcode of the VDBE and is disassembled by the
14593** OP_Column opcode.
14594**
14595** An instance of this object serves as a "key" for doing a search on
14596** an index b+tree. The goal of the search is to find the entry that
14597** is closed to the key described by this object.  This object might hold
14598** just a prefix of the key.  The number of fields is given by
14599** pKeyInfo->nField.
14600**
14601** The r1 and r2 fields are the values to return if this key is less than
14602** or greater than a key in the btree, respectively.  These are normally
14603** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
14604** is in DESC order.
14605**
14606** The key comparison functions actually return default_rc when they find
14607** an equals comparison.  default_rc can be -1, 0, or +1.  If there are
14608** multiple entries in the b-tree with the same key (when only looking
14609** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
14610** cause the search to find the last match, or +1 to cause the search to
14611** find the first match.
14612**
14613** The key comparison functions will set eqSeen to true if they ever
14614** get and equal results when comparing this structure to a b-tree record.
14615** When default_rc!=0, the search might end up on the record immediately
14616** before the first match or immediately after the last match.  The
14617** eqSeen field will indicate whether or not an exact match exists in the
14618** b-tree.
14619*/
14620struct UnpackedRecord {
14621  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
14622  Mem *aMem;          /* Values */
14623  u16 nField;         /* Number of entries in apMem[] */
14624  i8 default_rc;      /* Comparison result if keys are equal */
14625  u8 errCode;         /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
14626  i8 r1;              /* Value to return if (lhs > rhs) */
14627  i8 r2;              /* Value to return if (rhs < lhs) */
14628  u8 eqSeen;          /* True if an equality comparison has been seen */
14629};
14630
14631
14632/*
14633** Each SQL index is represented in memory by an
14634** instance of the following structure.
14635**
14636** The columns of the table that are to be indexed are described
14637** by the aiColumn[] field of this structure.  For example, suppose
14638** we have the following table and index:
14639**
14640**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
14641**     CREATE INDEX Ex2 ON Ex1(c3,c1);
14642**
14643** In the Table structure describing Ex1, nCol==3 because there are
14644** three columns in the table.  In the Index structure describing
14645** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
14646** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
14647** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
14648** The second column to be indexed (c1) has an index of 0 in
14649** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
14650**
14651** The Index.onError field determines whether or not the indexed columns
14652** must be unique and what to do if they are not.  When Index.onError=OE_None,
14653** it means this is not a unique index.  Otherwise it is a unique index
14654** and the value of Index.onError indicate the which conflict resolution
14655** algorithm to employ whenever an attempt is made to insert a non-unique
14656** element.
14657**
14658** While parsing a CREATE TABLE or CREATE INDEX statement in order to
14659** generate VDBE code (as opposed to parsing one read from an sqlite_master
14660** table as part of parsing an existing database schema), transient instances
14661** of this structure may be created. In this case the Index.tnum variable is
14662** used to store the address of a VDBE instruction, not a database page
14663** number (it cannot - the database page is not allocated until the VDBE
14664** program is executed). See convertToWithoutRowidTable() for details.
14665*/
14666struct Index {
14667  char *zName;             /* Name of this index */
14668  i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
14669  LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */
14670  Table *pTable;           /* The SQL table being indexed */
14671  char *zColAff;           /* String defining the affinity of each column */
14672  Index *pNext;            /* The next index associated with the same table */
14673  Schema *pSchema;         /* Schema containing this index */
14674  u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
14675  const char **azColl;     /* Array of collation sequence names for index */
14676  Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
14677  ExprList *aColExpr;      /* Column expressions */
14678  int tnum;                /* DB Page containing root of this index */
14679  LogEst szIdxRow;         /* Estimated average row size in bytes */
14680  u16 nKeyCol;             /* Number of columns forming the key */
14681  u16 nColumn;             /* Number of columns stored in the index */
14682  u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
14683  unsigned idxType:2;      /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
14684  unsigned bUnordered:1;   /* Use this index for == or IN queries only */
14685  unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
14686  unsigned isResized:1;    /* True if resizeIndexObject() has been called */
14687  unsigned isCovering:1;   /* True if this is a covering index */
14688  unsigned noSkipScan:1;   /* Do not try to use skip-scan if true */
14689#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
14690  int nSample;             /* Number of elements in aSample[] */
14691  int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
14692  tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
14693  IndexSample *aSample;    /* Samples of the left-most key */
14694  tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this index */
14695  tRowcnt nRowEst0;        /* Non-logarithmic number of rows in the index */
14696#endif
14697};
14698
14699/*
14700** Allowed values for Index.idxType
14701*/
14702#define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */
14703#define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */
14704#define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */
14705
14706/* Return true if index X is a PRIMARY KEY index */
14707#define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
14708
14709/* Return true if index X is a UNIQUE index */
14710#define IsUniqueIndex(X)      ((X)->onError!=OE_None)
14711
14712/* The Index.aiColumn[] values are normally positive integer.  But
14713** there are some negative values that have special meaning:
14714*/
14715#define XN_ROWID     (-1)     /* Indexed column is the rowid */
14716#define XN_EXPR      (-2)     /* Indexed column is an expression */
14717
14718/*
14719** Each sample stored in the sqlite_stat3 table is represented in memory
14720** using a structure of this type.  See documentation at the top of the
14721** analyze.c source file for additional information.
14722*/
14723struct IndexSample {
14724  void *p;          /* Pointer to sampled record */
14725  int n;            /* Size of record in bytes */
14726  tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
14727  tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
14728  tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
14729};
14730
14731/*
14732** Each token coming out of the lexer is an instance of
14733** this structure.  Tokens are also used as part of an expression.
14734**
14735** Note if Token.z==0 then Token.dyn and Token.n are undefined and
14736** may contain random values.  Do not make any assumptions about Token.dyn
14737** and Token.n when Token.z==0.
14738*/
14739struct Token {
14740  const char *z;     /* Text of the token.  Not NULL-terminated! */
14741  unsigned int n;    /* Number of characters in this token */
14742};
14743
14744/*
14745** An instance of this structure contains information needed to generate
14746** code for a SELECT that contains aggregate functions.
14747**
14748** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
14749** pointer to this structure.  The Expr.iColumn field is the index in
14750** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
14751** code for that node.
14752**
14753** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
14754** original Select structure that describes the SELECT statement.  These
14755** fields do not need to be freed when deallocating the AggInfo structure.
14756*/
14757struct AggInfo {
14758  u8 directMode;          /* Direct rendering mode means take data directly
14759                          ** from source tables rather than from accumulators */
14760  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
14761                          ** than the source table */
14762  int sortingIdx;         /* Cursor number of the sorting index */
14763  int sortingIdxPTab;     /* Cursor number of pseudo-table */
14764  int nSortingColumn;     /* Number of columns in the sorting index */
14765  int mnReg, mxReg;       /* Range of registers allocated for aCol and aFunc */
14766  ExprList *pGroupBy;     /* The group by clause */
14767  struct AggInfo_col {    /* For each column used in source tables */
14768    Table *pTab;             /* Source table */
14769    int iTable;              /* Cursor number of the source table */
14770    int iColumn;             /* Column number within the source table */
14771    int iSorterColumn;       /* Column number in the sorting index */
14772    int iMem;                /* Memory location that acts as accumulator */
14773    Expr *pExpr;             /* The original expression */
14774  } *aCol;
14775  int nColumn;            /* Number of used entries in aCol[] */
14776  int nAccumulator;       /* Number of columns that show through to the output.
14777                          ** Additional columns are used only as parameters to
14778                          ** aggregate functions */
14779  struct AggInfo_func {   /* For each aggregate function */
14780    Expr *pExpr;             /* Expression encoding the function */
14781    FuncDef *pFunc;          /* The aggregate function implementation */
14782    int iMem;                /* Memory location that acts as accumulator */
14783    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
14784  } *aFunc;
14785  int nFunc;              /* Number of entries in aFunc[] */
14786};
14787
14788/*
14789** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
14790** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
14791** than 32767 we have to make it 32-bit.  16-bit is preferred because
14792** it uses less memory in the Expr object, which is a big memory user
14793** in systems with lots of prepared statements.  And few applications
14794** need more than about 10 or 20 variables.  But some extreme users want
14795** to have prepared statements with over 32767 variables, and for them
14796** the option is available (at compile-time).
14797*/
14798#if SQLITE_MAX_VARIABLE_NUMBER<=32767
14799typedef i16 ynVar;
14800#else
14801typedef int ynVar;
14802#endif
14803
14804/*
14805** Each node of an expression in the parse tree is an instance
14806** of this structure.
14807**
14808** Expr.op is the opcode. The integer parser token codes are reused
14809** as opcodes here. For example, the parser defines TK_GE to be an integer
14810** code representing the ">=" operator. This same integer code is reused
14811** to represent the greater-than-or-equal-to operator in the expression
14812** tree.
14813**
14814** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
14815** or TK_STRING), then Expr.token contains the text of the SQL literal. If
14816** the expression is a variable (TK_VARIABLE), then Expr.token contains the
14817** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
14818** then Expr.token contains the name of the function.
14819**
14820** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
14821** binary operator. Either or both may be NULL.
14822**
14823** Expr.x.pList is a list of arguments if the expression is an SQL function,
14824** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
14825** Expr.x.pSelect is used if the expression is a sub-select or an expression of
14826** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
14827** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
14828** valid.
14829**
14830** An expression of the form ID or ID.ID refers to a column in a table.
14831** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
14832** the integer cursor number of a VDBE cursor pointing to that table and
14833** Expr.iColumn is the column number for the specific column.  If the
14834** expression is used as a result in an aggregate SELECT, then the
14835** value is also stored in the Expr.iAgg column in the aggregate so that
14836** it can be accessed after all aggregates are computed.
14837**
14838** If the expression is an unbound variable marker (a question mark
14839** character '?' in the original SQL) then the Expr.iTable holds the index
14840** number for that variable.
14841**
14842** If the expression is a subquery then Expr.iColumn holds an integer
14843** register number containing the result of the subquery.  If the
14844** subquery gives a constant result, then iTable is -1.  If the subquery
14845** gives a different answer at different times during statement processing
14846** then iTable is the address of a subroutine that computes the subquery.
14847**
14848** If the Expr is of type OP_Column, and the table it is selecting from
14849** is a disk table or the "old.*" pseudo-table, then pTab points to the
14850** corresponding table definition.
14851**
14852** ALLOCATION NOTES:
14853**
14854** Expr objects can use a lot of memory space in database schema.  To
14855** help reduce memory requirements, sometimes an Expr object will be
14856** truncated.  And to reduce the number of memory allocations, sometimes
14857** two or more Expr objects will be stored in a single memory allocation,
14858** together with Expr.zToken strings.
14859**
14860** If the EP_Reduced and EP_TokenOnly flags are set when
14861** an Expr object is truncated.  When EP_Reduced is set, then all
14862** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
14863** are contained within the same memory allocation.  Note, however, that
14864** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
14865** allocated, regardless of whether or not EP_Reduced is set.
14866*/
14867struct Expr {
14868  u8 op;                 /* Operation performed by this node */
14869  char affinity;         /* The affinity of the column or 0 if not a column */
14870  u32 flags;             /* Various flags.  EP_* See below */
14871  union {
14872    char *zToken;          /* Token value. Zero terminated and dequoted */
14873    int iValue;            /* Non-negative integer value if EP_IntValue */
14874  } u;
14875
14876  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
14877  ** space is allocated for the fields below this point. An attempt to
14878  ** access them will result in a segfault or malfunction.
14879  *********************************************************************/
14880
14881  Expr *pLeft;           /* Left subnode */
14882  Expr *pRight;          /* Right subnode */
14883  union {
14884    ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
14885    Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
14886  } x;
14887
14888  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
14889  ** space is allocated for the fields below this point. An attempt to
14890  ** access them will result in a segfault or malfunction.
14891  *********************************************************************/
14892
14893#if SQLITE_MAX_EXPR_DEPTH>0
14894  int nHeight;           /* Height of the tree headed by this node */
14895#endif
14896  int iTable;            /* TK_COLUMN: cursor number of table holding column
14897                         ** TK_REGISTER: register number
14898                         ** TK_TRIGGER: 1 -> new, 0 -> old
14899                         ** EP_Unlikely:  134217728 times likelihood */
14900  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
14901                         ** TK_VARIABLE: variable number (always >= 1). */
14902  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
14903  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
14904  u8 op2;                /* TK_REGISTER: original value of Expr.op
14905                         ** TK_COLUMN: the value of p5 for OP_Column
14906                         ** TK_AGG_FUNCTION: nesting depth */
14907  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
14908  Table *pTab;           /* Table for TK_COLUMN expressions. */
14909};
14910
14911/*
14912** The following are the meanings of bits in the Expr.flags field.
14913*/
14914#define EP_FromJoin  0x000001 /* Originates in ON/USING clause of outer join */
14915#define EP_Agg       0x000002 /* Contains one or more aggregate functions */
14916#define EP_Resolved  0x000004 /* IDs have been resolved to COLUMNs */
14917#define EP_Error     0x000008 /* Expression contains one or more errors */
14918#define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
14919#define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
14920#define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
14921#define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
14922#define EP_Collate   0x000100 /* Tree contains a TK_COLLATE operator */
14923#define EP_Generic   0x000200 /* Ignore COLLATE or affinity on this tree */
14924#define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
14925#define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
14926#define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
14927#define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
14928#define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
14929#define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
14930#define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
14931#define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
14932#define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
14933#define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
14934#define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
14935#define EP_Subquery  0x200000 /* Tree contains a TK_SELECT operator */
14936#define EP_Alias     0x400000 /* Is an alias for a result set column */
14937
14938/*
14939** Combinations of two or more EP_* flags
14940*/
14941#define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
14942
14943/*
14944** These macros can be used to test, set, or clear bits in the
14945** Expr.flags field.
14946*/
14947#define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
14948#define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
14949#define ExprSetProperty(E,P)     (E)->flags|=(P)
14950#define ExprClearProperty(E,P)   (E)->flags&=~(P)
14951
14952/* The ExprSetVVAProperty() macro is used for Verification, Validation,
14953** and Accreditation only.  It works like ExprSetProperty() during VVA
14954** processes but is a no-op for delivery.
14955*/
14956#ifdef SQLITE_DEBUG
14957# define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
14958#else
14959# define ExprSetVVAProperty(E,P)
14960#endif
14961
14962/*
14963** Macros to determine the number of bytes required by a normal Expr
14964** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
14965** and an Expr struct with the EP_TokenOnly flag set.
14966*/
14967#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
14968#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
14969#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
14970
14971/*
14972** Flags passed to the sqlite3ExprDup() function. See the header comment
14973** above sqlite3ExprDup() for details.
14974*/
14975#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
14976
14977/*
14978** A list of expressions.  Each expression may optionally have a
14979** name.  An expr/name combination can be used in several ways, such
14980** as the list of "expr AS ID" fields following a "SELECT" or in the
14981** list of "ID = expr" items in an UPDATE.  A list of expressions can
14982** also be used as the argument to a function, in which case the a.zName
14983** field is not used.
14984**
14985** By default the Expr.zSpan field holds a human-readable description of
14986** the expression that is used in the generation of error messages and
14987** column labels.  In this case, Expr.zSpan is typically the text of a
14988** column expression as it exists in a SELECT statement.  However, if
14989** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
14990** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
14991** form is used for name resolution with nested FROM clauses.
14992*/
14993struct ExprList {
14994  int nExpr;             /* Number of expressions on the list */
14995  struct ExprList_item { /* For each expression in the list */
14996    Expr *pExpr;            /* The list of expressions */
14997    char *zName;            /* Token associated with this expression */
14998    char *zSpan;            /* Original text of the expression */
14999    u8 sortOrder;           /* 1 for DESC or 0 for ASC */
15000    unsigned done :1;       /* A flag to indicate when processing is finished */
15001    unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
15002    unsigned reusable :1;   /* Constant expression is reusable */
15003    union {
15004      struct {
15005        u16 iOrderByCol;      /* For ORDER BY, column number in result set */
15006        u16 iAlias;           /* Index into Parse.aAlias[] for zName */
15007      } x;
15008      int iConstExprReg;      /* Register in which Expr value is cached */
15009    } u;
15010  } *a;                  /* Alloc a power of two greater or equal to nExpr */
15011};
15012
15013/*
15014** An instance of this structure is used by the parser to record both
15015** the parse tree for an expression and the span of input text for an
15016** expression.
15017*/
15018struct ExprSpan {
15019  Expr *pExpr;          /* The expression parse tree */
15020  const char *zStart;   /* First character of input text */
15021  const char *zEnd;     /* One character past the end of input text */
15022};
15023
15024/*
15025** An instance of this structure can hold a simple list of identifiers,
15026** such as the list "a,b,c" in the following statements:
15027**
15028**      INSERT INTO t(a,b,c) VALUES ...;
15029**      CREATE INDEX idx ON t(a,b,c);
15030**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
15031**
15032** The IdList.a.idx field is used when the IdList represents the list of
15033** column names after a table name in an INSERT statement.  In the statement
15034**
15035**     INSERT INTO t(a,b,c) ...
15036**
15037** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
15038*/
15039struct IdList {
15040  struct IdList_item {
15041    char *zName;      /* Name of the identifier */
15042    int idx;          /* Index in some Table.aCol[] of a column named zName */
15043  } *a;
15044  int nId;         /* Number of identifiers on the list */
15045};
15046
15047/*
15048** The bitmask datatype defined below is used for various optimizations.
15049**
15050** Changing this from a 64-bit to a 32-bit type limits the number of
15051** tables in a join to 32 instead of 64.  But it also reduces the size
15052** of the library by 738 bytes on ix86.
15053*/
15054#ifdef SQLITE_BITMASK_TYPE
15055  typedef SQLITE_BITMASK_TYPE Bitmask;
15056#else
15057  typedef u64 Bitmask;
15058#endif
15059
15060/*
15061** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
15062*/
15063#define BMS  ((int)(sizeof(Bitmask)*8))
15064
15065/*
15066** A bit in a Bitmask
15067*/
15068#define MASKBIT(n)   (((Bitmask)1)<<(n))
15069#define MASKBIT32(n) (((unsigned int)1)<<(n))
15070#define ALLBITS      ((Bitmask)-1)
15071
15072/*
15073** The following structure describes the FROM clause of a SELECT statement.
15074** Each table or subquery in the FROM clause is a separate element of
15075** the SrcList.a[] array.
15076**
15077** With the addition of multiple database support, the following structure
15078** can also be used to describe a particular table such as the table that
15079** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
15080** such a table must be a simple name: ID.  But in SQLite, the table can
15081** now be identified by a database name, a dot, then the table name: ID.ID.
15082**
15083** The jointype starts out showing the join type between the current table
15084** and the next table on the list.  The parser builds the list this way.
15085** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
15086** jointype expresses the join between the table and the previous table.
15087**
15088** In the colUsed field, the high-order bit (bit 63) is set if the table
15089** contains more than 63 columns and the 64-th or later column is used.
15090*/
15091struct SrcList {
15092  int nSrc;        /* Number of tables or subqueries in the FROM clause */
15093  u32 nAlloc;      /* Number of entries allocated in a[] below */
15094  struct SrcList_item {
15095    Schema *pSchema;  /* Schema to which this item is fixed */
15096    char *zDatabase;  /* Name of database holding this table */
15097    char *zName;      /* Name of the table */
15098    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
15099    Table *pTab;      /* An SQL table corresponding to zName */
15100    Select *pSelect;  /* A SELECT statement used in place of a table name */
15101    int addrFillSub;  /* Address of subroutine to manifest a subquery */
15102    int regReturn;    /* Register holding return address of addrFillSub */
15103    int regResult;    /* Registers holding results of a co-routine */
15104    struct {
15105      u8 jointype;      /* Type of join between this table and the previous */
15106      unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
15107      unsigned isIndexedBy :1;   /* True if there is an INDEXED BY clause */
15108      unsigned isTabFunc :1;     /* True if table-valued-function syntax */
15109      unsigned isCorrelated :1;  /* True if sub-query is correlated */
15110      unsigned viaCoroutine :1;  /* Implemented as a co-routine */
15111      unsigned isRecursive :1;   /* True for recursive reference in WITH */
15112    } fg;
15113#ifndef SQLITE_OMIT_EXPLAIN
15114    u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
15115#endif
15116    int iCursor;      /* The VDBE cursor number used to access this table */
15117    Expr *pOn;        /* The ON clause of a join */
15118    IdList *pUsing;   /* The USING clause of a join */
15119    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
15120    union {
15121      char *zIndexedBy;    /* Identifier from "INDEXED BY <zIndex>" clause */
15122      ExprList *pFuncArg;  /* Arguments to table-valued-function */
15123    } u1;
15124    Index *pIBIndex;  /* Index structure corresponding to u1.zIndexedBy */
15125  } a[1];             /* One entry for each identifier on the list */
15126};
15127
15128/*
15129** Permitted values of the SrcList.a.jointype field
15130*/
15131#define JT_INNER     0x0001    /* Any kind of inner or cross join */
15132#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
15133#define JT_NATURAL   0x0004    /* True for a "natural" join */
15134#define JT_LEFT      0x0008    /* Left outer join */
15135#define JT_RIGHT     0x0010    /* Right outer join */
15136#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
15137#define JT_ERROR     0x0040    /* unknown or unsupported join type */
15138
15139
15140/*
15141** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
15142** and the WhereInfo.wctrlFlags member.
15143**
15144** Value constraints (enforced via assert()):
15145**     WHERE_USE_LIMIT  == SF_FixedLimit
15146*/
15147#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
15148#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
15149#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
15150#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
15151#define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
15152#define WHERE_DUPLICATES_OK    0x0010 /* Ok to return a row more than once */
15153#define WHERE_OR_SUBCLAUSE     0x0020 /* Processing a sub-WHERE as part of
15154                                      ** the OR optimization  */
15155#define WHERE_GROUPBY          0x0040 /* pOrderBy is really a GROUP BY */
15156#define WHERE_DISTINCTBY       0x0080 /* pOrderby is really a DISTINCT clause */
15157#define WHERE_WANT_DISTINCT    0x0100 /* All output needs to be distinct */
15158#define WHERE_SORTBYGROUP      0x0200 /* Support sqlite3WhereIsSorted() */
15159#define WHERE_SEEK_TABLE       0x0400 /* Do not defer seeks on main table */
15160#define WHERE_ORDERBY_LIMIT    0x0800 /* ORDERBY+LIMIT on the inner loop */
15161                        /*     0x1000    not currently used */
15162                        /*     0x2000    not currently used */
15163#define WHERE_USE_LIMIT        0x4000 /* Use the LIMIT in cost estimates */
15164                        /*     0x8000    not currently used */
15165
15166/* Allowed return values from sqlite3WhereIsDistinct()
15167*/
15168#define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
15169#define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
15170#define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
15171#define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
15172
15173/*
15174** A NameContext defines a context in which to resolve table and column
15175** names.  The context consists of a list of tables (the pSrcList) field and
15176** a list of named expression (pEList).  The named expression list may
15177** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
15178** to the table being operated on by INSERT, UPDATE, or DELETE.  The
15179** pEList corresponds to the result set of a SELECT and is NULL for
15180** other statements.
15181**
15182** NameContexts can be nested.  When resolving names, the inner-most
15183** context is searched first.  If no match is found, the next outer
15184** context is checked.  If there is still no match, the next context
15185** is checked.  This process continues until either a match is found
15186** or all contexts are check.  When a match is found, the nRef member of
15187** the context containing the match is incremented.
15188**
15189** Each subquery gets a new NameContext.  The pNext field points to the
15190** NameContext in the parent query.  Thus the process of scanning the
15191** NameContext list corresponds to searching through successively outer
15192** subqueries looking for a match.
15193*/
15194struct NameContext {
15195  Parse *pParse;       /* The parser */
15196  SrcList *pSrcList;   /* One or more tables used to resolve names */
15197  ExprList *pEList;    /* Optional list of result-set columns */
15198  AggInfo *pAggInfo;   /* Information about aggregates at this level */
15199  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
15200  int nRef;            /* Number of names resolved by this context */
15201  int nErr;            /* Number of errors encountered while resolving names */
15202  u16 ncFlags;         /* Zero or more NC_* flags defined below */
15203};
15204
15205/*
15206** Allowed values for the NameContext, ncFlags field.
15207**
15208** Value constraints (all checked via assert()):
15209**    NC_HasAgg    == SF_HasAgg
15210**    NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
15211**
15212*/
15213#define NC_AllowAgg  0x0001  /* Aggregate functions are allowed here */
15214#define NC_PartIdx   0x0002  /* True if resolving a partial index WHERE */
15215#define NC_IsCheck   0x0004  /* True if resolving names in a CHECK constraint */
15216#define NC_InAggFunc 0x0008  /* True if analyzing arguments to an agg func */
15217#define NC_HasAgg    0x0010  /* One or more aggregate functions seen */
15218#define NC_IdxExpr   0x0020  /* True if resolving columns of CREATE INDEX */
15219#define NC_VarSelect 0x0040  /* A correlated subquery has been seen */
15220#define NC_MinMaxAgg 0x1000  /* min/max aggregates seen.  See note above */
15221
15222/*
15223** An instance of the following structure contains all information
15224** needed to generate code for a single SELECT statement.
15225**
15226** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
15227** If there is a LIMIT clause, the parser sets nLimit to the value of the
15228** limit and nOffset to the value of the offset (or 0 if there is not
15229** offset).  But later on, nLimit and nOffset become the memory locations
15230** in the VDBE that record the limit and offset counters.
15231**
15232** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
15233** These addresses must be stored so that we can go back and fill in
15234** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
15235** the number of columns in P2 can be computed at the same time
15236** as the OP_OpenEphm instruction is coded because not
15237** enough information about the compound query is known at that point.
15238** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
15239** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
15240** sequences for the ORDER BY clause.
15241*/
15242struct Select {
15243  ExprList *pEList;      /* The fields of the result */
15244  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
15245  LogEst nSelectRow;     /* Estimated number of result rows */
15246  u32 selFlags;          /* Various SF_* values */
15247  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
15248#if SELECTTRACE_ENABLED
15249  char zSelName[12];     /* Symbolic name of this SELECT use for debugging */
15250#endif
15251  int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
15252  SrcList *pSrc;         /* The FROM clause */
15253  Expr *pWhere;          /* The WHERE clause */
15254  ExprList *pGroupBy;    /* The GROUP BY clause */
15255  Expr *pHaving;         /* The HAVING clause */
15256  ExprList *pOrderBy;    /* The ORDER BY clause */
15257  Select *pPrior;        /* Prior select in a compound select statement */
15258  Select *pNext;         /* Next select to the left in a compound */
15259  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
15260  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
15261  With *pWith;           /* WITH clause attached to this select. Or NULL. */
15262};
15263
15264/*
15265** Allowed values for Select.selFlags.  The "SF" prefix stands for
15266** "Select Flag".
15267**
15268** Value constraints (all checked via assert())
15269**     SF_HasAgg     == NC_HasAgg
15270**     SF_MinMaxAgg  == NC_MinMaxAgg     == SQLITE_FUNC_MINMAX
15271**     SF_FixedLimit == WHERE_USE_LIMIT
15272*/
15273#define SF_Distinct       0x00001  /* Output should be DISTINCT */
15274#define SF_All            0x00002  /* Includes the ALL keyword */
15275#define SF_Resolved       0x00004  /* Identifiers have been resolved */
15276#define SF_Aggregate      0x00008  /* Contains agg functions or a GROUP BY */
15277#define SF_HasAgg         0x00010  /* Contains aggregate functions */
15278#define SF_UsesEphemeral  0x00020  /* Uses the OpenEphemeral opcode */
15279#define SF_Expanded       0x00040  /* sqlite3SelectExpand() called on this */
15280#define SF_HasTypeInfo    0x00080  /* FROM subqueries have Table metadata */
15281#define SF_Compound       0x00100  /* Part of a compound query */
15282#define SF_Values         0x00200  /* Synthesized from VALUES clause */
15283#define SF_MultiValue     0x00400  /* Single VALUES term with multiple rows */
15284#define SF_NestedFrom     0x00800  /* Part of a parenthesized FROM clause */
15285#define SF_MinMaxAgg      0x01000  /* Aggregate containing min() or max() */
15286#define SF_Recursive      0x02000  /* The recursive part of a recursive CTE */
15287#define SF_FixedLimit     0x04000  /* nSelectRow set by a constant LIMIT */
15288#define SF_MaybeConvert   0x08000  /* Need convertCompoundSelectToSubquery() */
15289#define SF_Converted      0x10000  /* By convertCompoundSelectToSubquery() */
15290#define SF_IncludeHidden  0x20000  /* Include hidden columns in output */
15291
15292
15293/*
15294** The results of a SELECT can be distributed in several ways, as defined
15295** by one of the following macros.  The "SRT" prefix means "SELECT Result
15296** Type".
15297**
15298**     SRT_Union       Store results as a key in a temporary index
15299**                     identified by pDest->iSDParm.
15300**
15301**     SRT_Except      Remove results from the temporary index pDest->iSDParm.
15302**
15303**     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
15304**                     set is not empty.
15305**
15306**     SRT_Discard     Throw the results away.  This is used by SELECT
15307**                     statements within triggers whose only purpose is
15308**                     the side-effects of functions.
15309**
15310** All of the above are free to ignore their ORDER BY clause. Those that
15311** follow must honor the ORDER BY clause.
15312**
15313**     SRT_Output      Generate a row of output (using the OP_ResultRow
15314**                     opcode) for each row in the result set.
15315**
15316**     SRT_Mem         Only valid if the result is a single column.
15317**                     Store the first column of the first result row
15318**                     in register pDest->iSDParm then abandon the rest
15319**                     of the query.  This destination implies "LIMIT 1".
15320**
15321**     SRT_Set         The result must be a single column.  Store each
15322**                     row of result as the key in table pDest->iSDParm.
15323**                     Apply the affinity pDest->affSdst before storing
15324**                     results.  Used to implement "IN (SELECT ...)".
15325**
15326**     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
15327**                     the result there. The cursor is left open after
15328**                     returning.  This is like SRT_Table except that
15329**                     this destination uses OP_OpenEphemeral to create
15330**                     the table first.
15331**
15332**     SRT_Coroutine   Generate a co-routine that returns a new row of
15333**                     results each time it is invoked.  The entry point
15334**                     of the co-routine is stored in register pDest->iSDParm
15335**                     and the result row is stored in pDest->nDest registers
15336**                     starting with pDest->iSdst.
15337**
15338**     SRT_Table       Store results in temporary table pDest->iSDParm.
15339**     SRT_Fifo        This is like SRT_EphemTab except that the table
15340**                     is assumed to already be open.  SRT_Fifo has
15341**                     the additional property of being able to ignore
15342**                     the ORDER BY clause.
15343**
15344**     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.
15345**                     But also use temporary table pDest->iSDParm+1 as
15346**                     a record of all prior results and ignore any duplicate
15347**                     rows.  Name means:  "Distinct Fifo".
15348**
15349**     SRT_Queue       Store results in priority queue pDest->iSDParm (really
15350**                     an index).  Append a sequence number so that all entries
15351**                     are distinct.
15352**
15353**     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
15354**                     the same record has never been stored before.  The
15355**                     index at pDest->iSDParm+1 hold all prior stores.
15356*/
15357#define SRT_Union        1  /* Store result as keys in an index */
15358#define SRT_Except       2  /* Remove result from a UNION index */
15359#define SRT_Exists       3  /* Store 1 if the result is not empty */
15360#define SRT_Discard      4  /* Do not save the results anywhere */
15361#define SRT_Fifo         5  /* Store result as data with an automatic rowid */
15362#define SRT_DistFifo     6  /* Like SRT_Fifo, but unique results only */
15363#define SRT_Queue        7  /* Store result in an queue */
15364#define SRT_DistQueue    8  /* Like SRT_Queue, but unique results only */
15365
15366/* The ORDER BY clause is ignored for all of the above */
15367#define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
15368
15369#define SRT_Output       9  /* Output each row of result */
15370#define SRT_Mem         10  /* Store result in a memory cell */
15371#define SRT_Set         11  /* Store results as keys in an index */
15372#define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */
15373#define SRT_Coroutine   13  /* Generate a single row of result */
15374#define SRT_Table       14  /* Store result as data with an automatic rowid */
15375
15376/*
15377** An instance of this object describes where to put of the results of
15378** a SELECT statement.
15379*/
15380struct SelectDest {
15381  u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */
15382  char affSdst;        /* Affinity used when eDest==SRT_Set */
15383  int iSDParm;         /* A parameter used by the eDest disposal method */
15384  int iSdst;           /* Base register where results are written */
15385  int nSdst;           /* Number of registers allocated */
15386  ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
15387};
15388
15389/*
15390** During code generation of statements that do inserts into AUTOINCREMENT
15391** tables, the following information is attached to the Table.u.autoInc.p
15392** pointer of each autoincrement table to record some side information that
15393** the code generator needs.  We have to keep per-table autoincrement
15394** information in case inserts are done within triggers.  Triggers do not
15395** normally coordinate their activities, but we do need to coordinate the
15396** loading and saving of autoincrement information.
15397*/
15398struct AutoincInfo {
15399  AutoincInfo *pNext;   /* Next info block in a list of them all */
15400  Table *pTab;          /* Table this info block refers to */
15401  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
15402  int regCtr;           /* Memory register holding the rowid counter */
15403};
15404
15405/*
15406** Size of the column cache
15407*/
15408#ifndef SQLITE_N_COLCACHE
15409# define SQLITE_N_COLCACHE 10
15410#endif
15411
15412/*
15413** At least one instance of the following structure is created for each
15414** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
15415** statement. All such objects are stored in the linked list headed at
15416** Parse.pTriggerPrg and deleted once statement compilation has been
15417** completed.
15418**
15419** A Vdbe sub-program that implements the body and WHEN clause of trigger
15420** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
15421** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
15422** The Parse.pTriggerPrg list never contains two entries with the same
15423** values for both pTrigger and orconf.
15424**
15425** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
15426** accessed (or set to 0 for triggers fired as a result of INSERT
15427** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
15428** a mask of new.* columns used by the program.
15429*/
15430struct TriggerPrg {
15431  Trigger *pTrigger;      /* Trigger this program was coded from */
15432  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
15433  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
15434  int orconf;             /* Default ON CONFLICT policy */
15435  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
15436};
15437
15438/*
15439** The yDbMask datatype for the bitmask of all attached databases.
15440*/
15441#if SQLITE_MAX_ATTACHED>30
15442  typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
15443# define DbMaskTest(M,I)    (((M)[(I)/8]&(1<<((I)&7)))!=0)
15444# define DbMaskZero(M)      memset((M),0,sizeof(M))
15445# define DbMaskSet(M,I)     (M)[(I)/8]|=(1<<((I)&7))
15446# define DbMaskAllZero(M)   sqlite3DbMaskAllZero(M)
15447# define DbMaskNonZero(M)   (sqlite3DbMaskAllZero(M)==0)
15448#else
15449  typedef unsigned int yDbMask;
15450# define DbMaskTest(M,I)    (((M)&(((yDbMask)1)<<(I)))!=0)
15451# define DbMaskZero(M)      (M)=0
15452# define DbMaskSet(M,I)     (M)|=(((yDbMask)1)<<(I))
15453# define DbMaskAllZero(M)   (M)==0
15454# define DbMaskNonZero(M)   (M)!=0
15455#endif
15456
15457/*
15458** An SQL parser context.  A copy of this structure is passed through
15459** the parser and down into all the parser action routine in order to
15460** carry around information that is global to the entire parse.
15461**
15462** The structure is divided into two parts.  When the parser and code
15463** generate call themselves recursively, the first part of the structure
15464** is constant but the second part is reset at the beginning and end of
15465** each recursion.
15466**
15467** The nTableLock and aTableLock variables are only used if the shared-cache
15468** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
15469** used to store the set of table-locks required by the statement being
15470** compiled. Function sqlite3TableLock() is used to add entries to the
15471** list.
15472*/
15473struct Parse {
15474  sqlite3 *db;         /* The main database structure */
15475  char *zErrMsg;       /* An error message */
15476  Vdbe *pVdbe;         /* An engine for executing database bytecode */
15477  int rc;              /* Return code from execution */
15478  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
15479  u8 checkSchema;      /* Causes schema cookie check after an error */
15480  u8 nested;           /* Number of nested calls to the parser/code generator */
15481  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
15482  u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
15483  u8 mayAbort;         /* True if statement may throw an ABORT exception */
15484  u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
15485  u8 okConstFactor;    /* OK to factor out constants */
15486  u8 disableLookaside; /* Number of times lookaside has been disabled */
15487  u8 nColCache;        /* Number of entries in aColCache[] */
15488  int aTempReg[8];     /* Holding area for temporary registers */
15489  int nRangeReg;       /* Size of the temporary register block */
15490  int iRangeReg;       /* First register in temporary register block */
15491  int nErr;            /* Number of errors seen */
15492  int nTab;            /* Number of previously allocated VDBE cursors */
15493  int nMem;            /* Number of memory cells used so far */
15494  int nSet;            /* Number of sets used so far */
15495  int nOnce;           /* Number of OP_Once instructions so far */
15496  int nOpAlloc;        /* Number of slots allocated for Vdbe.aOp[] */
15497  int szOpAlloc;       /* Bytes of memory space allocated for Vdbe.aOp[] */
15498  int iFixedOp;        /* Never back out opcodes iFixedOp-1 or earlier */
15499  int ckBase;          /* Base register of data during check constraints */
15500  int iSelfTab;        /* Table of an index whose exprs are being coded */
15501  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
15502  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
15503  int nLabel;          /* Number of labels used */
15504  int *aLabel;         /* Space to hold the labels */
15505  struct yColCache {
15506    int iTable;           /* Table cursor number */
15507    i16 iColumn;          /* Table column number */
15508    u8 tempReg;           /* iReg is a temp register that needs to be freed */
15509    int iLevel;           /* Nesting level */
15510    int iReg;             /* Reg with value of this column. 0 means none. */
15511    int lru;              /* Least recently used entry has the smallest value */
15512  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
15513  ExprList *pConstExpr;/* Constant expressions */
15514  Token constraintName;/* Name of the constraint currently being parsed */
15515  yDbMask writeMask;   /* Start a write transaction on these databases */
15516  yDbMask cookieMask;  /* Bitmask of schema verified databases */
15517  int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
15518  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
15519  int regRoot;         /* Register holding root page number for new objects */
15520  int nMaxArg;         /* Max args passed to user function by sub-program */
15521#if SELECTTRACE_ENABLED
15522  int nSelect;         /* Number of SELECT statements seen */
15523  int nSelectIndent;   /* How far to indent SELECTTRACE() output */
15524#endif
15525#ifndef SQLITE_OMIT_SHARED_CACHE
15526  int nTableLock;        /* Number of locks in aTableLock */
15527  TableLock *aTableLock; /* Required table locks for shared-cache mode */
15528#endif
15529  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
15530
15531  /* Information used while coding trigger programs. */
15532  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
15533  Table *pTriggerTab;  /* Table triggers are being coded for */
15534  int addrCrTab;       /* Address of OP_CreateTable opcode on CREATE TABLE */
15535  u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
15536  u32 oldmask;         /* Mask of old.* columns referenced */
15537  u32 newmask;         /* Mask of new.* columns referenced */
15538  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
15539  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
15540  u8 disableTriggers;  /* True to disable triggers */
15541
15542  /************************************************************************
15543  ** Above is constant between recursions.  Below is reset before and after
15544  ** each recursion.  The boundary between these two regions is determined
15545  ** using offsetof(Parse,nVar) so the nVar field must be the first field
15546  ** in the recursive region.
15547  ************************************************************************/
15548
15549  ynVar nVar;               /* Number of '?' variables seen in the SQL so far */
15550  int nzVar;                /* Number of available slots in azVar[] */
15551  u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
15552  u8 explain;               /* True if the EXPLAIN flag is found on the query */
15553#ifndef SQLITE_OMIT_VIRTUALTABLE
15554  u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
15555  int nVtabLock;            /* Number of virtual tables to lock */
15556#endif
15557  int nAlias;               /* Number of aliased result set columns */
15558  int nHeight;              /* Expression tree height of current sub-select */
15559#ifndef SQLITE_OMIT_EXPLAIN
15560  int iSelectId;            /* ID of current select for EXPLAIN output */
15561  int iNextSelectId;        /* Next available select ID for EXPLAIN output */
15562#endif
15563  char **azVar;             /* Pointers to names of parameters */
15564  Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
15565  const char *zTail;        /* All SQL text past the last semicolon parsed */
15566  Table *pNewTable;         /* A table being constructed by CREATE TABLE */
15567  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
15568  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
15569  Token sNameToken;         /* Token with unqualified schema object name */
15570  Token sLastToken;         /* The last token parsed */
15571#ifndef SQLITE_OMIT_VIRTUALTABLE
15572  Token sArg;               /* Complete text of a module argument */
15573  Table **apVtabLock;       /* Pointer to virtual tables needing locking */
15574#endif
15575  Table *pZombieTab;        /* List of Table objects to delete after code gen */
15576  TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
15577  With *pWith;              /* Current WITH clause, or NULL */
15578  With *pWithToFree;        /* Free this WITH object at the end of the parse */
15579};
15580
15581/*
15582** Return true if currently inside an sqlite3_declare_vtab() call.
15583*/
15584#ifdef SQLITE_OMIT_VIRTUALTABLE
15585  #define IN_DECLARE_VTAB 0
15586#else
15587  #define IN_DECLARE_VTAB (pParse->declareVtab)
15588#endif
15589
15590/*
15591** An instance of the following structure can be declared on a stack and used
15592** to save the Parse.zAuthContext value so that it can be restored later.
15593*/
15594struct AuthContext {
15595  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
15596  Parse *pParse;              /* The Parse structure */
15597};
15598
15599/*
15600** Bitfield flags for P5 value in various opcodes.
15601**
15602** Value constraints (enforced via assert()):
15603**    OPFLAG_LENGTHARG    == SQLITE_FUNC_LENGTH
15604**    OPFLAG_TYPEOFARG    == SQLITE_FUNC_TYPEOF
15605**    OPFLAG_BULKCSR      == BTREE_BULKLOAD
15606**    OPFLAG_SEEKEQ       == BTREE_SEEK_EQ
15607**    OPFLAG_FORDELETE    == BTREE_FORDELETE
15608**    OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
15609**    OPFLAG_AUXDELETE    == BTREE_AUXDELETE
15610*/
15611#define OPFLAG_NCHANGE       0x01    /* OP_Insert: Set to update db->nChange */
15612                                     /* Also used in P2 (not P5) of OP_Delete */
15613#define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */
15614#define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
15615#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
15616#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
15617#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
15618#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
15619#define OPFLAG_ISNOOP        0x40    /* OP_Delete does pre-update-hook only */
15620#endif
15621#define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
15622#define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
15623#define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
15624#define OPFLAG_SEEKEQ        0x02    /* OP_Open** cursor uses EQ seek only */
15625#define OPFLAG_FORDELETE     0x08    /* OP_Open should use BTREE_FORDELETE */
15626#define OPFLAG_P2ISREG       0x10    /* P2 to OP_Open** is a register number */
15627#define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
15628#define OPFLAG_SAVEPOSITION  0x02    /* OP_Delete: keep cursor position */
15629#define OPFLAG_AUXDELETE     0x04    /* OP_Delete: index in a DELETE op */
15630
15631/*
15632 * Each trigger present in the database schema is stored as an instance of
15633 * struct Trigger.
15634 *
15635 * Pointers to instances of struct Trigger are stored in two ways.
15636 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
15637 *    database). This allows Trigger structures to be retrieved by name.
15638 * 2. All triggers associated with a single table form a linked list, using the
15639 *    pNext member of struct Trigger. A pointer to the first element of the
15640 *    linked list is stored as the "pTrigger" member of the associated
15641 *    struct Table.
15642 *
15643 * The "step_list" member points to the first element of a linked list
15644 * containing the SQL statements specified as the trigger program.
15645 */
15646struct Trigger {
15647  char *zName;            /* The name of the trigger                        */
15648  char *table;            /* The table or view to which the trigger applies */
15649  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
15650  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
15651  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
15652  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
15653                             the <column-list> is stored here */
15654  Schema *pSchema;        /* Schema containing the trigger */
15655  Schema *pTabSchema;     /* Schema containing the table */
15656  TriggerStep *step_list; /* Link list of trigger program steps             */
15657  Trigger *pNext;         /* Next trigger associated with the table */
15658};
15659
15660/*
15661** A trigger is either a BEFORE or an AFTER trigger.  The following constants
15662** determine which.
15663**
15664** If there are multiple triggers, you might of some BEFORE and some AFTER.
15665** In that cases, the constants below can be ORed together.
15666*/
15667#define TRIGGER_BEFORE  1
15668#define TRIGGER_AFTER   2
15669
15670/*
15671 * An instance of struct TriggerStep is used to store a single SQL statement
15672 * that is a part of a trigger-program.
15673 *
15674 * Instances of struct TriggerStep are stored in a singly linked list (linked
15675 * using the "pNext" member) referenced by the "step_list" member of the
15676 * associated struct Trigger instance. The first element of the linked list is
15677 * the first step of the trigger-program.
15678 *
15679 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
15680 * "SELECT" statement. The meanings of the other members is determined by the
15681 * value of "op" as follows:
15682 *
15683 * (op == TK_INSERT)
15684 * orconf    -> stores the ON CONFLICT algorithm
15685 * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
15686 *              this stores a pointer to the SELECT statement. Otherwise NULL.
15687 * zTarget   -> Dequoted name of the table to insert into.
15688 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
15689 *              this stores values to be inserted. Otherwise NULL.
15690 * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
15691 *              statement, then this stores the column-names to be
15692 *              inserted into.
15693 *
15694 * (op == TK_DELETE)
15695 * zTarget   -> Dequoted name of the table to delete from.
15696 * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
15697 *              Otherwise NULL.
15698 *
15699 * (op == TK_UPDATE)
15700 * zTarget   -> Dequoted name of the table to update.
15701 * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
15702 *              Otherwise NULL.
15703 * pExprList -> A list of the columns to update and the expressions to update
15704 *              them to. See sqlite3Update() documentation of "pChanges"
15705 *              argument.
15706 *
15707 */
15708struct TriggerStep {
15709  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
15710  u8 orconf;           /* OE_Rollback etc. */
15711  Trigger *pTrig;      /* The trigger that this step is a part of */
15712  Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */
15713  char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */
15714  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
15715  ExprList *pExprList; /* SET clause for UPDATE. */
15716  IdList *pIdList;     /* Column names for INSERT */
15717  TriggerStep *pNext;  /* Next in the link-list */
15718  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
15719};
15720
15721/*
15722** The following structure contains information used by the sqliteFix...
15723** routines as they walk the parse tree to make database references
15724** explicit.
15725*/
15726typedef struct DbFixer DbFixer;
15727struct DbFixer {
15728  Parse *pParse;      /* The parsing context.  Error messages written here */
15729  Schema *pSchema;    /* Fix items to this schema */
15730  int bVarOnly;       /* Check for variable references only */
15731  const char *zDb;    /* Make sure all objects are contained in this database */
15732  const char *zType;  /* Type of the container - used for error messages */
15733  const Token *pName; /* Name of the container - used for error messages */
15734};
15735
15736/*
15737** An objected used to accumulate the text of a string where we
15738** do not necessarily know how big the string will be in the end.
15739*/
15740struct StrAccum {
15741  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
15742  char *zBase;         /* A base allocation.  Not from malloc. */
15743  char *zText;         /* The string collected so far */
15744  u32  nChar;          /* Length of the string so far */
15745  u32  nAlloc;         /* Amount of space allocated in zText */
15746  u32  mxAlloc;        /* Maximum allowed allocation.  0 for no malloc usage */
15747  u8   accError;       /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
15748  u8   printfFlags;    /* SQLITE_PRINTF flags below */
15749};
15750#define STRACCUM_NOMEM   1
15751#define STRACCUM_TOOBIG  2
15752#define SQLITE_PRINTF_INTERNAL 0x01  /* Internal-use-only converters allowed */
15753#define SQLITE_PRINTF_SQLFUNC  0x02  /* SQL function arguments to VXPrintf */
15754#define SQLITE_PRINTF_MALLOCED 0x04  /* True if xText is allocated space */
15755
15756#define isMalloced(X)  (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
15757
15758
15759/*
15760** A pointer to this structure is used to communicate information
15761** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
15762*/
15763typedef struct {
15764  sqlite3 *db;        /* The database being initialized */
15765  char **pzErrMsg;    /* Error message stored here */
15766  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
15767  int rc;             /* Result code stored here */
15768} InitData;
15769
15770/*
15771** Structure containing global configuration data for the SQLite library.
15772**
15773** This structure also contains some state information.
15774*/
15775struct Sqlite3Config {
15776  int bMemstat;                     /* True to enable memory status */
15777  int bCoreMutex;                   /* True to enable core mutexing */
15778  int bFullMutex;                   /* True to enable full mutexing */
15779  int bOpenUri;                     /* True to interpret filenames as URIs */
15780  int bUseCis;                      /* Use covering indices for full-scans */
15781  int mxStrlen;                     /* Maximum string length */
15782  int neverCorrupt;                 /* Database is always well-formed */
15783  int szLookaside;                  /* Default lookaside buffer size */
15784  int nLookaside;                   /* Default lookaside buffer count */
15785  int nStmtSpill;                   /* Stmt-journal spill-to-disk threshold */
15786  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
15787  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
15788  sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
15789  void *pHeap;                      /* Heap storage space */
15790  int nHeap;                        /* Size of pHeap[] */
15791  int mnReq, mxReq;                 /* Min and max heap requests sizes */
15792  sqlite3_int64 szMmap;             /* mmap() space per open file */
15793  sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
15794  void *pScratch;                   /* Scratch memory */
15795  int szScratch;                    /* Size of each scratch buffer */
15796  int nScratch;                     /* Number of scratch buffers */
15797  void *pPage;                      /* Page cache memory */
15798  int szPage;                       /* Size of each page in pPage[] */
15799  int nPage;                        /* Number of pages in pPage[] */
15800  int mxParserStack;                /* maximum depth of the parser stack */
15801  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
15802  u32 szPma;                        /* Maximum Sorter PMA size */
15803  /* The above might be initialized to non-zero.  The following need to always
15804  ** initially be zero, however. */
15805  int isInit;                       /* True after initialization has finished */
15806  int inProgress;                   /* True while initialization in progress */
15807  int isMutexInit;                  /* True after mutexes are initialized */
15808  int isMallocInit;                 /* True after malloc is initialized */
15809  int isPCacheInit;                 /* True after malloc is initialized */
15810  int nRefInitMutex;                /* Number of users of pInitMutex */
15811  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
15812  void (*xLog)(void*,int,const char*); /* Function for logging */
15813  void *pLogArg;                       /* First argument to xLog() */
15814#ifdef SQLITE_ENABLE_SQLLOG
15815  void(*xSqllog)(void*,sqlite3*,const char*, int);
15816  void *pSqllogArg;
15817#endif
15818#ifdef SQLITE_VDBE_COVERAGE
15819  /* The following callback (if not NULL) is invoked on every VDBE branch
15820  ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
15821  */
15822  void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx);  /* Callback */
15823  void *pVdbeBranchArg;                                     /* 1st argument */
15824#endif
15825#ifndef SQLITE_OMIT_BUILTIN_TEST
15826  int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
15827#endif
15828  int bLocaltimeFault;              /* True to fail localtime() calls */
15829};
15830
15831/*
15832** This macro is used inside of assert() statements to indicate that
15833** the assert is only valid on a well-formed database.  Instead of:
15834**
15835**     assert( X );
15836**
15837** One writes:
15838**
15839**     assert( X || CORRUPT_DB );
15840**
15841** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
15842** that the database is definitely corrupt, only that it might be corrupt.
15843** For most test cases, CORRUPT_DB is set to false using a special
15844** sqlite3_test_control().  This enables assert() statements to prove
15845** things that are always true for well-formed databases.
15846*/
15847#define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
15848
15849/*
15850** Context pointer passed down through the tree-walk.
15851*/
15852struct Walker {
15853  Parse *pParse;                            /* Parser context.  */
15854  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
15855  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
15856  void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
15857  int walkerDepth;                          /* Number of subqueries */
15858  u8 eCode;                                 /* A small processing code */
15859  union {                                   /* Extra data for callback */
15860    NameContext *pNC;                          /* Naming context */
15861    int n;                                     /* A counter */
15862    int iCur;                                  /* A cursor number */
15863    SrcList *pSrcList;                         /* FROM clause */
15864    struct SrcCount *pSrcCount;                /* Counting column references */
15865    struct CCurHint *pCCurHint;                /* Used by codeCursorHint() */
15866    int *aiCol;                                /* array of column indexes */
15867    struct IdxCover *pIdxCover;                /* Check for index coverage */
15868  } u;
15869};
15870
15871/* Forward declarations */
15872SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
15873SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
15874SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
15875SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
15876SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
15877SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
15878
15879/*
15880** Return code from the parse-tree walking primitives and their
15881** callbacks.
15882*/
15883#define WRC_Continue    0   /* Continue down into children */
15884#define WRC_Prune       1   /* Omit children but continue walking siblings */
15885#define WRC_Abort       2   /* Abandon the tree walk */
15886
15887/*
15888** An instance of this structure represents a set of one or more CTEs
15889** (common table expressions) created by a single WITH clause.
15890*/
15891struct With {
15892  int nCte;                       /* Number of CTEs in the WITH clause */
15893  With *pOuter;                   /* Containing WITH clause, or NULL */
15894  struct Cte {                    /* For each CTE in the WITH clause.... */
15895    char *zName;                    /* Name of this CTE */
15896    ExprList *pCols;                /* List of explicit column names, or NULL */
15897    Select *pSelect;                /* The definition of this CTE */
15898    const char *zCteErr;            /* Error message for circular references */
15899  } a[1];
15900};
15901
15902#ifdef SQLITE_DEBUG
15903/*
15904** An instance of the TreeView object is used for printing the content of
15905** data structures on sqlite3DebugPrintf() using a tree-like view.
15906*/
15907struct TreeView {
15908  int iLevel;             /* Which level of the tree we are on */
15909  u8  bLine[100];         /* Draw vertical in column i if bLine[i] is true */
15910};
15911#endif /* SQLITE_DEBUG */
15912
15913/*
15914** Assuming zIn points to the first byte of a UTF-8 character,
15915** advance zIn to point to the first byte of the next UTF-8 character.
15916*/
15917#define SQLITE_SKIP_UTF8(zIn) {                        \
15918  if( (*(zIn++))>=0xc0 ){                              \
15919    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
15920  }                                                    \
15921}
15922
15923/*
15924** The SQLITE_*_BKPT macros are substitutes for the error codes with
15925** the same name but without the _BKPT suffix.  These macros invoke
15926** routines that report the line-number on which the error originated
15927** using sqlite3_log().  The routines also provide a convenient place
15928** to set a debugger breakpoint.
15929*/
15930SQLITE_PRIVATE int sqlite3CorruptError(int);
15931SQLITE_PRIVATE int sqlite3MisuseError(int);
15932SQLITE_PRIVATE int sqlite3CantopenError(int);
15933#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
15934#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
15935#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
15936#ifdef SQLITE_DEBUG
15937SQLITE_PRIVATE   int sqlite3NomemError(int);
15938SQLITE_PRIVATE   int sqlite3IoerrnomemError(int);
15939# define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
15940# define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
15941#else
15942# define SQLITE_NOMEM_BKPT SQLITE_NOMEM
15943# define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
15944#endif
15945
15946/*
15947** FTS3 and FTS4 both require virtual table support
15948*/
15949#if defined(SQLITE_OMIT_VIRTUALTABLE)
15950# undef SQLITE_ENABLE_FTS3
15951# undef SQLITE_ENABLE_FTS4
15952#endif
15953
15954/*
15955** FTS4 is really an extension for FTS3.  It is enabled using the
15956** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call
15957** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
15958*/
15959#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
15960# define SQLITE_ENABLE_FTS3 1
15961#endif
15962
15963/*
15964** The ctype.h header is needed for non-ASCII systems.  It is also
15965** needed by FTS3 when FTS3 is included in the amalgamation.
15966*/
15967#if !defined(SQLITE_ASCII) || \
15968    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
15969# include <ctype.h>
15970#endif
15971
15972/*
15973** The following macros mimic the standard library functions toupper(),
15974** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
15975** sqlite versions only work for ASCII characters, regardless of locale.
15976*/
15977#ifdef SQLITE_ASCII
15978# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
15979# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
15980# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
15981# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
15982# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
15983# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
15984# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
15985# define sqlite3Isquote(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
15986#else
15987# define sqlite3Toupper(x)   toupper((unsigned char)(x))
15988# define sqlite3Isspace(x)   isspace((unsigned char)(x))
15989# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
15990# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
15991# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
15992# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
15993# define sqlite3Tolower(x)   tolower((unsigned char)(x))
15994# define sqlite3Isquote(x)   ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
15995#endif
15996#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
15997SQLITE_PRIVATE int sqlite3IsIdChar(u8);
15998#endif
15999
16000/*
16001** Internal function prototypes
16002*/
16003SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
16004SQLITE_PRIVATE int sqlite3Strlen30(const char*);
16005SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
16006#define sqlite3StrNICmp sqlite3_strnicmp
16007
16008SQLITE_PRIVATE int sqlite3MallocInit(void);
16009SQLITE_PRIVATE void sqlite3MallocEnd(void);
16010SQLITE_PRIVATE void *sqlite3Malloc(u64);
16011SQLITE_PRIVATE void *sqlite3MallocZero(u64);
16012SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
16013SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
16014SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
16015SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
16016SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
16017SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
16018SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
16019SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
16020SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
16021SQLITE_PRIVATE int sqlite3MallocSize(void*);
16022SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
16023SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
16024SQLITE_PRIVATE void sqlite3ScratchFree(void*);
16025SQLITE_PRIVATE void *sqlite3PageMalloc(int);
16026SQLITE_PRIVATE void sqlite3PageFree(void*);
16027SQLITE_PRIVATE void sqlite3MemSetDefault(void);
16028#ifndef SQLITE_OMIT_BUILTIN_TEST
16029SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
16030#endif
16031SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
16032
16033/*
16034** On systems with ample stack space and that support alloca(), make
16035** use of alloca() to obtain space for large automatic objects.  By default,
16036** obtain space from malloc().
16037**
16038** The alloca() routine never returns NULL.  This will cause code paths
16039** that deal with sqlite3StackAlloc() failures to be unreachable.
16040*/
16041#ifdef SQLITE_USE_ALLOCA
16042# define sqlite3StackAllocRaw(D,N)   alloca(N)
16043# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
16044# define sqlite3StackFree(D,P)
16045#else
16046# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
16047# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
16048# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
16049#endif
16050
16051/* Do not allow both MEMSYS5 and MEMSYS3 to be defined together.  If they
16052** are, disable MEMSYS3
16053*/
16054#ifdef SQLITE_ENABLE_MEMSYS5
16055SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
16056#undef SQLITE_ENABLE_MEMSYS3
16057#endif
16058#ifdef SQLITE_ENABLE_MEMSYS3
16059SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
16060#endif
16061
16062
16063#ifndef SQLITE_MUTEX_OMIT
16064SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
16065SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
16066SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
16067SQLITE_PRIVATE   int sqlite3MutexInit(void);
16068SQLITE_PRIVATE   int sqlite3MutexEnd(void);
16069#endif
16070#if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
16071SQLITE_PRIVATE   void sqlite3MemoryBarrier(void);
16072#else
16073# define sqlite3MemoryBarrier()
16074#endif
16075
16076SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
16077SQLITE_PRIVATE void sqlite3StatusUp(int, int);
16078SQLITE_PRIVATE void sqlite3StatusDown(int, int);
16079SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
16080
16081/* Access to mutexes used by sqlite3_status() */
16082SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
16083SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
16084
16085#ifndef SQLITE_OMIT_FLOATING_POINT
16086SQLITE_PRIVATE   int sqlite3IsNaN(double);
16087#else
16088# define sqlite3IsNaN(X)  0
16089#endif
16090
16091/*
16092** An instance of the following structure holds information about SQL
16093** functions arguments that are the parameters to the printf() function.
16094*/
16095struct PrintfArguments {
16096  int nArg;                /* Total number of arguments */
16097  int nUsed;               /* Number of arguments used so far */
16098  sqlite3_value **apArg;   /* The argument values */
16099};
16100
16101SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list);
16102SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
16103SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
16104SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
16105#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
16106SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
16107#endif
16108#if defined(SQLITE_TEST)
16109SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
16110#endif
16111
16112#if defined(SQLITE_DEBUG)
16113SQLITE_PRIVATE   void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
16114SQLITE_PRIVATE   void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
16115SQLITE_PRIVATE   void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
16116SQLITE_PRIVATE   void sqlite3TreeViewWith(TreeView*, const With*, u8);
16117#endif
16118
16119
16120SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
16121SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
16122SQLITE_PRIVATE void sqlite3Dequote(char*);
16123SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
16124SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
16125SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
16126SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
16127SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
16128SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
16129SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
16130SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
16131SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
16132#ifdef SQLITE_DEBUG
16133SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
16134#endif
16135SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
16136SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
16137SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
16138SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
16139SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
16140SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
16141SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
16142SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
16143SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
16144SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
16145SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
16146SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
16147SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
16148SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
16149SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
16150SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
16151SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
16152SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
16153SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
16154SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
16155SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
16156SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
16157SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
16158SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
16159SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
16160SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
16161SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
16162SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
16163SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
16164SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
16165#if SQLITE_ENABLE_HIDDEN_COLUMNS
16166SQLITE_PRIVATE   void sqlite3ColumnPropertiesFromName(Table*, Column*);
16167#else
16168# define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
16169#endif
16170SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
16171SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
16172SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
16173SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
16174SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
16175SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
16176SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
16177SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
16178                    sqlite3_vfs**,char**,char **);
16179SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
16180SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
16181
16182#ifdef SQLITE_OMIT_BUILTIN_TEST
16183# define sqlite3FaultSim(X) SQLITE_OK
16184#else
16185SQLITE_PRIVATE   int sqlite3FaultSim(int);
16186#endif
16187
16188SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
16189SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
16190SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
16191SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
16192SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
16193SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
16194SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
16195#ifndef SQLITE_OMIT_BUILTIN_TEST
16196SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
16197#endif
16198
16199SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
16200SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
16201SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
16202SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
16203SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
16204
16205SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
16206
16207#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
16208SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
16209#else
16210# define sqlite3ViewGetColumnNames(A,B) 0
16211#endif
16212
16213#if SQLITE_MAX_ATTACHED>30
16214SQLITE_PRIVATE   int sqlite3DbMaskAllZero(yDbMask);
16215#endif
16216SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
16217SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
16218SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
16219#ifndef SQLITE_OMIT_AUTOINCREMENT
16220SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
16221SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
16222#else
16223# define sqlite3AutoincrementBegin(X)
16224# define sqlite3AutoincrementEnd(X)
16225#endif
16226SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
16227SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
16228SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
16229SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
16230SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
16231SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
16232SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
16233                                      Token*, Select*, Expr*, IdList*);
16234SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
16235SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
16236SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
16237SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
16238SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
16239SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
16240SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
16241SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
16242SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
16243                          Expr*, int, int, u8);
16244SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
16245SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
16246SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
16247                         Expr*,ExprList*,u32,Expr*,Expr*);
16248SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
16249SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
16250SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
16251SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
16252#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
16253SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
16254#endif
16255SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
16256SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
16257SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
16258SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
16259SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
16260SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
16261SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
16262SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo*);
16263SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
16264SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
16265SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
16266SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
16267#define ONEPASS_OFF      0        /* Use of ONEPASS not allowed */
16268#define ONEPASS_SINGLE   1        /* ONEPASS valid for a single row update */
16269#define ONEPASS_MULTI    2        /* ONEPASS is valid for multiple rows */
16270SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
16271SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
16272SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int);
16273SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
16274SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
16275SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
16276SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
16277SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
16278SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
16279SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
16280SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
16281SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
16282SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
16283SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
16284SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
16285SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
16286SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
16287SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
16288SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
16289#define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
16290#define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
16291#define SQLITE_ECEL_REF      0x04  /* Use ExprList.u.x.iOrderByCol */
16292SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
16293SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
16294SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
16295SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
16296#define LOCATE_VIEW    0x01
16297#define LOCATE_NOERR   0x02
16298SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
16299SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
16300SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
16301SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
16302SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
16303SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
16304SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
16305SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
16306SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
16307SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
16308SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
16309SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
16310SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
16311SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
16312SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
16313SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
16314#ifndef SQLITE_OMIT_BUILTIN_TEST
16315SQLITE_PRIVATE void sqlite3PrngSaveState(void);
16316SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
16317#endif
16318SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
16319SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
16320SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
16321SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
16322SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
16323SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
16324SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
16325SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
16326SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
16327SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
16328SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
16329SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
16330SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
16331#ifdef SQLITE_ENABLE_CURSOR_HINTS
16332SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
16333#endif
16334SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
16335SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
16336SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
16337SQLITE_PRIVATE int sqlite3IsRowid(const char*);
16338SQLITE_PRIVATE void sqlite3GenerateRowDelete(
16339    Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
16340SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
16341SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
16342SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
16343SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
16344                                     u8,u8,int,int*,int*);
16345SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
16346SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
16347SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
16348SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
16349SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
16350SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
16351SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
16352SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
16353SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
16354SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
16355SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
16356SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
16357SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
16358#if SELECTTRACE_ENABLED
16359SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
16360#else
16361# define sqlite3SelectSetName(A,B)
16362#endif
16363SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
16364SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
16365SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
16366SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
16367SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
16368SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
16369SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
16370SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
16371
16372#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
16373SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
16374#endif
16375
16376#ifndef SQLITE_OMIT_TRIGGER
16377SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
16378                           Expr*,int, int);
16379SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
16380SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
16381SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
16382SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
16383SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
16384SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
16385                            int, int, int);
16386SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
16387  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
16388SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
16389SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
16390SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
16391                                        Select*,u8);
16392SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
16393SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
16394SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
16395SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
16396SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
16397# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
16398# define sqlite3IsToplevel(p) ((p)->pToplevel==0)
16399#else
16400# define sqlite3TriggersExist(B,C,D,E,F) 0
16401# define sqlite3DeleteTrigger(A,B)
16402# define sqlite3DropTriggerPtr(A,B)
16403# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
16404# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
16405# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
16406# define sqlite3TriggerList(X, Y) 0
16407# define sqlite3ParseToplevel(p) p
16408# define sqlite3IsToplevel(p) 1
16409# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
16410#endif
16411
16412SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
16413SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
16414SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
16415#ifndef SQLITE_OMIT_AUTHORIZATION
16416SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
16417SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
16418SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
16419SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
16420SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
16421#else
16422# define sqlite3AuthRead(a,b,c,d)
16423# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
16424# define sqlite3AuthContextPush(a,b,c)
16425# define sqlite3AuthContextPop(a)  ((void)(a))
16426#endif
16427SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
16428SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
16429SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
16430SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
16431SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
16432SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
16433SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
16434SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
16435SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
16436SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
16437SQLITE_PRIVATE int sqlite3Atoi(const char*);
16438SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
16439SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
16440SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
16441SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
16442SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
16443#ifndef SQLITE_OMIT_VIRTUALTABLE
16444SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
16445#endif
16446#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
16447    defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
16448    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
16449SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
16450#endif
16451
16452/*
16453** Routines to read and write variable-length integers.  These used to
16454** be defined locally, but now we use the varint routines in the util.c
16455** file.
16456*/
16457SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
16458SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
16459SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
16460SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
16461
16462/*
16463** The common case is for a varint to be a single byte.  They following
16464** macros handle the common case without a procedure call, but then call
16465** the procedure for larger varints.
16466*/
16467#define getVarint32(A,B)  \
16468  (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
16469#define putVarint32(A,B)  \
16470  (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
16471  sqlite3PutVarint((A),(B)))
16472#define getVarint    sqlite3GetVarint
16473#define putVarint    sqlite3PutVarint
16474
16475
16476SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
16477SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
16478SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
16479SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
16480SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
16481SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
16482SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
16483SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
16484SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
16485SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
16486SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
16487SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
16488SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
16489
16490#if defined(SQLITE_NEED_ERR_NAME)
16491SQLITE_PRIVATE const char *sqlite3ErrName(int);
16492#endif
16493
16494SQLITE_PRIVATE const char *sqlite3ErrStr(int);
16495SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
16496SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
16497SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
16498SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
16499SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
16500SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
16501SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
16502SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
16503SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
16504SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
16505SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
16506SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
16507SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
16508SQLITE_PRIVATE int sqlite3AbsInt32(int);
16509#ifdef SQLITE_ENABLE_8_3_NAMES
16510SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
16511#else
16512# define sqlite3FileSuffix3(X,Y)
16513#endif
16514SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
16515
16516SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
16517SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
16518SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
16519                        void(*)(void*));
16520SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
16521SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
16522SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
16523SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
16524SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
16525SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
16526#ifndef SQLITE_AMALGAMATION
16527SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
16528SQLITE_PRIVATE const char sqlite3StrBINARY[];
16529SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
16530SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
16531SQLITE_PRIVATE const Token sqlite3IntTokens[];
16532SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
16533SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
16534#ifndef SQLITE_OMIT_WSD
16535SQLITE_PRIVATE int sqlite3PendingByte;
16536#endif
16537#endif
16538SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
16539SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
16540SQLITE_PRIVATE void sqlite3AlterFunctions(void);
16541SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
16542SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
16543SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
16544SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
16545SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
16546SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
16547SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
16548SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
16549SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
16550SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
16551SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
16552SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
16553SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
16554SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
16555SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
16556SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
16557SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
16558SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
16559SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
16560SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
16561SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
16562SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
16563SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
16564SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
16565SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
16566SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
16567SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
16568SQLITE_PRIVATE void sqlite3SchemaClear(void *);
16569SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
16570SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
16571SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
16572SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
16573SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
16574SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
16575#ifdef SQLITE_DEBUG
16576SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
16577#endif
16578SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
16579  void (*)(sqlite3_context*,int,sqlite3_value **),
16580  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
16581  FuncDestructor *pDestructor
16582);
16583SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
16584SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
16585SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
16586SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
16587
16588SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
16589SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
16590SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
16591SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
16592SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
16593SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
16594SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
16595SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
16596
16597SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
16598SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
16599
16600#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
16601SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
16602SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
16603SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
16604SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
16605SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
16606#endif
16607
16608/*
16609** The interface to the LEMON-generated parser
16610*/
16611SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
16612SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
16613SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
16614#ifdef YYTRACKMAXSTACKDEPTH
16615SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
16616#endif
16617
16618SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
16619#ifndef SQLITE_OMIT_LOAD_EXTENSION
16620SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
16621#else
16622# define sqlite3CloseExtensions(X)
16623#endif
16624
16625#ifndef SQLITE_OMIT_SHARED_CACHE
16626SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
16627#else
16628  #define sqlite3TableLock(v,w,x,y,z)
16629#endif
16630
16631#ifdef SQLITE_TEST
16632SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
16633#endif
16634
16635#ifdef SQLITE_OMIT_VIRTUALTABLE
16636#  define sqlite3VtabClear(Y)
16637#  define sqlite3VtabSync(X,Y) SQLITE_OK
16638#  define sqlite3VtabRollback(X)
16639#  define sqlite3VtabCommit(X)
16640#  define sqlite3VtabInSync(db) 0
16641#  define sqlite3VtabLock(X)
16642#  define sqlite3VtabUnlock(X)
16643#  define sqlite3VtabUnlockList(X)
16644#  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
16645#  define sqlite3GetVTable(X,Y)  ((VTable*)0)
16646#else
16647SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
16648SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
16649SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);
16650SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
16651SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
16652SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
16653SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
16654SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
16655SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
16656SQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
16657SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
16658#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
16659#endif
16660SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
16661SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
16662SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
16663SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
16664SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
16665SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
16666SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
16667SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
16668SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
16669SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
16670SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
16671SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
16672SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
16673SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
16674SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
16675SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
16676SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
16677SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
16678SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
16679SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
16680SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
16681SQLITE_PRIVATE const char *sqlite3JournalModename(int);
16682#ifndef SQLITE_OMIT_WAL
16683SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
16684SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
16685#endif
16686#ifndef SQLITE_OMIT_CTE
16687SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
16688SQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);
16689SQLITE_PRIVATE   void sqlite3WithPush(Parse*, With*, u8);
16690#else
16691#define sqlite3WithPush(x,y,z)
16692#define sqlite3WithDelete(x,y)
16693#endif
16694
16695/* Declarations for functions in fkey.c. All of these are replaced by
16696** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
16697** key functionality is available. If OMIT_TRIGGER is defined but
16698** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
16699** this case foreign keys are parsed, but no other functionality is
16700** provided (enforcement of FK constraints requires the triggers sub-system).
16701*/
16702#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
16703SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
16704SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
16705SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
16706SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
16707SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
16708SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
16709#else
16710  #define sqlite3FkActions(a,b,c,d,e,f)
16711  #define sqlite3FkCheck(a,b,c,d,e,f)
16712  #define sqlite3FkDropTable(a,b,c)
16713  #define sqlite3FkOldmask(a,b)         0
16714  #define sqlite3FkRequired(a,b,c,d)    0
16715#endif
16716#ifndef SQLITE_OMIT_FOREIGN_KEY
16717SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
16718SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
16719#else
16720  #define sqlite3FkDelete(a,b)
16721  #define sqlite3FkLocateIndex(a,b,c,d,e)
16722#endif
16723
16724
16725/*
16726** Available fault injectors.  Should be numbered beginning with 0.
16727*/
16728#define SQLITE_FAULTINJECTOR_MALLOC     0
16729#define SQLITE_FAULTINJECTOR_COUNT      1
16730
16731/*
16732** The interface to the code in fault.c used for identifying "benign"
16733** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
16734** is not defined.
16735*/
16736#ifndef SQLITE_OMIT_BUILTIN_TEST
16737SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
16738SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
16739#else
16740  #define sqlite3BeginBenignMalloc()
16741  #define sqlite3EndBenignMalloc()
16742#endif
16743
16744/*
16745** Allowed return values from sqlite3FindInIndex()
16746*/
16747#define IN_INDEX_ROWID        1   /* Search the rowid of the table */
16748#define IN_INDEX_EPH          2   /* Search an ephemeral b-tree */
16749#define IN_INDEX_INDEX_ASC    3   /* Existing index ASCENDING */
16750#define IN_INDEX_INDEX_DESC   4   /* Existing index DESCENDING */
16751#define IN_INDEX_NOOP         5   /* No table available. Use comparisons */
16752/*
16753** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
16754*/
16755#define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */
16756#define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */
16757#define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */
16758SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
16759
16760SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
16761SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
16762#ifdef SQLITE_ENABLE_ATOMIC_WRITE
16763SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
16764#endif
16765
16766SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
16767SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
16768
16769SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
16770#if SQLITE_MAX_EXPR_DEPTH>0
16771SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
16772SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
16773#else
16774  #define sqlite3SelectExprHeight(x) 0
16775  #define sqlite3ExprCheckHeight(x,y)
16776#endif
16777
16778SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
16779SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
16780
16781#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
16782SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
16783SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
16784SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
16785#else
16786  #define sqlite3ConnectionBlocked(x,y)
16787  #define sqlite3ConnectionUnlocked(x)
16788  #define sqlite3ConnectionClosed(x)
16789#endif
16790
16791#ifdef SQLITE_DEBUG
16792SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
16793#endif
16794
16795/*
16796** If the SQLITE_ENABLE IOTRACE exists then the global variable
16797** sqlite3IoTrace is a pointer to a printf-like routine used to
16798** print I/O tracing messages.
16799*/
16800#ifdef SQLITE_ENABLE_IOTRACE
16801# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
16802SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
16803SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
16804#else
16805# define IOTRACE(A)
16806# define sqlite3VdbeIOTraceSql(X)
16807#endif
16808
16809/*
16810** These routines are available for the mem2.c debugging memory allocator
16811** only.  They are used to verify that different "types" of memory
16812** allocations are properly tracked by the system.
16813**
16814** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
16815** the MEMTYPE_* macros defined below.  The type must be a bitmask with
16816** a single bit set.
16817**
16818** sqlite3MemdebugHasType() returns true if any of the bits in its second
16819** argument match the type set by the previous sqlite3MemdebugSetType().
16820** sqlite3MemdebugHasType() is intended for use inside assert() statements.
16821**
16822** sqlite3MemdebugNoType() returns true if none of the bits in its second
16823** argument match the type set by the previous sqlite3MemdebugSetType().
16824**
16825** Perhaps the most important point is the difference between MEMTYPE_HEAP
16826** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
16827** it might have been allocated by lookaside, except the allocation was
16828** too large or lookaside was already full.  It is important to verify
16829** that allocations that might have been satisfied by lookaside are not
16830** passed back to non-lookaside free() routines.  Asserts such as the
16831** example above are placed on the non-lookaside free() routines to verify
16832** this constraint.
16833**
16834** All of this is no-op for a production build.  It only comes into
16835** play when the SQLITE_MEMDEBUG compile-time option is used.
16836*/
16837#ifdef SQLITE_MEMDEBUG
16838SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
16839SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
16840SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
16841#else
16842# define sqlite3MemdebugSetType(X,Y)  /* no-op */
16843# define sqlite3MemdebugHasType(X,Y)  1
16844# define sqlite3MemdebugNoType(X,Y)   1
16845#endif
16846#define MEMTYPE_HEAP       0x01  /* General heap allocations */
16847#define MEMTYPE_LOOKASIDE  0x02  /* Heap that might have been lookaside */
16848#define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
16849#define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
16850
16851/*
16852** Threading interface
16853*/
16854#if SQLITE_MAX_WORKER_THREADS>0
16855SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
16856SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
16857#endif
16858
16859#if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
16860SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
16861#endif
16862
16863#endif /* SQLITEINT_H */
16864
16865/************** End of sqliteInt.h *******************************************/
16866/************** Begin file global.c ******************************************/
16867/*
16868** 2008 June 13
16869**
16870** The author disclaims copyright to this source code.  In place of
16871** a legal notice, here is a blessing:
16872**
16873**    May you do good and not evil.
16874**    May you find forgiveness for yourself and forgive others.
16875**    May you share freely, never taking more than you give.
16876**
16877*************************************************************************
16878**
16879** This file contains definitions of global variables and constants.
16880*/
16881/* #include "sqliteInt.h" */
16882
16883/* An array to map all upper-case characters into their corresponding
16884** lower-case character.
16885**
16886** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
16887** handle case conversions for the UTF character set since the tables
16888** involved are nearly as big or bigger than SQLite itself.
16889*/
16890SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
16891#ifdef SQLITE_ASCII
16892      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
16893     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
16894     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
16895     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
16896    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
16897    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
16898    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
16899    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
16900    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
16901    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
16902    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
16903    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
16904    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
16905    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
16906    252,253,254,255
16907#endif
16908#ifdef SQLITE_EBCDIC
16909      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
16910     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
16911     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
16912     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
16913     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
16914     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
16915     96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
16916    112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
16917    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
16918    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
16919    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
16920    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
16921    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
16922    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
16923    224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
16924    240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
16925#endif
16926};
16927
16928/*
16929** The following 256 byte lookup table is used to support SQLites built-in
16930** equivalents to the following standard library functions:
16931**
16932**   isspace()                        0x01
16933**   isalpha()                        0x02
16934**   isdigit()                        0x04
16935**   isalnum()                        0x06
16936**   isxdigit()                       0x08
16937**   toupper()                        0x20
16938**   SQLite identifier character      0x40
16939**   Quote character                  0x80
16940**
16941** Bit 0x20 is set if the mapped character requires translation to upper
16942** case. i.e. if the character is a lower-case ASCII character.
16943** If x is a lower-case ASCII character, then its upper-case equivalent
16944** is (x - 0x20). Therefore toupper() can be implemented as:
16945**
16946**   (x & ~(map[x]&0x20))
16947**
16948** Standard function tolower() is implemented using the sqlite3UpperToLower[]
16949** array. tolower() is used more often than toupper() by SQLite.
16950**
16951** Bit 0x40 is set if the character non-alphanumeric and can be used in an
16952** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
16953** non-ASCII UTF character. Hence the test for whether or not a character is
16954** part of an identifier is 0x46.
16955**
16956** SQLite's versions are identical to the standard versions assuming a
16957** locale of "C". They are implemented as macros in sqliteInt.h.
16958*/
16959#ifdef SQLITE_ASCII
16960SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
16961  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
16962  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
16963  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
16964  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
16965  0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80,  /* 20..27     !"#$%&' */
16966  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
16967  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
16968  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
16969
16970  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
16971  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
16972  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
16973  0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
16974  0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
16975  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
16976  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
16977  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
16978
16979  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
16980  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
16981  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
16982  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
16983  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
16984  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
16985  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
16986  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
16987
16988  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
16989  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
16990  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
16991  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
16992  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
16993  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
16994  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
16995  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
16996};
16997#endif
16998
16999/* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
17000** compatibility for legacy applications, the URI filename capability is
17001** disabled by default.
17002**
17003** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
17004** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
17005**
17006** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
17007** disabled. The default value may be changed by compiling with the
17008** SQLITE_USE_URI symbol defined.
17009*/
17010#ifndef SQLITE_USE_URI
17011# define  SQLITE_USE_URI 0
17012#endif
17013
17014/* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
17015** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
17016** that compile-time option is omitted.
17017*/
17018#ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
17019# define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
17020#endif
17021
17022/* The minimum PMA size is set to this value multiplied by the database
17023** page size in bytes.
17024*/
17025#ifndef SQLITE_SORTER_PMASZ
17026# define SQLITE_SORTER_PMASZ 250
17027#endif
17028
17029/* Statement journals spill to disk when their size exceeds the following
17030** threashold (in bytes). 0 means that statement journals are created and
17031** written to disk immediately (the default behavior for SQLite versions
17032** before 3.12.0).  -1 means always keep the entire statement journal in
17033** memory.  (The statement journal is also always held entirely in memory
17034** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
17035** setting.)
17036*/
17037#ifndef SQLITE_STMTJRNL_SPILL
17038# define SQLITE_STMTJRNL_SPILL (64*1024)
17039#endif
17040
17041/*
17042** The following singleton contains the global configuration for
17043** the SQLite library.
17044*/
17045SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
17046   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
17047   1,                         /* bCoreMutex */
17048   SQLITE_THREADSAFE==1,      /* bFullMutex */
17049   SQLITE_USE_URI,            /* bOpenUri */
17050   SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
17051   0x7ffffffe,                /* mxStrlen */
17052   0,                         /* neverCorrupt */
17053   128,                       /* szLookaside */
17054   500,                       /* nLookaside */
17055   SQLITE_STMTJRNL_SPILL,     /* nStmtSpill */
17056   {0,0,0,0,0,0,0,0},         /* m */
17057   {0,0,0,0,0,0,0,0,0},       /* mutex */
17058   {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
17059   (void*)0,                  /* pHeap */
17060   0,                         /* nHeap */
17061   0, 0,                      /* mnHeap, mxHeap */
17062   SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
17063   SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
17064   (void*)0,                  /* pScratch */
17065   0,                         /* szScratch */
17066   0,                         /* nScratch */
17067   (void*)0,                  /* pPage */
17068   0,                         /* szPage */
17069   SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
17070   0,                         /* mxParserStack */
17071   0,                         /* sharedCacheEnabled */
17072   SQLITE_SORTER_PMASZ,       /* szPma */
17073   /* All the rest should always be initialized to zero */
17074   0,                         /* isInit */
17075   0,                         /* inProgress */
17076   0,                         /* isMutexInit */
17077   0,                         /* isMallocInit */
17078   0,                         /* isPCacheInit */
17079   0,                         /* nRefInitMutex */
17080   0,                         /* pInitMutex */
17081   0,                         /* xLog */
17082   0,                         /* pLogArg */
17083#ifdef SQLITE_ENABLE_SQLLOG
17084   0,                         /* xSqllog */
17085   0,                         /* pSqllogArg */
17086#endif
17087#ifdef SQLITE_VDBE_COVERAGE
17088   0,                         /* xVdbeBranch */
17089   0,                         /* pVbeBranchArg */
17090#endif
17091#ifndef SQLITE_OMIT_BUILTIN_TEST
17092   0,                         /* xTestCallback */
17093#endif
17094   0                          /* bLocaltimeFault */
17095};
17096
17097/*
17098** Hash table for global functions - functions common to all
17099** database connections.  After initialization, this table is
17100** read-only.
17101*/
17102SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
17103
17104/*
17105** Constant tokens for values 0 and 1.
17106*/
17107SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
17108   { "0", 1 },
17109   { "1", 1 }
17110};
17111
17112
17113/*
17114** The value of the "pending" byte must be 0x40000000 (1 byte past the
17115** 1-gibabyte boundary) in a compatible database.  SQLite never uses
17116** the database page that contains the pending byte.  It never attempts
17117** to read or write that page.  The pending byte page is set assign
17118** for use by the VFS layers as space for managing file locks.
17119**
17120** During testing, it is often desirable to move the pending byte to
17121** a different position in the file.  This allows code that has to
17122** deal with the pending byte to run on files that are much smaller
17123** than 1 GiB.  The sqlite3_test_control() interface can be used to
17124** move the pending byte.
17125**
17126** IMPORTANT:  Changing the pending byte to any value other than
17127** 0x40000000 results in an incompatible database file format!
17128** Changing the pending byte during operation will result in undefined
17129** and incorrect behavior.
17130*/
17131#ifndef SQLITE_OMIT_WSD
17132SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
17133#endif
17134
17135/* #include "opcodes.h" */
17136/*
17137** Properties of opcodes.  The OPFLG_INITIALIZER macro is
17138** created by mkopcodeh.awk during compilation.  Data is obtained
17139** from the comments following the "case OP_xxxx:" statements in
17140** the vdbe.c file.
17141*/
17142SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
17143
17144/*
17145** Name of the default collating sequence
17146*/
17147SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
17148
17149/************** End of global.c **********************************************/
17150/************** Begin file ctime.c *******************************************/
17151/*
17152** 2010 February 23
17153**
17154** The author disclaims copyright to this source code.  In place of
17155** a legal notice, here is a blessing:
17156**
17157**    May you do good and not evil.
17158**    May you find forgiveness for yourself and forgive others.
17159**    May you share freely, never taking more than you give.
17160**
17161*************************************************************************
17162**
17163** This file implements routines used to report what compile-time options
17164** SQLite was built with.
17165*/
17166
17167#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
17168
17169/* #include "sqliteInt.h" */
17170
17171/*
17172** An array of names of all compile-time options.  This array should
17173** be sorted A-Z.
17174**
17175** This array looks large, but in a typical installation actually uses
17176** only a handful of compile-time options, so most times this array is usually
17177** rather short and uses little memory space.
17178*/
17179static const char * const azCompileOpt[] = {
17180
17181/* These macros are provided to "stringify" the value of the define
17182** for those options in which the value is meaningful. */
17183#define CTIMEOPT_VAL_(opt) #opt
17184#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
17185
17186#if SQLITE_32BIT_ROWID
17187  "32BIT_ROWID",
17188#endif
17189#if SQLITE_4_BYTE_ALIGNED_MALLOC
17190  "4_BYTE_ALIGNED_MALLOC",
17191#endif
17192#if SQLITE_CASE_SENSITIVE_LIKE
17193  "CASE_SENSITIVE_LIKE",
17194#endif
17195#if SQLITE_CHECK_PAGES
17196  "CHECK_PAGES",
17197#endif
17198#if defined(__clang__) && defined(__clang_major__)
17199  "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
17200                    CTIMEOPT_VAL(__clang_minor__) "."
17201                    CTIMEOPT_VAL(__clang_patchlevel__),
17202#elif defined(_MSC_VER)
17203  "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
17204#elif defined(__GNUC__) && defined(__VERSION__)
17205  "COMPILER=gcc-" __VERSION__,
17206#endif
17207#if SQLITE_COVERAGE_TEST
17208  "COVERAGE_TEST",
17209#endif
17210#if SQLITE_DEBUG
17211  "DEBUG",
17212#endif
17213#if SQLITE_DEFAULT_LOCKING_MODE
17214  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
17215#endif
17216#if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
17217  "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
17218#endif
17219#if SQLITE_DISABLE_DIRSYNC
17220  "DISABLE_DIRSYNC",
17221#endif
17222#if SQLITE_DISABLE_LFS
17223  "DISABLE_LFS",
17224#endif
17225#if SQLITE_ENABLE_8_3_NAMES
17226  "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
17227#endif
17228#if SQLITE_ENABLE_API_ARMOR
17229  "ENABLE_API_ARMOR",
17230#endif
17231#if SQLITE_ENABLE_ATOMIC_WRITE
17232  "ENABLE_ATOMIC_WRITE",
17233#endif
17234#if SQLITE_ENABLE_CEROD
17235  "ENABLE_CEROD",
17236#endif
17237#if SQLITE_ENABLE_COLUMN_METADATA
17238  "ENABLE_COLUMN_METADATA",
17239#endif
17240#if SQLITE_ENABLE_DBSTAT_VTAB
17241  "ENABLE_DBSTAT_VTAB",
17242#endif
17243#if SQLITE_ENABLE_EXPENSIVE_ASSERT
17244  "ENABLE_EXPENSIVE_ASSERT",
17245#endif
17246#if SQLITE_ENABLE_FTS1
17247  "ENABLE_FTS1",
17248#endif
17249#if SQLITE_ENABLE_FTS2
17250  "ENABLE_FTS2",
17251#endif
17252#if SQLITE_ENABLE_FTS3
17253  "ENABLE_FTS3",
17254#endif
17255#if SQLITE_ENABLE_FTS3_PARENTHESIS
17256  "ENABLE_FTS3_PARENTHESIS",
17257#endif
17258#if SQLITE_ENABLE_FTS4
17259  "ENABLE_FTS4",
17260#endif
17261#if SQLITE_ENABLE_FTS5
17262  "ENABLE_FTS5",
17263#endif
17264#if SQLITE_ENABLE_ICU
17265  "ENABLE_ICU",
17266#endif
17267#if SQLITE_ENABLE_IOTRACE
17268  "ENABLE_IOTRACE",
17269#endif
17270#if SQLITE_ENABLE_JSON1
17271  "ENABLE_JSON1",
17272#endif
17273#if SQLITE_ENABLE_LOAD_EXTENSION
17274  "ENABLE_LOAD_EXTENSION",
17275#endif
17276#if SQLITE_ENABLE_LOCKING_STYLE
17277  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
17278#endif
17279#if SQLITE_ENABLE_MEMORY_MANAGEMENT
17280  "ENABLE_MEMORY_MANAGEMENT",
17281#endif
17282#if SQLITE_ENABLE_MEMSYS3
17283  "ENABLE_MEMSYS3",
17284#endif
17285#if SQLITE_ENABLE_MEMSYS5
17286  "ENABLE_MEMSYS5",
17287#endif
17288#if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
17289  "ENABLE_OVERSIZE_CELL_CHECK",
17290#endif
17291#if SQLITE_ENABLE_RTREE
17292  "ENABLE_RTREE",
17293#endif
17294#if defined(SQLITE_ENABLE_STAT4)
17295  "ENABLE_STAT4",
17296#elif defined(SQLITE_ENABLE_STAT3)
17297  "ENABLE_STAT3",
17298#endif
17299#if SQLITE_ENABLE_UNLOCK_NOTIFY
17300  "ENABLE_UNLOCK_NOTIFY",
17301#endif
17302#if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
17303  "ENABLE_UPDATE_DELETE_LIMIT",
17304#endif
17305#if SQLITE_HAS_CODEC
17306  "HAS_CODEC",
17307#endif
17308#if HAVE_ISNAN || SQLITE_HAVE_ISNAN
17309  "HAVE_ISNAN",
17310#endif
17311#if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17312  "HOMEGROWN_RECURSIVE_MUTEX",
17313#endif
17314#if SQLITE_IGNORE_AFP_LOCK_ERRORS
17315  "IGNORE_AFP_LOCK_ERRORS",
17316#endif
17317#if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
17318  "IGNORE_FLOCK_LOCK_ERRORS",
17319#endif
17320#ifdef SQLITE_INT64_TYPE
17321  "INT64_TYPE",
17322#endif
17323#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
17324  "LIKE_DOESNT_MATCH_BLOBS",
17325#endif
17326#if SQLITE_LOCK_TRACE
17327  "LOCK_TRACE",
17328#endif
17329#if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
17330  "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
17331#endif
17332#ifdef SQLITE_MAX_SCHEMA_RETRY
17333  "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
17334#endif
17335#if SQLITE_MEMDEBUG
17336  "MEMDEBUG",
17337#endif
17338#if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
17339  "MIXED_ENDIAN_64BIT_FLOAT",
17340#endif
17341#if SQLITE_NO_SYNC
17342  "NO_SYNC",
17343#endif
17344#if SQLITE_OMIT_ALTERTABLE
17345  "OMIT_ALTERTABLE",
17346#endif
17347#if SQLITE_OMIT_ANALYZE
17348  "OMIT_ANALYZE",
17349#endif
17350#if SQLITE_OMIT_ATTACH
17351  "OMIT_ATTACH",
17352#endif
17353#if SQLITE_OMIT_AUTHORIZATION
17354  "OMIT_AUTHORIZATION",
17355#endif
17356#if SQLITE_OMIT_AUTOINCREMENT
17357  "OMIT_AUTOINCREMENT",
17358#endif
17359#if SQLITE_OMIT_AUTOINIT
17360  "OMIT_AUTOINIT",
17361#endif
17362#if SQLITE_OMIT_AUTOMATIC_INDEX
17363  "OMIT_AUTOMATIC_INDEX",
17364#endif
17365#if SQLITE_OMIT_AUTORESET
17366  "OMIT_AUTORESET",
17367#endif
17368#if SQLITE_OMIT_AUTOVACUUM
17369  "OMIT_AUTOVACUUM",
17370#endif
17371#if SQLITE_OMIT_BETWEEN_OPTIMIZATION
17372  "OMIT_BETWEEN_OPTIMIZATION",
17373#endif
17374#if SQLITE_OMIT_BLOB_LITERAL
17375  "OMIT_BLOB_LITERAL",
17376#endif
17377#if SQLITE_OMIT_BTREECOUNT
17378  "OMIT_BTREECOUNT",
17379#endif
17380#if SQLITE_OMIT_BUILTIN_TEST
17381  "OMIT_BUILTIN_TEST",
17382#endif
17383#if SQLITE_OMIT_CAST
17384  "OMIT_CAST",
17385#endif
17386#if SQLITE_OMIT_CHECK
17387  "OMIT_CHECK",
17388#endif
17389#if SQLITE_OMIT_COMPLETE
17390  "OMIT_COMPLETE",
17391#endif
17392#if SQLITE_OMIT_COMPOUND_SELECT
17393  "OMIT_COMPOUND_SELECT",
17394#endif
17395#if SQLITE_OMIT_CTE
17396  "OMIT_CTE",
17397#endif
17398#if SQLITE_OMIT_DATETIME_FUNCS
17399  "OMIT_DATETIME_FUNCS",
17400#endif
17401#if SQLITE_OMIT_DECLTYPE
17402  "OMIT_DECLTYPE",
17403#endif
17404#if SQLITE_OMIT_DEPRECATED
17405  "OMIT_DEPRECATED",
17406#endif
17407#if SQLITE_OMIT_DISKIO
17408  "OMIT_DISKIO",
17409#endif
17410#if SQLITE_OMIT_EXPLAIN
17411  "OMIT_EXPLAIN",
17412#endif
17413#if SQLITE_OMIT_FLAG_PRAGMAS
17414  "OMIT_FLAG_PRAGMAS",
17415#endif
17416#if SQLITE_OMIT_FLOATING_POINT
17417  "OMIT_FLOATING_POINT",
17418#endif
17419#if SQLITE_OMIT_FOREIGN_KEY
17420  "OMIT_FOREIGN_KEY",
17421#endif
17422#if SQLITE_OMIT_GET_TABLE
17423  "OMIT_GET_TABLE",
17424#endif
17425#if SQLITE_OMIT_INCRBLOB
17426  "OMIT_INCRBLOB",
17427#endif
17428#if SQLITE_OMIT_INTEGRITY_CHECK
17429  "OMIT_INTEGRITY_CHECK",
17430#endif
17431#if SQLITE_OMIT_LIKE_OPTIMIZATION
17432  "OMIT_LIKE_OPTIMIZATION",
17433#endif
17434#if SQLITE_OMIT_LOAD_EXTENSION
17435  "OMIT_LOAD_EXTENSION",
17436#endif
17437#if SQLITE_OMIT_LOCALTIME
17438  "OMIT_LOCALTIME",
17439#endif
17440#if SQLITE_OMIT_LOOKASIDE
17441  "OMIT_LOOKASIDE",
17442#endif
17443#if SQLITE_OMIT_MEMORYDB
17444  "OMIT_MEMORYDB",
17445#endif
17446#if SQLITE_OMIT_OR_OPTIMIZATION
17447  "OMIT_OR_OPTIMIZATION",
17448#endif
17449#if SQLITE_OMIT_PAGER_PRAGMAS
17450  "OMIT_PAGER_PRAGMAS",
17451#endif
17452#if SQLITE_OMIT_PRAGMA
17453  "OMIT_PRAGMA",
17454#endif
17455#if SQLITE_OMIT_PROGRESS_CALLBACK
17456  "OMIT_PROGRESS_CALLBACK",
17457#endif
17458#if SQLITE_OMIT_QUICKBALANCE
17459  "OMIT_QUICKBALANCE",
17460#endif
17461#if SQLITE_OMIT_REINDEX
17462  "OMIT_REINDEX",
17463#endif
17464#if SQLITE_OMIT_SCHEMA_PRAGMAS
17465  "OMIT_SCHEMA_PRAGMAS",
17466#endif
17467#if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
17468  "OMIT_SCHEMA_VERSION_PRAGMAS",
17469#endif
17470#if SQLITE_OMIT_SHARED_CACHE
17471  "OMIT_SHARED_CACHE",
17472#endif
17473#if SQLITE_OMIT_SUBQUERY
17474  "OMIT_SUBQUERY",
17475#endif
17476#if SQLITE_OMIT_TCL_VARIABLE
17477  "OMIT_TCL_VARIABLE",
17478#endif
17479#if SQLITE_OMIT_TEMPDB
17480  "OMIT_TEMPDB",
17481#endif
17482#if SQLITE_OMIT_TRACE
17483  "OMIT_TRACE",
17484#endif
17485#if SQLITE_OMIT_TRIGGER
17486  "OMIT_TRIGGER",
17487#endif
17488#if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
17489  "OMIT_TRUNCATE_OPTIMIZATION",
17490#endif
17491#if SQLITE_OMIT_UTF16
17492  "OMIT_UTF16",
17493#endif
17494#if SQLITE_OMIT_VACUUM
17495  "OMIT_VACUUM",
17496#endif
17497#if SQLITE_OMIT_VIEW
17498  "OMIT_VIEW",
17499#endif
17500#if SQLITE_OMIT_VIRTUALTABLE
17501  "OMIT_VIRTUALTABLE",
17502#endif
17503#if SQLITE_OMIT_WAL
17504  "OMIT_WAL",
17505#endif
17506#if SQLITE_OMIT_WSD
17507  "OMIT_WSD",
17508#endif
17509#if SQLITE_OMIT_XFER_OPT
17510  "OMIT_XFER_OPT",
17511#endif
17512#if SQLITE_PERFORMANCE_TRACE
17513  "PERFORMANCE_TRACE",
17514#endif
17515#if SQLITE_PROXY_DEBUG
17516  "PROXY_DEBUG",
17517#endif
17518#if SQLITE_RTREE_INT_ONLY
17519  "RTREE_INT_ONLY",
17520#endif
17521#if SQLITE_SECURE_DELETE
17522  "SECURE_DELETE",
17523#endif
17524#if SQLITE_SMALL_STACK
17525  "SMALL_STACK",
17526#endif
17527#if SQLITE_SOUNDEX
17528  "SOUNDEX",
17529#endif
17530#if SQLITE_SYSTEM_MALLOC
17531  "SYSTEM_MALLOC",
17532#endif
17533#if SQLITE_TCL
17534  "TCL",
17535#endif
17536#if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
17537  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
17538#endif
17539#if SQLITE_TEST
17540  "TEST",
17541#endif
17542#if defined(SQLITE_THREADSAFE)
17543  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
17544#endif
17545#if SQLITE_USE_ALLOCA
17546  "USE_ALLOCA",
17547#endif
17548#if SQLITE_USER_AUTHENTICATION
17549  "USER_AUTHENTICATION",
17550#endif
17551#if SQLITE_WIN32_MALLOC
17552  "WIN32_MALLOC",
17553#endif
17554#if SQLITE_ZERO_MALLOC
17555  "ZERO_MALLOC"
17556#endif
17557};
17558
17559/*
17560** Given the name of a compile-time option, return true if that option
17561** was used and false if not.
17562**
17563** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
17564** is not required for a match.
17565*/
17566SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName){
17567  int i, n;
17568
17569#if SQLITE_ENABLE_API_ARMOR
17570  if( zOptName==0 ){
17571    (void)SQLITE_MISUSE_BKPT;
17572    return 0;
17573  }
17574#endif
17575  if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
17576  n = sqlite3Strlen30(zOptName);
17577
17578  /* Since ArraySize(azCompileOpt) is normally in single digits, a
17579  ** linear search is adequate.  No need for a binary search. */
17580  for(i=0; i<ArraySize(azCompileOpt); i++){
17581    if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
17582     && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
17583    ){
17584      return 1;
17585    }
17586  }
17587  return 0;
17588}
17589
17590/*
17591** Return the N-th compile-time option string.  If N is out of range,
17592** return a NULL pointer.
17593*/
17594SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N){
17595  if( N>=0 && N<ArraySize(azCompileOpt) ){
17596    return azCompileOpt[N];
17597  }
17598  return 0;
17599}
17600
17601#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
17602
17603/************** End of ctime.c ***********************************************/
17604/************** Begin file status.c ******************************************/
17605/*
17606** 2008 June 18
17607**
17608** The author disclaims copyright to this source code.  In place of
17609** a legal notice, here is a blessing:
17610**
17611**    May you do good and not evil.
17612**    May you find forgiveness for yourself and forgive others.
17613**    May you share freely, never taking more than you give.
17614**
17615*************************************************************************
17616**
17617** This module implements the sqlite3_status() interface and related
17618** functionality.
17619*/
17620/* #include "sqliteInt.h" */
17621/************** Include vdbeInt.h in the middle of status.c ******************/
17622/************** Begin file vdbeInt.h *****************************************/
17623/*
17624** 2003 September 6
17625**
17626** The author disclaims copyright to this source code.  In place of
17627** a legal notice, here is a blessing:
17628**
17629**    May you do good and not evil.
17630**    May you find forgiveness for yourself and forgive others.
17631**    May you share freely, never taking more than you give.
17632**
17633*************************************************************************
17634** This is the header file for information that is private to the
17635** VDBE.  This information used to all be at the top of the single
17636** source code file "vdbe.c".  When that file became too big (over
17637** 6000 lines long) it was split up into several smaller files and
17638** this header information was factored out.
17639*/
17640#ifndef SQLITE_VDBEINT_H
17641#define SQLITE_VDBEINT_H
17642
17643/*
17644** The maximum number of times that a statement will try to reparse
17645** itself before giving up and returning SQLITE_SCHEMA.
17646*/
17647#ifndef SQLITE_MAX_SCHEMA_RETRY
17648# define SQLITE_MAX_SCHEMA_RETRY 50
17649#endif
17650
17651/*
17652** VDBE_DISPLAY_P4 is true or false depending on whether or not the
17653** "explain" P4 display logic is enabled.
17654*/
17655#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
17656     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
17657# define VDBE_DISPLAY_P4 1
17658#else
17659# define VDBE_DISPLAY_P4 0
17660#endif
17661
17662/*
17663** SQL is translated into a sequence of instructions to be
17664** executed by a virtual machine.  Each instruction is an instance
17665** of the following structure.
17666*/
17667typedef struct VdbeOp Op;
17668
17669/*
17670** Boolean values
17671*/
17672typedef unsigned Bool;
17673
17674/* Opaque type used by code in vdbesort.c */
17675typedef struct VdbeSorter VdbeSorter;
17676
17677/* Opaque type used by the explainer */
17678typedef struct Explain Explain;
17679
17680/* Elements of the linked list at Vdbe.pAuxData */
17681typedef struct AuxData AuxData;
17682
17683/* Types of VDBE cursors */
17684#define CURTYPE_BTREE       0
17685#define CURTYPE_SORTER      1
17686#define CURTYPE_VTAB        2
17687#define CURTYPE_PSEUDO      3
17688
17689/*
17690** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
17691**
17692**      * A b-tree cursor
17693**          -  In the main database or in an ephemeral database
17694**          -  On either an index or a table
17695**      * A sorter
17696**      * A virtual table
17697**      * A one-row "pseudotable" stored in a single register
17698*/
17699typedef struct VdbeCursor VdbeCursor;
17700struct VdbeCursor {
17701  u8 eCurType;          /* One of the CURTYPE_* values above */
17702  i8 iDb;               /* Index of cursor database in db->aDb[] (or -1) */
17703  u8 nullRow;           /* True if pointing to a row with no data */
17704  u8 deferredMoveto;    /* A call to sqlite3BtreeMoveto() is needed */
17705  u8 isTable;           /* True for rowid tables.  False for indexes */
17706#ifdef SQLITE_DEBUG
17707  u8 seekOp;            /* Most recent seek operation on this cursor */
17708  u8 wrFlag;            /* The wrFlag argument to sqlite3BtreeCursor() */
17709#endif
17710  Bool isEphemeral:1;   /* True for an ephemeral table */
17711  Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
17712  Bool isOrdered:1;     /* True if the table is not BTREE_UNORDERED */
17713  Pgno pgnoRoot;        /* Root page of the open btree cursor */
17714  i16 nField;           /* Number of fields in the header */
17715  u16 nHdrParsed;       /* Number of header fields parsed so far */
17716  union {
17717    BtCursor *pCursor;          /* CURTYPE_BTREE.  Btree cursor */
17718    sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB.   Vtab cursor */
17719    int pseudoTableReg;         /* CURTYPE_PSEUDO. Reg holding content. */
17720    VdbeSorter *pSorter;        /* CURTYPE_SORTER. Sorter object */
17721  } uc;
17722  Btree *pBt;           /* Separate file holding temporary table */
17723  KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
17724  int seekResult;       /* Result of previous sqlite3BtreeMoveto() */
17725  i64 seqCount;         /* Sequence counter */
17726  i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
17727  VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
17728  int *aAltMap;           /* Mapping from table to index column numbers */
17729#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
17730  u64 maskUsed;         /* Mask of columns used by this cursor */
17731#endif
17732
17733  /* Cached information about the header for the data record that the
17734  ** cursor is currently pointing to.  Only valid if cacheStatus matches
17735  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
17736  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
17737  ** the cache is out of date.
17738  **
17739  ** aRow might point to (ephemeral) data for the current row, or it might
17740  ** be NULL.
17741  */
17742  u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
17743  u32 payloadSize;      /* Total number of bytes in the record */
17744  u32 szRow;            /* Byte available in aRow */
17745  u32 iHdrOffset;       /* Offset to next unparsed byte of the header */
17746  const u8 *aRow;       /* Data for the current row, if all on one page */
17747  u32 *aOffset;         /* Pointer to aType[nField] */
17748  u32 aType[1];         /* Type values for all entries in the record */
17749  /* 2*nField extra array elements allocated for aType[], beyond the one
17750  ** static element declared in the structure.  nField total array slots for
17751  ** aType[] and nField+1 array slots for aOffset[] */
17752};
17753
17754/*
17755** When a sub-program is executed (OP_Program), a structure of this type
17756** is allocated to store the current value of the program counter, as
17757** well as the current memory cell array and various other frame specific
17758** values stored in the Vdbe struct. When the sub-program is finished,
17759** these values are copied back to the Vdbe from the VdbeFrame structure,
17760** restoring the state of the VM to as it was before the sub-program
17761** began executing.
17762**
17763** The memory for a VdbeFrame object is allocated and managed by a memory
17764** cell in the parent (calling) frame. When the memory cell is deleted or
17765** overwritten, the VdbeFrame object is not freed immediately. Instead, it
17766** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
17767** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
17768** this instead of deleting the VdbeFrame immediately is to avoid recursive
17769** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
17770** child frame are released.
17771**
17772** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
17773** set to NULL if the currently executing frame is the main program.
17774*/
17775typedef struct VdbeFrame VdbeFrame;
17776struct VdbeFrame {
17777  Vdbe *v;                /* VM this frame belongs to */
17778  VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
17779  Op *aOp;                /* Program instructions for parent frame */
17780  i64 *anExec;            /* Event counters from parent frame */
17781  Mem *aMem;              /* Array of memory cells for parent frame */
17782  u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
17783  VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
17784  void *token;            /* Copy of SubProgram.token */
17785  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
17786  AuxData *pAuxData;      /* Linked list of auxdata allocations */
17787  int nCursor;            /* Number of entries in apCsr */
17788  int pc;                 /* Program Counter in parent (calling) frame */
17789  int nOp;                /* Size of aOp array */
17790  int nMem;               /* Number of entries in aMem */
17791  int nOnceFlag;          /* Number of entries in aOnceFlag */
17792  int nChildMem;          /* Number of memory cells for child frame */
17793  int nChildCsr;          /* Number of cursors for child frame */
17794  int nChange;            /* Statement changes (Vdbe.nChange)     */
17795  int nDbChange;          /* Value of db->nChange */
17796};
17797
17798#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
17799
17800/*
17801** A value for VdbeCursor.cacheValid that means the cache is always invalid.
17802*/
17803#define CACHE_STALE 0
17804
17805/*
17806** Internally, the vdbe manipulates nearly all SQL values as Mem
17807** structures. Each Mem struct may cache multiple representations (string,
17808** integer etc.) of the same value.
17809*/
17810struct Mem {
17811  union MemValue {
17812    double r;           /* Real value used when MEM_Real is set in flags */
17813    i64 i;              /* Integer value used when MEM_Int is set in flags */
17814    int nZero;          /* Used when bit MEM_Zero is set in flags */
17815    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
17816    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
17817    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
17818  } u;
17819  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
17820  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
17821  u8  eSubtype;       /* Subtype for this value */
17822  int n;              /* Number of characters in string value, excluding '\0' */
17823  char *z;            /* String or BLOB value */
17824  /* ShallowCopy only needs to copy the information above */
17825  char *zMalloc;      /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
17826  int szMalloc;       /* Size of the zMalloc allocation */
17827  u32 uTemp;          /* Transient storage for serial_type in OP_MakeRecord */
17828  sqlite3 *db;        /* The associated database connection */
17829  void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
17830#ifdef SQLITE_DEBUG
17831  Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
17832  void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
17833#endif
17834};
17835
17836/*
17837** Size of struct Mem not including the Mem.zMalloc member or anything that
17838** follows.
17839*/
17840#define MEMCELLSIZE offsetof(Mem,zMalloc)
17841
17842/* One or more of the following flags are set to indicate the validOK
17843** representations of the value stored in the Mem struct.
17844**
17845** If the MEM_Null flag is set, then the value is an SQL NULL value.
17846** No other flags may be set in this case.
17847**
17848** If the MEM_Str flag is set then Mem.z points at a string representation.
17849** Usually this is encoded in the same unicode encoding as the main
17850** database (see below for exceptions). If the MEM_Term flag is also
17851** set, then the string is nul terminated. The MEM_Int and MEM_Real
17852** flags may coexist with the MEM_Str flag.
17853*/
17854#define MEM_Null      0x0001   /* Value is NULL */
17855#define MEM_Str       0x0002   /* Value is a string */
17856#define MEM_Int       0x0004   /* Value is an integer */
17857#define MEM_Real      0x0008   /* Value is a real number */
17858#define MEM_Blob      0x0010   /* Value is a BLOB */
17859#define MEM_AffMask   0x001f   /* Mask of affinity bits */
17860#define MEM_RowSet    0x0020   /* Value is a RowSet object */
17861#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
17862#define MEM_Undefined 0x0080   /* Value is undefined */
17863#define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
17864#define MEM_TypeMask  0x81ff   /* Mask of type bits */
17865
17866
17867/* Whenever Mem contains a valid string or blob representation, one of
17868** the following flags must be set to determine the memory management
17869** policy for Mem.z.  The MEM_Term flag tells us whether or not the
17870** string is \000 or \u0000 terminated
17871*/
17872#define MEM_Term      0x0200   /* String rep is nul terminated */
17873#define MEM_Dyn       0x0400   /* Need to call Mem.xDel() on Mem.z */
17874#define MEM_Static    0x0800   /* Mem.z points to a static string */
17875#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
17876#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
17877#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
17878#define MEM_Subtype   0x8000   /* Mem.eSubtype is valid */
17879#ifdef SQLITE_OMIT_INCRBLOB
17880  #undef MEM_Zero
17881  #define MEM_Zero 0x0000
17882#endif
17883
17884/* Return TRUE if Mem X contains dynamically allocated content - anything
17885** that needs to be deallocated to avoid a leak.
17886*/
17887#define VdbeMemDynamic(X)  \
17888  (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
17889
17890/*
17891** Clear any existing type flags from a Mem and replace them with f
17892*/
17893#define MemSetTypeFlag(p, f) \
17894   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
17895
17896/*
17897** Return true if a memory cell is not marked as invalid.  This macro
17898** is for use inside assert() statements only.
17899*/
17900#ifdef SQLITE_DEBUG
17901#define memIsValid(M)  ((M)->flags & MEM_Undefined)==0
17902#endif
17903
17904/*
17905** Each auxiliary data pointer stored by a user defined function
17906** implementation calling sqlite3_set_auxdata() is stored in an instance
17907** of this structure. All such structures associated with a single VM
17908** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
17909** when the VM is halted (if not before).
17910*/
17911struct AuxData {
17912  int iOp;                        /* Instruction number of OP_Function opcode */
17913  int iArg;                       /* Index of function argument. */
17914  void *pAux;                     /* Aux data pointer */
17915  void (*xDelete)(void *);        /* Destructor for the aux data */
17916  AuxData *pNext;                 /* Next element in list */
17917};
17918
17919/*
17920** The "context" argument for an installable function.  A pointer to an
17921** instance of this structure is the first argument to the routines used
17922** implement the SQL functions.
17923**
17924** There is a typedef for this structure in sqlite.h.  So all routines,
17925** even the public interface to SQLite, can use a pointer to this structure.
17926** But this file is the only place where the internal details of this
17927** structure are known.
17928**
17929** This structure is defined inside of vdbeInt.h because it uses substructures
17930** (Mem) which are only defined there.
17931*/
17932struct sqlite3_context {
17933  Mem *pOut;              /* The return value is stored here */
17934  FuncDef *pFunc;         /* Pointer to function information */
17935  Mem *pMem;              /* Memory cell used to store aggregate context */
17936  Vdbe *pVdbe;            /* The VM that owns this context */
17937  int iOp;                /* Instruction number of OP_Function */
17938  int isError;            /* Error code returned by the function. */
17939  u8 skipFlag;            /* Skip accumulator loading if true */
17940  u8 fErrorOrAux;         /* isError!=0 or pVdbe->pAuxData modified */
17941  u8 argc;                /* Number of arguments */
17942  sqlite3_value *argv[1]; /* Argument set */
17943};
17944
17945/*
17946** An Explain object accumulates indented output which is helpful
17947** in describing recursive data structures.
17948*/
17949struct Explain {
17950  Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
17951  StrAccum str;      /* The string being accumulated */
17952  int nIndent;       /* Number of elements in aIndent */
17953  u16 aIndent[100];  /* Levels of indentation */
17954  char zBase[100];   /* Initial space */
17955};
17956
17957/* A bitfield type for use inside of structures.  Always follow with :N where
17958** N is the number of bits.
17959*/
17960typedef unsigned bft;  /* Bit Field Type */
17961
17962typedef struct ScanStatus ScanStatus;
17963struct ScanStatus {
17964  int addrExplain;                /* OP_Explain for loop */
17965  int addrLoop;                   /* Address of "loops" counter */
17966  int addrVisit;                  /* Address of "rows visited" counter */
17967  int iSelectID;                  /* The "Select-ID" for this loop */
17968  LogEst nEst;                    /* Estimated output rows per loop */
17969  char *zName;                    /* Name of table or index */
17970};
17971
17972/*
17973** An instance of the virtual machine.  This structure contains the complete
17974** state of the virtual machine.
17975**
17976** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
17977** is really a pointer to an instance of this structure.
17978*/
17979struct Vdbe {
17980  sqlite3 *db;            /* The database connection that owns this statement */
17981  Op *aOp;                /* Space to hold the virtual machine's program */
17982  Mem *aMem;              /* The memory locations */
17983  Mem **apArg;            /* Arguments to currently executing user function */
17984  Mem *aColName;          /* Column names to return */
17985  Mem *pResultSet;        /* Pointer to an array of results */
17986  Parse *pParse;          /* Parsing context used to create this Vdbe */
17987  int nMem;               /* Number of memory locations currently allocated */
17988  int nOp;                /* Number of instructions in the program */
17989  int nCursor;            /* Number of slots in apCsr[] */
17990  u32 magic;              /* Magic number for sanity checking */
17991  char *zErrMsg;          /* Error message written here */
17992  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
17993  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
17994  Mem *aVar;              /* Values for the OP_Variable opcode. */
17995  char **azVar;           /* Name of variables */
17996  ynVar nVar;             /* Number of entries in aVar[] */
17997  ynVar nzVar;            /* Number of entries in azVar[] */
17998  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
17999  int pc;                 /* The program counter */
18000  int rc;                 /* Value to return */
18001#ifdef SQLITE_DEBUG
18002  int rcApp;              /* errcode set by sqlite3_result_error_code() */
18003#endif
18004  u16 nResColumn;         /* Number of columns in one row of the result set */
18005  u8 errorAction;         /* Recovery action to do in case of an error */
18006  bft expired:1;          /* True if the VM needs to be recompiled */
18007  bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
18008  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
18009  bft explain:2;          /* True if EXPLAIN present on SQL command */
18010  bft changeCntOn:1;      /* True to update the change-counter */
18011  bft runOnlyOnce:1;      /* Automatically expire on reset */
18012  bft usesStmtJournal:1;  /* True if uses a statement journal */
18013  bft readOnly:1;         /* True for statements that do not write */
18014  bft bIsReader:1;        /* True for statements that read */
18015  bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
18016  int nChange;            /* Number of db changes made since last reset */
18017  yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
18018  yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
18019  int iStatement;         /* Statement number (or 0 if has not opened stmt) */
18020  u32 aCounter[5];        /* Counters used by sqlite3_stmt_status() */
18021#ifndef SQLITE_OMIT_TRACE
18022  i64 startTime;          /* Time when query started - used for profiling */
18023#endif
18024  i64 iCurrentTime;       /* Value of julianday('now') for this statement */
18025  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
18026  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
18027  i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */
18028  char *zSql;             /* Text of the SQL statement that generated this */
18029  void *pFree;            /* Free this when deleting the vdbe */
18030  VdbeFrame *pFrame;      /* Parent frame */
18031  VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
18032  int nFrame;             /* Number of frames in pFrame list */
18033  u32 expmask;            /* Binding to these vars invalidates VM */
18034  SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
18035  int nOnceFlag;          /* Size of array aOnceFlag[] */
18036  u8 *aOnceFlag;          /* Flags for OP_Once */
18037  AuxData *pAuxData;      /* Linked list of auxdata allocations */
18038#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
18039  i64 *anExec;            /* Number of times each op has been executed */
18040  int nScan;              /* Entries in aScan[] */
18041  ScanStatus *aScan;      /* Scan definitions for sqlite3_stmt_scanstatus() */
18042#endif
18043};
18044
18045/*
18046** The following are allowed values for Vdbe.magic
18047*/
18048#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
18049#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
18050#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
18051#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
18052
18053/*
18054** Structure used to store the context required by the
18055** sqlite3_preupdate_*() API functions.
18056*/
18057struct PreUpdate {
18058  Vdbe *v;
18059  VdbeCursor *pCsr;               /* Cursor to read old values from */
18060  int op;                         /* One of SQLITE_INSERT, UPDATE, DELETE */
18061  u8 *aRecord;                    /* old.* database record */
18062  KeyInfo keyinfo;
18063  UnpackedRecord *pUnpacked;      /* Unpacked version of aRecord[] */
18064  UnpackedRecord *pNewUnpacked;   /* Unpacked version of new.* record */
18065  int iNewReg;                    /* Register for new.* values */
18066  i64 iKey1;                      /* First key value passed to hook */
18067  i64 iKey2;                      /* Second key value passed to hook */
18068  int iPKey;                      /* If not negative index of IPK column */
18069  Mem *aNew;                      /* Array of new.* values */
18070};
18071
18072/*
18073** Function prototypes
18074*/
18075SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
18076SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
18077void sqliteVdbePopStack(Vdbe*,int);
18078SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
18079SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
18080#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
18081SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
18082#endif
18083SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
18084SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
18085SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
18086SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
18087SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
18088SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
18089
18090int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
18091SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
18092SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
18093SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
18094SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
18095SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
18096SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
18097SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
18098SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
18099SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
18100SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
18101SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
18102SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
18103SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
18104#ifdef SQLITE_OMIT_FLOATING_POINT
18105# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
18106#else
18107SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
18108#endif
18109SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
18110SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
18111SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
18112SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
18113SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
18114SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
18115SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
18116SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
18117SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
18118SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
18119SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
18120SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
18121SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
18122SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
18123SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
18124SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
18125SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
18126SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
18127SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
18128SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
18129SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
18130SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
18131#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
18132SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
18133#endif
18134SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
18135
18136SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
18137SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
18138SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
18139SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
18140SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
18141SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
18142SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
18143SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
18144
18145#if !defined(SQLITE_OMIT_SHARED_CACHE)
18146SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
18147#else
18148# define sqlite3VdbeEnter(X)
18149#endif
18150
18151#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
18152SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
18153#else
18154# define sqlite3VdbeLeave(X)
18155#endif
18156
18157#ifdef SQLITE_DEBUG
18158SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
18159SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
18160#endif
18161
18162#ifndef SQLITE_OMIT_FOREIGN_KEY
18163SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
18164#else
18165# define sqlite3VdbeCheckFk(p,i) 0
18166#endif
18167
18168SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
18169#ifdef SQLITE_DEBUG
18170SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
18171SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
18172#endif
18173SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
18174
18175#ifndef SQLITE_OMIT_INCRBLOB
18176SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
18177  #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
18178#else
18179  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
18180  #define ExpandBlob(P) SQLITE_OK
18181#endif
18182
18183#endif /* !defined(SQLITE_VDBEINT_H) */
18184
18185/************** End of vdbeInt.h *********************************************/
18186/************** Continuing where we left off in status.c *********************/
18187
18188/*
18189** Variables in which to record status information.
18190*/
18191#if SQLITE_PTRSIZE>4
18192typedef sqlite3_int64 sqlite3StatValueType;
18193#else
18194typedef u32 sqlite3StatValueType;
18195#endif
18196typedef struct sqlite3StatType sqlite3StatType;
18197static SQLITE_WSD struct sqlite3StatType {
18198  sqlite3StatValueType nowValue[10];  /* Current value */
18199  sqlite3StatValueType mxValue[10];   /* Maximum value */
18200} sqlite3Stat = { {0,}, {0,} };
18201
18202/*
18203** Elements of sqlite3Stat[] are protected by either the memory allocator
18204** mutex, or by the pcache1 mutex.  The following array determines which.
18205*/
18206static const char statMutex[] = {
18207  0,  /* SQLITE_STATUS_MEMORY_USED */
18208  1,  /* SQLITE_STATUS_PAGECACHE_USED */
18209  1,  /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
18210  0,  /* SQLITE_STATUS_SCRATCH_USED */
18211  0,  /* SQLITE_STATUS_SCRATCH_OVERFLOW */
18212  0,  /* SQLITE_STATUS_MALLOC_SIZE */
18213  0,  /* SQLITE_STATUS_PARSER_STACK */
18214  1,  /* SQLITE_STATUS_PAGECACHE_SIZE */
18215  0,  /* SQLITE_STATUS_SCRATCH_SIZE */
18216  0,  /* SQLITE_STATUS_MALLOC_COUNT */
18217};
18218
18219
18220/* The "wsdStat" macro will resolve to the status information
18221** state vector.  If writable static data is unsupported on the target,
18222** we have to locate the state vector at run-time.  In the more common
18223** case where writable static data is supported, wsdStat can refer directly
18224** to the "sqlite3Stat" state vector declared above.
18225*/
18226#ifdef SQLITE_OMIT_WSD
18227# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
18228# define wsdStat x[0]
18229#else
18230# define wsdStatInit
18231# define wsdStat sqlite3Stat
18232#endif
18233
18234/*
18235** Return the current value of a status parameter.  The caller must
18236** be holding the appropriate mutex.
18237*/
18238SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
18239  wsdStatInit;
18240  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18241  assert( op>=0 && op<ArraySize(statMutex) );
18242  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18243                                           : sqlite3MallocMutex()) );
18244  return wsdStat.nowValue[op];
18245}
18246
18247/*
18248** Add N to the value of a status record.  The caller must hold the
18249** appropriate mutex.  (Locking is checked by assert()).
18250**
18251** The StatusUp() routine can accept positive or negative values for N.
18252** The value of N is added to the current status value and the high-water
18253** mark is adjusted if necessary.
18254**
18255** The StatusDown() routine lowers the current value by N.  The highwater
18256** mark is unchanged.  N must be non-negative for StatusDown().
18257*/
18258SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
18259  wsdStatInit;
18260  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18261  assert( op>=0 && op<ArraySize(statMutex) );
18262  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18263                                           : sqlite3MallocMutex()) );
18264  wsdStat.nowValue[op] += N;
18265  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
18266    wsdStat.mxValue[op] = wsdStat.nowValue[op];
18267  }
18268}
18269SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
18270  wsdStatInit;
18271  assert( N>=0 );
18272  assert( op>=0 && op<ArraySize(statMutex) );
18273  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18274                                           : sqlite3MallocMutex()) );
18275  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18276  wsdStat.nowValue[op] -= N;
18277}
18278
18279/*
18280** Adjust the highwater mark if necessary.
18281** The caller must hold the appropriate mutex.
18282*/
18283SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
18284  sqlite3StatValueType newValue;
18285  wsdStatInit;
18286  assert( X>=0 );
18287  newValue = (sqlite3StatValueType)X;
18288  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18289  assert( op>=0 && op<ArraySize(statMutex) );
18290  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18291                                           : sqlite3MallocMutex()) );
18292  assert( op==SQLITE_STATUS_MALLOC_SIZE
18293          || op==SQLITE_STATUS_PAGECACHE_SIZE
18294          || op==SQLITE_STATUS_SCRATCH_SIZE
18295          || op==SQLITE_STATUS_PARSER_STACK );
18296  if( newValue>wsdStat.mxValue[op] ){
18297    wsdStat.mxValue[op] = newValue;
18298  }
18299}
18300
18301/*
18302** Query status information.
18303*/
18304SQLITE_API int SQLITE_STDCALL sqlite3_status64(
18305  int op,
18306  sqlite3_int64 *pCurrent,
18307  sqlite3_int64 *pHighwater,
18308  int resetFlag
18309){
18310  sqlite3_mutex *pMutex;
18311  wsdStatInit;
18312  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
18313    return SQLITE_MISUSE_BKPT;
18314  }
18315#ifdef SQLITE_ENABLE_API_ARMOR
18316  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
18317#endif
18318  pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
18319  sqlite3_mutex_enter(pMutex);
18320  *pCurrent = wsdStat.nowValue[op];
18321  *pHighwater = wsdStat.mxValue[op];
18322  if( resetFlag ){
18323    wsdStat.mxValue[op] = wsdStat.nowValue[op];
18324  }
18325  sqlite3_mutex_leave(pMutex);
18326  (void)pMutex;  /* Prevent warning when SQLITE_THREADSAFE=0 */
18327  return SQLITE_OK;
18328}
18329SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
18330  sqlite3_int64 iCur = 0, iHwtr = 0;
18331  int rc;
18332#ifdef SQLITE_ENABLE_API_ARMOR
18333  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
18334#endif
18335  rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
18336  if( rc==0 ){
18337    *pCurrent = (int)iCur;
18338    *pHighwater = (int)iHwtr;
18339  }
18340  return rc;
18341}
18342
18343/*
18344** Query status information for a single database connection
18345*/
18346SQLITE_API int SQLITE_STDCALL sqlite3_db_status(
18347  sqlite3 *db,          /* The database connection whose status is desired */
18348  int op,               /* Status verb */
18349  int *pCurrent,        /* Write current value here */
18350  int *pHighwater,      /* Write high-water mark here */
18351  int resetFlag         /* Reset high-water mark if true */
18352){
18353  int rc = SQLITE_OK;   /* Return code */
18354#ifdef SQLITE_ENABLE_API_ARMOR
18355  if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
18356    return SQLITE_MISUSE_BKPT;
18357  }
18358#endif
18359  sqlite3_mutex_enter(db->mutex);
18360  switch( op ){
18361    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
18362      *pCurrent = db->lookaside.nOut;
18363      *pHighwater = db->lookaside.mxOut;
18364      if( resetFlag ){
18365        db->lookaside.mxOut = db->lookaside.nOut;
18366      }
18367      break;
18368    }
18369
18370    case SQLITE_DBSTATUS_LOOKASIDE_HIT:
18371    case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
18372    case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
18373      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
18374      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
18375      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
18376      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
18377      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
18378      *pCurrent = 0;
18379      *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
18380      if( resetFlag ){
18381        db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
18382      }
18383      break;
18384    }
18385
18386    /*
18387    ** Return an approximation for the amount of memory currently used
18388    ** by all pagers associated with the given database connection.  The
18389    ** highwater mark is meaningless and is returned as zero.
18390    */
18391    case SQLITE_DBSTATUS_CACHE_USED_SHARED:
18392    case SQLITE_DBSTATUS_CACHE_USED: {
18393      int totalUsed = 0;
18394      int i;
18395      sqlite3BtreeEnterAll(db);
18396      for(i=0; i<db->nDb; i++){
18397        Btree *pBt = db->aDb[i].pBt;
18398        if( pBt ){
18399          Pager *pPager = sqlite3BtreePager(pBt);
18400          int nByte = sqlite3PagerMemUsed(pPager);
18401          if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
18402            nByte = nByte / sqlite3BtreeConnectionCount(pBt);
18403          }
18404          totalUsed += nByte;
18405        }
18406      }
18407      sqlite3BtreeLeaveAll(db);
18408      *pCurrent = totalUsed;
18409      *pHighwater = 0;
18410      break;
18411    }
18412
18413    /*
18414    ** *pCurrent gets an accurate estimate of the amount of memory used
18415    ** to store the schema for all databases (main, temp, and any ATTACHed
18416    ** databases.  *pHighwater is set to zero.
18417    */
18418    case SQLITE_DBSTATUS_SCHEMA_USED: {
18419      int i;                      /* Used to iterate through schemas */
18420      int nByte = 0;              /* Used to accumulate return value */
18421
18422      sqlite3BtreeEnterAll(db);
18423      db->pnBytesFreed = &nByte;
18424      for(i=0; i<db->nDb; i++){
18425        Schema *pSchema = db->aDb[i].pSchema;
18426        if( ALWAYS(pSchema!=0) ){
18427          HashElem *p;
18428
18429          nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
18430              pSchema->tblHash.count
18431            + pSchema->trigHash.count
18432            + pSchema->idxHash.count
18433            + pSchema->fkeyHash.count
18434          );
18435          nByte += sqlite3_msize(pSchema->tblHash.ht);
18436          nByte += sqlite3_msize(pSchema->trigHash.ht);
18437          nByte += sqlite3_msize(pSchema->idxHash.ht);
18438          nByte += sqlite3_msize(pSchema->fkeyHash.ht);
18439
18440          for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
18441            sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
18442          }
18443          for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
18444            sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
18445          }
18446        }
18447      }
18448      db->pnBytesFreed = 0;
18449      sqlite3BtreeLeaveAll(db);
18450
18451      *pHighwater = 0;
18452      *pCurrent = nByte;
18453      break;
18454    }
18455
18456    /*
18457    ** *pCurrent gets an accurate estimate of the amount of memory used
18458    ** to store all prepared statements.
18459    ** *pHighwater is set to zero.
18460    */
18461    case SQLITE_DBSTATUS_STMT_USED: {
18462      struct Vdbe *pVdbe;         /* Used to iterate through VMs */
18463      int nByte = 0;              /* Used to accumulate return value */
18464
18465      db->pnBytesFreed = &nByte;
18466      for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
18467        sqlite3VdbeClearObject(db, pVdbe);
18468        sqlite3DbFree(db, pVdbe);
18469      }
18470      db->pnBytesFreed = 0;
18471
18472      *pHighwater = 0;  /* IMP: R-64479-57858 */
18473      *pCurrent = nByte;
18474
18475      break;
18476    }
18477
18478    /*
18479    ** Set *pCurrent to the total cache hits or misses encountered by all
18480    ** pagers the database handle is connected to. *pHighwater is always set
18481    ** to zero.
18482    */
18483    case SQLITE_DBSTATUS_CACHE_HIT:
18484    case SQLITE_DBSTATUS_CACHE_MISS:
18485    case SQLITE_DBSTATUS_CACHE_WRITE:{
18486      int i;
18487      int nRet = 0;
18488      assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
18489      assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
18490
18491      for(i=0; i<db->nDb; i++){
18492        if( db->aDb[i].pBt ){
18493          Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
18494          sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
18495        }
18496      }
18497      *pHighwater = 0; /* IMP: R-42420-56072 */
18498                       /* IMP: R-54100-20147 */
18499                       /* IMP: R-29431-39229 */
18500      *pCurrent = nRet;
18501      break;
18502    }
18503
18504    /* Set *pCurrent to non-zero if there are unresolved deferred foreign
18505    ** key constraints.  Set *pCurrent to zero if all foreign key constraints
18506    ** have been satisfied.  The *pHighwater is always set to zero.
18507    */
18508    case SQLITE_DBSTATUS_DEFERRED_FKS: {
18509      *pHighwater = 0;  /* IMP: R-11967-56545 */
18510      *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
18511      break;
18512    }
18513
18514    default: {
18515      rc = SQLITE_ERROR;
18516    }
18517  }
18518  sqlite3_mutex_leave(db->mutex);
18519  return rc;
18520}
18521
18522/************** End of status.c **********************************************/
18523/************** Begin file date.c ********************************************/
18524/*
18525** 2003 October 31
18526**
18527** The author disclaims copyright to this source code.  In place of
18528** a legal notice, here is a blessing:
18529**
18530**    May you do good and not evil.
18531**    May you find forgiveness for yourself and forgive others.
18532**    May you share freely, never taking more than you give.
18533**
18534*************************************************************************
18535** This file contains the C functions that implement date and time
18536** functions for SQLite.
18537**
18538** There is only one exported symbol in this file - the function
18539** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
18540** All other code has file scope.
18541**
18542** SQLite processes all times and dates as julian day numbers.  The
18543** dates and times are stored as the number of days since noon
18544** in Greenwich on November 24, 4714 B.C. according to the Gregorian
18545** calendar system.
18546**
18547** 1970-01-01 00:00:00 is JD 2440587.5
18548** 2000-01-01 00:00:00 is JD 2451544.5
18549**
18550** This implementation requires years to be expressed as a 4-digit number
18551** which means that only dates between 0000-01-01 and 9999-12-31 can
18552** be represented, even though julian day numbers allow a much wider
18553** range of dates.
18554**
18555** The Gregorian calendar system is used for all dates and times,
18556** even those that predate the Gregorian calendar.  Historians usually
18557** use the julian calendar for dates prior to 1582-10-15 and for some
18558** dates afterwards, depending on locale.  Beware of this difference.
18559**
18560** The conversion algorithms are implemented based on descriptions
18561** in the following text:
18562**
18563**      Jean Meeus
18564**      Astronomical Algorithms, 2nd Edition, 1998
18565**      ISBM 0-943396-61-1
18566**      Willmann-Bell, Inc
18567**      Richmond, Virginia (USA)
18568*/
18569/* #include "sqliteInt.h" */
18570/* #include <stdlib.h> */
18571/* #include <assert.h> */
18572#include <time.h>
18573
18574#ifndef SQLITE_OMIT_DATETIME_FUNCS
18575
18576/*
18577** The MSVC CRT on Windows CE may not have a localtime() function.
18578** So declare a substitute.  The substitute function itself is
18579** defined in "os_win.c".
18580*/
18581#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
18582    (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
18583struct tm *__cdecl localtime(const time_t *);
18584#endif
18585
18586/*
18587** A structure for holding a single date and time.
18588*/
18589typedef struct DateTime DateTime;
18590struct DateTime {
18591  sqlite3_int64 iJD; /* The julian day number times 86400000 */
18592  int Y, M, D;       /* Year, month, and day */
18593  int h, m;          /* Hour and minutes */
18594  int tz;            /* Timezone offset in minutes */
18595  double s;          /* Seconds */
18596  char validYMD;     /* True (1) if Y,M,D are valid */
18597  char validHMS;     /* True (1) if h,m,s are valid */
18598  char validJD;      /* True (1) if iJD is valid */
18599  char validTZ;      /* True (1) if tz is valid */
18600  char tzSet;        /* Timezone was set explicitly */
18601};
18602
18603
18604/*
18605** Convert zDate into one or more integers according to the conversion
18606** specifier zFormat.
18607**
18608** zFormat[] contains 4 characters for each integer converted, except for
18609** the last integer which is specified by three characters.  The meaning
18610** of a four-character format specifiers ABCD is:
18611**
18612**    A:   number of digits to convert.  Always "2" or "4".
18613**    B:   minimum value.  Always "0" or "1".
18614**    C:   maximum value, decoded as:
18615**           a:  12
18616**           b:  14
18617**           c:  24
18618**           d:  31
18619**           e:  59
18620**           f:  9999
18621**    D:   the separator character, or \000 to indicate this is the
18622**         last number to convert.
18623**
18624** Example:  To translate an ISO-8601 date YYYY-MM-DD, the format would
18625** be "40f-21a-20c".  The "40f-" indicates the 4-digit year followed by "-".
18626** The "21a-" indicates the 2-digit month followed by "-".  The "20c" indicates
18627** the 2-digit day which is the last integer in the set.
18628**
18629** The function returns the number of successful conversions.
18630*/
18631static int getDigits(const char *zDate, const char *zFormat, ...){
18632  /* The aMx[] array translates the 3rd character of each format
18633  ** spec into a max size:    a   b   c   d   e     f */
18634  static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
18635  va_list ap;
18636  int cnt = 0;
18637  char nextC;
18638  va_start(ap, zFormat);
18639  do{
18640    char N = zFormat[0] - '0';
18641    char min = zFormat[1] - '0';
18642    int val = 0;
18643    u16 max;
18644
18645    assert( zFormat[2]>='a' && zFormat[2]<='f' );
18646    max = aMx[zFormat[2] - 'a'];
18647    nextC = zFormat[3];
18648    val = 0;
18649    while( N-- ){
18650      if( !sqlite3Isdigit(*zDate) ){
18651        goto end_getDigits;
18652      }
18653      val = val*10 + *zDate - '0';
18654      zDate++;
18655    }
18656    if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
18657      goto end_getDigits;
18658    }
18659    *va_arg(ap,int*) = val;
18660    zDate++;
18661    cnt++;
18662    zFormat += 4;
18663  }while( nextC );
18664end_getDigits:
18665  va_end(ap);
18666  return cnt;
18667}
18668
18669/*
18670** Parse a timezone extension on the end of a date-time.
18671** The extension is of the form:
18672**
18673**        (+/-)HH:MM
18674**
18675** Or the "zulu" notation:
18676**
18677**        Z
18678**
18679** If the parse is successful, write the number of minutes
18680** of change in p->tz and return 0.  If a parser error occurs,
18681** return non-zero.
18682**
18683** A missing specifier is not considered an error.
18684*/
18685static int parseTimezone(const char *zDate, DateTime *p){
18686  int sgn = 0;
18687  int nHr, nMn;
18688  int c;
18689  while( sqlite3Isspace(*zDate) ){ zDate++; }
18690  p->tz = 0;
18691  c = *zDate;
18692  if( c=='-' ){
18693    sgn = -1;
18694  }else if( c=='+' ){
18695    sgn = +1;
18696  }else if( c=='Z' || c=='z' ){
18697    zDate++;
18698    goto zulu_time;
18699  }else{
18700    return c!=0;
18701  }
18702  zDate++;
18703  if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
18704    return 1;
18705  }
18706  zDate += 5;
18707  p->tz = sgn*(nMn + nHr*60);
18708zulu_time:
18709  while( sqlite3Isspace(*zDate) ){ zDate++; }
18710  p->tzSet = 1;
18711  return *zDate!=0;
18712}
18713
18714/*
18715** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
18716** The HH, MM, and SS must each be exactly 2 digits.  The
18717** fractional seconds FFFF can be one or more digits.
18718**
18719** Return 1 if there is a parsing error and 0 on success.
18720*/
18721static int parseHhMmSs(const char *zDate, DateTime *p){
18722  int h, m, s;
18723  double ms = 0.0;
18724  if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
18725    return 1;
18726  }
18727  zDate += 5;
18728  if( *zDate==':' ){
18729    zDate++;
18730    if( getDigits(zDate, "20e", &s)!=1 ){
18731      return 1;
18732    }
18733    zDate += 2;
18734    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
18735      double rScale = 1.0;
18736      zDate++;
18737      while( sqlite3Isdigit(*zDate) ){
18738        ms = ms*10.0 + *zDate - '0';
18739        rScale *= 10.0;
18740        zDate++;
18741      }
18742      ms /= rScale;
18743    }
18744  }else{
18745    s = 0;
18746  }
18747  p->validJD = 0;
18748  p->validHMS = 1;
18749  p->h = h;
18750  p->m = m;
18751  p->s = s + ms;
18752  if( parseTimezone(zDate, p) ) return 1;
18753  p->validTZ = (p->tz!=0)?1:0;
18754  return 0;
18755}
18756
18757/*
18758** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
18759** that the YYYY-MM-DD is according to the Gregorian calendar.
18760**
18761** Reference:  Meeus page 61
18762*/
18763static void computeJD(DateTime *p){
18764  int Y, M, D, A, B, X1, X2;
18765
18766  if( p->validJD ) return;
18767  if( p->validYMD ){
18768    Y = p->Y;
18769    M = p->M;
18770    D = p->D;
18771  }else{
18772    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
18773    M = 1;
18774    D = 1;
18775  }
18776  if( M<=2 ){
18777    Y--;
18778    M += 12;
18779  }
18780  A = Y/100;
18781  B = 2 - A + (A/4);
18782  X1 = 36525*(Y+4716)/100;
18783  X2 = 306001*(M+1)/10000;
18784  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
18785  p->validJD = 1;
18786  if( p->validHMS ){
18787    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
18788    if( p->validTZ ){
18789      p->iJD -= p->tz*60000;
18790      p->validYMD = 0;
18791      p->validHMS = 0;
18792      p->validTZ = 0;
18793    }
18794  }
18795}
18796
18797/*
18798** Parse dates of the form
18799**
18800**     YYYY-MM-DD HH:MM:SS.FFF
18801**     YYYY-MM-DD HH:MM:SS
18802**     YYYY-MM-DD HH:MM
18803**     YYYY-MM-DD
18804**
18805** Write the result into the DateTime structure and return 0
18806** on success and 1 if the input string is not a well-formed
18807** date.
18808*/
18809static int parseYyyyMmDd(const char *zDate, DateTime *p){
18810  int Y, M, D, neg;
18811
18812  if( zDate[0]=='-' ){
18813    zDate++;
18814    neg = 1;
18815  }else{
18816    neg = 0;
18817  }
18818  if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
18819    return 1;
18820  }
18821  zDate += 10;
18822  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
18823  if( parseHhMmSs(zDate, p)==0 ){
18824    /* We got the time */
18825  }else if( *zDate==0 ){
18826    p->validHMS = 0;
18827  }else{
18828    return 1;
18829  }
18830  p->validJD = 0;
18831  p->validYMD = 1;
18832  p->Y = neg ? -Y : Y;
18833  p->M = M;
18834  p->D = D;
18835  if( p->validTZ ){
18836    computeJD(p);
18837  }
18838  return 0;
18839}
18840
18841/*
18842** Set the time to the current time reported by the VFS.
18843**
18844** Return the number of errors.
18845*/
18846static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
18847  p->iJD = sqlite3StmtCurrentTime(context);
18848  if( p->iJD>0 ){
18849    p->validJD = 1;
18850    return 0;
18851  }else{
18852    return 1;
18853  }
18854}
18855
18856/*
18857** Attempt to parse the given string into a julian day number.  Return
18858** the number of errors.
18859**
18860** The following are acceptable forms for the input string:
18861**
18862**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
18863**      DDDD.DD
18864**      now
18865**
18866** In the first form, the +/-HH:MM is always optional.  The fractional
18867** seconds extension (the ".FFF") is optional.  The seconds portion
18868** (":SS.FFF") is option.  The year and date can be omitted as long
18869** as there is a time string.  The time string can be omitted as long
18870** as there is a year and date.
18871*/
18872static int parseDateOrTime(
18873  sqlite3_context *context,
18874  const char *zDate,
18875  DateTime *p
18876){
18877  double r;
18878  if( parseYyyyMmDd(zDate,p)==0 ){
18879    return 0;
18880  }else if( parseHhMmSs(zDate, p)==0 ){
18881    return 0;
18882  }else if( sqlite3StrICmp(zDate,"now")==0){
18883    return setDateTimeToCurrent(context, p);
18884  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
18885    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
18886    p->validJD = 1;
18887    return 0;
18888  }
18889  return 1;
18890}
18891
18892/*
18893** Compute the Year, Month, and Day from the julian day number.
18894*/
18895static void computeYMD(DateTime *p){
18896  int Z, A, B, C, D, E, X1;
18897  if( p->validYMD ) return;
18898  if( !p->validJD ){
18899    p->Y = 2000;
18900    p->M = 1;
18901    p->D = 1;
18902  }else{
18903    Z = (int)((p->iJD + 43200000)/86400000);
18904    A = (int)((Z - 1867216.25)/36524.25);
18905    A = Z + 1 + A - (A/4);
18906    B = A + 1524;
18907    C = (int)((B - 122.1)/365.25);
18908    D = (36525*(C&32767))/100;
18909    E = (int)((B-D)/30.6001);
18910    X1 = (int)(30.6001*E);
18911    p->D = B - D - X1;
18912    p->M = E<14 ? E-1 : E-13;
18913    p->Y = p->M>2 ? C - 4716 : C - 4715;
18914  }
18915  p->validYMD = 1;
18916}
18917
18918/*
18919** Compute the Hour, Minute, and Seconds from the julian day number.
18920*/
18921static void computeHMS(DateTime *p){
18922  int s;
18923  if( p->validHMS ) return;
18924  computeJD(p);
18925  s = (int)((p->iJD + 43200000) % 86400000);
18926  p->s = s/1000.0;
18927  s = (int)p->s;
18928  p->s -= s;
18929  p->h = s/3600;
18930  s -= p->h*3600;
18931  p->m = s/60;
18932  p->s += s - p->m*60;
18933  p->validHMS = 1;
18934}
18935
18936/*
18937** Compute both YMD and HMS
18938*/
18939static void computeYMD_HMS(DateTime *p){
18940  computeYMD(p);
18941  computeHMS(p);
18942}
18943
18944/*
18945** Clear the YMD and HMS and the TZ
18946*/
18947static void clearYMD_HMS_TZ(DateTime *p){
18948  p->validYMD = 0;
18949  p->validHMS = 0;
18950  p->validTZ = 0;
18951}
18952
18953#ifndef SQLITE_OMIT_LOCALTIME
18954/*
18955** On recent Windows platforms, the localtime_s() function is available
18956** as part of the "Secure CRT". It is essentially equivalent to
18957** localtime_r() available under most POSIX platforms, except that the
18958** order of the parameters is reversed.
18959**
18960** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
18961**
18962** If the user has not indicated to use localtime_r() or localtime_s()
18963** already, check for an MSVC build environment that provides
18964** localtime_s().
18965*/
18966#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
18967    && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
18968#undef  HAVE_LOCALTIME_S
18969#define HAVE_LOCALTIME_S 1
18970#endif
18971
18972/*
18973** The following routine implements the rough equivalent of localtime_r()
18974** using whatever operating-system specific localtime facility that
18975** is available.  This routine returns 0 on success and
18976** non-zero on any kind of error.
18977**
18978** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
18979** routine will always fail.
18980**
18981** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
18982** library function localtime_r() is used to assist in the calculation of
18983** local time.
18984*/
18985static int osLocaltime(time_t *t, struct tm *pTm){
18986  int rc;
18987#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
18988  struct tm *pX;
18989#if SQLITE_THREADSAFE>0
18990  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
18991#endif
18992  sqlite3_mutex_enter(mutex);
18993  pX = localtime(t);
18994#ifndef SQLITE_OMIT_BUILTIN_TEST
18995  if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
18996#endif
18997  if( pX ) *pTm = *pX;
18998  sqlite3_mutex_leave(mutex);
18999  rc = pX==0;
19000#else
19001#ifndef SQLITE_OMIT_BUILTIN_TEST
19002  if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
19003#endif
19004#if HAVE_LOCALTIME_R
19005  rc = localtime_r(t, pTm)==0;
19006#else
19007  rc = localtime_s(pTm, t);
19008#endif /* HAVE_LOCALTIME_R */
19009#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
19010  return rc;
19011}
19012#endif /* SQLITE_OMIT_LOCALTIME */
19013
19014
19015#ifndef SQLITE_OMIT_LOCALTIME
19016/*
19017** Compute the difference (in milliseconds) between localtime and UTC
19018** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
19019** return this value and set *pRc to SQLITE_OK.
19020**
19021** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
19022** is undefined in this case.
19023*/
19024static sqlite3_int64 localtimeOffset(
19025  DateTime *p,                    /* Date at which to calculate offset */
19026  sqlite3_context *pCtx,          /* Write error here if one occurs */
19027  int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
19028){
19029  DateTime x, y;
19030  time_t t;
19031  struct tm sLocal;
19032
19033  /* Initialize the contents of sLocal to avoid a compiler warning. */
19034  memset(&sLocal, 0, sizeof(sLocal));
19035
19036  x = *p;
19037  computeYMD_HMS(&x);
19038  if( x.Y<1971 || x.Y>=2038 ){
19039    /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
19040    ** works for years between 1970 and 2037. For dates outside this range,
19041    ** SQLite attempts to map the year into an equivalent year within this
19042    ** range, do the calculation, then map the year back.
19043    */
19044    x.Y = 2000;
19045    x.M = 1;
19046    x.D = 1;
19047    x.h = 0;
19048    x.m = 0;
19049    x.s = 0.0;
19050  } else {
19051    int s = (int)(x.s + 0.5);
19052    x.s = s;
19053  }
19054  x.tz = 0;
19055  x.validJD = 0;
19056  computeJD(&x);
19057  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
19058  if( osLocaltime(&t, &sLocal) ){
19059    sqlite3_result_error(pCtx, "local time unavailable", -1);
19060    *pRc = SQLITE_ERROR;
19061    return 0;
19062  }
19063  y.Y = sLocal.tm_year + 1900;
19064  y.M = sLocal.tm_mon + 1;
19065  y.D = sLocal.tm_mday;
19066  y.h = sLocal.tm_hour;
19067  y.m = sLocal.tm_min;
19068  y.s = sLocal.tm_sec;
19069  y.validYMD = 1;
19070  y.validHMS = 1;
19071  y.validJD = 0;
19072  y.validTZ = 0;
19073  computeJD(&y);
19074  *pRc = SQLITE_OK;
19075  return y.iJD - x.iJD;
19076}
19077#endif /* SQLITE_OMIT_LOCALTIME */
19078
19079/*
19080** Process a modifier to a date-time stamp.  The modifiers are
19081** as follows:
19082**
19083**     NNN days
19084**     NNN hours
19085**     NNN minutes
19086**     NNN.NNNN seconds
19087**     NNN months
19088**     NNN years
19089**     start of month
19090**     start of year
19091**     start of week
19092**     start of day
19093**     weekday N
19094**     unixepoch
19095**     localtime
19096**     utc
19097**
19098** Return 0 on success and 1 if there is any kind of error. If the error
19099** is in a system call (i.e. localtime()), then an error message is written
19100** to context pCtx. If the error is an unrecognized modifier, no error is
19101** written to pCtx.
19102*/
19103static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
19104  int rc = 1;
19105  int n;
19106  double r;
19107  char *z, zBuf[30];
19108  z = zBuf;
19109  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
19110    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
19111  }
19112  z[n] = 0;
19113  switch( z[0] ){
19114#ifndef SQLITE_OMIT_LOCALTIME
19115    case 'l': {
19116      /*    localtime
19117      **
19118      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
19119      ** show local time.
19120      */
19121      if( strcmp(z, "localtime")==0 ){
19122        computeJD(p);
19123        p->iJD += localtimeOffset(p, pCtx, &rc);
19124        clearYMD_HMS_TZ(p);
19125      }
19126      break;
19127    }
19128#endif
19129    case 'u': {
19130      /*
19131      **    unixepoch
19132      **
19133      ** Treat the current value of p->iJD as the number of
19134      ** seconds since 1970.  Convert to a real julian day number.
19135      */
19136      if( strcmp(z, "unixepoch")==0 && p->validJD ){
19137        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
19138        clearYMD_HMS_TZ(p);
19139        rc = 0;
19140      }
19141#ifndef SQLITE_OMIT_LOCALTIME
19142      else if( strcmp(z, "utc")==0 ){
19143        if( p->tzSet==0 ){
19144          sqlite3_int64 c1;
19145          computeJD(p);
19146          c1 = localtimeOffset(p, pCtx, &rc);
19147          if( rc==SQLITE_OK ){
19148            p->iJD -= c1;
19149            clearYMD_HMS_TZ(p);
19150            p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
19151          }
19152          p->tzSet = 1;
19153        }else{
19154          rc = SQLITE_OK;
19155        }
19156      }
19157#endif
19158      break;
19159    }
19160    case 'w': {
19161      /*
19162      **    weekday N
19163      **
19164      ** Move the date to the same time on the next occurrence of
19165      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
19166      ** date is already on the appropriate weekday, this is a no-op.
19167      */
19168      if( strncmp(z, "weekday ", 8)==0
19169               && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
19170               && (n=(int)r)==r && n>=0 && r<7 ){
19171        sqlite3_int64 Z;
19172        computeYMD_HMS(p);
19173        p->validTZ = 0;
19174        p->validJD = 0;
19175        computeJD(p);
19176        Z = ((p->iJD + 129600000)/86400000) % 7;
19177        if( Z>n ) Z -= 7;
19178        p->iJD += (n - Z)*86400000;
19179        clearYMD_HMS_TZ(p);
19180        rc = 0;
19181      }
19182      break;
19183    }
19184    case 's': {
19185      /*
19186      **    start of TTTTT
19187      **
19188      ** Move the date backwards to the beginning of the current day,
19189      ** or month or year.
19190      */
19191      if( strncmp(z, "start of ", 9)!=0 ) break;
19192      z += 9;
19193      computeYMD(p);
19194      p->validHMS = 1;
19195      p->h = p->m = 0;
19196      p->s = 0.0;
19197      p->validTZ = 0;
19198      p->validJD = 0;
19199      if( strcmp(z,"month")==0 ){
19200        p->D = 1;
19201        rc = 0;
19202      }else if( strcmp(z,"year")==0 ){
19203        computeYMD(p);
19204        p->M = 1;
19205        p->D = 1;
19206        rc = 0;
19207      }else if( strcmp(z,"day")==0 ){
19208        rc = 0;
19209      }
19210      break;
19211    }
19212    case '+':
19213    case '-':
19214    case '0':
19215    case '1':
19216    case '2':
19217    case '3':
19218    case '4':
19219    case '5':
19220    case '6':
19221    case '7':
19222    case '8':
19223    case '9': {
19224      double rRounder;
19225      for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
19226      if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
19227        rc = 1;
19228        break;
19229      }
19230      if( z[n]==':' ){
19231        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
19232        ** specified number of hours, minutes, seconds, and fractional seconds
19233        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
19234        ** omitted.
19235        */
19236        const char *z2 = z;
19237        DateTime tx;
19238        sqlite3_int64 day;
19239        if( !sqlite3Isdigit(*z2) ) z2++;
19240        memset(&tx, 0, sizeof(tx));
19241        if( parseHhMmSs(z2, &tx) ) break;
19242        computeJD(&tx);
19243        tx.iJD -= 43200000;
19244        day = tx.iJD/86400000;
19245        tx.iJD -= day*86400000;
19246        if( z[0]=='-' ) tx.iJD = -tx.iJD;
19247        computeJD(p);
19248        clearYMD_HMS_TZ(p);
19249        p->iJD += tx.iJD;
19250        rc = 0;
19251        break;
19252      }
19253      z += n;
19254      while( sqlite3Isspace(*z) ) z++;
19255      n = sqlite3Strlen30(z);
19256      if( n>10 || n<3 ) break;
19257      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
19258      computeJD(p);
19259      rc = 0;
19260      rRounder = r<0 ? -0.5 : +0.5;
19261      if( n==3 && strcmp(z,"day")==0 ){
19262        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
19263      }else if( n==4 && strcmp(z,"hour")==0 ){
19264        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
19265      }else if( n==6 && strcmp(z,"minute")==0 ){
19266        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
19267      }else if( n==6 && strcmp(z,"second")==0 ){
19268        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
19269      }else if( n==5 && strcmp(z,"month")==0 ){
19270        int x, y;
19271        computeYMD_HMS(p);
19272        p->M += (int)r;
19273        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
19274        p->Y += x;
19275        p->M -= x*12;
19276        p->validJD = 0;
19277        computeJD(p);
19278        y = (int)r;
19279        if( y!=r ){
19280          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
19281        }
19282      }else if( n==4 && strcmp(z,"year")==0 ){
19283        int y = (int)r;
19284        computeYMD_HMS(p);
19285        p->Y += y;
19286        p->validJD = 0;
19287        computeJD(p);
19288        if( y!=r ){
19289          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
19290        }
19291      }else{
19292        rc = 1;
19293      }
19294      clearYMD_HMS_TZ(p);
19295      break;
19296    }
19297    default: {
19298      break;
19299    }
19300  }
19301  return rc;
19302}
19303
19304/*
19305** Process time function arguments.  argv[0] is a date-time stamp.
19306** argv[1] and following are modifiers.  Parse them all and write
19307** the resulting time into the DateTime structure p.  Return 0
19308** on success and 1 if there are any errors.
19309**
19310** If there are zero parameters (if even argv[0] is undefined)
19311** then assume a default value of "now" for argv[0].
19312*/
19313static int isDate(
19314  sqlite3_context *context,
19315  int argc,
19316  sqlite3_value **argv,
19317  DateTime *p
19318){
19319  int i;
19320  const unsigned char *z;
19321  int eType;
19322  memset(p, 0, sizeof(*p));
19323  if( argc==0 ){
19324    return setDateTimeToCurrent(context, p);
19325  }
19326  if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
19327                   || eType==SQLITE_INTEGER ){
19328    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
19329    p->validJD = 1;
19330  }else{
19331    z = sqlite3_value_text(argv[0]);
19332    if( !z || parseDateOrTime(context, (char*)z, p) ){
19333      return 1;
19334    }
19335  }
19336  for(i=1; i<argc; i++){
19337    z = sqlite3_value_text(argv[i]);
19338    if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
19339  }
19340  return 0;
19341}
19342
19343
19344/*
19345** The following routines implement the various date and time functions
19346** of SQLite.
19347*/
19348
19349/*
19350**    julianday( TIMESTRING, MOD, MOD, ...)
19351**
19352** Return the julian day number of the date specified in the arguments
19353*/
19354static void juliandayFunc(
19355  sqlite3_context *context,
19356  int argc,
19357  sqlite3_value **argv
19358){
19359  DateTime x;
19360  if( isDate(context, argc, argv, &x)==0 ){
19361    computeJD(&x);
19362    sqlite3_result_double(context, x.iJD/86400000.0);
19363  }
19364}
19365
19366/*
19367**    datetime( TIMESTRING, MOD, MOD, ...)
19368**
19369** Return YYYY-MM-DD HH:MM:SS
19370*/
19371static void datetimeFunc(
19372  sqlite3_context *context,
19373  int argc,
19374  sqlite3_value **argv
19375){
19376  DateTime x;
19377  if( isDate(context, argc, argv, &x)==0 ){
19378    char zBuf[100];
19379    computeYMD_HMS(&x);
19380    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
19381                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
19382    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19383  }
19384}
19385
19386/*
19387**    time( TIMESTRING, MOD, MOD, ...)
19388**
19389** Return HH:MM:SS
19390*/
19391static void timeFunc(
19392  sqlite3_context *context,
19393  int argc,
19394  sqlite3_value **argv
19395){
19396  DateTime x;
19397  if( isDate(context, argc, argv, &x)==0 ){
19398    char zBuf[100];
19399    computeHMS(&x);
19400    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
19401    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19402  }
19403}
19404
19405/*
19406**    date( TIMESTRING, MOD, MOD, ...)
19407**
19408** Return YYYY-MM-DD
19409*/
19410static void dateFunc(
19411  sqlite3_context *context,
19412  int argc,
19413  sqlite3_value **argv
19414){
19415  DateTime x;
19416  if( isDate(context, argc, argv, &x)==0 ){
19417    char zBuf[100];
19418    computeYMD(&x);
19419    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
19420    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19421  }
19422}
19423
19424/*
19425**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
19426**
19427** Return a string described by FORMAT.  Conversions as follows:
19428**
19429**   %d  day of month
19430**   %f  ** fractional seconds  SS.SSS
19431**   %H  hour 00-24
19432**   %j  day of year 000-366
19433**   %J  ** julian day number
19434**   %m  month 01-12
19435**   %M  minute 00-59
19436**   %s  seconds since 1970-01-01
19437**   %S  seconds 00-59
19438**   %w  day of week 0-6  sunday==0
19439**   %W  week of year 00-53
19440**   %Y  year 0000-9999
19441**   %%  %
19442*/
19443static void strftimeFunc(
19444  sqlite3_context *context,
19445  int argc,
19446  sqlite3_value **argv
19447){
19448  DateTime x;
19449  u64 n;
19450  size_t i,j;
19451  char *z;
19452  sqlite3 *db;
19453  const char *zFmt;
19454  char zBuf[100];
19455  if( argc==0 ) return;
19456  zFmt = (const char*)sqlite3_value_text(argv[0]);
19457  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
19458  db = sqlite3_context_db_handle(context);
19459  for(i=0, n=1; zFmt[i]; i++, n++){
19460    if( zFmt[i]=='%' ){
19461      switch( zFmt[i+1] ){
19462        case 'd':
19463        case 'H':
19464        case 'm':
19465        case 'M':
19466        case 'S':
19467        case 'W':
19468          n++;
19469          /* fall thru */
19470        case 'w':
19471        case '%':
19472          break;
19473        case 'f':
19474          n += 8;
19475          break;
19476        case 'j':
19477          n += 3;
19478          break;
19479        case 'Y':
19480          n += 8;
19481          break;
19482        case 's':
19483        case 'J':
19484          n += 50;
19485          break;
19486        default:
19487          return;  /* ERROR.  return a NULL */
19488      }
19489      i++;
19490    }
19491  }
19492  testcase( n==sizeof(zBuf)-1 );
19493  testcase( n==sizeof(zBuf) );
19494  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
19495  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
19496  if( n<sizeof(zBuf) ){
19497    z = zBuf;
19498  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
19499    sqlite3_result_error_toobig(context);
19500    return;
19501  }else{
19502    z = sqlite3DbMallocRawNN(db, (int)n);
19503    if( z==0 ){
19504      sqlite3_result_error_nomem(context);
19505      return;
19506    }
19507  }
19508  computeJD(&x);
19509  computeYMD_HMS(&x);
19510  for(i=j=0; zFmt[i]; i++){
19511    if( zFmt[i]!='%' ){
19512      z[j++] = zFmt[i];
19513    }else{
19514      i++;
19515      switch( zFmt[i] ){
19516        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
19517        case 'f': {
19518          double s = x.s;
19519          if( s>59.999 ) s = 59.999;
19520          sqlite3_snprintf(7, &z[j],"%06.3f", s);
19521          j += sqlite3Strlen30(&z[j]);
19522          break;
19523        }
19524        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
19525        case 'W': /* Fall thru */
19526        case 'j': {
19527          int nDay;             /* Number of days since 1st day of year */
19528          DateTime y = x;
19529          y.validJD = 0;
19530          y.M = 1;
19531          y.D = 1;
19532          computeJD(&y);
19533          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
19534          if( zFmt[i]=='W' ){
19535            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
19536            wd = (int)(((x.iJD+43200000)/86400000)%7);
19537            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
19538            j += 2;
19539          }else{
19540            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
19541            j += 3;
19542          }
19543          break;
19544        }
19545        case 'J': {
19546          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
19547          j+=sqlite3Strlen30(&z[j]);
19548          break;
19549        }
19550        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
19551        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
19552        case 's': {
19553          sqlite3_snprintf(30,&z[j],"%lld",
19554                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
19555          j += sqlite3Strlen30(&z[j]);
19556          break;
19557        }
19558        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
19559        case 'w': {
19560          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
19561          break;
19562        }
19563        case 'Y': {
19564          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
19565          break;
19566        }
19567        default:   z[j++] = '%'; break;
19568      }
19569    }
19570  }
19571  z[j] = 0;
19572  sqlite3_result_text(context, z, -1,
19573                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
19574}
19575
19576/*
19577** current_time()
19578**
19579** This function returns the same value as time('now').
19580*/
19581static void ctimeFunc(
19582  sqlite3_context *context,
19583  int NotUsed,
19584  sqlite3_value **NotUsed2
19585){
19586  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19587  timeFunc(context, 0, 0);
19588}
19589
19590/*
19591** current_date()
19592**
19593** This function returns the same value as date('now').
19594*/
19595static void cdateFunc(
19596  sqlite3_context *context,
19597  int NotUsed,
19598  sqlite3_value **NotUsed2
19599){
19600  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19601  dateFunc(context, 0, 0);
19602}
19603
19604/*
19605** current_timestamp()
19606**
19607** This function returns the same value as datetime('now').
19608*/
19609static void ctimestampFunc(
19610  sqlite3_context *context,
19611  int NotUsed,
19612  sqlite3_value **NotUsed2
19613){
19614  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19615  datetimeFunc(context, 0, 0);
19616}
19617#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
19618
19619#ifdef SQLITE_OMIT_DATETIME_FUNCS
19620/*
19621** If the library is compiled to omit the full-scale date and time
19622** handling (to get a smaller binary), the following minimal version
19623** of the functions current_time(), current_date() and current_timestamp()
19624** are included instead. This is to support column declarations that
19625** include "DEFAULT CURRENT_TIME" etc.
19626**
19627** This function uses the C-library functions time(), gmtime()
19628** and strftime(). The format string to pass to strftime() is supplied
19629** as the user-data for the function.
19630*/
19631static void currentTimeFunc(
19632  sqlite3_context *context,
19633  int argc,
19634  sqlite3_value **argv
19635){
19636  time_t t;
19637  char *zFormat = (char *)sqlite3_user_data(context);
19638  sqlite3_int64 iT;
19639  struct tm *pTm;
19640  struct tm sNow;
19641  char zBuf[20];
19642
19643  UNUSED_PARAMETER(argc);
19644  UNUSED_PARAMETER(argv);
19645
19646  iT = sqlite3StmtCurrentTime(context);
19647  if( iT<=0 ) return;
19648  t = iT/1000 - 10000*(sqlite3_int64)21086676;
19649#if HAVE_GMTIME_R
19650  pTm = gmtime_r(&t, &sNow);
19651#else
19652  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
19653  pTm = gmtime(&t);
19654  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
19655  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
19656#endif
19657  if( pTm ){
19658    strftime(zBuf, 20, zFormat, &sNow);
19659    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19660  }
19661}
19662#endif
19663
19664/*
19665** This function registered all of the above C functions as SQL
19666** functions.  This should be the only routine in this file with
19667** external linkage.
19668*/
19669SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
19670  static FuncDef aDateTimeFuncs[] = {
19671#ifndef SQLITE_OMIT_DATETIME_FUNCS
19672    DFUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
19673    DFUNCTION(date,             -1, 0, 0, dateFunc      ),
19674    DFUNCTION(time,             -1, 0, 0, timeFunc      ),
19675    DFUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
19676    DFUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
19677    DFUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
19678    DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
19679    DFUNCTION(current_date,      0, 0, 0, cdateFunc     ),
19680#else
19681    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
19682    STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
19683    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
19684#endif
19685  };
19686  sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
19687}
19688
19689/************** End of date.c ************************************************/
19690/************** Begin file os.c **********************************************/
19691/*
19692** 2005 November 29
19693**
19694** The author disclaims copyright to this source code.  In place of
19695** a legal notice, here is a blessing:
19696**
19697**    May you do good and not evil.
19698**    May you find forgiveness for yourself and forgive others.
19699**    May you share freely, never taking more than you give.
19700**
19701******************************************************************************
19702**
19703** This file contains OS interface code that is common to all
19704** architectures.
19705*/
19706/* #include "sqliteInt.h" */
19707
19708/*
19709** If we compile with the SQLITE_TEST macro set, then the following block
19710** of code will give us the ability to simulate a disk I/O error.  This
19711** is used for testing the I/O recovery logic.
19712*/
19713#if defined(SQLITE_TEST)
19714SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
19715SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
19716SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
19717SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
19718SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
19719SQLITE_API int sqlite3_diskfull_pending = 0;
19720SQLITE_API int sqlite3_diskfull = 0;
19721#endif /* defined(SQLITE_TEST) */
19722
19723/*
19724** When testing, also keep a count of the number of open files.
19725*/
19726#if defined(SQLITE_TEST)
19727SQLITE_API int sqlite3_open_file_count = 0;
19728#endif /* defined(SQLITE_TEST) */
19729
19730/*
19731** The default SQLite sqlite3_vfs implementations do not allocate
19732** memory (actually, os_unix.c allocates a small amount of memory
19733** from within OsOpen()), but some third-party implementations may.
19734** So we test the effects of a malloc() failing and the sqlite3OsXXX()
19735** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
19736**
19737** The following functions are instrumented for malloc() failure
19738** testing:
19739**
19740**     sqlite3OsRead()
19741**     sqlite3OsWrite()
19742**     sqlite3OsSync()
19743**     sqlite3OsFileSize()
19744**     sqlite3OsLock()
19745**     sqlite3OsCheckReservedLock()
19746**     sqlite3OsFileControl()
19747**     sqlite3OsShmMap()
19748**     sqlite3OsOpen()
19749**     sqlite3OsDelete()
19750**     sqlite3OsAccess()
19751**     sqlite3OsFullPathname()
19752**
19753*/
19754#if defined(SQLITE_TEST)
19755SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
19756  #define DO_OS_MALLOC_TEST(x)                                       \
19757  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
19758    void *pTstAlloc = sqlite3Malloc(10);                             \
19759    if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT;                  \
19760    sqlite3_free(pTstAlloc);                                         \
19761  }
19762#else
19763  #define DO_OS_MALLOC_TEST(x)
19764#endif
19765
19766/*
19767** The following routines are convenience wrappers around methods
19768** of the sqlite3_file object.  This is mostly just syntactic sugar. All
19769** of this would be completely automatic if SQLite were coded using
19770** C++ instead of plain old C.
19771*/
19772SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
19773  if( pId->pMethods ){
19774    pId->pMethods->xClose(pId);
19775    pId->pMethods = 0;
19776  }
19777}
19778SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
19779  DO_OS_MALLOC_TEST(id);
19780  return id->pMethods->xRead(id, pBuf, amt, offset);
19781}
19782SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
19783  DO_OS_MALLOC_TEST(id);
19784  return id->pMethods->xWrite(id, pBuf, amt, offset);
19785}
19786SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
19787  return id->pMethods->xTruncate(id, size);
19788}
19789SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
19790  DO_OS_MALLOC_TEST(id);
19791  return id->pMethods->xSync(id, flags);
19792}
19793SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
19794  DO_OS_MALLOC_TEST(id);
19795  return id->pMethods->xFileSize(id, pSize);
19796}
19797SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
19798  DO_OS_MALLOC_TEST(id);
19799  return id->pMethods->xLock(id, lockType);
19800}
19801SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
19802  return id->pMethods->xUnlock(id, lockType);
19803}
19804SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
19805  DO_OS_MALLOC_TEST(id);
19806  return id->pMethods->xCheckReservedLock(id, pResOut);
19807}
19808
19809/*
19810** Use sqlite3OsFileControl() when we are doing something that might fail
19811** and we need to know about the failures.  Use sqlite3OsFileControlHint()
19812** when simply tossing information over the wall to the VFS and we do not
19813** really care if the VFS receives and understands the information since it
19814** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
19815** routine has no return value since the return value would be meaningless.
19816*/
19817SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
19818#ifdef SQLITE_TEST
19819  if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
19820    /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
19821    ** is using a regular VFS, it is called after the corresponding
19822    ** transaction has been committed. Injecting a fault at this point
19823    ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
19824    ** but the transaction is committed anyway.
19825    **
19826    ** The core must call OsFileControl() though, not OsFileControlHint(),
19827    ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
19828    ** means the commit really has failed and an error should be returned
19829    ** to the user.  */
19830    DO_OS_MALLOC_TEST(id);
19831  }
19832#endif
19833  return id->pMethods->xFileControl(id, op, pArg);
19834}
19835SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
19836  (void)id->pMethods->xFileControl(id, op, pArg);
19837}
19838
19839SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
19840  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
19841  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
19842}
19843SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
19844  return id->pMethods->xDeviceCharacteristics(id);
19845}
19846SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
19847  return id->pMethods->xShmLock(id, offset, n, flags);
19848}
19849SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
19850  id->pMethods->xShmBarrier(id);
19851}
19852SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
19853  return id->pMethods->xShmUnmap(id, deleteFlag);
19854}
19855SQLITE_PRIVATE int sqlite3OsShmMap(
19856  sqlite3_file *id,               /* Database file handle */
19857  int iPage,
19858  int pgsz,
19859  int bExtend,                    /* True to extend file if necessary */
19860  void volatile **pp              /* OUT: Pointer to mapping */
19861){
19862  DO_OS_MALLOC_TEST(id);
19863  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
19864}
19865
19866#if SQLITE_MAX_MMAP_SIZE>0
19867/* The real implementation of xFetch and xUnfetch */
19868SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
19869  DO_OS_MALLOC_TEST(id);
19870  return id->pMethods->xFetch(id, iOff, iAmt, pp);
19871}
19872SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
19873  return id->pMethods->xUnfetch(id, iOff, p);
19874}
19875#else
19876/* No-op stubs to use when memory-mapped I/O is disabled */
19877SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
19878  *pp = 0;
19879  return SQLITE_OK;
19880}
19881SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
19882  return SQLITE_OK;
19883}
19884#endif
19885
19886/*
19887** The next group of routines are convenience wrappers around the
19888** VFS methods.
19889*/
19890SQLITE_PRIVATE int sqlite3OsOpen(
19891  sqlite3_vfs *pVfs,
19892  const char *zPath,
19893  sqlite3_file *pFile,
19894  int flags,
19895  int *pFlagsOut
19896){
19897  int rc;
19898  DO_OS_MALLOC_TEST(0);
19899  /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
19900  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
19901  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
19902  ** reaching the VFS. */
19903  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
19904  assert( rc==SQLITE_OK || pFile->pMethods==0 );
19905  return rc;
19906}
19907SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
19908  DO_OS_MALLOC_TEST(0);
19909  assert( dirSync==0 || dirSync==1 );
19910  return pVfs->xDelete(pVfs, zPath, dirSync);
19911}
19912SQLITE_PRIVATE int sqlite3OsAccess(
19913  sqlite3_vfs *pVfs,
19914  const char *zPath,
19915  int flags,
19916  int *pResOut
19917){
19918  DO_OS_MALLOC_TEST(0);
19919  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
19920}
19921SQLITE_PRIVATE int sqlite3OsFullPathname(
19922  sqlite3_vfs *pVfs,
19923  const char *zPath,
19924  int nPathOut,
19925  char *zPathOut
19926){
19927  DO_OS_MALLOC_TEST(0);
19928  zPathOut[0] = 0;
19929  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
19930}
19931#ifndef SQLITE_OMIT_LOAD_EXTENSION
19932SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
19933  return pVfs->xDlOpen(pVfs, zPath);
19934}
19935SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
19936  pVfs->xDlError(pVfs, nByte, zBufOut);
19937}
19938SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
19939  return pVfs->xDlSym(pVfs, pHdle, zSym);
19940}
19941SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
19942  pVfs->xDlClose(pVfs, pHandle);
19943}
19944#endif /* SQLITE_OMIT_LOAD_EXTENSION */
19945SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
19946  return pVfs->xRandomness(pVfs, nByte, zBufOut);
19947}
19948SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
19949  return pVfs->xSleep(pVfs, nMicro);
19950}
19951SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
19952  return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
19953}
19954SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
19955  int rc;
19956  /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
19957  ** method to get the current date and time if that method is available
19958  ** (if iVersion is 2 or greater and the function pointer is not NULL) and
19959  ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
19960  ** unavailable.
19961  */
19962  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
19963    rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
19964  }else{
19965    double r;
19966    rc = pVfs->xCurrentTime(pVfs, &r);
19967    *pTimeOut = (sqlite3_int64)(r*86400000.0);
19968  }
19969  return rc;
19970}
19971
19972SQLITE_PRIVATE int sqlite3OsOpenMalloc(
19973  sqlite3_vfs *pVfs,
19974  const char *zFile,
19975  sqlite3_file **ppFile,
19976  int flags,
19977  int *pOutFlags
19978){
19979  int rc;
19980  sqlite3_file *pFile;
19981  pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
19982  if( pFile ){
19983    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
19984    if( rc!=SQLITE_OK ){
19985      sqlite3_free(pFile);
19986    }else{
19987      *ppFile = pFile;
19988    }
19989  }else{
19990    rc = SQLITE_NOMEM_BKPT;
19991  }
19992  return rc;
19993}
19994SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
19995  assert( pFile );
19996  sqlite3OsClose(pFile);
19997  sqlite3_free(pFile);
19998}
19999
20000/*
20001** This function is a wrapper around the OS specific implementation of
20002** sqlite3_os_init(). The purpose of the wrapper is to provide the
20003** ability to simulate a malloc failure, so that the handling of an
20004** error in sqlite3_os_init() by the upper layers can be tested.
20005*/
20006SQLITE_PRIVATE int sqlite3OsInit(void){
20007  void *p = sqlite3_malloc(10);
20008  if( p==0 ) return SQLITE_NOMEM_BKPT;
20009  sqlite3_free(p);
20010  return sqlite3_os_init();
20011}
20012
20013/*
20014** The list of all registered VFS implementations.
20015*/
20016static sqlite3_vfs * SQLITE_WSD vfsList = 0;
20017#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
20018
20019/*
20020** Locate a VFS by name.  If no name is given, simply return the
20021** first VFS on the list.
20022*/
20023SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfs){
20024  sqlite3_vfs *pVfs = 0;
20025#if SQLITE_THREADSAFE
20026  sqlite3_mutex *mutex;
20027#endif
20028#ifndef SQLITE_OMIT_AUTOINIT
20029  int rc = sqlite3_initialize();
20030  if( rc ) return 0;
20031#endif
20032#if SQLITE_THREADSAFE
20033  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
20034#endif
20035  sqlite3_mutex_enter(mutex);
20036  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
20037    if( zVfs==0 ) break;
20038    if( strcmp(zVfs, pVfs->zName)==0 ) break;
20039  }
20040  sqlite3_mutex_leave(mutex);
20041  return pVfs;
20042}
20043
20044/*
20045** Unlink a VFS from the linked list
20046*/
20047static void vfsUnlink(sqlite3_vfs *pVfs){
20048  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
20049  if( pVfs==0 ){
20050    /* No-op */
20051  }else if( vfsList==pVfs ){
20052    vfsList = pVfs->pNext;
20053  }else if( vfsList ){
20054    sqlite3_vfs *p = vfsList;
20055    while( p->pNext && p->pNext!=pVfs ){
20056      p = p->pNext;
20057    }
20058    if( p->pNext==pVfs ){
20059      p->pNext = pVfs->pNext;
20060    }
20061  }
20062}
20063
20064/*
20065** Register a VFS with the system.  It is harmless to register the same
20066** VFS multiple times.  The new VFS becomes the default if makeDflt is
20067** true.
20068*/
20069SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
20070  MUTEX_LOGIC(sqlite3_mutex *mutex;)
20071#ifndef SQLITE_OMIT_AUTOINIT
20072  int rc = sqlite3_initialize();
20073  if( rc ) return rc;
20074#endif
20075#ifdef SQLITE_ENABLE_API_ARMOR
20076  if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
20077#endif
20078
20079  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
20080  sqlite3_mutex_enter(mutex);
20081  vfsUnlink(pVfs);
20082  if( makeDflt || vfsList==0 ){
20083    pVfs->pNext = vfsList;
20084    vfsList = pVfs;
20085  }else{
20086    pVfs->pNext = vfsList->pNext;
20087    vfsList->pNext = pVfs;
20088  }
20089  assert(vfsList);
20090  sqlite3_mutex_leave(mutex);
20091  return SQLITE_OK;
20092}
20093
20094/*
20095** Unregister a VFS so that it is no longer accessible.
20096*/
20097SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
20098#if SQLITE_THREADSAFE
20099  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
20100#endif
20101  sqlite3_mutex_enter(mutex);
20102  vfsUnlink(pVfs);
20103  sqlite3_mutex_leave(mutex);
20104  return SQLITE_OK;
20105}
20106
20107/************** End of os.c **************************************************/
20108/************** Begin file fault.c *******************************************/
20109/*
20110** 2008 Jan 22
20111**
20112** The author disclaims copyright to this source code.  In place of
20113** a legal notice, here is a blessing:
20114**
20115**    May you do good and not evil.
20116**    May you find forgiveness for yourself and forgive others.
20117**    May you share freely, never taking more than you give.
20118**
20119*************************************************************************
20120**
20121** This file contains code to support the concept of "benign"
20122** malloc failures (when the xMalloc() or xRealloc() method of the
20123** sqlite3_mem_methods structure fails to allocate a block of memory
20124** and returns 0).
20125**
20126** Most malloc failures are non-benign. After they occur, SQLite
20127** abandons the current operation and returns an error code (usually
20128** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
20129** fatal. For example, if a malloc fails while resizing a hash table, this
20130** is completely recoverable simply by not carrying out the resize. The
20131** hash table will continue to function normally.  So a malloc failure
20132** during a hash table resize is a benign fault.
20133*/
20134
20135/* #include "sqliteInt.h" */
20136
20137#ifndef SQLITE_OMIT_BUILTIN_TEST
20138
20139/*
20140** Global variables.
20141*/
20142typedef struct BenignMallocHooks BenignMallocHooks;
20143static SQLITE_WSD struct BenignMallocHooks {
20144  void (*xBenignBegin)(void);
20145  void (*xBenignEnd)(void);
20146} sqlite3Hooks = { 0, 0 };
20147
20148/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
20149** structure.  If writable static data is unsupported on the target,
20150** we have to locate the state vector at run-time.  In the more common
20151** case where writable static data is supported, wsdHooks can refer directly
20152** to the "sqlite3Hooks" state vector declared above.
20153*/
20154#ifdef SQLITE_OMIT_WSD
20155# define wsdHooksInit \
20156  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
20157# define wsdHooks x[0]
20158#else
20159# define wsdHooksInit
20160# define wsdHooks sqlite3Hooks
20161#endif
20162
20163
20164/*
20165** Register hooks to call when sqlite3BeginBenignMalloc() and
20166** sqlite3EndBenignMalloc() are called, respectively.
20167*/
20168SQLITE_PRIVATE void sqlite3BenignMallocHooks(
20169  void (*xBenignBegin)(void),
20170  void (*xBenignEnd)(void)
20171){
20172  wsdHooksInit;
20173  wsdHooks.xBenignBegin = xBenignBegin;
20174  wsdHooks.xBenignEnd = xBenignEnd;
20175}
20176
20177/*
20178** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
20179** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
20180** indicates that subsequent malloc failures are non-benign.
20181*/
20182SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
20183  wsdHooksInit;
20184  if( wsdHooks.xBenignBegin ){
20185    wsdHooks.xBenignBegin();
20186  }
20187}
20188SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
20189  wsdHooksInit;
20190  if( wsdHooks.xBenignEnd ){
20191    wsdHooks.xBenignEnd();
20192  }
20193}
20194
20195#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
20196
20197/************** End of fault.c ***********************************************/
20198/************** Begin file mem0.c ********************************************/
20199/*
20200** 2008 October 28
20201**
20202** The author disclaims copyright to this source code.  In place of
20203** a legal notice, here is a blessing:
20204**
20205**    May you do good and not evil.
20206**    May you find forgiveness for yourself and forgive others.
20207**    May you share freely, never taking more than you give.
20208**
20209*************************************************************************
20210**
20211** This file contains a no-op memory allocation drivers for use when
20212** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
20213** here always fail.  SQLite will not operate with these drivers.  These
20214** are merely placeholders.  Real drivers must be substituted using
20215** sqlite3_config() before SQLite will operate.
20216*/
20217/* #include "sqliteInt.h" */
20218
20219/*
20220** This version of the memory allocator is the default.  It is
20221** used when no other memory allocator is specified using compile-time
20222** macros.
20223*/
20224#ifdef SQLITE_ZERO_MALLOC
20225
20226/*
20227** No-op versions of all memory allocation routines
20228*/
20229static void *sqlite3MemMalloc(int nByte){ return 0; }
20230static void sqlite3MemFree(void *pPrior){ return; }
20231static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
20232static int sqlite3MemSize(void *pPrior){ return 0; }
20233static int sqlite3MemRoundup(int n){ return n; }
20234static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
20235static void sqlite3MemShutdown(void *NotUsed){ return; }
20236
20237/*
20238** This routine is the only routine in this file with external linkage.
20239**
20240** Populate the low-level memory allocation function pointers in
20241** sqlite3GlobalConfig.m with pointers to the routines in this file.
20242*/
20243SQLITE_PRIVATE void sqlite3MemSetDefault(void){
20244  static const sqlite3_mem_methods defaultMethods = {
20245     sqlite3MemMalloc,
20246     sqlite3MemFree,
20247     sqlite3MemRealloc,
20248     sqlite3MemSize,
20249     sqlite3MemRoundup,
20250     sqlite3MemInit,
20251     sqlite3MemShutdown,
20252     0
20253  };
20254  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20255}
20256
20257#endif /* SQLITE_ZERO_MALLOC */
20258
20259/************** End of mem0.c ************************************************/
20260/************** Begin file mem1.c ********************************************/
20261/*
20262** 2007 August 14
20263**
20264** The author disclaims copyright to this source code.  In place of
20265** a legal notice, here is a blessing:
20266**
20267**    May you do good and not evil.
20268**    May you find forgiveness for yourself and forgive others.
20269**    May you share freely, never taking more than you give.
20270**
20271*************************************************************************
20272**
20273** This file contains low-level memory allocation drivers for when
20274** SQLite will use the standard C-library malloc/realloc/free interface
20275** to obtain the memory it needs.
20276**
20277** This file contains implementations of the low-level memory allocation
20278** routines specified in the sqlite3_mem_methods object.  The content of
20279** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
20280** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
20281** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
20282** default configuration is to use memory allocation routines in this
20283** file.
20284**
20285** C-preprocessor macro summary:
20286**
20287**    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
20288**                                the malloc_usable_size() interface exists
20289**                                on the target platform.  Or, this symbol
20290**                                can be set manually, if desired.
20291**                                If an equivalent interface exists by
20292**                                a different name, using a separate -D
20293**                                option to rename it.
20294**
20295**    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
20296**                                memory allocator.  Set this symbol to enable
20297**                                building on older macs.
20298**
20299**    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
20300**                                _msize() on windows systems.  This might
20301**                                be necessary when compiling for Delphi,
20302**                                for example.
20303*/
20304/* #include "sqliteInt.h" */
20305
20306/*
20307** This version of the memory allocator is the default.  It is
20308** used when no other memory allocator is specified using compile-time
20309** macros.
20310*/
20311#ifdef SQLITE_SYSTEM_MALLOC
20312#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
20313
20314/*
20315** Use the zone allocator available on apple products unless the
20316** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
20317*/
20318#include <sys/sysctl.h>
20319#include <malloc/malloc.h>
20320#include <libkern/OSAtomic.h>
20321static malloc_zone_t* _sqliteZone_;
20322#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
20323#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
20324#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
20325#define SQLITE_MALLOCSIZE(x) \
20326        (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
20327
20328#else /* if not __APPLE__ */
20329
20330/*
20331** Use standard C library malloc and free on non-Apple systems.
20332** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
20333*/
20334#define SQLITE_MALLOC(x)             malloc(x)
20335#define SQLITE_FREE(x)               free(x)
20336#define SQLITE_REALLOC(x,y)          realloc((x),(y))
20337
20338/*
20339** The malloc.h header file is needed for malloc_usable_size() function
20340** on some systems (e.g. Linux).
20341*/
20342#if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
20343#  define SQLITE_USE_MALLOC_H 1
20344#  define SQLITE_USE_MALLOC_USABLE_SIZE 1
20345/*
20346** The MSVCRT has malloc_usable_size(), but it is called _msize().  The
20347** use of _msize() is automatic, but can be disabled by compiling with
20348** -DSQLITE_WITHOUT_MSIZE.  Using the _msize() function also requires
20349** the malloc.h header file.
20350*/
20351#elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
20352#  define SQLITE_USE_MALLOC_H
20353#  define SQLITE_USE_MSIZE
20354#endif
20355
20356/*
20357** Include the malloc.h header file, if necessary.  Also set define macro
20358** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
20359** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
20360** The memory size function can always be overridden manually by defining
20361** the macro SQLITE_MALLOCSIZE to the desired function name.
20362*/
20363#if defined(SQLITE_USE_MALLOC_H)
20364#  include <malloc.h>
20365#  if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
20366#    if !defined(SQLITE_MALLOCSIZE)
20367#      define SQLITE_MALLOCSIZE(x)   malloc_usable_size(x)
20368#    endif
20369#  elif defined(SQLITE_USE_MSIZE)
20370#    if !defined(SQLITE_MALLOCSIZE)
20371#      define SQLITE_MALLOCSIZE      _msize
20372#    endif
20373#  endif
20374#endif /* defined(SQLITE_USE_MALLOC_H) */
20375
20376#endif /* __APPLE__ or not __APPLE__ */
20377
20378/*
20379** Like malloc(), but remember the size of the allocation
20380** so that we can find it later using sqlite3MemSize().
20381**
20382** For this low-level routine, we are guaranteed that nByte>0 because
20383** cases of nByte<=0 will be intercepted and dealt with by higher level
20384** routines.
20385*/
20386static void *sqlite3MemMalloc(int nByte){
20387#ifdef SQLITE_MALLOCSIZE
20388  void *p = SQLITE_MALLOC( nByte );
20389  if( p==0 ){
20390    testcase( sqlite3GlobalConfig.xLog!=0 );
20391    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
20392  }
20393  return p;
20394#else
20395  sqlite3_int64 *p;
20396  assert( nByte>0 );
20397  nByte = ROUND8(nByte);
20398  p = SQLITE_MALLOC( nByte+8 );
20399  if( p ){
20400    p[0] = nByte;
20401    p++;
20402  }else{
20403    testcase( sqlite3GlobalConfig.xLog!=0 );
20404    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
20405  }
20406  return (void *)p;
20407#endif
20408}
20409
20410/*
20411** Like free() but works for allocations obtained from sqlite3MemMalloc()
20412** or sqlite3MemRealloc().
20413**
20414** For this low-level routine, we already know that pPrior!=0 since
20415** cases where pPrior==0 will have been intecepted and dealt with
20416** by higher-level routines.
20417*/
20418static void sqlite3MemFree(void *pPrior){
20419#ifdef SQLITE_MALLOCSIZE
20420  SQLITE_FREE(pPrior);
20421#else
20422  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
20423  assert( pPrior!=0 );
20424  p--;
20425  SQLITE_FREE(p);
20426#endif
20427}
20428
20429/*
20430** Report the allocated size of a prior return from xMalloc()
20431** or xRealloc().
20432*/
20433static int sqlite3MemSize(void *pPrior){
20434#ifdef SQLITE_MALLOCSIZE
20435  assert( pPrior!=0 );
20436  return (int)SQLITE_MALLOCSIZE(pPrior);
20437#else
20438  sqlite3_int64 *p;
20439  assert( pPrior!=0 );
20440  p = (sqlite3_int64*)pPrior;
20441  p--;
20442  return (int)p[0];
20443#endif
20444}
20445
20446/*
20447** Like realloc().  Resize an allocation previously obtained from
20448** sqlite3MemMalloc().
20449**
20450** For this low-level interface, we know that pPrior!=0.  Cases where
20451** pPrior==0 while have been intercepted by higher-level routine and
20452** redirected to xMalloc.  Similarly, we know that nByte>0 because
20453** cases where nByte<=0 will have been intercepted by higher-level
20454** routines and redirected to xFree.
20455*/
20456static void *sqlite3MemRealloc(void *pPrior, int nByte){
20457#ifdef SQLITE_MALLOCSIZE
20458  void *p = SQLITE_REALLOC(pPrior, nByte);
20459  if( p==0 ){
20460    testcase( sqlite3GlobalConfig.xLog!=0 );
20461    sqlite3_log(SQLITE_NOMEM,
20462      "failed memory resize %u to %u bytes",
20463      SQLITE_MALLOCSIZE(pPrior), nByte);
20464  }
20465  return p;
20466#else
20467  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
20468  assert( pPrior!=0 && nByte>0 );
20469  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
20470  p--;
20471  p = SQLITE_REALLOC(p, nByte+8 );
20472  if( p ){
20473    p[0] = nByte;
20474    p++;
20475  }else{
20476    testcase( sqlite3GlobalConfig.xLog!=0 );
20477    sqlite3_log(SQLITE_NOMEM,
20478      "failed memory resize %u to %u bytes",
20479      sqlite3MemSize(pPrior), nByte);
20480  }
20481  return (void*)p;
20482#endif
20483}
20484
20485/*
20486** Round up a request size to the next valid allocation size.
20487*/
20488static int sqlite3MemRoundup(int n){
20489  return ROUND8(n);
20490}
20491
20492/*
20493** Initialize this module.
20494*/
20495static int sqlite3MemInit(void *NotUsed){
20496#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
20497  int cpuCount;
20498  size_t len;
20499  if( _sqliteZone_ ){
20500    return SQLITE_OK;
20501  }
20502  len = sizeof(cpuCount);
20503  /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
20504  sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
20505  if( cpuCount>1 ){
20506    /* defer MT decisions to system malloc */
20507    _sqliteZone_ = malloc_default_zone();
20508  }else{
20509    /* only 1 core, use our own zone to contention over global locks,
20510    ** e.g. we have our own dedicated locks */
20511    bool success;
20512    malloc_zone_t* newzone = malloc_create_zone(4096, 0);
20513    malloc_set_zone_name(newzone, "Sqlite_Heap");
20514    do{
20515      success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
20516                                 (void * volatile *)&_sqliteZone_);
20517    }while(!_sqliteZone_);
20518    if( !success ){
20519      /* somebody registered a zone first */
20520      malloc_destroy_zone(newzone);
20521    }
20522  }
20523#endif
20524  UNUSED_PARAMETER(NotUsed);
20525  return SQLITE_OK;
20526}
20527
20528/*
20529** Deinitialize this module.
20530*/
20531static void sqlite3MemShutdown(void *NotUsed){
20532  UNUSED_PARAMETER(NotUsed);
20533  return;
20534}
20535
20536/*
20537** This routine is the only routine in this file with external linkage.
20538**
20539** Populate the low-level memory allocation function pointers in
20540** sqlite3GlobalConfig.m with pointers to the routines in this file.
20541*/
20542SQLITE_PRIVATE void sqlite3MemSetDefault(void){
20543  static const sqlite3_mem_methods defaultMethods = {
20544     sqlite3MemMalloc,
20545     sqlite3MemFree,
20546     sqlite3MemRealloc,
20547     sqlite3MemSize,
20548     sqlite3MemRoundup,
20549     sqlite3MemInit,
20550     sqlite3MemShutdown,
20551     0
20552  };
20553  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20554}
20555
20556#endif /* SQLITE_SYSTEM_MALLOC */
20557
20558/************** End of mem1.c ************************************************/
20559/************** Begin file mem2.c ********************************************/
20560/*
20561** 2007 August 15
20562**
20563** The author disclaims copyright to this source code.  In place of
20564** a legal notice, here is a blessing:
20565**
20566**    May you do good and not evil.
20567**    May you find forgiveness for yourself and forgive others.
20568**    May you share freely, never taking more than you give.
20569**
20570*************************************************************************
20571**
20572** This file contains low-level memory allocation drivers for when
20573** SQLite will use the standard C-library malloc/realloc/free interface
20574** to obtain the memory it needs while adding lots of additional debugging
20575** information to each allocation in order to help detect and fix memory
20576** leaks and memory usage errors.
20577**
20578** This file contains implementations of the low-level memory allocation
20579** routines specified in the sqlite3_mem_methods object.
20580*/
20581/* #include "sqliteInt.h" */
20582
20583/*
20584** This version of the memory allocator is used only if the
20585** SQLITE_MEMDEBUG macro is defined
20586*/
20587#ifdef SQLITE_MEMDEBUG
20588
20589/*
20590** The backtrace functionality is only available with GLIBC
20591*/
20592#ifdef __GLIBC__
20593  extern int backtrace(void**,int);
20594  extern void backtrace_symbols_fd(void*const*,int,int);
20595#else
20596# define backtrace(A,B) 1
20597# define backtrace_symbols_fd(A,B,C)
20598#endif
20599/* #include <stdio.h> */
20600
20601/*
20602** Each memory allocation looks like this:
20603**
20604**  ------------------------------------------------------------------------
20605**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
20606**  ------------------------------------------------------------------------
20607**
20608** The application code sees only a pointer to the allocation.  We have
20609** to back up from the allocation pointer to find the MemBlockHdr.  The
20610** MemBlockHdr tells us the size of the allocation and the number of
20611** backtrace pointers.  There is also a guard word at the end of the
20612** MemBlockHdr.
20613*/
20614struct MemBlockHdr {
20615  i64 iSize;                          /* Size of this allocation */
20616  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
20617  char nBacktrace;                    /* Number of backtraces on this alloc */
20618  char nBacktraceSlots;               /* Available backtrace slots */
20619  u8 nTitle;                          /* Bytes of title; includes '\0' */
20620  u8 eType;                           /* Allocation type code */
20621  int iForeGuard;                     /* Guard word for sanity */
20622};
20623
20624/*
20625** Guard words
20626*/
20627#define FOREGUARD 0x80F5E153
20628#define REARGUARD 0xE4676B53
20629
20630/*
20631** Number of malloc size increments to track.
20632*/
20633#define NCSIZE  1000
20634
20635/*
20636** All of the static variables used by this module are collected
20637** into a single structure named "mem".  This is to keep the
20638** static variables organized and to reduce namespace pollution
20639** when this module is combined with other in the amalgamation.
20640*/
20641static struct {
20642
20643  /*
20644  ** Mutex to control access to the memory allocation subsystem.
20645  */
20646  sqlite3_mutex *mutex;
20647
20648  /*
20649  ** Head and tail of a linked list of all outstanding allocations
20650  */
20651  struct MemBlockHdr *pFirst;
20652  struct MemBlockHdr *pLast;
20653
20654  /*
20655  ** The number of levels of backtrace to save in new allocations.
20656  */
20657  int nBacktrace;
20658  void (*xBacktrace)(int, int, void **);
20659
20660  /*
20661  ** Title text to insert in front of each block
20662  */
20663  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
20664  char zTitle[100];  /* The title text */
20665
20666  /*
20667  ** sqlite3MallocDisallow() increments the following counter.
20668  ** sqlite3MallocAllow() decrements it.
20669  */
20670  int disallow; /* Do not allow memory allocation */
20671
20672  /*
20673  ** Gather statistics on the sizes of memory allocations.
20674  ** nAlloc[i] is the number of allocation attempts of i*8
20675  ** bytes.  i==NCSIZE is the number of allocation attempts for
20676  ** sizes more than NCSIZE*8 bytes.
20677  */
20678  int nAlloc[NCSIZE];      /* Total number of allocations */
20679  int nCurrent[NCSIZE];    /* Current number of allocations */
20680  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
20681
20682} mem;
20683
20684
20685/*
20686** Adjust memory usage statistics
20687*/
20688static void adjustStats(int iSize, int increment){
20689  int i = ROUND8(iSize)/8;
20690  if( i>NCSIZE-1 ){
20691    i = NCSIZE - 1;
20692  }
20693  if( increment>0 ){
20694    mem.nAlloc[i]++;
20695    mem.nCurrent[i]++;
20696    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
20697      mem.mxCurrent[i] = mem.nCurrent[i];
20698    }
20699  }else{
20700    mem.nCurrent[i]--;
20701    assert( mem.nCurrent[i]>=0 );
20702  }
20703}
20704
20705/*
20706** Given an allocation, find the MemBlockHdr for that allocation.
20707**
20708** This routine checks the guards at either end of the allocation and
20709** if they are incorrect it asserts.
20710*/
20711static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
20712  struct MemBlockHdr *p;
20713  int *pInt;
20714  u8 *pU8;
20715  int nReserve;
20716
20717  p = (struct MemBlockHdr*)pAllocation;
20718  p--;
20719  assert( p->iForeGuard==(int)FOREGUARD );
20720  nReserve = ROUND8(p->iSize);
20721  pInt = (int*)pAllocation;
20722  pU8 = (u8*)pAllocation;
20723  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
20724  /* This checks any of the "extra" bytes allocated due
20725  ** to rounding up to an 8 byte boundary to ensure
20726  ** they haven't been overwritten.
20727  */
20728  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
20729  return p;
20730}
20731
20732/*
20733** Return the number of bytes currently allocated at address p.
20734*/
20735static int sqlite3MemSize(void *p){
20736  struct MemBlockHdr *pHdr;
20737  if( !p ){
20738    return 0;
20739  }
20740  pHdr = sqlite3MemsysGetHeader(p);
20741  return (int)pHdr->iSize;
20742}
20743
20744/*
20745** Initialize the memory allocation subsystem.
20746*/
20747static int sqlite3MemInit(void *NotUsed){
20748  UNUSED_PARAMETER(NotUsed);
20749  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
20750  if( !sqlite3GlobalConfig.bMemstat ){
20751    /* If memory status is enabled, then the malloc.c wrapper will already
20752    ** hold the STATIC_MEM mutex when the routines here are invoked. */
20753    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
20754  }
20755  return SQLITE_OK;
20756}
20757
20758/*
20759** Deinitialize the memory allocation subsystem.
20760*/
20761static void sqlite3MemShutdown(void *NotUsed){
20762  UNUSED_PARAMETER(NotUsed);
20763  mem.mutex = 0;
20764}
20765
20766/*
20767** Round up a request size to the next valid allocation size.
20768*/
20769static int sqlite3MemRoundup(int n){
20770  return ROUND8(n);
20771}
20772
20773/*
20774** Fill a buffer with pseudo-random bytes.  This is used to preset
20775** the content of a new memory allocation to unpredictable values and
20776** to clear the content of a freed allocation to unpredictable values.
20777*/
20778static void randomFill(char *pBuf, int nByte){
20779  unsigned int x, y, r;
20780  x = SQLITE_PTR_TO_INT(pBuf);
20781  y = nByte | 1;
20782  while( nByte >= 4 ){
20783    x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
20784    y = y*1103515245 + 12345;
20785    r = x ^ y;
20786    *(int*)pBuf = r;
20787    pBuf += 4;
20788    nByte -= 4;
20789  }
20790  while( nByte-- > 0 ){
20791    x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
20792    y = y*1103515245 + 12345;
20793    r = x ^ y;
20794    *(pBuf++) = r & 0xff;
20795  }
20796}
20797
20798/*
20799** Allocate nByte bytes of memory.
20800*/
20801static void *sqlite3MemMalloc(int nByte){
20802  struct MemBlockHdr *pHdr;
20803  void **pBt;
20804  char *z;
20805  int *pInt;
20806  void *p = 0;
20807  int totalSize;
20808  int nReserve;
20809  sqlite3_mutex_enter(mem.mutex);
20810  assert( mem.disallow==0 );
20811  nReserve = ROUND8(nByte);
20812  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
20813               mem.nBacktrace*sizeof(void*) + mem.nTitle;
20814  p = malloc(totalSize);
20815  if( p ){
20816    z = p;
20817    pBt = (void**)&z[mem.nTitle];
20818    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
20819    pHdr->pNext = 0;
20820    pHdr->pPrev = mem.pLast;
20821    if( mem.pLast ){
20822      mem.pLast->pNext = pHdr;
20823    }else{
20824      mem.pFirst = pHdr;
20825    }
20826    mem.pLast = pHdr;
20827    pHdr->iForeGuard = FOREGUARD;
20828    pHdr->eType = MEMTYPE_HEAP;
20829    pHdr->nBacktraceSlots = mem.nBacktrace;
20830    pHdr->nTitle = mem.nTitle;
20831    if( mem.nBacktrace ){
20832      void *aAddr[40];
20833      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
20834      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
20835      assert(pBt[0]);
20836      if( mem.xBacktrace ){
20837        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
20838      }
20839    }else{
20840      pHdr->nBacktrace = 0;
20841    }
20842    if( mem.nTitle ){
20843      memcpy(z, mem.zTitle, mem.nTitle);
20844    }
20845    pHdr->iSize = nByte;
20846    adjustStats(nByte, +1);
20847    pInt = (int*)&pHdr[1];
20848    pInt[nReserve/sizeof(int)] = REARGUARD;
20849    randomFill((char*)pInt, nByte);
20850    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
20851    p = (void*)pInt;
20852  }
20853  sqlite3_mutex_leave(mem.mutex);
20854  return p;
20855}
20856
20857/*
20858** Free memory.
20859*/
20860static void sqlite3MemFree(void *pPrior){
20861  struct MemBlockHdr *pHdr;
20862  void **pBt;
20863  char *z;
20864  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
20865       || mem.mutex!=0 );
20866  pHdr = sqlite3MemsysGetHeader(pPrior);
20867  pBt = (void**)pHdr;
20868  pBt -= pHdr->nBacktraceSlots;
20869  sqlite3_mutex_enter(mem.mutex);
20870  if( pHdr->pPrev ){
20871    assert( pHdr->pPrev->pNext==pHdr );
20872    pHdr->pPrev->pNext = pHdr->pNext;
20873  }else{
20874    assert( mem.pFirst==pHdr );
20875    mem.pFirst = pHdr->pNext;
20876  }
20877  if( pHdr->pNext ){
20878    assert( pHdr->pNext->pPrev==pHdr );
20879    pHdr->pNext->pPrev = pHdr->pPrev;
20880  }else{
20881    assert( mem.pLast==pHdr );
20882    mem.pLast = pHdr->pPrev;
20883  }
20884  z = (char*)pBt;
20885  z -= pHdr->nTitle;
20886  adjustStats((int)pHdr->iSize, -1);
20887  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
20888                (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
20889  free(z);
20890  sqlite3_mutex_leave(mem.mutex);
20891}
20892
20893/*
20894** Change the size of an existing memory allocation.
20895**
20896** For this debugging implementation, we *always* make a copy of the
20897** allocation into a new place in memory.  In this way, if the
20898** higher level code is using pointer to the old allocation, it is
20899** much more likely to break and we are much more liking to find
20900** the error.
20901*/
20902static void *sqlite3MemRealloc(void *pPrior, int nByte){
20903  struct MemBlockHdr *pOldHdr;
20904  void *pNew;
20905  assert( mem.disallow==0 );
20906  assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
20907  pOldHdr = sqlite3MemsysGetHeader(pPrior);
20908  pNew = sqlite3MemMalloc(nByte);
20909  if( pNew ){
20910    memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
20911    if( nByte>pOldHdr->iSize ){
20912      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
20913    }
20914    sqlite3MemFree(pPrior);
20915  }
20916  return pNew;
20917}
20918
20919/*
20920** Populate the low-level memory allocation function pointers in
20921** sqlite3GlobalConfig.m with pointers to the routines in this file.
20922*/
20923SQLITE_PRIVATE void sqlite3MemSetDefault(void){
20924  static const sqlite3_mem_methods defaultMethods = {
20925     sqlite3MemMalloc,
20926     sqlite3MemFree,
20927     sqlite3MemRealloc,
20928     sqlite3MemSize,
20929     sqlite3MemRoundup,
20930     sqlite3MemInit,
20931     sqlite3MemShutdown,
20932     0
20933  };
20934  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20935}
20936
20937/*
20938** Set the "type" of an allocation.
20939*/
20940SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
20941  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
20942    struct MemBlockHdr *pHdr;
20943    pHdr = sqlite3MemsysGetHeader(p);
20944    assert( pHdr->iForeGuard==FOREGUARD );
20945    pHdr->eType = eType;
20946  }
20947}
20948
20949/*
20950** Return TRUE if the mask of type in eType matches the type of the
20951** allocation p.  Also return true if p==NULL.
20952**
20953** This routine is designed for use within an assert() statement, to
20954** verify the type of an allocation.  For example:
20955**
20956**     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20957*/
20958SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
20959  int rc = 1;
20960  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
20961    struct MemBlockHdr *pHdr;
20962    pHdr = sqlite3MemsysGetHeader(p);
20963    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
20964    if( (pHdr->eType&eType)==0 ){
20965      rc = 0;
20966    }
20967  }
20968  return rc;
20969}
20970
20971/*
20972** Return TRUE if the mask of type in eType matches no bits of the type of the
20973** allocation p.  Also return true if p==NULL.
20974**
20975** This routine is designed for use within an assert() statement, to
20976** verify the type of an allocation.  For example:
20977**
20978**     assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
20979*/
20980SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
20981  int rc = 1;
20982  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
20983    struct MemBlockHdr *pHdr;
20984    pHdr = sqlite3MemsysGetHeader(p);
20985    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
20986    if( (pHdr->eType&eType)!=0 ){
20987      rc = 0;
20988    }
20989  }
20990  return rc;
20991}
20992
20993/*
20994** Set the number of backtrace levels kept for each allocation.
20995** A value of zero turns off backtracing.  The number is always rounded
20996** up to a multiple of 2.
20997*/
20998SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
20999  if( depth<0 ){ depth = 0; }
21000  if( depth>20 ){ depth = 20; }
21001  depth = (depth+1)&0xfe;
21002  mem.nBacktrace = depth;
21003}
21004
21005SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
21006  mem.xBacktrace = xBacktrace;
21007}
21008
21009/*
21010** Set the title string for subsequent allocations.
21011*/
21012SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
21013  unsigned int n = sqlite3Strlen30(zTitle) + 1;
21014  sqlite3_mutex_enter(mem.mutex);
21015  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
21016  memcpy(mem.zTitle, zTitle, n);
21017  mem.zTitle[n] = 0;
21018  mem.nTitle = ROUND8(n);
21019  sqlite3_mutex_leave(mem.mutex);
21020}
21021
21022SQLITE_PRIVATE void sqlite3MemdebugSync(){
21023  struct MemBlockHdr *pHdr;
21024  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
21025    void **pBt = (void**)pHdr;
21026    pBt -= pHdr->nBacktraceSlots;
21027    mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
21028  }
21029}
21030
21031/*
21032** Open the file indicated and write a log of all unfreed memory
21033** allocations into that log.
21034*/
21035SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
21036  FILE *out;
21037  struct MemBlockHdr *pHdr;
21038  void **pBt;
21039  int i;
21040  out = fopen(zFilename, "w");
21041  if( out==0 ){
21042    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
21043                    zFilename);
21044    return;
21045  }
21046  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
21047    char *z = (char*)pHdr;
21048    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
21049    fprintf(out, "**** %lld bytes at %p from %s ****\n",
21050            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
21051    if( pHdr->nBacktrace ){
21052      fflush(out);
21053      pBt = (void**)pHdr;
21054      pBt -= pHdr->nBacktraceSlots;
21055      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
21056      fprintf(out, "\n");
21057    }
21058  }
21059  fprintf(out, "COUNTS:\n");
21060  for(i=0; i<NCSIZE-1; i++){
21061    if( mem.nAlloc[i] ){
21062      fprintf(out, "   %5d: %10d %10d %10d\n",
21063            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
21064    }
21065  }
21066  if( mem.nAlloc[NCSIZE-1] ){
21067    fprintf(out, "   %5d: %10d %10d %10d\n",
21068             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
21069             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
21070  }
21071  fclose(out);
21072}
21073
21074/*
21075** Return the number of times sqlite3MemMalloc() has been called.
21076*/
21077SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
21078  int i;
21079  int nTotal = 0;
21080  for(i=0; i<NCSIZE; i++){
21081    nTotal += mem.nAlloc[i];
21082  }
21083  return nTotal;
21084}
21085
21086
21087#endif /* SQLITE_MEMDEBUG */
21088
21089/************** End of mem2.c ************************************************/
21090/************** Begin file mem3.c ********************************************/
21091/*
21092** 2007 October 14
21093**
21094** The author disclaims copyright to this source code.  In place of
21095** a legal notice, here is a blessing:
21096**
21097**    May you do good and not evil.
21098**    May you find forgiveness for yourself and forgive others.
21099**    May you share freely, never taking more than you give.
21100**
21101*************************************************************************
21102** This file contains the C functions that implement a memory
21103** allocation subsystem for use by SQLite.
21104**
21105** This version of the memory allocation subsystem omits all
21106** use of malloc(). The SQLite user supplies a block of memory
21107** before calling sqlite3_initialize() from which allocations
21108** are made and returned by the xMalloc() and xRealloc()
21109** implementations. Once sqlite3_initialize() has been called,
21110** the amount of memory available to SQLite is fixed and cannot
21111** be changed.
21112**
21113** This version of the memory allocation subsystem is included
21114** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
21115*/
21116/* #include "sqliteInt.h" */
21117
21118/*
21119** This version of the memory allocator is only built into the library
21120** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
21121** mean that the library will use a memory-pool by default, just that
21122** it is available. The mempool allocator is activated by calling
21123** sqlite3_config().
21124*/
21125#ifdef SQLITE_ENABLE_MEMSYS3
21126
21127/*
21128** Maximum size (in Mem3Blocks) of a "small" chunk.
21129*/
21130#define MX_SMALL 10
21131
21132
21133/*
21134** Number of freelist hash slots
21135*/
21136#define N_HASH  61
21137
21138/*
21139** A memory allocation (also called a "chunk") consists of two or
21140** more blocks where each block is 8 bytes.  The first 8 bytes are
21141** a header that is not returned to the user.
21142**
21143** A chunk is two or more blocks that is either checked out or
21144** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
21145** size of the allocation in blocks if the allocation is free.
21146** The u.hdr.size4x&1 bit is true if the chunk is checked out and
21147** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
21148** is true if the previous chunk is checked out and false if the
21149** previous chunk is free.  The u.hdr.prevSize field is the size of
21150** the previous chunk in blocks if the previous chunk is on the
21151** freelist. If the previous chunk is checked out, then
21152** u.hdr.prevSize can be part of the data for that chunk and should
21153** not be read or written.
21154**
21155** We often identify a chunk by its index in mem3.aPool[].  When
21156** this is done, the chunk index refers to the second block of
21157** the chunk.  In this way, the first chunk has an index of 1.
21158** A chunk index of 0 means "no such chunk" and is the equivalent
21159** of a NULL pointer.
21160**
21161** The second block of free chunks is of the form u.list.  The
21162** two fields form a double-linked list of chunks of related sizes.
21163** Pointers to the head of the list are stored in mem3.aiSmall[]
21164** for smaller chunks and mem3.aiHash[] for larger chunks.
21165**
21166** The second block of a chunk is user data if the chunk is checked
21167** out.  If a chunk is checked out, the user data may extend into
21168** the u.hdr.prevSize value of the following chunk.
21169*/
21170typedef struct Mem3Block Mem3Block;
21171struct Mem3Block {
21172  union {
21173    struct {
21174      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
21175      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
21176    } hdr;
21177    struct {
21178      u32 next;       /* Index in mem3.aPool[] of next free chunk */
21179      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
21180    } list;
21181  } u;
21182};
21183
21184/*
21185** All of the static variables used by this module are collected
21186** into a single structure named "mem3".  This is to keep the
21187** static variables organized and to reduce namespace pollution
21188** when this module is combined with other in the amalgamation.
21189*/
21190static SQLITE_WSD struct Mem3Global {
21191  /*
21192  ** Memory available for allocation. nPool is the size of the array
21193  ** (in Mem3Blocks) pointed to by aPool less 2.
21194  */
21195  u32 nPool;
21196  Mem3Block *aPool;
21197
21198  /*
21199  ** True if we are evaluating an out-of-memory callback.
21200  */
21201  int alarmBusy;
21202
21203  /*
21204  ** Mutex to control access to the memory allocation subsystem.
21205  */
21206  sqlite3_mutex *mutex;
21207
21208  /*
21209  ** The minimum amount of free space that we have seen.
21210  */
21211  u32 mnMaster;
21212
21213  /*
21214  ** iMaster is the index of the master chunk.  Most new allocations
21215  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
21216  ** of the current master.  iMaster is 0 if there is not master chunk.
21217  ** The master chunk is not in either the aiHash[] or aiSmall[].
21218  */
21219  u32 iMaster;
21220  u32 szMaster;
21221
21222  /*
21223  ** Array of lists of free blocks according to the block size
21224  ** for smaller chunks, or a hash on the block size for larger
21225  ** chunks.
21226  */
21227  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
21228  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
21229} mem3 = { 97535575 };
21230
21231#define mem3 GLOBAL(struct Mem3Global, mem3)
21232
21233/*
21234** Unlink the chunk at mem3.aPool[i] from list it is currently
21235** on.  *pRoot is the list that i is a member of.
21236*/
21237static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
21238  u32 next = mem3.aPool[i].u.list.next;
21239  u32 prev = mem3.aPool[i].u.list.prev;
21240  assert( sqlite3_mutex_held(mem3.mutex) );
21241  if( prev==0 ){
21242    *pRoot = next;
21243  }else{
21244    mem3.aPool[prev].u.list.next = next;
21245  }
21246  if( next ){
21247    mem3.aPool[next].u.list.prev = prev;
21248  }
21249  mem3.aPool[i].u.list.next = 0;
21250  mem3.aPool[i].u.list.prev = 0;
21251}
21252
21253/*
21254** Unlink the chunk at index i from
21255** whatever list is currently a member of.
21256*/
21257static void memsys3Unlink(u32 i){
21258  u32 size, hash;
21259  assert( sqlite3_mutex_held(mem3.mutex) );
21260  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
21261  assert( i>=1 );
21262  size = mem3.aPool[i-1].u.hdr.size4x/4;
21263  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
21264  assert( size>=2 );
21265  if( size <= MX_SMALL ){
21266    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
21267  }else{
21268    hash = size % N_HASH;
21269    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
21270  }
21271}
21272
21273/*
21274** Link the chunk at mem3.aPool[i] so that is on the list rooted
21275** at *pRoot.
21276*/
21277static void memsys3LinkIntoList(u32 i, u32 *pRoot){
21278  assert( sqlite3_mutex_held(mem3.mutex) );
21279  mem3.aPool[i].u.list.next = *pRoot;
21280  mem3.aPool[i].u.list.prev = 0;
21281  if( *pRoot ){
21282    mem3.aPool[*pRoot].u.list.prev = i;
21283  }
21284  *pRoot = i;
21285}
21286
21287/*
21288** Link the chunk at index i into either the appropriate
21289** small chunk list, or into the large chunk hash table.
21290*/
21291static void memsys3Link(u32 i){
21292  u32 size, hash;
21293  assert( sqlite3_mutex_held(mem3.mutex) );
21294  assert( i>=1 );
21295  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
21296  size = mem3.aPool[i-1].u.hdr.size4x/4;
21297  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
21298  assert( size>=2 );
21299  if( size <= MX_SMALL ){
21300    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
21301  }else{
21302    hash = size % N_HASH;
21303    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
21304  }
21305}
21306
21307/*
21308** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
21309** will already be held (obtained by code in malloc.c) if
21310** sqlite3GlobalConfig.bMemStat is true.
21311*/
21312static void memsys3Enter(void){
21313  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
21314    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
21315  }
21316  sqlite3_mutex_enter(mem3.mutex);
21317}
21318static void memsys3Leave(void){
21319  sqlite3_mutex_leave(mem3.mutex);
21320}
21321
21322/*
21323** Called when we are unable to satisfy an allocation of nBytes.
21324*/
21325static void memsys3OutOfMemory(int nByte){
21326  if( !mem3.alarmBusy ){
21327    mem3.alarmBusy = 1;
21328    assert( sqlite3_mutex_held(mem3.mutex) );
21329    sqlite3_mutex_leave(mem3.mutex);
21330    sqlite3_release_memory(nByte);
21331    sqlite3_mutex_enter(mem3.mutex);
21332    mem3.alarmBusy = 0;
21333  }
21334}
21335
21336
21337/*
21338** Chunk i is a free chunk that has been unlinked.  Adjust its
21339** size parameters for check-out and return a pointer to the
21340** user portion of the chunk.
21341*/
21342static void *memsys3Checkout(u32 i, u32 nBlock){
21343  u32 x;
21344  assert( sqlite3_mutex_held(mem3.mutex) );
21345  assert( i>=1 );
21346  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
21347  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
21348  x = mem3.aPool[i-1].u.hdr.size4x;
21349  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
21350  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
21351  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
21352  return &mem3.aPool[i];
21353}
21354
21355/*
21356** Carve a piece off of the end of the mem3.iMaster free chunk.
21357** Return a pointer to the new allocation.  Or, if the master chunk
21358** is not large enough, return 0.
21359*/
21360static void *memsys3FromMaster(u32 nBlock){
21361  assert( sqlite3_mutex_held(mem3.mutex) );
21362  assert( mem3.szMaster>=nBlock );
21363  if( nBlock>=mem3.szMaster-1 ){
21364    /* Use the entire master */
21365    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
21366    mem3.iMaster = 0;
21367    mem3.szMaster = 0;
21368    mem3.mnMaster = 0;
21369    return p;
21370  }else{
21371    /* Split the master block.  Return the tail. */
21372    u32 newi, x;
21373    newi = mem3.iMaster + mem3.szMaster - nBlock;
21374    assert( newi > mem3.iMaster+1 );
21375    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
21376    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
21377    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
21378    mem3.szMaster -= nBlock;
21379    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
21380    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21381    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21382    if( mem3.szMaster < mem3.mnMaster ){
21383      mem3.mnMaster = mem3.szMaster;
21384    }
21385    return (void*)&mem3.aPool[newi];
21386  }
21387}
21388
21389/*
21390** *pRoot is the head of a list of free chunks of the same size
21391** or same size hash.  In other words, *pRoot is an entry in either
21392** mem3.aiSmall[] or mem3.aiHash[].
21393**
21394** This routine examines all entries on the given list and tries
21395** to coalesce each entries with adjacent free chunks.
21396**
21397** If it sees a chunk that is larger than mem3.iMaster, it replaces
21398** the current mem3.iMaster with the new larger chunk.  In order for
21399** this mem3.iMaster replacement to work, the master chunk must be
21400** linked into the hash tables.  That is not the normal state of
21401** affairs, of course.  The calling routine must link the master
21402** chunk before invoking this routine, then must unlink the (possibly
21403** changed) master chunk once this routine has finished.
21404*/
21405static void memsys3Merge(u32 *pRoot){
21406  u32 iNext, prev, size, i, x;
21407
21408  assert( sqlite3_mutex_held(mem3.mutex) );
21409  for(i=*pRoot; i>0; i=iNext){
21410    iNext = mem3.aPool[i].u.list.next;
21411    size = mem3.aPool[i-1].u.hdr.size4x;
21412    assert( (size&1)==0 );
21413    if( (size&2)==0 ){
21414      memsys3UnlinkFromList(i, pRoot);
21415      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
21416      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
21417      if( prev==iNext ){
21418        iNext = mem3.aPool[prev].u.list.next;
21419      }
21420      memsys3Unlink(prev);
21421      size = i + size/4 - prev;
21422      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
21423      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
21424      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
21425      memsys3Link(prev);
21426      i = prev;
21427    }else{
21428      size /= 4;
21429    }
21430    if( size>mem3.szMaster ){
21431      mem3.iMaster = i;
21432      mem3.szMaster = size;
21433    }
21434  }
21435}
21436
21437/*
21438** Return a block of memory of at least nBytes in size.
21439** Return NULL if unable.
21440**
21441** This function assumes that the necessary mutexes, if any, are
21442** already held by the caller. Hence "Unsafe".
21443*/
21444static void *memsys3MallocUnsafe(int nByte){
21445  u32 i;
21446  u32 nBlock;
21447  u32 toFree;
21448
21449  assert( sqlite3_mutex_held(mem3.mutex) );
21450  assert( sizeof(Mem3Block)==8 );
21451  if( nByte<=12 ){
21452    nBlock = 2;
21453  }else{
21454    nBlock = (nByte + 11)/8;
21455  }
21456  assert( nBlock>=2 );
21457
21458  /* STEP 1:
21459  ** Look for an entry of the correct size in either the small
21460  ** chunk table or in the large chunk hash table.  This is
21461  ** successful most of the time (about 9 times out of 10).
21462  */
21463  if( nBlock <= MX_SMALL ){
21464    i = mem3.aiSmall[nBlock-2];
21465    if( i>0 ){
21466      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
21467      return memsys3Checkout(i, nBlock);
21468    }
21469  }else{
21470    int hash = nBlock % N_HASH;
21471    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
21472      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
21473        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
21474        return memsys3Checkout(i, nBlock);
21475      }
21476    }
21477  }
21478
21479  /* STEP 2:
21480  ** Try to satisfy the allocation by carving a piece off of the end
21481  ** of the master chunk.  This step usually works if step 1 fails.
21482  */
21483  if( mem3.szMaster>=nBlock ){
21484    return memsys3FromMaster(nBlock);
21485  }
21486
21487
21488  /* STEP 3:
21489  ** Loop through the entire memory pool.  Coalesce adjacent free
21490  ** chunks.  Recompute the master chunk as the largest free chunk.
21491  ** Then try again to satisfy the allocation by carving a piece off
21492  ** of the end of the master chunk.  This step happens very
21493  ** rarely (we hope!)
21494  */
21495  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
21496    memsys3OutOfMemory(toFree);
21497    if( mem3.iMaster ){
21498      memsys3Link(mem3.iMaster);
21499      mem3.iMaster = 0;
21500      mem3.szMaster = 0;
21501    }
21502    for(i=0; i<N_HASH; i++){
21503      memsys3Merge(&mem3.aiHash[i]);
21504    }
21505    for(i=0; i<MX_SMALL-1; i++){
21506      memsys3Merge(&mem3.aiSmall[i]);
21507    }
21508    if( mem3.szMaster ){
21509      memsys3Unlink(mem3.iMaster);
21510      if( mem3.szMaster>=nBlock ){
21511        return memsys3FromMaster(nBlock);
21512      }
21513    }
21514  }
21515
21516  /* If none of the above worked, then we fail. */
21517  return 0;
21518}
21519
21520/*
21521** Free an outstanding memory allocation.
21522**
21523** This function assumes that the necessary mutexes, if any, are
21524** already held by the caller. Hence "Unsafe".
21525*/
21526static void memsys3FreeUnsafe(void *pOld){
21527  Mem3Block *p = (Mem3Block*)pOld;
21528  int i;
21529  u32 size, x;
21530  assert( sqlite3_mutex_held(mem3.mutex) );
21531  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
21532  i = p - mem3.aPool;
21533  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
21534  size = mem3.aPool[i-1].u.hdr.size4x/4;
21535  assert( i+size<=mem3.nPool+1 );
21536  mem3.aPool[i-1].u.hdr.size4x &= ~1;
21537  mem3.aPool[i+size-1].u.hdr.prevSize = size;
21538  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
21539  memsys3Link(i);
21540
21541  /* Try to expand the master using the newly freed chunk */
21542  if( mem3.iMaster ){
21543    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
21544      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
21545      mem3.iMaster -= size;
21546      mem3.szMaster += size;
21547      memsys3Unlink(mem3.iMaster);
21548      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21549      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21550      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
21551    }
21552    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21553    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
21554      memsys3Unlink(mem3.iMaster+mem3.szMaster);
21555      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
21556      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21557      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
21558    }
21559  }
21560}
21561
21562/*
21563** Return the size of an outstanding allocation, in bytes.  The
21564** size returned omits the 8-byte header overhead.  This only
21565** works for chunks that are currently checked out.
21566*/
21567static int memsys3Size(void *p){
21568  Mem3Block *pBlock;
21569  assert( p!=0 );
21570  pBlock = (Mem3Block*)p;
21571  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
21572  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
21573}
21574
21575/*
21576** Round up a request size to the next valid allocation size.
21577*/
21578static int memsys3Roundup(int n){
21579  if( n<=12 ){
21580    return 12;
21581  }else{
21582    return ((n+11)&~7) - 4;
21583  }
21584}
21585
21586/*
21587** Allocate nBytes of memory.
21588*/
21589static void *memsys3Malloc(int nBytes){
21590  sqlite3_int64 *p;
21591  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
21592  memsys3Enter();
21593  p = memsys3MallocUnsafe(nBytes);
21594  memsys3Leave();
21595  return (void*)p;
21596}
21597
21598/*
21599** Free memory.
21600*/
21601static void memsys3Free(void *pPrior){
21602  assert( pPrior );
21603  memsys3Enter();
21604  memsys3FreeUnsafe(pPrior);
21605  memsys3Leave();
21606}
21607
21608/*
21609** Change the size of an existing memory allocation
21610*/
21611static void *memsys3Realloc(void *pPrior, int nBytes){
21612  int nOld;
21613  void *p;
21614  if( pPrior==0 ){
21615    return sqlite3_malloc(nBytes);
21616  }
21617  if( nBytes<=0 ){
21618    sqlite3_free(pPrior);
21619    return 0;
21620  }
21621  nOld = memsys3Size(pPrior);
21622  if( nBytes<=nOld && nBytes>=nOld-128 ){
21623    return pPrior;
21624  }
21625  memsys3Enter();
21626  p = memsys3MallocUnsafe(nBytes);
21627  if( p ){
21628    if( nOld<nBytes ){
21629      memcpy(p, pPrior, nOld);
21630    }else{
21631      memcpy(p, pPrior, nBytes);
21632    }
21633    memsys3FreeUnsafe(pPrior);
21634  }
21635  memsys3Leave();
21636  return p;
21637}
21638
21639/*
21640** Initialize this module.
21641*/
21642static int memsys3Init(void *NotUsed){
21643  UNUSED_PARAMETER(NotUsed);
21644  if( !sqlite3GlobalConfig.pHeap ){
21645    return SQLITE_ERROR;
21646  }
21647
21648  /* Store a pointer to the memory block in global structure mem3. */
21649  assert( sizeof(Mem3Block)==8 );
21650  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
21651  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
21652
21653  /* Initialize the master block. */
21654  mem3.szMaster = mem3.nPool;
21655  mem3.mnMaster = mem3.szMaster;
21656  mem3.iMaster = 1;
21657  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
21658  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
21659  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
21660
21661  return SQLITE_OK;
21662}
21663
21664/*
21665** Deinitialize this module.
21666*/
21667static void memsys3Shutdown(void *NotUsed){
21668  UNUSED_PARAMETER(NotUsed);
21669  mem3.mutex = 0;
21670  return;
21671}
21672
21673
21674
21675/*
21676** Open the file indicated and write a log of all unfreed memory
21677** allocations into that log.
21678*/
21679SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
21680#ifdef SQLITE_DEBUG
21681  FILE *out;
21682  u32 i, j;
21683  u32 size;
21684  if( zFilename==0 || zFilename[0]==0 ){
21685    out = stdout;
21686  }else{
21687    out = fopen(zFilename, "w");
21688    if( out==0 ){
21689      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
21690                      zFilename);
21691      return;
21692    }
21693  }
21694  memsys3Enter();
21695  fprintf(out, "CHUNKS:\n");
21696  for(i=1; i<=mem3.nPool; i+=size/4){
21697    size = mem3.aPool[i-1].u.hdr.size4x;
21698    if( size/4<=1 ){
21699      fprintf(out, "%p size error\n", &mem3.aPool[i]);
21700      assert( 0 );
21701      break;
21702    }
21703    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
21704      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
21705      assert( 0 );
21706      break;
21707    }
21708    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
21709      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
21710      assert( 0 );
21711      break;
21712    }
21713    if( size&1 ){
21714      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
21715    }else{
21716      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
21717                  i==mem3.iMaster ? " **master**" : "");
21718    }
21719  }
21720  for(i=0; i<MX_SMALL-1; i++){
21721    if( mem3.aiSmall[i]==0 ) continue;
21722    fprintf(out, "small(%2d):", i);
21723    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
21724      fprintf(out, " %p(%d)", &mem3.aPool[j],
21725              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
21726    }
21727    fprintf(out, "\n");
21728  }
21729  for(i=0; i<N_HASH; i++){
21730    if( mem3.aiHash[i]==0 ) continue;
21731    fprintf(out, "hash(%2d):", i);
21732    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
21733      fprintf(out, " %p(%d)", &mem3.aPool[j],
21734              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
21735    }
21736    fprintf(out, "\n");
21737  }
21738  fprintf(out, "master=%d\n", mem3.iMaster);
21739  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
21740  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
21741  sqlite3_mutex_leave(mem3.mutex);
21742  if( out==stdout ){
21743    fflush(stdout);
21744  }else{
21745    fclose(out);
21746  }
21747#else
21748  UNUSED_PARAMETER(zFilename);
21749#endif
21750}
21751
21752/*
21753** This routine is the only routine in this file with external
21754** linkage.
21755**
21756** Populate the low-level memory allocation function pointers in
21757** sqlite3GlobalConfig.m with pointers to the routines in this file. The
21758** arguments specify the block of memory to manage.
21759**
21760** This routine is only called by sqlite3_config(), and therefore
21761** is not required to be threadsafe (it is not).
21762*/
21763SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
21764  static const sqlite3_mem_methods mempoolMethods = {
21765     memsys3Malloc,
21766     memsys3Free,
21767     memsys3Realloc,
21768     memsys3Size,
21769     memsys3Roundup,
21770     memsys3Init,
21771     memsys3Shutdown,
21772     0
21773  };
21774  return &mempoolMethods;
21775}
21776
21777#endif /* SQLITE_ENABLE_MEMSYS3 */
21778
21779/************** End of mem3.c ************************************************/
21780/************** Begin file mem5.c ********************************************/
21781/*
21782** 2007 October 14
21783**
21784** The author disclaims copyright to this source code.  In place of
21785** a legal notice, here is a blessing:
21786**
21787**    May you do good and not evil.
21788**    May you find forgiveness for yourself and forgive others.
21789**    May you share freely, never taking more than you give.
21790**
21791*************************************************************************
21792** This file contains the C functions that implement a memory
21793** allocation subsystem for use by SQLite.
21794**
21795** This version of the memory allocation subsystem omits all
21796** use of malloc(). The application gives SQLite a block of memory
21797** before calling sqlite3_initialize() from which allocations
21798** are made and returned by the xMalloc() and xRealloc()
21799** implementations. Once sqlite3_initialize() has been called,
21800** the amount of memory available to SQLite is fixed and cannot
21801** be changed.
21802**
21803** This version of the memory allocation subsystem is included
21804** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
21805**
21806** This memory allocator uses the following algorithm:
21807**
21808**   1.  All memory allocation sizes are rounded up to a power of 2.
21809**
21810**   2.  If two adjacent free blocks are the halves of a larger block,
21811**       then the two blocks are coalesced into the single larger block.
21812**
21813**   3.  New memory is allocated from the first available free block.
21814**
21815** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
21816** Concerning Dynamic Storage Allocation". Journal of the Association for
21817** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
21818**
21819** Let n be the size of the largest allocation divided by the minimum
21820** allocation size (after rounding all sizes up to a power of 2.)  Let M
21821** be the maximum amount of memory ever outstanding at one time.  Let
21822** N be the total amount of memory available for allocation.  Robson
21823** proved that this memory allocator will never breakdown due to
21824** fragmentation as long as the following constraint holds:
21825**
21826**      N >=  M*(1 + log2(n)/2) - n + 1
21827**
21828** The sqlite3_status() logic tracks the maximum values of n and M so
21829** that an application can, at any time, verify this constraint.
21830*/
21831/* #include "sqliteInt.h" */
21832
21833/*
21834** This version of the memory allocator is used only when
21835** SQLITE_ENABLE_MEMSYS5 is defined.
21836*/
21837#ifdef SQLITE_ENABLE_MEMSYS5
21838
21839/*
21840** A minimum allocation is an instance of the following structure.
21841** Larger allocations are an array of these structures where the
21842** size of the array is a power of 2.
21843**
21844** The size of this object must be a power of two.  That fact is
21845** verified in memsys5Init().
21846*/
21847typedef struct Mem5Link Mem5Link;
21848struct Mem5Link {
21849  int next;       /* Index of next free chunk */
21850  int prev;       /* Index of previous free chunk */
21851};
21852
21853/*
21854** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
21855** mem5.szAtom is always at least 8 and 32-bit integers are used,
21856** it is not actually possible to reach this limit.
21857*/
21858#define LOGMAX 30
21859
21860/*
21861** Masks used for mem5.aCtrl[] elements.
21862*/
21863#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
21864#define CTRL_FREE     0x20    /* True if not checked out */
21865
21866/*
21867** All of the static variables used by this module are collected
21868** into a single structure named "mem5".  This is to keep the
21869** static variables organized and to reduce namespace pollution
21870** when this module is combined with other in the amalgamation.
21871*/
21872static SQLITE_WSD struct Mem5Global {
21873  /*
21874  ** Memory available for allocation
21875  */
21876  int szAtom;      /* Smallest possible allocation in bytes */
21877  int nBlock;      /* Number of szAtom sized blocks in zPool */
21878  u8 *zPool;       /* Memory available to be allocated */
21879
21880  /*
21881  ** Mutex to control access to the memory allocation subsystem.
21882  */
21883  sqlite3_mutex *mutex;
21884
21885#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
21886  /*
21887  ** Performance statistics
21888  */
21889  u64 nAlloc;         /* Total number of calls to malloc */
21890  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
21891  u64 totalExcess;    /* Total internal fragmentation */
21892  u32 currentOut;     /* Current checkout, including internal fragmentation */
21893  u32 currentCount;   /* Current number of distinct checkouts */
21894  u32 maxOut;         /* Maximum instantaneous currentOut */
21895  u32 maxCount;       /* Maximum instantaneous currentCount */
21896  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
21897#endif
21898
21899  /*
21900  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
21901  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
21902  ** aiFreelist[2] holds free blocks of size szAtom*4.  And so forth.
21903  */
21904  int aiFreelist[LOGMAX+1];
21905
21906  /*
21907  ** Space for tracking which blocks are checked out and the size
21908  ** of each block.  One byte per block.
21909  */
21910  u8 *aCtrl;
21911
21912} mem5;
21913
21914/*
21915** Access the static variable through a macro for SQLITE_OMIT_WSD.
21916*/
21917#define mem5 GLOBAL(struct Mem5Global, mem5)
21918
21919/*
21920** Assuming mem5.zPool is divided up into an array of Mem5Link
21921** structures, return a pointer to the idx-th such link.
21922*/
21923#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
21924
21925/*
21926** Unlink the chunk at mem5.aPool[i] from list it is currently
21927** on.  It should be found on mem5.aiFreelist[iLogsize].
21928*/
21929static void memsys5Unlink(int i, int iLogsize){
21930  int next, prev;
21931  assert( i>=0 && i<mem5.nBlock );
21932  assert( iLogsize>=0 && iLogsize<=LOGMAX );
21933  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
21934
21935  next = MEM5LINK(i)->next;
21936  prev = MEM5LINK(i)->prev;
21937  if( prev<0 ){
21938    mem5.aiFreelist[iLogsize] = next;
21939  }else{
21940    MEM5LINK(prev)->next = next;
21941  }
21942  if( next>=0 ){
21943    MEM5LINK(next)->prev = prev;
21944  }
21945}
21946
21947/*
21948** Link the chunk at mem5.aPool[i] so that is on the iLogsize
21949** free list.
21950*/
21951static void memsys5Link(int i, int iLogsize){
21952  int x;
21953  assert( sqlite3_mutex_held(mem5.mutex) );
21954  assert( i>=0 && i<mem5.nBlock );
21955  assert( iLogsize>=0 && iLogsize<=LOGMAX );
21956  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
21957
21958  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
21959  MEM5LINK(i)->prev = -1;
21960  if( x>=0 ){
21961    assert( x<mem5.nBlock );
21962    MEM5LINK(x)->prev = i;
21963  }
21964  mem5.aiFreelist[iLogsize] = i;
21965}
21966
21967/*
21968** Obtain or release the mutex needed to access global data structures.
21969*/
21970static void memsys5Enter(void){
21971  sqlite3_mutex_enter(mem5.mutex);
21972}
21973static void memsys5Leave(void){
21974  sqlite3_mutex_leave(mem5.mutex);
21975}
21976
21977/*
21978** Return the size of an outstanding allocation, in bytes.
21979** This only works for chunks that are currently checked out.
21980*/
21981static int memsys5Size(void *p){
21982  int iSize, i;
21983  assert( p!=0 );
21984  i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
21985  assert( i>=0 && i<mem5.nBlock );
21986  iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
21987  return iSize;
21988}
21989
21990/*
21991** Return a block of memory of at least nBytes in size.
21992** Return NULL if unable.  Return NULL if nBytes==0.
21993**
21994** The caller guarantees that nByte is positive.
21995**
21996** The caller has obtained a mutex prior to invoking this
21997** routine so there is never any chance that two or more
21998** threads can be in this routine at the same time.
21999*/
22000static void *memsys5MallocUnsafe(int nByte){
22001  int i;           /* Index of a mem5.aPool[] slot */
22002  int iBin;        /* Index into mem5.aiFreelist[] */
22003  int iFullSz;     /* Size of allocation rounded up to power of 2 */
22004  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
22005
22006  /* nByte must be a positive */
22007  assert( nByte>0 );
22008
22009  /* No more than 1GiB per allocation */
22010  if( nByte > 0x40000000 ) return 0;
22011
22012#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22013  /* Keep track of the maximum allocation request.  Even unfulfilled
22014  ** requests are counted */
22015  if( (u32)nByte>mem5.maxRequest ){
22016    mem5.maxRequest = nByte;
22017  }
22018#endif
22019
22020
22021  /* Round nByte up to the next valid power of two */
22022  for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
22023
22024  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
22025  ** block.  If not, then split a block of the next larger power of
22026  ** two in order to create a new free block of size iLogsize.
22027  */
22028  for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
22029  if( iBin>LOGMAX ){
22030    testcase( sqlite3GlobalConfig.xLog!=0 );
22031    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
22032    return 0;
22033  }
22034  i = mem5.aiFreelist[iBin];
22035  memsys5Unlink(i, iBin);
22036  while( iBin>iLogsize ){
22037    int newSize;
22038
22039    iBin--;
22040    newSize = 1 << iBin;
22041    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
22042    memsys5Link(i+newSize, iBin);
22043  }
22044  mem5.aCtrl[i] = iLogsize;
22045
22046#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22047  /* Update allocator performance statistics. */
22048  mem5.nAlloc++;
22049  mem5.totalAlloc += iFullSz;
22050  mem5.totalExcess += iFullSz - nByte;
22051  mem5.currentCount++;
22052  mem5.currentOut += iFullSz;
22053  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
22054  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
22055#endif
22056
22057#ifdef SQLITE_DEBUG
22058  /* Make sure the allocated memory does not assume that it is set to zero
22059  ** or retains a value from a previous allocation */
22060  memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
22061#endif
22062
22063  /* Return a pointer to the allocated memory. */
22064  return (void*)&mem5.zPool[i*mem5.szAtom];
22065}
22066
22067/*
22068** Free an outstanding memory allocation.
22069*/
22070static void memsys5FreeUnsafe(void *pOld){
22071  u32 size, iLogsize;
22072  int iBlock;
22073
22074  /* Set iBlock to the index of the block pointed to by pOld in
22075  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
22076  */
22077  iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
22078
22079  /* Check that the pointer pOld points to a valid, non-free block. */
22080  assert( iBlock>=0 && iBlock<mem5.nBlock );
22081  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
22082  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
22083
22084  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
22085  size = 1<<iLogsize;
22086  assert( iBlock+size-1<(u32)mem5.nBlock );
22087
22088  mem5.aCtrl[iBlock] |= CTRL_FREE;
22089  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
22090
22091#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22092  assert( mem5.currentCount>0 );
22093  assert( mem5.currentOut>=(size*mem5.szAtom) );
22094  mem5.currentCount--;
22095  mem5.currentOut -= size*mem5.szAtom;
22096  assert( mem5.currentOut>0 || mem5.currentCount==0 );
22097  assert( mem5.currentCount>0 || mem5.currentOut==0 );
22098#endif
22099
22100  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
22101  while( ALWAYS(iLogsize<LOGMAX) ){
22102    int iBuddy;
22103    if( (iBlock>>iLogsize) & 1 ){
22104      iBuddy = iBlock - size;
22105      assert( iBuddy>=0 );
22106    }else{
22107      iBuddy = iBlock + size;
22108      if( iBuddy>=mem5.nBlock ) break;
22109    }
22110    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
22111    memsys5Unlink(iBuddy, iLogsize);
22112    iLogsize++;
22113    if( iBuddy<iBlock ){
22114      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
22115      mem5.aCtrl[iBlock] = 0;
22116      iBlock = iBuddy;
22117    }else{
22118      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
22119      mem5.aCtrl[iBuddy] = 0;
22120    }
22121    size *= 2;
22122  }
22123
22124#ifdef SQLITE_DEBUG
22125  /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
22126  ** not used after being freed */
22127  memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
22128#endif
22129
22130  memsys5Link(iBlock, iLogsize);
22131}
22132
22133/*
22134** Allocate nBytes of memory.
22135*/
22136static void *memsys5Malloc(int nBytes){
22137  sqlite3_int64 *p = 0;
22138  if( nBytes>0 ){
22139    memsys5Enter();
22140    p = memsys5MallocUnsafe(nBytes);
22141    memsys5Leave();
22142  }
22143  return (void*)p;
22144}
22145
22146/*
22147** Free memory.
22148**
22149** The outer layer memory allocator prevents this routine from
22150** being called with pPrior==0.
22151*/
22152static void memsys5Free(void *pPrior){
22153  assert( pPrior!=0 );
22154  memsys5Enter();
22155  memsys5FreeUnsafe(pPrior);
22156  memsys5Leave();
22157}
22158
22159/*
22160** Change the size of an existing memory allocation.
22161**
22162** The outer layer memory allocator prevents this routine from
22163** being called with pPrior==0.
22164**
22165** nBytes is always a value obtained from a prior call to
22166** memsys5Round().  Hence nBytes is always a non-negative power
22167** of two.  If nBytes==0 that means that an oversize allocation
22168** (an allocation larger than 0x40000000) was requested and this
22169** routine should return 0 without freeing pPrior.
22170*/
22171static void *memsys5Realloc(void *pPrior, int nBytes){
22172  int nOld;
22173  void *p;
22174  assert( pPrior!=0 );
22175  assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
22176  assert( nBytes>=0 );
22177  if( nBytes==0 ){
22178    return 0;
22179  }
22180  nOld = memsys5Size(pPrior);
22181  if( nBytes<=nOld ){
22182    return pPrior;
22183  }
22184  p = memsys5Malloc(nBytes);
22185  if( p ){
22186    memcpy(p, pPrior, nOld);
22187    memsys5Free(pPrior);
22188  }
22189  return p;
22190}
22191
22192/*
22193** Round up a request size to the next valid allocation size.  If
22194** the allocation is too large to be handled by this allocation system,
22195** return 0.
22196**
22197** All allocations must be a power of two and must be expressed by a
22198** 32-bit signed integer.  Hence the largest allocation is 0x40000000
22199** or 1073741824 bytes.
22200*/
22201static int memsys5Roundup(int n){
22202  int iFullSz;
22203  if( n > 0x40000000 ) return 0;
22204  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
22205  return iFullSz;
22206}
22207
22208/*
22209** Return the ceiling of the logarithm base 2 of iValue.
22210**
22211** Examples:   memsys5Log(1) -> 0
22212**             memsys5Log(2) -> 1
22213**             memsys5Log(4) -> 2
22214**             memsys5Log(5) -> 3
22215**             memsys5Log(8) -> 3
22216**             memsys5Log(9) -> 4
22217*/
22218static int memsys5Log(int iValue){
22219  int iLog;
22220  for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
22221  return iLog;
22222}
22223
22224/*
22225** Initialize the memory allocator.
22226**
22227** This routine is not threadsafe.  The caller must be holding a mutex
22228** to prevent multiple threads from entering at the same time.
22229*/
22230static int memsys5Init(void *NotUsed){
22231  int ii;            /* Loop counter */
22232  int nByte;         /* Number of bytes of memory available to this allocator */
22233  u8 *zByte;         /* Memory usable by this allocator */
22234  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
22235  int iOffset;       /* An offset into mem5.aCtrl[] */
22236
22237  UNUSED_PARAMETER(NotUsed);
22238
22239  /* For the purposes of this routine, disable the mutex */
22240  mem5.mutex = 0;
22241
22242  /* The size of a Mem5Link object must be a power of two.  Verify that
22243  ** this is case.
22244  */
22245  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
22246
22247  nByte = sqlite3GlobalConfig.nHeap;
22248  zByte = (u8*)sqlite3GlobalConfig.pHeap;
22249  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
22250
22251  /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
22252  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
22253  mem5.szAtom = (1<<nMinLog);
22254  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
22255    mem5.szAtom = mem5.szAtom << 1;
22256  }
22257
22258  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
22259  mem5.zPool = zByte;
22260  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
22261
22262  for(ii=0; ii<=LOGMAX; ii++){
22263    mem5.aiFreelist[ii] = -1;
22264  }
22265
22266  iOffset = 0;
22267  for(ii=LOGMAX; ii>=0; ii--){
22268    int nAlloc = (1<<ii);
22269    if( (iOffset+nAlloc)<=mem5.nBlock ){
22270      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
22271      memsys5Link(iOffset, ii);
22272      iOffset += nAlloc;
22273    }
22274    assert((iOffset+nAlloc)>mem5.nBlock);
22275  }
22276
22277  /* If a mutex is required for normal operation, allocate one */
22278  if( sqlite3GlobalConfig.bMemstat==0 ){
22279    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
22280  }
22281
22282  return SQLITE_OK;
22283}
22284
22285/*
22286** Deinitialize this module.
22287*/
22288static void memsys5Shutdown(void *NotUsed){
22289  UNUSED_PARAMETER(NotUsed);
22290  mem5.mutex = 0;
22291  return;
22292}
22293
22294#ifdef SQLITE_TEST
22295/*
22296** Open the file indicated and write a log of all unfreed memory
22297** allocations into that log.
22298*/
22299SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
22300  FILE *out;
22301  int i, j, n;
22302  int nMinLog;
22303
22304  if( zFilename==0 || zFilename[0]==0 ){
22305    out = stdout;
22306  }else{
22307    out = fopen(zFilename, "w");
22308    if( out==0 ){
22309      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
22310                      zFilename);
22311      return;
22312    }
22313  }
22314  memsys5Enter();
22315  nMinLog = memsys5Log(mem5.szAtom);
22316  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
22317    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
22318    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
22319  }
22320  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
22321  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
22322  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
22323  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
22324  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
22325  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
22326  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
22327  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
22328  memsys5Leave();
22329  if( out==stdout ){
22330    fflush(stdout);
22331  }else{
22332    fclose(out);
22333  }
22334}
22335#endif
22336
22337/*
22338** This routine is the only routine in this file with external
22339** linkage. It returns a pointer to a static sqlite3_mem_methods
22340** struct populated with the memsys5 methods.
22341*/
22342SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
22343  static const sqlite3_mem_methods memsys5Methods = {
22344     memsys5Malloc,
22345     memsys5Free,
22346     memsys5Realloc,
22347     memsys5Size,
22348     memsys5Roundup,
22349     memsys5Init,
22350     memsys5Shutdown,
22351     0
22352  };
22353  return &memsys5Methods;
22354}
22355
22356#endif /* SQLITE_ENABLE_MEMSYS5 */
22357
22358/************** End of mem5.c ************************************************/
22359/************** Begin file mutex.c *******************************************/
22360/*
22361** 2007 August 14
22362**
22363** The author disclaims copyright to this source code.  In place of
22364** a legal notice, here is a blessing:
22365**
22366**    May you do good and not evil.
22367**    May you find forgiveness for yourself and forgive others.
22368**    May you share freely, never taking more than you give.
22369**
22370*************************************************************************
22371** This file contains the C functions that implement mutexes.
22372**
22373** This file contains code that is common across all mutex implementations.
22374*/
22375/* #include "sqliteInt.h" */
22376
22377#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
22378/*
22379** For debugging purposes, record when the mutex subsystem is initialized
22380** and uninitialized so that we can assert() if there is an attempt to
22381** allocate a mutex while the system is uninitialized.
22382*/
22383static SQLITE_WSD int mutexIsInit = 0;
22384#endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
22385
22386
22387#ifndef SQLITE_MUTEX_OMIT
22388/*
22389** Initialize the mutex system.
22390*/
22391SQLITE_PRIVATE int sqlite3MutexInit(void){
22392  int rc = SQLITE_OK;
22393  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
22394    /* If the xMutexAlloc method has not been set, then the user did not
22395    ** install a mutex implementation via sqlite3_config() prior to
22396    ** sqlite3_initialize() being called. This block copies pointers to
22397    ** the default implementation into the sqlite3GlobalConfig structure.
22398    */
22399    sqlite3_mutex_methods const *pFrom;
22400    sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
22401
22402    if( sqlite3GlobalConfig.bCoreMutex ){
22403      pFrom = sqlite3DefaultMutex();
22404    }else{
22405      pFrom = sqlite3NoopMutex();
22406    }
22407    pTo->xMutexInit = pFrom->xMutexInit;
22408    pTo->xMutexEnd = pFrom->xMutexEnd;
22409    pTo->xMutexFree = pFrom->xMutexFree;
22410    pTo->xMutexEnter = pFrom->xMutexEnter;
22411    pTo->xMutexTry = pFrom->xMutexTry;
22412    pTo->xMutexLeave = pFrom->xMutexLeave;
22413    pTo->xMutexHeld = pFrom->xMutexHeld;
22414    pTo->xMutexNotheld = pFrom->xMutexNotheld;
22415    sqlite3MemoryBarrier();
22416    pTo->xMutexAlloc = pFrom->xMutexAlloc;
22417  }
22418  assert( sqlite3GlobalConfig.mutex.xMutexInit );
22419  rc = sqlite3GlobalConfig.mutex.xMutexInit();
22420
22421#ifdef SQLITE_DEBUG
22422  GLOBAL(int, mutexIsInit) = 1;
22423#endif
22424
22425  return rc;
22426}
22427
22428/*
22429** Shutdown the mutex system. This call frees resources allocated by
22430** sqlite3MutexInit().
22431*/
22432SQLITE_PRIVATE int sqlite3MutexEnd(void){
22433  int rc = SQLITE_OK;
22434  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
22435    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
22436  }
22437
22438#ifdef SQLITE_DEBUG
22439  GLOBAL(int, mutexIsInit) = 0;
22440#endif
22441
22442  return rc;
22443}
22444
22445/*
22446** Retrieve a pointer to a static mutex or allocate a new dynamic one.
22447*/
22448SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int id){
22449#ifndef SQLITE_OMIT_AUTOINIT
22450  if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
22451  if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
22452#endif
22453  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
22454  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
22455}
22456
22457SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
22458  if( !sqlite3GlobalConfig.bCoreMutex ){
22459    return 0;
22460  }
22461  assert( GLOBAL(int, mutexIsInit) );
22462  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
22463  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
22464}
22465
22466/*
22467** Free a dynamic mutex.
22468*/
22469SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex *p){
22470  if( p ){
22471    assert( sqlite3GlobalConfig.mutex.xMutexFree );
22472    sqlite3GlobalConfig.mutex.xMutexFree(p);
22473  }
22474}
22475
22476/*
22477** Obtain the mutex p. If some other thread already has the mutex, block
22478** until it can be obtained.
22479*/
22480SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex *p){
22481  if( p ){
22482    assert( sqlite3GlobalConfig.mutex.xMutexEnter );
22483    sqlite3GlobalConfig.mutex.xMutexEnter(p);
22484  }
22485}
22486
22487/*
22488** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
22489** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
22490*/
22491SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex *p){
22492  int rc = SQLITE_OK;
22493  if( p ){
22494    assert( sqlite3GlobalConfig.mutex.xMutexTry );
22495    return sqlite3GlobalConfig.mutex.xMutexTry(p);
22496  }
22497  return rc;
22498}
22499
22500/*
22501** The sqlite3_mutex_leave() routine exits a mutex that was previously
22502** entered by the same thread.  The behavior is undefined if the mutex
22503** is not currently entered. If a NULL pointer is passed as an argument
22504** this function is a no-op.
22505*/
22506SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex *p){
22507  if( p ){
22508    assert( sqlite3GlobalConfig.mutex.xMutexLeave );
22509    sqlite3GlobalConfig.mutex.xMutexLeave(p);
22510  }
22511}
22512
22513#ifndef NDEBUG
22514/*
22515** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22516** intended for use inside assert() statements.
22517*/
22518SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex *p){
22519  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
22520  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
22521}
22522SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex *p){
22523  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
22524  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
22525}
22526#endif
22527
22528#endif /* !defined(SQLITE_MUTEX_OMIT) */
22529
22530/************** End of mutex.c ***********************************************/
22531/************** Begin file mutex_noop.c **************************************/
22532/*
22533** 2008 October 07
22534**
22535** The author disclaims copyright to this source code.  In place of
22536** a legal notice, here is a blessing:
22537**
22538**    May you do good and not evil.
22539**    May you find forgiveness for yourself and forgive others.
22540**    May you share freely, never taking more than you give.
22541**
22542*************************************************************************
22543** This file contains the C functions that implement mutexes.
22544**
22545** This implementation in this file does not provide any mutual
22546** exclusion and is thus suitable for use only in applications
22547** that use SQLite in a single thread.  The routines defined
22548** here are place-holders.  Applications can substitute working
22549** mutex routines at start-time using the
22550**
22551**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
22552**
22553** interface.
22554**
22555** If compiled with SQLITE_DEBUG, then additional logic is inserted
22556** that does error checking on mutexes to make sure they are being
22557** called correctly.
22558*/
22559/* #include "sqliteInt.h" */
22560
22561#ifndef SQLITE_MUTEX_OMIT
22562
22563#ifndef SQLITE_DEBUG
22564/*
22565** Stub routines for all mutex methods.
22566**
22567** This routines provide no mutual exclusion or error checking.
22568*/
22569static int noopMutexInit(void){ return SQLITE_OK; }
22570static int noopMutexEnd(void){ return SQLITE_OK; }
22571static sqlite3_mutex *noopMutexAlloc(int id){
22572  UNUSED_PARAMETER(id);
22573  return (sqlite3_mutex*)8;
22574}
22575static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22576static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22577static int noopMutexTry(sqlite3_mutex *p){
22578  UNUSED_PARAMETER(p);
22579  return SQLITE_OK;
22580}
22581static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22582
22583SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
22584  static const sqlite3_mutex_methods sMutex = {
22585    noopMutexInit,
22586    noopMutexEnd,
22587    noopMutexAlloc,
22588    noopMutexFree,
22589    noopMutexEnter,
22590    noopMutexTry,
22591    noopMutexLeave,
22592
22593    0,
22594    0,
22595  };
22596
22597  return &sMutex;
22598}
22599#endif /* !SQLITE_DEBUG */
22600
22601#ifdef SQLITE_DEBUG
22602/*
22603** In this implementation, error checking is provided for testing
22604** and debugging purposes.  The mutexes still do not provide any
22605** mutual exclusion.
22606*/
22607
22608/*
22609** The mutex object
22610*/
22611typedef struct sqlite3_debug_mutex {
22612  int id;     /* The mutex type */
22613  int cnt;    /* Number of entries without a matching leave */
22614} sqlite3_debug_mutex;
22615
22616/*
22617** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22618** intended for use inside assert() statements.
22619*/
22620static int debugMutexHeld(sqlite3_mutex *pX){
22621  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22622  return p==0 || p->cnt>0;
22623}
22624static int debugMutexNotheld(sqlite3_mutex *pX){
22625  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22626  return p==0 || p->cnt==0;
22627}
22628
22629/*
22630** Initialize and deinitialize the mutex subsystem.
22631*/
22632static int debugMutexInit(void){ return SQLITE_OK; }
22633static int debugMutexEnd(void){ return SQLITE_OK; }
22634
22635/*
22636** The sqlite3_mutex_alloc() routine allocates a new
22637** mutex and returns a pointer to it.  If it returns NULL
22638** that means that a mutex could not be allocated.
22639*/
22640static sqlite3_mutex *debugMutexAlloc(int id){
22641  static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
22642  sqlite3_debug_mutex *pNew = 0;
22643  switch( id ){
22644    case SQLITE_MUTEX_FAST:
22645    case SQLITE_MUTEX_RECURSIVE: {
22646      pNew = sqlite3Malloc(sizeof(*pNew));
22647      if( pNew ){
22648        pNew->id = id;
22649        pNew->cnt = 0;
22650      }
22651      break;
22652    }
22653    default: {
22654#ifdef SQLITE_ENABLE_API_ARMOR
22655      if( id-2<0 || id-2>=ArraySize(aStatic) ){
22656        (void)SQLITE_MISUSE_BKPT;
22657        return 0;
22658      }
22659#endif
22660      pNew = &aStatic[id-2];
22661      pNew->id = id;
22662      break;
22663    }
22664  }
22665  return (sqlite3_mutex*)pNew;
22666}
22667
22668/*
22669** This routine deallocates a previously allocated mutex.
22670*/
22671static void debugMutexFree(sqlite3_mutex *pX){
22672  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22673  assert( p->cnt==0 );
22674  if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
22675    sqlite3_free(p);
22676  }else{
22677#ifdef SQLITE_ENABLE_API_ARMOR
22678    (void)SQLITE_MISUSE_BKPT;
22679#endif
22680  }
22681}
22682
22683/*
22684** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
22685** to enter a mutex.  If another thread is already within the mutex,
22686** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
22687** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
22688** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
22689** be entered multiple times by the same thread.  In such cases the,
22690** mutex must be exited an equal number of times before another thread
22691** can enter.  If the same thread tries to enter any other kind of mutex
22692** more than once, the behavior is undefined.
22693*/
22694static void debugMutexEnter(sqlite3_mutex *pX){
22695  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22696  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22697  p->cnt++;
22698}
22699static int debugMutexTry(sqlite3_mutex *pX){
22700  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22701  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22702  p->cnt++;
22703  return SQLITE_OK;
22704}
22705
22706/*
22707** The sqlite3_mutex_leave() routine exits a mutex that was
22708** previously entered by the same thread.  The behavior
22709** is undefined if the mutex is not currently entered or
22710** is not currently allocated.  SQLite will never do either.
22711*/
22712static void debugMutexLeave(sqlite3_mutex *pX){
22713  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22714  assert( debugMutexHeld(pX) );
22715  p->cnt--;
22716  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22717}
22718
22719SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
22720  static const sqlite3_mutex_methods sMutex = {
22721    debugMutexInit,
22722    debugMutexEnd,
22723    debugMutexAlloc,
22724    debugMutexFree,
22725    debugMutexEnter,
22726    debugMutexTry,
22727    debugMutexLeave,
22728
22729    debugMutexHeld,
22730    debugMutexNotheld
22731  };
22732
22733  return &sMutex;
22734}
22735#endif /* SQLITE_DEBUG */
22736
22737/*
22738** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
22739** is used regardless of the run-time threadsafety setting.
22740*/
22741#ifdef SQLITE_MUTEX_NOOP
22742SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
22743  return sqlite3NoopMutex();
22744}
22745#endif /* defined(SQLITE_MUTEX_NOOP) */
22746#endif /* !defined(SQLITE_MUTEX_OMIT) */
22747
22748/************** End of mutex_noop.c ******************************************/
22749/************** Begin file mutex_unix.c **************************************/
22750/*
22751** 2007 August 28
22752**
22753** The author disclaims copyright to this source code.  In place of
22754** a legal notice, here is a blessing:
22755**
22756**    May you do good and not evil.
22757**    May you find forgiveness for yourself and forgive others.
22758**    May you share freely, never taking more than you give.
22759**
22760*************************************************************************
22761** This file contains the C functions that implement mutexes for pthreads
22762*/
22763/* #include "sqliteInt.h" */
22764
22765/*
22766** The code in this file is only used if we are compiling threadsafe
22767** under unix with pthreads.
22768**
22769** Note that this implementation requires a version of pthreads that
22770** supports recursive mutexes.
22771*/
22772#ifdef SQLITE_MUTEX_PTHREADS
22773
22774#include <pthread.h>
22775
22776/*
22777** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
22778** are necessary under two condidtions:  (1) Debug builds and (2) using
22779** home-grown mutexes.  Encapsulate these conditions into a single #define.
22780*/
22781#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
22782# define SQLITE_MUTEX_NREF 1
22783#else
22784# define SQLITE_MUTEX_NREF 0
22785#endif
22786
22787/*
22788** Each recursive mutex is an instance of the following structure.
22789*/
22790struct sqlite3_mutex {
22791  pthread_mutex_t mutex;     /* Mutex controlling the lock */
22792#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
22793  int id;                    /* Mutex type */
22794#endif
22795#if SQLITE_MUTEX_NREF
22796  volatile int nRef;         /* Number of entrances */
22797  volatile pthread_t owner;  /* Thread that is within this mutex */
22798  int trace;                 /* True to trace changes */
22799#endif
22800};
22801#if SQLITE_MUTEX_NREF
22802#define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0}
22803#elif defined(SQLITE_ENABLE_API_ARMOR)
22804#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 }
22805#else
22806#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
22807#endif
22808
22809/*
22810** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22811** intended for use only inside assert() statements.  On some platforms,
22812** there might be race conditions that can cause these routines to
22813** deliver incorrect results.  In particular, if pthread_equal() is
22814** not an atomic operation, then these routines might delivery
22815** incorrect results.  On most platforms, pthread_equal() is a
22816** comparison of two integers and is therefore atomic.  But we are
22817** told that HPUX is not such a platform.  If so, then these routines
22818** will not always work correctly on HPUX.
22819**
22820** On those platforms where pthread_equal() is not atomic, SQLite
22821** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
22822** make sure no assert() statements are evaluated and hence these
22823** routines are never called.
22824*/
22825#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
22826static int pthreadMutexHeld(sqlite3_mutex *p){
22827  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
22828}
22829static int pthreadMutexNotheld(sqlite3_mutex *p){
22830  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
22831}
22832#endif
22833
22834/*
22835** Try to provide a memory barrier operation, needed for initialization
22836** and also for the implementation of xShmBarrier in the VFS in cases
22837** where SQLite is compiled without mutexes.
22838*/
22839SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
22840#if defined(SQLITE_MEMORY_BARRIER)
22841  SQLITE_MEMORY_BARRIER;
22842#elif defined(__GNUC__) && GCC_VERSION>=4001000
22843  __sync_synchronize();
22844#endif
22845}
22846
22847/*
22848** Initialize and deinitialize the mutex subsystem.
22849*/
22850static int pthreadMutexInit(void){ return SQLITE_OK; }
22851static int pthreadMutexEnd(void){ return SQLITE_OK; }
22852
22853/*
22854** The sqlite3_mutex_alloc() routine allocates a new
22855** mutex and returns a pointer to it.  If it returns NULL
22856** that means that a mutex could not be allocated.  SQLite
22857** will unwind its stack and return an error.  The argument
22858** to sqlite3_mutex_alloc() is one of these integer constants:
22859**
22860** <ul>
22861** <li>  SQLITE_MUTEX_FAST
22862** <li>  SQLITE_MUTEX_RECURSIVE
22863** <li>  SQLITE_MUTEX_STATIC_MASTER
22864** <li>  SQLITE_MUTEX_STATIC_MEM
22865** <li>  SQLITE_MUTEX_STATIC_OPEN
22866** <li>  SQLITE_MUTEX_STATIC_PRNG
22867** <li>  SQLITE_MUTEX_STATIC_LRU
22868** <li>  SQLITE_MUTEX_STATIC_PMEM
22869** <li>  SQLITE_MUTEX_STATIC_APP1
22870** <li>  SQLITE_MUTEX_STATIC_APP2
22871** <li>  SQLITE_MUTEX_STATIC_APP3
22872** <li>  SQLITE_MUTEX_STATIC_VFS1
22873** <li>  SQLITE_MUTEX_STATIC_VFS2
22874** <li>  SQLITE_MUTEX_STATIC_VFS3
22875** </ul>
22876**
22877** The first two constants cause sqlite3_mutex_alloc() to create
22878** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
22879** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
22880** The mutex implementation does not need to make a distinction
22881** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
22882** not want to.  But SQLite will only request a recursive mutex in
22883** cases where it really needs one.  If a faster non-recursive mutex
22884** implementation is available on the host platform, the mutex subsystem
22885** might return such a mutex in response to SQLITE_MUTEX_FAST.
22886**
22887** The other allowed parameters to sqlite3_mutex_alloc() each return
22888** a pointer to a static preexisting mutex.  Six static mutexes are
22889** used by the current version of SQLite.  Future versions of SQLite
22890** may add additional static mutexes.  Static mutexes are for internal
22891** use by SQLite only.  Applications that use SQLite mutexes should
22892** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
22893** SQLITE_MUTEX_RECURSIVE.
22894**
22895** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
22896** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
22897** returns a different mutex on every call.  But for the static
22898** mutex types, the same mutex is returned on every call that has
22899** the same type number.
22900*/
22901static sqlite3_mutex *pthreadMutexAlloc(int iType){
22902  static sqlite3_mutex staticMutexes[] = {
22903    SQLITE3_MUTEX_INITIALIZER,
22904    SQLITE3_MUTEX_INITIALIZER,
22905    SQLITE3_MUTEX_INITIALIZER,
22906    SQLITE3_MUTEX_INITIALIZER,
22907    SQLITE3_MUTEX_INITIALIZER,
22908    SQLITE3_MUTEX_INITIALIZER,
22909    SQLITE3_MUTEX_INITIALIZER,
22910    SQLITE3_MUTEX_INITIALIZER,
22911    SQLITE3_MUTEX_INITIALIZER,
22912    SQLITE3_MUTEX_INITIALIZER,
22913    SQLITE3_MUTEX_INITIALIZER,
22914    SQLITE3_MUTEX_INITIALIZER
22915  };
22916  sqlite3_mutex *p;
22917  switch( iType ){
22918    case SQLITE_MUTEX_RECURSIVE: {
22919      p = sqlite3MallocZero( sizeof(*p) );
22920      if( p ){
22921#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
22922        /* If recursive mutexes are not available, we will have to
22923        ** build our own.  See below. */
22924        pthread_mutex_init(&p->mutex, 0);
22925#else
22926        /* Use a recursive mutex if it is available */
22927        pthread_mutexattr_t recursiveAttr;
22928        pthread_mutexattr_init(&recursiveAttr);
22929        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
22930        pthread_mutex_init(&p->mutex, &recursiveAttr);
22931        pthread_mutexattr_destroy(&recursiveAttr);
22932#endif
22933      }
22934      break;
22935    }
22936    case SQLITE_MUTEX_FAST: {
22937      p = sqlite3MallocZero( sizeof(*p) );
22938      if( p ){
22939        pthread_mutex_init(&p->mutex, 0);
22940      }
22941      break;
22942    }
22943    default: {
22944#ifdef SQLITE_ENABLE_API_ARMOR
22945      if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
22946        (void)SQLITE_MISUSE_BKPT;
22947        return 0;
22948      }
22949#endif
22950      p = &staticMutexes[iType-2];
22951      break;
22952    }
22953  }
22954#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
22955  if( p ) p->id = iType;
22956#endif
22957  return p;
22958}
22959
22960
22961/*
22962** This routine deallocates a previously
22963** allocated mutex.  SQLite is careful to deallocate every
22964** mutex that it allocates.
22965*/
22966static void pthreadMutexFree(sqlite3_mutex *p){
22967  assert( p->nRef==0 );
22968#if SQLITE_ENABLE_API_ARMOR
22969  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
22970#endif
22971  {
22972    pthread_mutex_destroy(&p->mutex);
22973    sqlite3_free(p);
22974  }
22975#ifdef SQLITE_ENABLE_API_ARMOR
22976  else{
22977    (void)SQLITE_MISUSE_BKPT;
22978  }
22979#endif
22980}
22981
22982/*
22983** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
22984** to enter a mutex.  If another thread is already within the mutex,
22985** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
22986** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
22987** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
22988** be entered multiple times by the same thread.  In such cases the,
22989** mutex must be exited an equal number of times before another thread
22990** can enter.  If the same thread tries to enter any other kind of mutex
22991** more than once, the behavior is undefined.
22992*/
22993static void pthreadMutexEnter(sqlite3_mutex *p){
22994  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
22995
22996#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
22997  /* If recursive mutexes are not available, then we have to grow
22998  ** our own.  This implementation assumes that pthread_equal()
22999  ** is atomic - that it cannot be deceived into thinking self
23000  ** and p->owner are equal if p->owner changes between two values
23001  ** that are not equal to self while the comparison is taking place.
23002  ** This implementation also assumes a coherent cache - that
23003  ** separate processes cannot read different values from the same
23004  ** address at the same time.  If either of these two conditions
23005  ** are not met, then the mutexes will fail and problems will result.
23006  */
23007  {
23008    pthread_t self = pthread_self();
23009    if( p->nRef>0 && pthread_equal(p->owner, self) ){
23010      p->nRef++;
23011    }else{
23012      pthread_mutex_lock(&p->mutex);
23013      assert( p->nRef==0 );
23014      p->owner = self;
23015      p->nRef = 1;
23016    }
23017  }
23018#else
23019  /* Use the built-in recursive mutexes if they are available.
23020  */
23021  pthread_mutex_lock(&p->mutex);
23022#if SQLITE_MUTEX_NREF
23023  assert( p->nRef>0 || p->owner==0 );
23024  p->owner = pthread_self();
23025  p->nRef++;
23026#endif
23027#endif
23028
23029#ifdef SQLITE_DEBUG
23030  if( p->trace ){
23031    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23032  }
23033#endif
23034}
23035static int pthreadMutexTry(sqlite3_mutex *p){
23036  int rc;
23037  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
23038
23039#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23040  /* If recursive mutexes are not available, then we have to grow
23041  ** our own.  This implementation assumes that pthread_equal()
23042  ** is atomic - that it cannot be deceived into thinking self
23043  ** and p->owner are equal if p->owner changes between two values
23044  ** that are not equal to self while the comparison is taking place.
23045  ** This implementation also assumes a coherent cache - that
23046  ** separate processes cannot read different values from the same
23047  ** address at the same time.  If either of these two conditions
23048  ** are not met, then the mutexes will fail and problems will result.
23049  */
23050  {
23051    pthread_t self = pthread_self();
23052    if( p->nRef>0 && pthread_equal(p->owner, self) ){
23053      p->nRef++;
23054      rc = SQLITE_OK;
23055    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
23056      assert( p->nRef==0 );
23057      p->owner = self;
23058      p->nRef = 1;
23059      rc = SQLITE_OK;
23060    }else{
23061      rc = SQLITE_BUSY;
23062    }
23063  }
23064#else
23065  /* Use the built-in recursive mutexes if they are available.
23066  */
23067  if( pthread_mutex_trylock(&p->mutex)==0 ){
23068#if SQLITE_MUTEX_NREF
23069    p->owner = pthread_self();
23070    p->nRef++;
23071#endif
23072    rc = SQLITE_OK;
23073  }else{
23074    rc = SQLITE_BUSY;
23075  }
23076#endif
23077
23078#ifdef SQLITE_DEBUG
23079  if( rc==SQLITE_OK && p->trace ){
23080    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23081  }
23082#endif
23083  return rc;
23084}
23085
23086/*
23087** The sqlite3_mutex_leave() routine exits a mutex that was
23088** previously entered by the same thread.  The behavior
23089** is undefined if the mutex is not currently entered or
23090** is not currently allocated.  SQLite will never do either.
23091*/
23092static void pthreadMutexLeave(sqlite3_mutex *p){
23093  assert( pthreadMutexHeld(p) );
23094#if SQLITE_MUTEX_NREF
23095  p->nRef--;
23096  if( p->nRef==0 ) p->owner = 0;
23097#endif
23098  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
23099
23100#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23101  if( p->nRef==0 ){
23102    pthread_mutex_unlock(&p->mutex);
23103  }
23104#else
23105  pthread_mutex_unlock(&p->mutex);
23106#endif
23107
23108#ifdef SQLITE_DEBUG
23109  if( p->trace ){
23110    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23111  }
23112#endif
23113}
23114
23115SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
23116  static const sqlite3_mutex_methods sMutex = {
23117    pthreadMutexInit,
23118    pthreadMutexEnd,
23119    pthreadMutexAlloc,
23120    pthreadMutexFree,
23121    pthreadMutexEnter,
23122    pthreadMutexTry,
23123    pthreadMutexLeave,
23124#ifdef SQLITE_DEBUG
23125    pthreadMutexHeld,
23126    pthreadMutexNotheld
23127#else
23128    0,
23129    0
23130#endif
23131  };
23132
23133  return &sMutex;
23134}
23135
23136#endif /* SQLITE_MUTEX_PTHREADS */
23137
23138/************** End of mutex_unix.c ******************************************/
23139/************** Begin file mutex_w32.c ***************************************/
23140/*
23141** 2007 August 14
23142**
23143** The author disclaims copyright to this source code.  In place of
23144** a legal notice, here is a blessing:
23145**
23146**    May you do good and not evil.
23147**    May you find forgiveness for yourself and forgive others.
23148**    May you share freely, never taking more than you give.
23149**
23150*************************************************************************
23151** This file contains the C functions that implement mutexes for Win32.
23152*/
23153/* #include "sqliteInt.h" */
23154
23155#if SQLITE_OS_WIN
23156/*
23157** Include code that is common to all os_*.c files
23158*/
23159/************** Include os_common.h in the middle of mutex_w32.c *************/
23160/************** Begin file os_common.h ***************************************/
23161/*
23162** 2004 May 22
23163**
23164** The author disclaims copyright to this source code.  In place of
23165** a legal notice, here is a blessing:
23166**
23167**    May you do good and not evil.
23168**    May you find forgiveness for yourself and forgive others.
23169**    May you share freely, never taking more than you give.
23170**
23171******************************************************************************
23172**
23173** This file contains macros and a little bit of code that is common to
23174** all of the platform-specific files (os_*.c) and is #included into those
23175** files.
23176**
23177** This file should be #included by the os_*.c files only.  It is not a
23178** general purpose header file.
23179*/
23180#ifndef _OS_COMMON_H_
23181#define _OS_COMMON_H_
23182
23183/*
23184** At least two bugs have slipped in because we changed the MEMORY_DEBUG
23185** macro to SQLITE_DEBUG and some older makefiles have not yet made the
23186** switch.  The following code should catch this problem at compile-time.
23187*/
23188#ifdef MEMORY_DEBUG
23189# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
23190#endif
23191
23192/*
23193** Macros for performance tracing.  Normally turned off.  Only works
23194** on i486 hardware.
23195*/
23196#ifdef SQLITE_PERFORMANCE_TRACE
23197
23198/*
23199** hwtime.h contains inline assembler code for implementing
23200** high-performance timing routines.
23201*/
23202/************** Include hwtime.h in the middle of os_common.h ****************/
23203/************** Begin file hwtime.h ******************************************/
23204/*
23205** 2008 May 27
23206**
23207** The author disclaims copyright to this source code.  In place of
23208** a legal notice, here is a blessing:
23209**
23210**    May you do good and not evil.
23211**    May you find forgiveness for yourself and forgive others.
23212**    May you share freely, never taking more than you give.
23213**
23214******************************************************************************
23215**
23216** This file contains inline asm code for retrieving "high-performance"
23217** counters for x86 class CPUs.
23218*/
23219#ifndef SQLITE_HWTIME_H
23220#define SQLITE_HWTIME_H
23221
23222/*
23223** The following routine only works on pentium-class (or newer) processors.
23224** It uses the RDTSC opcode to read the cycle count value out of the
23225** processor and returns that value.  This can be used for high-res
23226** profiling.
23227*/
23228#if (defined(__GNUC__) || defined(_MSC_VER)) && \
23229      (defined(i386) || defined(__i386__) || defined(_M_IX86))
23230
23231  #if defined(__GNUC__)
23232
23233  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23234     unsigned int lo, hi;
23235     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23236     return (sqlite_uint64)hi << 32 | lo;
23237  }
23238
23239  #elif defined(_MSC_VER)
23240
23241  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23242     __asm {
23243        rdtsc
23244        ret       ; return value at EDX:EAX
23245     }
23246  }
23247
23248  #endif
23249
23250#elif (defined(__GNUC__) && defined(__x86_64__))
23251
23252  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23253      unsigned long val;
23254      __asm__ __volatile__ ("rdtsc" : "=A" (val));
23255      return val;
23256  }
23257
23258#elif (defined(__GNUC__) && defined(__ppc__))
23259
23260  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23261      unsigned long long retval;
23262      unsigned long junk;
23263      __asm__ __volatile__ ("\n\
23264          1:      mftbu   %1\n\
23265                  mftb    %L0\n\
23266                  mftbu   %0\n\
23267                  cmpw    %0,%1\n\
23268                  bne     1b"
23269                  : "=r" (retval), "=r" (junk));
23270      return retval;
23271  }
23272
23273#else
23274
23275  #error Need implementation of sqlite3Hwtime() for your platform.
23276
23277  /*
23278  ** To compile without implementing sqlite3Hwtime() for your platform,
23279  ** you can remove the above #error and use the following
23280  ** stub function.  You will lose timing support for many
23281  ** of the debugging and testing utilities, but it should at
23282  ** least compile and run.
23283  */
23284SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23285
23286#endif
23287
23288#endif /* !defined(SQLITE_HWTIME_H) */
23289
23290/************** End of hwtime.h **********************************************/
23291/************** Continuing where we left off in os_common.h ******************/
23292
23293static sqlite_uint64 g_start;
23294static sqlite_uint64 g_elapsed;
23295#define TIMER_START       g_start=sqlite3Hwtime()
23296#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
23297#define TIMER_ELAPSED     g_elapsed
23298#else
23299#define TIMER_START
23300#define TIMER_END
23301#define TIMER_ELAPSED     ((sqlite_uint64)0)
23302#endif
23303
23304/*
23305** If we compile with the SQLITE_TEST macro set, then the following block
23306** of code will give us the ability to simulate a disk I/O error.  This
23307** is used for testing the I/O recovery logic.
23308*/
23309#if defined(SQLITE_TEST)
23310SQLITE_API extern int sqlite3_io_error_hit;
23311SQLITE_API extern int sqlite3_io_error_hardhit;
23312SQLITE_API extern int sqlite3_io_error_pending;
23313SQLITE_API extern int sqlite3_io_error_persist;
23314SQLITE_API extern int sqlite3_io_error_benign;
23315SQLITE_API extern int sqlite3_diskfull_pending;
23316SQLITE_API extern int sqlite3_diskfull;
23317#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23318#define SimulateIOError(CODE)  \
23319  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23320       || sqlite3_io_error_pending-- == 1 )  \
23321              { local_ioerr(); CODE; }
23322static void local_ioerr(){
23323  IOTRACE(("IOERR\n"));
23324  sqlite3_io_error_hit++;
23325  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23326}
23327#define SimulateDiskfullError(CODE) \
23328   if( sqlite3_diskfull_pending ){ \
23329     if( sqlite3_diskfull_pending == 1 ){ \
23330       local_ioerr(); \
23331       sqlite3_diskfull = 1; \
23332       sqlite3_io_error_hit = 1; \
23333       CODE; \
23334     }else{ \
23335       sqlite3_diskfull_pending--; \
23336     } \
23337   }
23338#else
23339#define SimulateIOErrorBenign(X)
23340#define SimulateIOError(A)
23341#define SimulateDiskfullError(A)
23342#endif /* defined(SQLITE_TEST) */
23343
23344/*
23345** When testing, keep a count of the number of open files.
23346*/
23347#if defined(SQLITE_TEST)
23348SQLITE_API extern int sqlite3_open_file_count;
23349#define OpenCounter(X)  sqlite3_open_file_count+=(X)
23350#else
23351#define OpenCounter(X)
23352#endif /* defined(SQLITE_TEST) */
23353
23354#endif /* !defined(_OS_COMMON_H_) */
23355
23356/************** End of os_common.h *******************************************/
23357/************** Continuing where we left off in mutex_w32.c ******************/
23358
23359/*
23360** Include the header file for the Windows VFS.
23361*/
23362/************** Include os_win.h in the middle of mutex_w32.c ****************/
23363/************** Begin file os_win.h ******************************************/
23364/*
23365** 2013 November 25
23366**
23367** The author disclaims copyright to this source code.  In place of
23368** a legal notice, here is a blessing:
23369**
23370**    May you do good and not evil.
23371**    May you find forgiveness for yourself and forgive others.
23372**    May you share freely, never taking more than you give.
23373**
23374******************************************************************************
23375**
23376** This file contains code that is specific to Windows.
23377*/
23378#ifndef SQLITE_OS_WIN_H
23379#define SQLITE_OS_WIN_H
23380
23381/*
23382** Include the primary Windows SDK header file.
23383*/
23384#include "windows.h"
23385
23386#ifdef __CYGWIN__
23387# include <sys/cygwin.h>
23388# include <errno.h> /* amalgamator: dontcache */
23389#endif
23390
23391/*
23392** Determine if we are dealing with Windows NT.
23393**
23394** We ought to be able to determine if we are compiling for Windows 9x or
23395** Windows NT using the _WIN32_WINNT macro as follows:
23396**
23397** #if defined(_WIN32_WINNT)
23398** # define SQLITE_OS_WINNT 1
23399** #else
23400** # define SQLITE_OS_WINNT 0
23401** #endif
23402**
23403** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
23404** it ought to, so the above test does not work.  We'll just assume that
23405** everything is Windows NT unless the programmer explicitly says otherwise
23406** by setting SQLITE_OS_WINNT to 0.
23407*/
23408#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
23409# define SQLITE_OS_WINNT 1
23410#endif
23411
23412/*
23413** Determine if we are dealing with Windows CE - which has a much reduced
23414** API.
23415*/
23416#if defined(_WIN32_WCE)
23417# define SQLITE_OS_WINCE 1
23418#else
23419# define SQLITE_OS_WINCE 0
23420#endif
23421
23422/*
23423** Determine if we are dealing with WinRT, which provides only a subset of
23424** the full Win32 API.
23425*/
23426#if !defined(SQLITE_OS_WINRT)
23427# define SQLITE_OS_WINRT 0
23428#endif
23429
23430/*
23431** For WinCE, some API function parameters do not appear to be declared as
23432** volatile.
23433*/
23434#if SQLITE_OS_WINCE
23435# define SQLITE_WIN32_VOLATILE
23436#else
23437# define SQLITE_WIN32_VOLATILE volatile
23438#endif
23439
23440/*
23441** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
23442** functions are not available (e.g. those not using MSVC, Cygwin, etc).
23443*/
23444#if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
23445    SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
23446# define SQLITE_OS_WIN_THREADS 1
23447#else
23448# define SQLITE_OS_WIN_THREADS 0
23449#endif
23450
23451#endif /* SQLITE_OS_WIN_H */
23452
23453/************** End of os_win.h **********************************************/
23454/************** Continuing where we left off in mutex_w32.c ******************/
23455#endif
23456
23457/*
23458** The code in this file is only used if we are compiling multithreaded
23459** on a Win32 system.
23460*/
23461#ifdef SQLITE_MUTEX_W32
23462
23463/*
23464** Each recursive mutex is an instance of the following structure.
23465*/
23466struct sqlite3_mutex {
23467  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
23468  int id;                    /* Mutex type */
23469#ifdef SQLITE_DEBUG
23470  volatile int nRef;         /* Number of enterances */
23471  volatile DWORD owner;      /* Thread holding this mutex */
23472  volatile int trace;        /* True to trace changes */
23473#endif
23474};
23475
23476/*
23477** These are the initializer values used when declaring a "static" mutex
23478** on Win32.  It should be noted that all mutexes require initialization
23479** on the Win32 platform.
23480*/
23481#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
23482
23483#ifdef SQLITE_DEBUG
23484#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
23485                                    0L, (DWORD)0, 0 }
23486#else
23487#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
23488#endif
23489
23490#ifdef SQLITE_DEBUG
23491/*
23492** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
23493** intended for use only inside assert() statements.
23494*/
23495static int winMutexHeld(sqlite3_mutex *p){
23496  return p->nRef!=0 && p->owner==GetCurrentThreadId();
23497}
23498
23499static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
23500  return p->nRef==0 || p->owner!=tid;
23501}
23502
23503static int winMutexNotheld(sqlite3_mutex *p){
23504  DWORD tid = GetCurrentThreadId();
23505  return winMutexNotheld2(p, tid);
23506}
23507#endif
23508
23509/*
23510** Try to provide a memory barrier operation, needed for initialization
23511** and also for the xShmBarrier method of the VFS in cases when SQLite is
23512** compiled without mutexes (SQLITE_THREADSAFE=0).
23513*/
23514SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
23515#if defined(SQLITE_MEMORY_BARRIER)
23516  SQLITE_MEMORY_BARRIER;
23517#elif defined(__GNUC__)
23518  __sync_synchronize();
23519#elif !defined(SQLITE_DISABLE_INTRINSIC) && \
23520      defined(_MSC_VER) && _MSC_VER>=1300
23521  _ReadWriteBarrier();
23522#elif defined(MemoryBarrier)
23523  MemoryBarrier();
23524#endif
23525}
23526
23527/*
23528** Initialize and deinitialize the mutex subsystem.
23529*/
23530static sqlite3_mutex winMutex_staticMutexes[] = {
23531  SQLITE3_MUTEX_INITIALIZER,
23532  SQLITE3_MUTEX_INITIALIZER,
23533  SQLITE3_MUTEX_INITIALIZER,
23534  SQLITE3_MUTEX_INITIALIZER,
23535  SQLITE3_MUTEX_INITIALIZER,
23536  SQLITE3_MUTEX_INITIALIZER,
23537  SQLITE3_MUTEX_INITIALIZER,
23538  SQLITE3_MUTEX_INITIALIZER,
23539  SQLITE3_MUTEX_INITIALIZER,
23540  SQLITE3_MUTEX_INITIALIZER,
23541  SQLITE3_MUTEX_INITIALIZER,
23542  SQLITE3_MUTEX_INITIALIZER
23543};
23544
23545static int winMutex_isInit = 0;
23546static int winMutex_isNt = -1; /* <0 means "need to query" */
23547
23548/* As the winMutexInit() and winMutexEnd() functions are called as part
23549** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
23550** "interlocked" magic used here is probably not strictly necessary.
23551*/
23552static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
23553
23554SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void); /* os_win.c */
23555SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
23556
23557static int winMutexInit(void){
23558  /* The first to increment to 1 does actual initialization */
23559  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
23560    int i;
23561    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
23562#if SQLITE_OS_WINRT
23563      InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
23564#else
23565      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
23566#endif
23567    }
23568    winMutex_isInit = 1;
23569  }else{
23570    /* Another thread is (in the process of) initializing the static
23571    ** mutexes */
23572    while( !winMutex_isInit ){
23573      sqlite3_win32_sleep(1);
23574    }
23575  }
23576  return SQLITE_OK;
23577}
23578
23579static int winMutexEnd(void){
23580  /* The first to decrement to 0 does actual shutdown
23581  ** (which should be the last to shutdown.) */
23582  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
23583    if( winMutex_isInit==1 ){
23584      int i;
23585      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
23586        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
23587      }
23588      winMutex_isInit = 0;
23589    }
23590  }
23591  return SQLITE_OK;
23592}
23593
23594/*
23595** The sqlite3_mutex_alloc() routine allocates a new
23596** mutex and returns a pointer to it.  If it returns NULL
23597** that means that a mutex could not be allocated.  SQLite
23598** will unwind its stack and return an error.  The argument
23599** to sqlite3_mutex_alloc() is one of these integer constants:
23600**
23601** <ul>
23602** <li>  SQLITE_MUTEX_FAST
23603** <li>  SQLITE_MUTEX_RECURSIVE
23604** <li>  SQLITE_MUTEX_STATIC_MASTER
23605** <li>  SQLITE_MUTEX_STATIC_MEM
23606** <li>  SQLITE_MUTEX_STATIC_OPEN
23607** <li>  SQLITE_MUTEX_STATIC_PRNG
23608** <li>  SQLITE_MUTEX_STATIC_LRU
23609** <li>  SQLITE_MUTEX_STATIC_PMEM
23610** <li>  SQLITE_MUTEX_STATIC_APP1
23611** <li>  SQLITE_MUTEX_STATIC_APP2
23612** <li>  SQLITE_MUTEX_STATIC_APP3
23613** <li>  SQLITE_MUTEX_STATIC_VFS1
23614** <li>  SQLITE_MUTEX_STATIC_VFS2
23615** <li>  SQLITE_MUTEX_STATIC_VFS3
23616** </ul>
23617**
23618** The first two constants cause sqlite3_mutex_alloc() to create
23619** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
23620** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
23621** The mutex implementation does not need to make a distinction
23622** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
23623** not want to.  But SQLite will only request a recursive mutex in
23624** cases where it really needs one.  If a faster non-recursive mutex
23625** implementation is available on the host platform, the mutex subsystem
23626** might return such a mutex in response to SQLITE_MUTEX_FAST.
23627**
23628** The other allowed parameters to sqlite3_mutex_alloc() each return
23629** a pointer to a static preexisting mutex.  Six static mutexes are
23630** used by the current version of SQLite.  Future versions of SQLite
23631** may add additional static mutexes.  Static mutexes are for internal
23632** use by SQLite only.  Applications that use SQLite mutexes should
23633** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
23634** SQLITE_MUTEX_RECURSIVE.
23635**
23636** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
23637** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
23638** returns a different mutex on every call.  But for the static
23639** mutex types, the same mutex is returned on every call that has
23640** the same type number.
23641*/
23642static sqlite3_mutex *winMutexAlloc(int iType){
23643  sqlite3_mutex *p;
23644
23645  switch( iType ){
23646    case SQLITE_MUTEX_FAST:
23647    case SQLITE_MUTEX_RECURSIVE: {
23648      p = sqlite3MallocZero( sizeof(*p) );
23649      if( p ){
23650        p->id = iType;
23651#ifdef SQLITE_DEBUG
23652#ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
23653        p->trace = 1;
23654#endif
23655#endif
23656#if SQLITE_OS_WINRT
23657        InitializeCriticalSectionEx(&p->mutex, 0, 0);
23658#else
23659        InitializeCriticalSection(&p->mutex);
23660#endif
23661      }
23662      break;
23663    }
23664    default: {
23665#ifdef SQLITE_ENABLE_API_ARMOR
23666      if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
23667        (void)SQLITE_MISUSE_BKPT;
23668        return 0;
23669      }
23670#endif
23671      p = &winMutex_staticMutexes[iType-2];
23672      p->id = iType;
23673#ifdef SQLITE_DEBUG
23674#ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
23675      p->trace = 1;
23676#endif
23677#endif
23678      break;
23679    }
23680  }
23681  return p;
23682}
23683
23684
23685/*
23686** This routine deallocates a previously
23687** allocated mutex.  SQLite is careful to deallocate every
23688** mutex that it allocates.
23689*/
23690static void winMutexFree(sqlite3_mutex *p){
23691  assert( p );
23692  assert( p->nRef==0 && p->owner==0 );
23693  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
23694    DeleteCriticalSection(&p->mutex);
23695    sqlite3_free(p);
23696  }else{
23697#ifdef SQLITE_ENABLE_API_ARMOR
23698    (void)SQLITE_MISUSE_BKPT;
23699#endif
23700  }
23701}
23702
23703/*
23704** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
23705** to enter a mutex.  If another thread is already within the mutex,
23706** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
23707** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
23708** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
23709** be entered multiple times by the same thread.  In such cases the,
23710** mutex must be exited an equal number of times before another thread
23711** can enter.  If the same thread tries to enter any other kind of mutex
23712** more than once, the behavior is undefined.
23713*/
23714static void winMutexEnter(sqlite3_mutex *p){
23715#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23716  DWORD tid = GetCurrentThreadId();
23717#endif
23718#ifdef SQLITE_DEBUG
23719  assert( p );
23720  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
23721#else
23722  assert( p );
23723#endif
23724  assert( winMutex_isInit==1 );
23725  EnterCriticalSection(&p->mutex);
23726#ifdef SQLITE_DEBUG
23727  assert( p->nRef>0 || p->owner==0 );
23728  p->owner = tid;
23729  p->nRef++;
23730  if( p->trace ){
23731    OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
23732             tid, p, p->trace, p->nRef));
23733  }
23734#endif
23735}
23736
23737static int winMutexTry(sqlite3_mutex *p){
23738#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23739  DWORD tid = GetCurrentThreadId();
23740#endif
23741  int rc = SQLITE_BUSY;
23742  assert( p );
23743  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
23744  /*
23745  ** The sqlite3_mutex_try() routine is very rarely used, and when it
23746  ** is used it is merely an optimization.  So it is OK for it to always
23747  ** fail.
23748  **
23749  ** The TryEnterCriticalSection() interface is only available on WinNT.
23750  ** And some windows compilers complain if you try to use it without
23751  ** first doing some #defines that prevent SQLite from building on Win98.
23752  ** For that reason, we will omit this optimization for now.  See
23753  ** ticket #2685.
23754  */
23755#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
23756  assert( winMutex_isInit==1 );
23757  assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
23758  if( winMutex_isNt<0 ){
23759    winMutex_isNt = sqlite3_win32_is_nt();
23760  }
23761  assert( winMutex_isNt==0 || winMutex_isNt==1 );
23762  if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
23763#ifdef SQLITE_DEBUG
23764    p->owner = tid;
23765    p->nRef++;
23766#endif
23767    rc = SQLITE_OK;
23768  }
23769#else
23770  UNUSED_PARAMETER(p);
23771#endif
23772#ifdef SQLITE_DEBUG
23773  if( p->trace ){
23774    OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
23775             tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
23776  }
23777#endif
23778  return rc;
23779}
23780
23781/*
23782** The sqlite3_mutex_leave() routine exits a mutex that was
23783** previously entered by the same thread.  The behavior
23784** is undefined if the mutex is not currently entered or
23785** is not currently allocated.  SQLite will never do either.
23786*/
23787static void winMutexLeave(sqlite3_mutex *p){
23788#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23789  DWORD tid = GetCurrentThreadId();
23790#endif
23791  assert( p );
23792#ifdef SQLITE_DEBUG
23793  assert( p->nRef>0 );
23794  assert( p->owner==tid );
23795  p->nRef--;
23796  if( p->nRef==0 ) p->owner = 0;
23797  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
23798#endif
23799  assert( winMutex_isInit==1 );
23800  LeaveCriticalSection(&p->mutex);
23801#ifdef SQLITE_DEBUG
23802  if( p->trace ){
23803    OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
23804             tid, p, p->trace, p->nRef));
23805  }
23806#endif
23807}
23808
23809SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
23810  static const sqlite3_mutex_methods sMutex = {
23811    winMutexInit,
23812    winMutexEnd,
23813    winMutexAlloc,
23814    winMutexFree,
23815    winMutexEnter,
23816    winMutexTry,
23817    winMutexLeave,
23818#ifdef SQLITE_DEBUG
23819    winMutexHeld,
23820    winMutexNotheld
23821#else
23822    0,
23823    0
23824#endif
23825  };
23826  return &sMutex;
23827}
23828
23829#endif /* SQLITE_MUTEX_W32 */
23830
23831/************** End of mutex_w32.c *******************************************/
23832/************** Begin file malloc.c ******************************************/
23833/*
23834** 2001 September 15
23835**
23836** The author disclaims copyright to this source code.  In place of
23837** a legal notice, here is a blessing:
23838**
23839**    May you do good and not evil.
23840**    May you find forgiveness for yourself and forgive others.
23841**    May you share freely, never taking more than you give.
23842**
23843*************************************************************************
23844**
23845** Memory allocation functions used throughout sqlite.
23846*/
23847/* #include "sqliteInt.h" */
23848/* #include <stdarg.h> */
23849
23850/*
23851** Attempt to release up to n bytes of non-essential memory currently
23852** held by SQLite. An example of non-essential memory is memory used to
23853** cache database pages that are not currently in use.
23854*/
23855SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int n){
23856#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23857  return sqlite3PcacheReleaseMemory(n);
23858#else
23859  /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
23860  ** is a no-op returning zero if SQLite is not compiled with
23861  ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
23862  UNUSED_PARAMETER(n);
23863  return 0;
23864#endif
23865}
23866
23867/*
23868** An instance of the following object records the location of
23869** each unused scratch buffer.
23870*/
23871typedef struct ScratchFreeslot {
23872  struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
23873} ScratchFreeslot;
23874
23875/*
23876** State information local to the memory allocation subsystem.
23877*/
23878static SQLITE_WSD struct Mem0Global {
23879  sqlite3_mutex *mutex;         /* Mutex to serialize access */
23880  sqlite3_int64 alarmThreshold; /* The soft heap limit */
23881
23882  /*
23883  ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
23884  ** (so that a range test can be used to determine if an allocation
23885  ** being freed came from pScratch) and a pointer to the list of
23886  ** unused scratch allocations.
23887  */
23888  void *pScratchEnd;
23889  ScratchFreeslot *pScratchFree;
23890  u32 nScratchFree;
23891
23892  /*
23893  ** True if heap is nearly "full" where "full" is defined by the
23894  ** sqlite3_soft_heap_limit() setting.
23895  */
23896  int nearlyFull;
23897} mem0 = { 0, 0, 0, 0, 0, 0 };
23898
23899#define mem0 GLOBAL(struct Mem0Global, mem0)
23900
23901/*
23902** Return the memory allocator mutex. sqlite3_status() needs it.
23903*/
23904SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
23905  return mem0.mutex;
23906}
23907
23908#ifndef SQLITE_OMIT_DEPRECATED
23909/*
23910** Deprecated external interface.  It used to set an alarm callback
23911** that was invoked when memory usage grew too large.  Now it is a
23912** no-op.
23913*/
23914SQLITE_API int SQLITE_STDCALL sqlite3_memory_alarm(
23915  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
23916  void *pArg,
23917  sqlite3_int64 iThreshold
23918){
23919  (void)xCallback;
23920  (void)pArg;
23921  (void)iThreshold;
23922  return SQLITE_OK;
23923}
23924#endif
23925
23926/*
23927** Set the soft heap-size limit for the library. Passing a zero or
23928** negative value indicates no limit.
23929*/
23930SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 n){
23931  sqlite3_int64 priorLimit;
23932  sqlite3_int64 excess;
23933  sqlite3_int64 nUsed;
23934#ifndef SQLITE_OMIT_AUTOINIT
23935  int rc = sqlite3_initialize();
23936  if( rc ) return -1;
23937#endif
23938  sqlite3_mutex_enter(mem0.mutex);
23939  priorLimit = mem0.alarmThreshold;
23940  if( n<0 ){
23941    sqlite3_mutex_leave(mem0.mutex);
23942    return priorLimit;
23943  }
23944  mem0.alarmThreshold = n;
23945  nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
23946  mem0.nearlyFull = (n>0 && n<=nUsed);
23947  sqlite3_mutex_leave(mem0.mutex);
23948  excess = sqlite3_memory_used() - n;
23949  if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
23950  return priorLimit;
23951}
23952SQLITE_API void SQLITE_STDCALL sqlite3_soft_heap_limit(int n){
23953  if( n<0 ) n = 0;
23954  sqlite3_soft_heap_limit64(n);
23955}
23956
23957/*
23958** Initialize the memory allocation subsystem.
23959*/
23960SQLITE_PRIVATE int sqlite3MallocInit(void){
23961  int rc;
23962  if( sqlite3GlobalConfig.m.xMalloc==0 ){
23963    sqlite3MemSetDefault();
23964  }
23965  memset(&mem0, 0, sizeof(mem0));
23966  mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
23967  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
23968      && sqlite3GlobalConfig.nScratch>0 ){
23969    int i, n, sz;
23970    ScratchFreeslot *pSlot;
23971    sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
23972    sqlite3GlobalConfig.szScratch = sz;
23973    pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
23974    n = sqlite3GlobalConfig.nScratch;
23975    mem0.pScratchFree = pSlot;
23976    mem0.nScratchFree = n;
23977    for(i=0; i<n-1; i++){
23978      pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
23979      pSlot = pSlot->pNext;
23980    }
23981    pSlot->pNext = 0;
23982    mem0.pScratchEnd = (void*)&pSlot[1];
23983  }else{
23984    mem0.pScratchEnd = 0;
23985    sqlite3GlobalConfig.pScratch = 0;
23986    sqlite3GlobalConfig.szScratch = 0;
23987    sqlite3GlobalConfig.nScratch = 0;
23988  }
23989  if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
23990      || sqlite3GlobalConfig.nPage<=0 ){
23991    sqlite3GlobalConfig.pPage = 0;
23992    sqlite3GlobalConfig.szPage = 0;
23993  }
23994  rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
23995  if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
23996  return rc;
23997}
23998
23999/*
24000** Return true if the heap is currently under memory pressure - in other
24001** words if the amount of heap used is close to the limit set by
24002** sqlite3_soft_heap_limit().
24003*/
24004SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
24005  return mem0.nearlyFull;
24006}
24007
24008/*
24009** Deinitialize the memory allocation subsystem.
24010*/
24011SQLITE_PRIVATE void sqlite3MallocEnd(void){
24012  if( sqlite3GlobalConfig.m.xShutdown ){
24013    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
24014  }
24015  memset(&mem0, 0, sizeof(mem0));
24016}
24017
24018/*
24019** Return the amount of memory currently checked out.
24020*/
24021SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void){
24022  sqlite3_int64 res, mx;
24023  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
24024  return res;
24025}
24026
24027/*
24028** Return the maximum amount of memory that has ever been
24029** checked out since either the beginning of this process
24030** or since the most recent reset.
24031*/
24032SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag){
24033  sqlite3_int64 res, mx;
24034  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
24035  return mx;
24036}
24037
24038/*
24039** Trigger the alarm
24040*/
24041static void sqlite3MallocAlarm(int nByte){
24042  if( mem0.alarmThreshold<=0 ) return;
24043  sqlite3_mutex_leave(mem0.mutex);
24044  sqlite3_release_memory(nByte);
24045  sqlite3_mutex_enter(mem0.mutex);
24046}
24047
24048/*
24049** Do a memory allocation with statistics and alarms.  Assume the
24050** lock is already held.
24051*/
24052static int mallocWithAlarm(int n, void **pp){
24053  int nFull;
24054  void *p;
24055  assert( sqlite3_mutex_held(mem0.mutex) );
24056  nFull = sqlite3GlobalConfig.m.xRoundup(n);
24057  sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
24058  if( mem0.alarmThreshold>0 ){
24059    sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
24060    if( nUsed >= mem0.alarmThreshold - nFull ){
24061      mem0.nearlyFull = 1;
24062      sqlite3MallocAlarm(nFull);
24063    }else{
24064      mem0.nearlyFull = 0;
24065    }
24066  }
24067  p = sqlite3GlobalConfig.m.xMalloc(nFull);
24068#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24069  if( p==0 && mem0.alarmThreshold>0 ){
24070    sqlite3MallocAlarm(nFull);
24071    p = sqlite3GlobalConfig.m.xMalloc(nFull);
24072  }
24073#endif
24074  if( p ){
24075    nFull = sqlite3MallocSize(p);
24076    sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
24077    sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
24078  }
24079  *pp = p;
24080  return nFull;
24081}
24082
24083/*
24084** Allocate memory.  This routine is like sqlite3_malloc() except that it
24085** assumes the memory subsystem has already been initialized.
24086*/
24087SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
24088  void *p;
24089  if( n==0 || n>=0x7fffff00 ){
24090    /* A memory allocation of a number of bytes which is near the maximum
24091    ** signed integer value might cause an integer overflow inside of the
24092    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
24093    ** 255 bytes of overhead.  SQLite itself will never use anything near
24094    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
24095    p = 0;
24096  }else if( sqlite3GlobalConfig.bMemstat ){
24097    sqlite3_mutex_enter(mem0.mutex);
24098    mallocWithAlarm((int)n, &p);
24099    sqlite3_mutex_leave(mem0.mutex);
24100  }else{
24101    p = sqlite3GlobalConfig.m.xMalloc((int)n);
24102  }
24103  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-11148-40995 */
24104  return p;
24105}
24106
24107/*
24108** This version of the memory allocation is for use by the application.
24109** First make sure the memory subsystem is initialized, then do the
24110** allocation.
24111*/
24112SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int n){
24113#ifndef SQLITE_OMIT_AUTOINIT
24114  if( sqlite3_initialize() ) return 0;
24115#endif
24116  return n<=0 ? 0 : sqlite3Malloc(n);
24117}
24118SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64 n){
24119#ifndef SQLITE_OMIT_AUTOINIT
24120  if( sqlite3_initialize() ) return 0;
24121#endif
24122  return sqlite3Malloc(n);
24123}
24124
24125/*
24126** Each thread may only have a single outstanding allocation from
24127** xScratchMalloc().  We verify this constraint in the single-threaded
24128** case by setting scratchAllocOut to 1 when an allocation
24129** is outstanding clearing it when the allocation is freed.
24130*/
24131#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24132static int scratchAllocOut = 0;
24133#endif
24134
24135
24136/*
24137** Allocate memory that is to be used and released right away.
24138** This routine is similar to alloca() in that it is not intended
24139** for situations where the memory might be held long-term.  This
24140** routine is intended to get memory to old large transient data
24141** structures that would not normally fit on the stack of an
24142** embedded processor.
24143*/
24144SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
24145  void *p;
24146  assert( n>0 );
24147
24148  sqlite3_mutex_enter(mem0.mutex);
24149  sqlite3StatusHighwater(SQLITE_STATUS_SCRATCH_SIZE, n);
24150  if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
24151    p = mem0.pScratchFree;
24152    mem0.pScratchFree = mem0.pScratchFree->pNext;
24153    mem0.nScratchFree--;
24154    sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
24155    sqlite3_mutex_leave(mem0.mutex);
24156  }else{
24157    sqlite3_mutex_leave(mem0.mutex);
24158    p = sqlite3Malloc(n);
24159    if( sqlite3GlobalConfig.bMemstat && p ){
24160      sqlite3_mutex_enter(mem0.mutex);
24161      sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
24162      sqlite3_mutex_leave(mem0.mutex);
24163    }
24164    sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
24165  }
24166  assert( sqlite3_mutex_notheld(mem0.mutex) );
24167
24168
24169#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24170  /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
24171  ** buffers per thread.
24172  **
24173  ** This can only be checked in single-threaded mode.
24174  */
24175  assert( scratchAllocOut==0 );
24176  if( p ) scratchAllocOut++;
24177#endif
24178
24179  return p;
24180}
24181SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
24182  if( p ){
24183
24184#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24185    /* Verify that no more than two scratch allocation per thread
24186    ** is outstanding at one time.  (This is only checked in the
24187    ** single-threaded case since checking in the multi-threaded case
24188    ** would be much more complicated.) */
24189    assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
24190    scratchAllocOut--;
24191#endif
24192
24193    if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){
24194      /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
24195      ScratchFreeslot *pSlot;
24196      pSlot = (ScratchFreeslot*)p;
24197      sqlite3_mutex_enter(mem0.mutex);
24198      pSlot->pNext = mem0.pScratchFree;
24199      mem0.pScratchFree = pSlot;
24200      mem0.nScratchFree++;
24201      assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
24202      sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
24203      sqlite3_mutex_leave(mem0.mutex);
24204    }else{
24205      /* Release memory back to the heap */
24206      assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
24207      assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
24208      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24209      if( sqlite3GlobalConfig.bMemstat ){
24210        int iSize = sqlite3MallocSize(p);
24211        sqlite3_mutex_enter(mem0.mutex);
24212        sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
24213        sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
24214        sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
24215        sqlite3GlobalConfig.m.xFree(p);
24216        sqlite3_mutex_leave(mem0.mutex);
24217      }else{
24218        sqlite3GlobalConfig.m.xFree(p);
24219      }
24220    }
24221  }
24222}
24223
24224/*
24225** TRUE if p is a lookaside memory allocation from db
24226*/
24227#ifndef SQLITE_OMIT_LOOKASIDE
24228static int isLookaside(sqlite3 *db, void *p){
24229  return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
24230}
24231#else
24232#define isLookaside(A,B) 0
24233#endif
24234
24235/*
24236** Return the size of a memory allocation previously obtained from
24237** sqlite3Malloc() or sqlite3_malloc().
24238*/
24239SQLITE_PRIVATE int sqlite3MallocSize(void *p){
24240  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24241  return sqlite3GlobalConfig.m.xSize(p);
24242}
24243SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
24244  assert( p!=0 );
24245  if( db==0 || !isLookaside(db,p) ){
24246#if SQLITE_DEBUG
24247    if( db==0 ){
24248      assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24249      assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24250    }else{
24251      assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24252      assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24253    }
24254#endif
24255    return sqlite3GlobalConfig.m.xSize(p);
24256  }else{
24257    assert( sqlite3_mutex_held(db->mutex) );
24258    return db->lookaside.sz;
24259  }
24260}
24261SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void *p){
24262  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24263  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24264  return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
24265}
24266
24267/*
24268** Free memory previously obtained from sqlite3Malloc().
24269*/
24270SQLITE_API void SQLITE_STDCALL sqlite3_free(void *p){
24271  if( p==0 ) return;  /* IMP: R-49053-54554 */
24272  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24273  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24274  if( sqlite3GlobalConfig.bMemstat ){
24275    sqlite3_mutex_enter(mem0.mutex);
24276    sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
24277    sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
24278    sqlite3GlobalConfig.m.xFree(p);
24279    sqlite3_mutex_leave(mem0.mutex);
24280  }else{
24281    sqlite3GlobalConfig.m.xFree(p);
24282  }
24283}
24284
24285/*
24286** Add the size of memory allocation "p" to the count in
24287** *db->pnBytesFreed.
24288*/
24289static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
24290  *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
24291}
24292
24293/*
24294** Free memory that might be associated with a particular database
24295** connection.
24296*/
24297SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
24298  assert( db==0 || sqlite3_mutex_held(db->mutex) );
24299  if( p==0 ) return;
24300  if( db ){
24301    if( db->pnBytesFreed ){
24302      measureAllocationSize(db, p);
24303      return;
24304    }
24305    if( isLookaside(db, p) ){
24306      LookasideSlot *pBuf = (LookasideSlot*)p;
24307#if SQLITE_DEBUG
24308      /* Trash all content in the buffer being freed */
24309      memset(p, 0xaa, db->lookaside.sz);
24310#endif
24311      pBuf->pNext = db->lookaside.pFree;
24312      db->lookaside.pFree = pBuf;
24313      db->lookaside.nOut--;
24314      return;
24315    }
24316  }
24317  assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24318  assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24319  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
24320  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24321  sqlite3_free(p);
24322}
24323
24324/*
24325** Change the size of an existing memory allocation
24326*/
24327SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
24328  int nOld, nNew, nDiff;
24329  void *pNew;
24330  assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
24331  assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
24332  if( pOld==0 ){
24333    return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
24334  }
24335  if( nBytes==0 ){
24336    sqlite3_free(pOld); /* IMP: R-26507-47431 */
24337    return 0;
24338  }
24339  if( nBytes>=0x7fffff00 ){
24340    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
24341    return 0;
24342  }
24343  nOld = sqlite3MallocSize(pOld);
24344  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
24345  ** argument to xRealloc is always a value returned by a prior call to
24346  ** xRoundup. */
24347  nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
24348  if( nOld==nNew ){
24349    pNew = pOld;
24350  }else if( sqlite3GlobalConfig.bMemstat ){
24351    sqlite3_mutex_enter(mem0.mutex);
24352    sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
24353    nDiff = nNew - nOld;
24354    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
24355          mem0.alarmThreshold-nDiff ){
24356      sqlite3MallocAlarm(nDiff);
24357    }
24358    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24359    if( pNew==0 && mem0.alarmThreshold>0 ){
24360      sqlite3MallocAlarm((int)nBytes);
24361      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24362    }
24363    if( pNew ){
24364      nNew = sqlite3MallocSize(pNew);
24365      sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
24366    }
24367    sqlite3_mutex_leave(mem0.mutex);
24368  }else{
24369    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24370  }
24371  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
24372  return pNew;
24373}
24374
24375/*
24376** The public interface to sqlite3Realloc.  Make sure that the memory
24377** subsystem is initialized prior to invoking sqliteRealloc.
24378*/
24379SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void *pOld, int n){
24380#ifndef SQLITE_OMIT_AUTOINIT
24381  if( sqlite3_initialize() ) return 0;
24382#endif
24383  if( n<0 ) n = 0;  /* IMP: R-26507-47431 */
24384  return sqlite3Realloc(pOld, n);
24385}
24386SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
24387#ifndef SQLITE_OMIT_AUTOINIT
24388  if( sqlite3_initialize() ) return 0;
24389#endif
24390  return sqlite3Realloc(pOld, n);
24391}
24392
24393
24394/*
24395** Allocate and zero memory.
24396*/
24397SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
24398  void *p = sqlite3Malloc(n);
24399  if( p ){
24400    memset(p, 0, (size_t)n);
24401  }
24402  return p;
24403}
24404
24405/*
24406** Allocate and zero memory.  If the allocation fails, make
24407** the mallocFailed flag in the connection pointer.
24408*/
24409SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
24410  void *p;
24411  testcase( db==0 );
24412  p = sqlite3DbMallocRaw(db, n);
24413  if( p ) memset(p, 0, (size_t)n);
24414  return p;
24415}
24416
24417
24418/* Finish the work of sqlite3DbMallocRawNN for the unusual and
24419** slower case when the allocation cannot be fulfilled using lookaside.
24420*/
24421static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
24422  void *p;
24423  assert( db!=0 );
24424  p = sqlite3Malloc(n);
24425  if( !p ) sqlite3OomFault(db);
24426  sqlite3MemdebugSetType(p,
24427         (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
24428  return p;
24429}
24430
24431/*
24432** Allocate memory, either lookaside (if possible) or heap.
24433** If the allocation fails, set the mallocFailed flag in
24434** the connection pointer.
24435**
24436** If db!=0 and db->mallocFailed is true (indicating a prior malloc
24437** failure on the same database connection) then always return 0.
24438** Hence for a particular database connection, once malloc starts
24439** failing, it fails consistently until mallocFailed is reset.
24440** This is an important assumption.  There are many places in the
24441** code that do things like this:
24442**
24443**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
24444**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
24445**         if( b ) a[10] = 9;
24446**
24447** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
24448** that all prior mallocs (ex: "a") worked too.
24449**
24450** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
24451** not a NULL pointer.
24452*/
24453SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
24454  void *p;
24455  if( db ) return sqlite3DbMallocRawNN(db, n);
24456  p = sqlite3Malloc(n);
24457  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24458  return p;
24459}
24460SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
24461#ifndef SQLITE_OMIT_LOOKASIDE
24462  LookasideSlot *pBuf;
24463  assert( db!=0 );
24464  assert( sqlite3_mutex_held(db->mutex) );
24465  assert( db->pnBytesFreed==0 );
24466  if( db->lookaside.bDisable==0 ){
24467    assert( db->mallocFailed==0 );
24468    if( n>db->lookaside.sz ){
24469      db->lookaside.anStat[1]++;
24470    }else if( (pBuf = db->lookaside.pFree)==0 ){
24471      db->lookaside.anStat[2]++;
24472    }else{
24473      db->lookaside.pFree = pBuf->pNext;
24474      db->lookaside.nOut++;
24475      db->lookaside.anStat[0]++;
24476      if( db->lookaside.nOut>db->lookaside.mxOut ){
24477        db->lookaside.mxOut = db->lookaside.nOut;
24478      }
24479      return (void*)pBuf;
24480    }
24481  }else if( db->mallocFailed ){
24482    return 0;
24483  }
24484#else
24485  assert( db!=0 );
24486  assert( sqlite3_mutex_held(db->mutex) );
24487  assert( db->pnBytesFreed==0 );
24488  if( db->mallocFailed ){
24489    return 0;
24490  }
24491#endif
24492  return dbMallocRawFinish(db, n);
24493}
24494
24495/* Forward declaration */
24496static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
24497
24498/*
24499** Resize the block of memory pointed to by p to n bytes. If the
24500** resize fails, set the mallocFailed flag in the connection object.
24501*/
24502SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
24503  assert( db!=0 );
24504  if( p==0 ) return sqlite3DbMallocRawNN(db, n);
24505  assert( sqlite3_mutex_held(db->mutex) );
24506  if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
24507  return dbReallocFinish(db, p, n);
24508}
24509static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
24510  void *pNew = 0;
24511  assert( db!=0 );
24512  assert( p!=0 );
24513  if( db->mallocFailed==0 ){
24514    if( isLookaside(db, p) ){
24515      pNew = sqlite3DbMallocRawNN(db, n);
24516      if( pNew ){
24517        memcpy(pNew, p, db->lookaside.sz);
24518        sqlite3DbFree(db, p);
24519      }
24520    }else{
24521      assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24522      assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24523      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24524      pNew = sqlite3_realloc64(p, n);
24525      if( !pNew ){
24526        sqlite3OomFault(db);
24527      }
24528      sqlite3MemdebugSetType(pNew,
24529            (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
24530    }
24531  }
24532  return pNew;
24533}
24534
24535/*
24536** Attempt to reallocate p.  If the reallocation fails, then free p
24537** and set the mallocFailed flag in the database connection.
24538*/
24539SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
24540  void *pNew;
24541  pNew = sqlite3DbRealloc(db, p, n);
24542  if( !pNew ){
24543    sqlite3DbFree(db, p);
24544  }
24545  return pNew;
24546}
24547
24548/*
24549** Make a copy of a string in memory obtained from sqliteMalloc(). These
24550** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
24551** is because when memory debugging is turned on, these two functions are
24552** called via macros that record the current file and line number in the
24553** ThreadData structure.
24554*/
24555SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
24556  char *zNew;
24557  size_t n;
24558  if( z==0 ){
24559    return 0;
24560  }
24561  n = sqlite3Strlen30(z) + 1;
24562  assert( (n&0x7fffffff)==n );
24563  zNew = sqlite3DbMallocRaw(db, (int)n);
24564  if( zNew ){
24565    memcpy(zNew, z, n);
24566  }
24567  return zNew;
24568}
24569SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
24570  char *zNew;
24571  assert( db!=0 );
24572  if( z==0 ){
24573    return 0;
24574  }
24575  assert( (n&0x7fffffff)==n );
24576  zNew = sqlite3DbMallocRawNN(db, n+1);
24577  if( zNew ){
24578    memcpy(zNew, z, (size_t)n);
24579    zNew[n] = 0;
24580  }
24581  return zNew;
24582}
24583
24584/*
24585** Free any prior content in *pz and replace it with a copy of zNew.
24586*/
24587SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
24588  sqlite3DbFree(db, *pz);
24589  *pz = sqlite3DbStrDup(db, zNew);
24590}
24591
24592/*
24593** Call this routine to record the fact that an OOM (out-of-memory) error
24594** has happened.  This routine will set db->mallocFailed, and also
24595** temporarily disable the lookaside memory allocator and interrupt
24596** any running VDBEs.
24597*/
24598SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
24599  if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
24600    db->mallocFailed = 1;
24601    if( db->nVdbeExec>0 ){
24602      db->u1.isInterrupted = 1;
24603    }
24604    db->lookaside.bDisable++;
24605  }
24606}
24607
24608/*
24609** This routine reactivates the memory allocator and clears the
24610** db->mallocFailed flag as necessary.
24611**
24612** The memory allocator is not restarted if there are running
24613** VDBEs.
24614*/
24615SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
24616  if( db->mallocFailed && db->nVdbeExec==0 ){
24617    db->mallocFailed = 0;
24618    db->u1.isInterrupted = 0;
24619    assert( db->lookaside.bDisable>0 );
24620    db->lookaside.bDisable--;
24621  }
24622}
24623
24624/*
24625** Take actions at the end of an API call to indicate an OOM error
24626*/
24627static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
24628  sqlite3OomClear(db);
24629  sqlite3Error(db, SQLITE_NOMEM);
24630  return SQLITE_NOMEM_BKPT;
24631}
24632
24633/*
24634** This function must be called before exiting any API function (i.e.
24635** returning control to the user) that has called sqlite3_malloc or
24636** sqlite3_realloc.
24637**
24638** The returned value is normally a copy of the second argument to this
24639** function. However, if a malloc() failure has occurred since the previous
24640** invocation SQLITE_NOMEM is returned instead.
24641**
24642** If an OOM as occurred, then the connection error-code (the value
24643** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
24644*/
24645SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
24646  /* If the db handle must hold the connection handle mutex here.
24647  ** Otherwise the read (and possible write) of db->mallocFailed
24648  ** is unsafe, as is the call to sqlite3Error().
24649  */
24650  assert( db!=0 );
24651  assert( sqlite3_mutex_held(db->mutex) );
24652  if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
24653    return apiOomError(db);
24654  }
24655  return rc & db->errMask;
24656}
24657
24658/************** End of malloc.c **********************************************/
24659/************** Begin file printf.c ******************************************/
24660/*
24661** The "printf" code that follows dates from the 1980's.  It is in
24662** the public domain.
24663**
24664**************************************************************************
24665**
24666** This file contains code for a set of "printf"-like routines.  These
24667** routines format strings much like the printf() from the standard C
24668** library, though the implementation here has enhancements to support
24669** SQLite.
24670*/
24671/* #include "sqliteInt.h" */
24672
24673/*
24674** Conversion types fall into various categories as defined by the
24675** following enumeration.
24676*/
24677#define etRADIX       0 /* Integer types.  %d, %x, %o, and so forth */
24678#define etFLOAT       1 /* Floating point.  %f */
24679#define etEXP         2 /* Exponentional notation. %e and %E */
24680#define etGENERIC     3 /* Floating or exponential, depending on exponent. %g */
24681#define etSIZE        4 /* Return number of characters processed so far. %n */
24682#define etSTRING      5 /* Strings. %s */
24683#define etDYNSTRING   6 /* Dynamically allocated strings. %z */
24684#define etPERCENT     7 /* Percent symbol. %% */
24685#define etCHARX       8 /* Characters. %c */
24686/* The rest are extensions, not normally found in printf() */
24687#define etSQLESCAPE   9 /* Strings with '\'' doubled.  %q */
24688#define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
24689                          NULL pointers replaced by SQL NULL.  %Q */
24690#define etTOKEN      11 /* a pointer to a Token structure */
24691#define etSRCLIST    12 /* a pointer to a SrcList */
24692#define etPOINTER    13 /* The %p conversion */
24693#define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
24694#define etORDINAL    15 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
24695
24696#define etINVALID    16 /* Any unrecognized conversion type */
24697
24698
24699/*
24700** An "etByte" is an 8-bit unsigned value.
24701*/
24702typedef unsigned char etByte;
24703
24704/*
24705** Each builtin conversion character (ex: the 'd' in "%d") is described
24706** by an instance of the following structure
24707*/
24708typedef struct et_info {   /* Information about each format field */
24709  char fmttype;            /* The format field code letter */
24710  etByte base;             /* The base for radix conversion */
24711  etByte flags;            /* One or more of FLAG_ constants below */
24712  etByte type;             /* Conversion paradigm */
24713  etByte charset;          /* Offset into aDigits[] of the digits string */
24714  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
24715} et_info;
24716
24717/*
24718** Allowed values for et_info.flags
24719*/
24720#define FLAG_SIGNED  1     /* True if the value to convert is signed */
24721#define FLAG_INTERN  2     /* True if for internal use only */
24722#define FLAG_STRING  4     /* Allow infinity precision */
24723
24724
24725/*
24726** The following table is searched linearly, so it is good to put the
24727** most frequently used conversion types first.
24728*/
24729static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
24730static const char aPrefix[] = "-x0\000X0";
24731static const et_info fmtinfo[] = {
24732  {  'd', 10, 1, etRADIX,      0,  0 },
24733  {  's',  0, 4, etSTRING,     0,  0 },
24734  {  'g',  0, 1, etGENERIC,    30, 0 },
24735  {  'z',  0, 4, etDYNSTRING,  0,  0 },
24736  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
24737  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
24738  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
24739  {  'c',  0, 0, etCHARX,      0,  0 },
24740  {  'o',  8, 0, etRADIX,      0,  2 },
24741  {  'u', 10, 0, etRADIX,      0,  0 },
24742  {  'x', 16, 0, etRADIX,      16, 1 },
24743  {  'X', 16, 0, etRADIX,      0,  4 },
24744#ifndef SQLITE_OMIT_FLOATING_POINT
24745  {  'f',  0, 1, etFLOAT,      0,  0 },
24746  {  'e',  0, 1, etEXP,        30, 0 },
24747  {  'E',  0, 1, etEXP,        14, 0 },
24748  {  'G',  0, 1, etGENERIC,    14, 0 },
24749#endif
24750  {  'i', 10, 1, etRADIX,      0,  0 },
24751  {  'n',  0, 0, etSIZE,       0,  0 },
24752  {  '%',  0, 0, etPERCENT,    0,  0 },
24753  {  'p', 16, 0, etPOINTER,    0,  1 },
24754
24755/* All the rest have the FLAG_INTERN bit set and are thus for internal
24756** use only */
24757  {  'T',  0, 2, etTOKEN,      0,  0 },
24758  {  'S',  0, 2, etSRCLIST,    0,  0 },
24759  {  'r', 10, 3, etORDINAL,    0,  0 },
24760};
24761
24762/*
24763** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
24764** conversions will work.
24765*/
24766#ifndef SQLITE_OMIT_FLOATING_POINT
24767/*
24768** "*val" is a double such that 0.1 <= *val < 10.0
24769** Return the ascii code for the leading digit of *val, then
24770** multiply "*val" by 10.0 to renormalize.
24771**
24772** Example:
24773**     input:     *val = 3.14159
24774**     output:    *val = 1.4159    function return = '3'
24775**
24776** The counter *cnt is incremented each time.  After counter exceeds
24777** 16 (the number of significant digits in a 64-bit float) '0' is
24778** always returned.
24779*/
24780static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
24781  int digit;
24782  LONGDOUBLE_TYPE d;
24783  if( (*cnt)<=0 ) return '0';
24784  (*cnt)--;
24785  digit = (int)*val;
24786  d = digit;
24787  digit += '0';
24788  *val = (*val - d)*10.0;
24789  return (char)digit;
24790}
24791#endif /* SQLITE_OMIT_FLOATING_POINT */
24792
24793/*
24794** Set the StrAccum object to an error mode.
24795*/
24796static void setStrAccumError(StrAccum *p, u8 eError){
24797  assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
24798  p->accError = eError;
24799  p->nAlloc = 0;
24800}
24801
24802/*
24803** Extra argument values from a PrintfArguments object
24804*/
24805static sqlite3_int64 getIntArg(PrintfArguments *p){
24806  if( p->nArg<=p->nUsed ) return 0;
24807  return sqlite3_value_int64(p->apArg[p->nUsed++]);
24808}
24809static double getDoubleArg(PrintfArguments *p){
24810  if( p->nArg<=p->nUsed ) return 0.0;
24811  return sqlite3_value_double(p->apArg[p->nUsed++]);
24812}
24813static char *getTextArg(PrintfArguments *p){
24814  if( p->nArg<=p->nUsed ) return 0;
24815  return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
24816}
24817
24818
24819/*
24820** On machines with a small stack size, you can redefine the
24821** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
24822*/
24823#ifndef SQLITE_PRINT_BUF_SIZE
24824# define SQLITE_PRINT_BUF_SIZE 70
24825#endif
24826#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
24827
24828/*
24829** Render a string given by "fmt" into the StrAccum object.
24830*/
24831SQLITE_PRIVATE void sqlite3VXPrintf(
24832  StrAccum *pAccum,          /* Accumulate results here */
24833  const char *fmt,           /* Format string */
24834  va_list ap                 /* arguments */
24835){
24836  int c;                     /* Next character in the format string */
24837  char *bufpt;               /* Pointer to the conversion buffer */
24838  int precision;             /* Precision of the current field */
24839  int length;                /* Length of the field */
24840  int idx;                   /* A general purpose loop counter */
24841  int width;                 /* Width of the current field */
24842  etByte flag_leftjustify;   /* True if "-" flag is present */
24843  etByte flag_plussign;      /* True if "+" flag is present */
24844  etByte flag_blanksign;     /* True if " " flag is present */
24845  etByte flag_alternateform; /* True if "#" flag is present */
24846  etByte flag_altform2;      /* True if "!" flag is present */
24847  etByte flag_zeropad;       /* True if field width constant starts with zero */
24848  etByte flag_long;          /* True if "l" flag is present */
24849  etByte flag_longlong;      /* True if the "ll" flag is present */
24850  etByte done;               /* Loop termination flag */
24851  etByte xtype = etINVALID;  /* Conversion paradigm */
24852  u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
24853  u8 useIntern;              /* Ok to use internal conversions (ex: %T) */
24854  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
24855  sqlite_uint64 longvalue;   /* Value for integer types */
24856  LONGDOUBLE_TYPE realvalue; /* Value for real types */
24857  const et_info *infop;      /* Pointer to the appropriate info structure */
24858  char *zOut;                /* Rendering buffer */
24859  int nOut;                  /* Size of the rendering buffer */
24860  char *zExtra = 0;          /* Malloced memory used by some conversion */
24861#ifndef SQLITE_OMIT_FLOATING_POINT
24862  int  exp, e2;              /* exponent of real numbers */
24863  int nsd;                   /* Number of significant digits returned */
24864  double rounder;            /* Used for rounding floating point values */
24865  etByte flag_dp;            /* True if decimal point should be shown */
24866  etByte flag_rtz;           /* True if trailing zeros should be removed */
24867#endif
24868  PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
24869  char buf[etBUFSIZE];       /* Conversion buffer */
24870
24871  bufpt = 0;
24872  if( pAccum->printfFlags ){
24873    if( (bArgList = (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
24874      pArgList = va_arg(ap, PrintfArguments*);
24875    }
24876    useIntern = pAccum->printfFlags & SQLITE_PRINTF_INTERNAL;
24877  }else{
24878    bArgList = useIntern = 0;
24879  }
24880  for(; (c=(*fmt))!=0; ++fmt){
24881    if( c!='%' ){
24882      bufpt = (char *)fmt;
24883#if HAVE_STRCHRNUL
24884      fmt = strchrnul(fmt, '%');
24885#else
24886      do{ fmt++; }while( *fmt && *fmt != '%' );
24887#endif
24888      sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
24889      if( *fmt==0 ) break;
24890    }
24891    if( (c=(*++fmt))==0 ){
24892      sqlite3StrAccumAppend(pAccum, "%", 1);
24893      break;
24894    }
24895    /* Find out what flags are present */
24896    flag_leftjustify = flag_plussign = flag_blanksign =
24897     flag_alternateform = flag_altform2 = flag_zeropad = 0;
24898    done = 0;
24899    do{
24900      switch( c ){
24901        case '-':   flag_leftjustify = 1;     break;
24902        case '+':   flag_plussign = 1;        break;
24903        case ' ':   flag_blanksign = 1;       break;
24904        case '#':   flag_alternateform = 1;   break;
24905        case '!':   flag_altform2 = 1;        break;
24906        case '0':   flag_zeropad = 1;         break;
24907        default:    done = 1;                 break;
24908      }
24909    }while( !done && (c=(*++fmt))!=0 );
24910    /* Get the field width */
24911    if( c=='*' ){
24912      if( bArgList ){
24913        width = (int)getIntArg(pArgList);
24914      }else{
24915        width = va_arg(ap,int);
24916      }
24917      if( width<0 ){
24918        flag_leftjustify = 1;
24919        width = width >= -2147483647 ? -width : 0;
24920      }
24921      c = *++fmt;
24922    }else{
24923      unsigned wx = 0;
24924      while( c>='0' && c<='9' ){
24925        wx = wx*10 + c - '0';
24926        c = *++fmt;
24927      }
24928      testcase( wx>0x7fffffff );
24929      width = wx & 0x7fffffff;
24930    }
24931    assert( width>=0 );
24932#ifdef SQLITE_PRINTF_PRECISION_LIMIT
24933    if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
24934      width = SQLITE_PRINTF_PRECISION_LIMIT;
24935    }
24936#endif
24937
24938    /* Get the precision */
24939    if( c=='.' ){
24940      c = *++fmt;
24941      if( c=='*' ){
24942        if( bArgList ){
24943          precision = (int)getIntArg(pArgList);
24944        }else{
24945          precision = va_arg(ap,int);
24946        }
24947        c = *++fmt;
24948        if( precision<0 ){
24949          precision = precision >= -2147483647 ? -precision : -1;
24950        }
24951      }else{
24952        unsigned px = 0;
24953        while( c>='0' && c<='9' ){
24954          px = px*10 + c - '0';
24955          c = *++fmt;
24956        }
24957        testcase( px>0x7fffffff );
24958        precision = px & 0x7fffffff;
24959      }
24960    }else{
24961      precision = -1;
24962    }
24963    assert( precision>=(-1) );
24964#ifdef SQLITE_PRINTF_PRECISION_LIMIT
24965    if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
24966      precision = SQLITE_PRINTF_PRECISION_LIMIT;
24967    }
24968#endif
24969
24970
24971    /* Get the conversion type modifier */
24972    if( c=='l' ){
24973      flag_long = 1;
24974      c = *++fmt;
24975      if( c=='l' ){
24976        flag_longlong = 1;
24977        c = *++fmt;
24978      }else{
24979        flag_longlong = 0;
24980      }
24981    }else{
24982      flag_long = flag_longlong = 0;
24983    }
24984    /* Fetch the info entry for the field */
24985    infop = &fmtinfo[0];
24986    xtype = etINVALID;
24987    for(idx=0; idx<ArraySize(fmtinfo); idx++){
24988      if( c==fmtinfo[idx].fmttype ){
24989        infop = &fmtinfo[idx];
24990        if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
24991          xtype = infop->type;
24992        }else{
24993          return;
24994        }
24995        break;
24996      }
24997    }
24998
24999    /*
25000    ** At this point, variables are initialized as follows:
25001    **
25002    **   flag_alternateform          TRUE if a '#' is present.
25003    **   flag_altform2               TRUE if a '!' is present.
25004    **   flag_plussign               TRUE if a '+' is present.
25005    **   flag_leftjustify            TRUE if a '-' is present or if the
25006    **                               field width was negative.
25007    **   flag_zeropad                TRUE if the width began with 0.
25008    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
25009    **                               the conversion character.
25010    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
25011    **                               the conversion character.
25012    **   flag_blanksign              TRUE if a ' ' is present.
25013    **   width                       The specified field width.  This is
25014    **                               always non-negative.  Zero is the default.
25015    **   precision                   The specified precision.  The default
25016    **                               is -1.
25017    **   xtype                       The class of the conversion.
25018    **   infop                       Pointer to the appropriate info struct.
25019    */
25020    switch( xtype ){
25021      case etPOINTER:
25022        flag_longlong = sizeof(char*)==sizeof(i64);
25023        flag_long = sizeof(char*)==sizeof(long int);
25024        /* Fall through into the next case */
25025      case etORDINAL:
25026      case etRADIX:
25027        if( infop->flags & FLAG_SIGNED ){
25028          i64 v;
25029          if( bArgList ){
25030            v = getIntArg(pArgList);
25031          }else if( flag_longlong ){
25032            v = va_arg(ap,i64);
25033          }else if( flag_long ){
25034            v = va_arg(ap,long int);
25035          }else{
25036            v = va_arg(ap,int);
25037          }
25038          if( v<0 ){
25039            if( v==SMALLEST_INT64 ){
25040              longvalue = ((u64)1)<<63;
25041            }else{
25042              longvalue = -v;
25043            }
25044            prefix = '-';
25045          }else{
25046            longvalue = v;
25047            if( flag_plussign )        prefix = '+';
25048            else if( flag_blanksign )  prefix = ' ';
25049            else                       prefix = 0;
25050          }
25051        }else{
25052          if( bArgList ){
25053            longvalue = (u64)getIntArg(pArgList);
25054          }else if( flag_longlong ){
25055            longvalue = va_arg(ap,u64);
25056          }else if( flag_long ){
25057            longvalue = va_arg(ap,unsigned long int);
25058          }else{
25059            longvalue = va_arg(ap,unsigned int);
25060          }
25061          prefix = 0;
25062        }
25063        if( longvalue==0 ) flag_alternateform = 0;
25064        if( flag_zeropad && precision<width-(prefix!=0) ){
25065          precision = width-(prefix!=0);
25066        }
25067        if( precision<etBUFSIZE-10 ){
25068          nOut = etBUFSIZE;
25069          zOut = buf;
25070        }else{
25071          nOut = precision + 10;
25072          zOut = zExtra = sqlite3Malloc( nOut );
25073          if( zOut==0 ){
25074            setStrAccumError(pAccum, STRACCUM_NOMEM);
25075            return;
25076          }
25077        }
25078        bufpt = &zOut[nOut-1];
25079        if( xtype==etORDINAL ){
25080          static const char zOrd[] = "thstndrd";
25081          int x = (int)(longvalue % 10);
25082          if( x>=4 || (longvalue/10)%10==1 ){
25083            x = 0;
25084          }
25085          *(--bufpt) = zOrd[x*2+1];
25086          *(--bufpt) = zOrd[x*2];
25087        }
25088        {
25089          const char *cset = &aDigits[infop->charset];
25090          u8 base = infop->base;
25091          do{                                           /* Convert to ascii */
25092            *(--bufpt) = cset[longvalue%base];
25093            longvalue = longvalue/base;
25094          }while( longvalue>0 );
25095        }
25096        length = (int)(&zOut[nOut-1]-bufpt);
25097        for(idx=precision-length; idx>0; idx--){
25098          *(--bufpt) = '0';                             /* Zero pad */
25099        }
25100        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
25101        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
25102          const char *pre;
25103          char x;
25104          pre = &aPrefix[infop->prefix];
25105          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
25106        }
25107        length = (int)(&zOut[nOut-1]-bufpt);
25108        break;
25109      case etFLOAT:
25110      case etEXP:
25111      case etGENERIC:
25112        if( bArgList ){
25113          realvalue = getDoubleArg(pArgList);
25114        }else{
25115          realvalue = va_arg(ap,double);
25116        }
25117#ifdef SQLITE_OMIT_FLOATING_POINT
25118        length = 0;
25119#else
25120        if( precision<0 ) precision = 6;         /* Set default precision */
25121        if( realvalue<0.0 ){
25122          realvalue = -realvalue;
25123          prefix = '-';
25124        }else{
25125          if( flag_plussign )          prefix = '+';
25126          else if( flag_blanksign )    prefix = ' ';
25127          else                         prefix = 0;
25128        }
25129        if( xtype==etGENERIC && precision>0 ) precision--;
25130        testcase( precision>0xfff );
25131        for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
25132        if( xtype==etFLOAT ) realvalue += rounder;
25133        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
25134        exp = 0;
25135        if( sqlite3IsNaN((double)realvalue) ){
25136          bufpt = "NaN";
25137          length = 3;
25138          break;
25139        }
25140        if( realvalue>0.0 ){
25141          LONGDOUBLE_TYPE scale = 1.0;
25142          while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
25143          while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
25144          while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
25145          realvalue /= scale;
25146          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
25147          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
25148          if( exp>350 ){
25149            bufpt = buf;
25150            buf[0] = prefix;
25151            memcpy(buf+(prefix!=0),"Inf",4);
25152            length = 3+(prefix!=0);
25153            break;
25154          }
25155        }
25156        bufpt = buf;
25157        /*
25158        ** If the field type is etGENERIC, then convert to either etEXP
25159        ** or etFLOAT, as appropriate.
25160        */
25161        if( xtype!=etFLOAT ){
25162          realvalue += rounder;
25163          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
25164        }
25165        if( xtype==etGENERIC ){
25166          flag_rtz = !flag_alternateform;
25167          if( exp<-4 || exp>precision ){
25168            xtype = etEXP;
25169          }else{
25170            precision = precision - exp;
25171            xtype = etFLOAT;
25172          }
25173        }else{
25174          flag_rtz = flag_altform2;
25175        }
25176        if( xtype==etEXP ){
25177          e2 = 0;
25178        }else{
25179          e2 = exp;
25180        }
25181        if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
25182          bufpt = zExtra
25183              = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
25184          if( bufpt==0 ){
25185            setStrAccumError(pAccum, STRACCUM_NOMEM);
25186            return;
25187          }
25188        }
25189        zOut = bufpt;
25190        nsd = 16 + flag_altform2*10;
25191        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
25192        /* The sign in front of the number */
25193        if( prefix ){
25194          *(bufpt++) = prefix;
25195        }
25196        /* Digits prior to the decimal point */
25197        if( e2<0 ){
25198          *(bufpt++) = '0';
25199        }else{
25200          for(; e2>=0; e2--){
25201            *(bufpt++) = et_getdigit(&realvalue,&nsd);
25202          }
25203        }
25204        /* The decimal point */
25205        if( flag_dp ){
25206          *(bufpt++) = '.';
25207        }
25208        /* "0" digits after the decimal point but before the first
25209        ** significant digit of the number */
25210        for(e2++; e2<0; precision--, e2++){
25211          assert( precision>0 );
25212          *(bufpt++) = '0';
25213        }
25214        /* Significant digits after the decimal point */
25215        while( (precision--)>0 ){
25216          *(bufpt++) = et_getdigit(&realvalue,&nsd);
25217        }
25218        /* Remove trailing zeros and the "." if no digits follow the "." */
25219        if( flag_rtz && flag_dp ){
25220          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
25221          assert( bufpt>zOut );
25222          if( bufpt[-1]=='.' ){
25223            if( flag_altform2 ){
25224              *(bufpt++) = '0';
25225            }else{
25226              *(--bufpt) = 0;
25227            }
25228          }
25229        }
25230        /* Add the "eNNN" suffix */
25231        if( xtype==etEXP ){
25232          *(bufpt++) = aDigits[infop->charset];
25233          if( exp<0 ){
25234            *(bufpt++) = '-'; exp = -exp;
25235          }else{
25236            *(bufpt++) = '+';
25237          }
25238          if( exp>=100 ){
25239            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
25240            exp %= 100;
25241          }
25242          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
25243          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
25244        }
25245        *bufpt = 0;
25246
25247        /* The converted number is in buf[] and zero terminated. Output it.
25248        ** Note that the number is in the usual order, not reversed as with
25249        ** integer conversions. */
25250        length = (int)(bufpt-zOut);
25251        bufpt = zOut;
25252
25253        /* Special case:  Add leading zeros if the flag_zeropad flag is
25254        ** set and we are not left justified */
25255        if( flag_zeropad && !flag_leftjustify && length < width){
25256          int i;
25257          int nPad = width - length;
25258          for(i=width; i>=nPad; i--){
25259            bufpt[i] = bufpt[i-nPad];
25260          }
25261          i = prefix!=0;
25262          while( nPad-- ) bufpt[i++] = '0';
25263          length = width;
25264        }
25265#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
25266        break;
25267      case etSIZE:
25268        if( !bArgList ){
25269          *(va_arg(ap,int*)) = pAccum->nChar;
25270        }
25271        length = width = 0;
25272        break;
25273      case etPERCENT:
25274        buf[0] = '%';
25275        bufpt = buf;
25276        length = 1;
25277        break;
25278      case etCHARX:
25279        if( bArgList ){
25280          bufpt = getTextArg(pArgList);
25281          c = bufpt ? bufpt[0] : 0;
25282        }else{
25283          c = va_arg(ap,int);
25284        }
25285        if( precision>1 ){
25286          width -= precision-1;
25287          if( width>1 && !flag_leftjustify ){
25288            sqlite3AppendChar(pAccum, width-1, ' ');
25289            width = 0;
25290          }
25291          sqlite3AppendChar(pAccum, precision-1, c);
25292        }
25293        length = 1;
25294        buf[0] = c;
25295        bufpt = buf;
25296        break;
25297      case etSTRING:
25298      case etDYNSTRING:
25299        if( bArgList ){
25300          bufpt = getTextArg(pArgList);
25301          xtype = etSTRING;
25302        }else{
25303          bufpt = va_arg(ap,char*);
25304        }
25305        if( bufpt==0 ){
25306          bufpt = "";
25307        }else if( xtype==etDYNSTRING ){
25308          zExtra = bufpt;
25309        }
25310        if( precision>=0 ){
25311          for(length=0; length<precision && bufpt[length]; length++){}
25312        }else{
25313          length = sqlite3Strlen30(bufpt);
25314        }
25315        break;
25316      case etSQLESCAPE:           /* Escape ' characters */
25317      case etSQLESCAPE2:          /* Escape ' and enclose in '...' */
25318      case etSQLESCAPE3: {        /* Escape " characters */
25319        int i, j, k, n, isnull;
25320        int needQuote;
25321        char ch;
25322        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
25323        char *escarg;
25324
25325        if( bArgList ){
25326          escarg = getTextArg(pArgList);
25327        }else{
25328          escarg = va_arg(ap,char*);
25329        }
25330        isnull = escarg==0;
25331        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
25332        k = precision;
25333        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
25334          if( ch==q )  n++;
25335        }
25336        needQuote = !isnull && xtype==etSQLESCAPE2;
25337        n += i + 3;
25338        if( n>etBUFSIZE ){
25339          bufpt = zExtra = sqlite3Malloc( n );
25340          if( bufpt==0 ){
25341            setStrAccumError(pAccum, STRACCUM_NOMEM);
25342            return;
25343          }
25344        }else{
25345          bufpt = buf;
25346        }
25347        j = 0;
25348        if( needQuote ) bufpt[j++] = q;
25349        k = i;
25350        for(i=0; i<k; i++){
25351          bufpt[j++] = ch = escarg[i];
25352          if( ch==q ) bufpt[j++] = ch;
25353        }
25354        if( needQuote ) bufpt[j++] = q;
25355        bufpt[j] = 0;
25356        length = j;
25357        /* The precision in %q and %Q means how many input characters to
25358        ** consume, not the length of the output...
25359        ** if( precision>=0 && precision<length ) length = precision; */
25360        break;
25361      }
25362      case etTOKEN: {
25363        Token *pToken = va_arg(ap, Token*);
25364        assert( bArgList==0 );
25365        if( pToken && pToken->n ){
25366          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
25367        }
25368        length = width = 0;
25369        break;
25370      }
25371      case etSRCLIST: {
25372        SrcList *pSrc = va_arg(ap, SrcList*);
25373        int k = va_arg(ap, int);
25374        struct SrcList_item *pItem = &pSrc->a[k];
25375        assert( bArgList==0 );
25376        assert( k>=0 && k<pSrc->nSrc );
25377        if( pItem->zDatabase ){
25378          sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
25379          sqlite3StrAccumAppend(pAccum, ".", 1);
25380        }
25381        sqlite3StrAccumAppendAll(pAccum, pItem->zName);
25382        length = width = 0;
25383        break;
25384      }
25385      default: {
25386        assert( xtype==etINVALID );
25387        return;
25388      }
25389    }/* End switch over the format type */
25390    /*
25391    ** The text of the conversion is pointed to by "bufpt" and is
25392    ** "length" characters long.  The field width is "width".  Do
25393    ** the output.
25394    */
25395    width -= length;
25396    if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
25397    sqlite3StrAccumAppend(pAccum, bufpt, length);
25398    if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
25399
25400    if( zExtra ){
25401      sqlite3DbFree(pAccum->db, zExtra);
25402      zExtra = 0;
25403    }
25404  }/* End for loop over the format string */
25405} /* End of function */
25406
25407/*
25408** Enlarge the memory allocation on a StrAccum object so that it is
25409** able to accept at least N more bytes of text.
25410**
25411** Return the number of bytes of text that StrAccum is able to accept
25412** after the attempted enlargement.  The value returned might be zero.
25413*/
25414static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
25415  char *zNew;
25416  assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
25417  if( p->accError ){
25418    testcase(p->accError==STRACCUM_TOOBIG);
25419    testcase(p->accError==STRACCUM_NOMEM);
25420    return 0;
25421  }
25422  if( p->mxAlloc==0 ){
25423    N = p->nAlloc - p->nChar - 1;
25424    setStrAccumError(p, STRACCUM_TOOBIG);
25425    return N;
25426  }else{
25427    char *zOld = isMalloced(p) ? p->zText : 0;
25428    i64 szNew = p->nChar;
25429    assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25430    szNew += N + 1;
25431    if( szNew+p->nChar<=p->mxAlloc ){
25432      /* Force exponential buffer size growth as long as it does not overflow,
25433      ** to avoid having to call this routine too often */
25434      szNew += p->nChar;
25435    }
25436    if( szNew > p->mxAlloc ){
25437      sqlite3StrAccumReset(p);
25438      setStrAccumError(p, STRACCUM_TOOBIG);
25439      return 0;
25440    }else{
25441      p->nAlloc = (int)szNew;
25442    }
25443    if( p->db ){
25444      zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
25445    }else{
25446      zNew = sqlite3_realloc64(zOld, p->nAlloc);
25447    }
25448    if( zNew ){
25449      assert( p->zText!=0 || p->nChar==0 );
25450      if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
25451      p->zText = zNew;
25452      p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
25453      p->printfFlags |= SQLITE_PRINTF_MALLOCED;
25454    }else{
25455      sqlite3StrAccumReset(p);
25456      setStrAccumError(p, STRACCUM_NOMEM);
25457      return 0;
25458    }
25459  }
25460  return N;
25461}
25462
25463/*
25464** Append N copies of character c to the given string buffer.
25465*/
25466SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
25467  testcase( p->nChar + (i64)N > 0x7fffffff );
25468  if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
25469    return;
25470  }
25471  assert( (p->zText==p->zBase)==!isMalloced(p) );
25472  while( (N--)>0 ) p->zText[p->nChar++] = c;
25473}
25474
25475/*
25476** The StrAccum "p" is not large enough to accept N new bytes of z[].
25477** So enlarge if first, then do the append.
25478**
25479** This is a helper routine to sqlite3StrAccumAppend() that does special-case
25480** work (enlarging the buffer) using tail recursion, so that the
25481** sqlite3StrAccumAppend() routine can use fast calling semantics.
25482*/
25483static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
25484  N = sqlite3StrAccumEnlarge(p, N);
25485  if( N>0 ){
25486    memcpy(&p->zText[p->nChar], z, N);
25487    p->nChar += N;
25488  }
25489  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25490}
25491
25492/*
25493** Append N bytes of text from z to the StrAccum object.  Increase the
25494** size of the memory allocation for StrAccum if necessary.
25495*/
25496SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
25497  assert( z!=0 || N==0 );
25498  assert( p->zText!=0 || p->nChar==0 || p->accError );
25499  assert( N>=0 );
25500  assert( p->accError==0 || p->nAlloc==0 );
25501  if( p->nChar+N >= p->nAlloc ){
25502    enlargeAndAppend(p,z,N);
25503  }else{
25504    assert( p->zText );
25505    p->nChar += N;
25506    memcpy(&p->zText[p->nChar-N], z, N);
25507  }
25508}
25509
25510/*
25511** Append the complete text of zero-terminated string z[] to the p string.
25512*/
25513SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
25514  sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
25515}
25516
25517
25518/*
25519** Finish off a string by making sure it is zero-terminated.
25520** Return a pointer to the resulting string.  Return a NULL
25521** pointer if any kind of error was encountered.
25522*/
25523SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
25524  if( p->zText ){
25525    assert( (p->zText==p->zBase)==!isMalloced(p) );
25526    p->zText[p->nChar] = 0;
25527    if( p->mxAlloc>0 && !isMalloced(p) ){
25528      p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
25529      if( p->zText ){
25530        memcpy(p->zText, p->zBase, p->nChar+1);
25531        p->printfFlags |= SQLITE_PRINTF_MALLOCED;
25532      }else{
25533        setStrAccumError(p, STRACCUM_NOMEM);
25534      }
25535    }
25536  }
25537  return p->zText;
25538}
25539
25540/*
25541** Reset an StrAccum string.  Reclaim all malloced memory.
25542*/
25543SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
25544  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25545  if( isMalloced(p) ){
25546    sqlite3DbFree(p->db, p->zText);
25547    p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
25548  }
25549  p->zText = 0;
25550}
25551
25552/*
25553** Initialize a string accumulator.
25554**
25555** p:     The accumulator to be initialized.
25556** db:    Pointer to a database connection.  May be NULL.  Lookaside
25557**        memory is used if not NULL. db->mallocFailed is set appropriately
25558**        when not NULL.
25559** zBase: An initial buffer.  May be NULL in which case the initial buffer
25560**        is malloced.
25561** n:     Size of zBase in bytes.  If total space requirements never exceed
25562**        n then no memory allocations ever occur.
25563** mx:    Maximum number of bytes to accumulate.  If mx==0 then no memory
25564**        allocations will ever occur.
25565*/
25566SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
25567  p->zText = p->zBase = zBase;
25568  p->db = db;
25569  p->nChar = 0;
25570  p->nAlloc = n;
25571  p->mxAlloc = mx;
25572  p->accError = 0;
25573  p->printfFlags = 0;
25574}
25575
25576/*
25577** Print into memory obtained from sqliteMalloc().  Use the internal
25578** %-conversion extensions.
25579*/
25580SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
25581  char *z;
25582  char zBase[SQLITE_PRINT_BUF_SIZE];
25583  StrAccum acc;
25584  assert( db!=0 );
25585  sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
25586                      db->aLimit[SQLITE_LIMIT_LENGTH]);
25587  acc.printfFlags = SQLITE_PRINTF_INTERNAL;
25588  sqlite3VXPrintf(&acc, zFormat, ap);
25589  z = sqlite3StrAccumFinish(&acc);
25590  if( acc.accError==STRACCUM_NOMEM ){
25591    sqlite3OomFault(db);
25592  }
25593  return z;
25594}
25595
25596/*
25597** Print into memory obtained from sqliteMalloc().  Use the internal
25598** %-conversion extensions.
25599*/
25600SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
25601  va_list ap;
25602  char *z;
25603  va_start(ap, zFormat);
25604  z = sqlite3VMPrintf(db, zFormat, ap);
25605  va_end(ap);
25606  return z;
25607}
25608
25609/*
25610** Print into memory obtained from sqlite3_malloc().  Omit the internal
25611** %-conversion extensions.
25612*/
25613SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char *zFormat, va_list ap){
25614  char *z;
25615  char zBase[SQLITE_PRINT_BUF_SIZE];
25616  StrAccum acc;
25617
25618#ifdef SQLITE_ENABLE_API_ARMOR
25619  if( zFormat==0 ){
25620    (void)SQLITE_MISUSE_BKPT;
25621    return 0;
25622  }
25623#endif
25624#ifndef SQLITE_OMIT_AUTOINIT
25625  if( sqlite3_initialize() ) return 0;
25626#endif
25627  sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
25628  sqlite3VXPrintf(&acc, zFormat, ap);
25629  z = sqlite3StrAccumFinish(&acc);
25630  return z;
25631}
25632
25633/*
25634** Print into memory obtained from sqlite3_malloc()().  Omit the internal
25635** %-conversion extensions.
25636*/
25637SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char *zFormat, ...){
25638  va_list ap;
25639  char *z;
25640#ifndef SQLITE_OMIT_AUTOINIT
25641  if( sqlite3_initialize() ) return 0;
25642#endif
25643  va_start(ap, zFormat);
25644  z = sqlite3_vmprintf(zFormat, ap);
25645  va_end(ap);
25646  return z;
25647}
25648
25649/*
25650** sqlite3_snprintf() works like snprintf() except that it ignores the
25651** current locale settings.  This is important for SQLite because we
25652** are not able to use a "," as the decimal point in place of "." as
25653** specified by some locales.
25654**
25655** Oops:  The first two arguments of sqlite3_snprintf() are backwards
25656** from the snprintf() standard.  Unfortunately, it is too late to change
25657** this without breaking compatibility, so we just have to live with the
25658** mistake.
25659**
25660** sqlite3_vsnprintf() is the varargs version.
25661*/
25662SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
25663  StrAccum acc;
25664  if( n<=0 ) return zBuf;
25665#ifdef SQLITE_ENABLE_API_ARMOR
25666  if( zBuf==0 || zFormat==0 ) {
25667    (void)SQLITE_MISUSE_BKPT;
25668    if( zBuf ) zBuf[0] = 0;
25669    return zBuf;
25670  }
25671#endif
25672  sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
25673  sqlite3VXPrintf(&acc, zFormat, ap);
25674  return sqlite3StrAccumFinish(&acc);
25675}
25676SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
25677  char *z;
25678  va_list ap;
25679  va_start(ap,zFormat);
25680  z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
25681  va_end(ap);
25682  return z;
25683}
25684
25685/*
25686** This is the routine that actually formats the sqlite3_log() message.
25687** We house it in a separate routine from sqlite3_log() to avoid using
25688** stack space on small-stack systems when logging is disabled.
25689**
25690** sqlite3_log() must render into a static buffer.  It cannot dynamically
25691** allocate memory because it might be called while the memory allocator
25692** mutex is held.
25693**
25694** sqlite3VXPrintf() might ask for *temporary* memory allocations for
25695** certain format characters (%q) or for very large precisions or widths.
25696** Care must be taken that any sqlite3_log() calls that occur while the
25697** memory mutex is held do not use these mechanisms.
25698*/
25699static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
25700  StrAccum acc;                          /* String accumulator */
25701  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
25702
25703  sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
25704  sqlite3VXPrintf(&acc, zFormat, ap);
25705  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
25706                           sqlite3StrAccumFinish(&acc));
25707}
25708
25709/*
25710** Format and write a message to the log if logging is enabled.
25711*/
25712SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...){
25713  va_list ap;                             /* Vararg list */
25714  if( sqlite3GlobalConfig.xLog ){
25715    va_start(ap, zFormat);
25716    renderLogMsg(iErrCode, zFormat, ap);
25717    va_end(ap);
25718  }
25719}
25720
25721#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
25722/*
25723** A version of printf() that understands %lld.  Used for debugging.
25724** The printf() built into some versions of windows does not understand %lld
25725** and segfaults if you give it a long long int.
25726*/
25727SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
25728  va_list ap;
25729  StrAccum acc;
25730  char zBuf[500];
25731  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
25732  va_start(ap,zFormat);
25733  sqlite3VXPrintf(&acc, zFormat, ap);
25734  va_end(ap);
25735  sqlite3StrAccumFinish(&acc);
25736  fprintf(stdout,"%s", zBuf);
25737  fflush(stdout);
25738}
25739#endif
25740
25741
25742/*
25743** variable-argument wrapper around sqlite3VXPrintf().  The bFlags argument
25744** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
25745*/
25746SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
25747  va_list ap;
25748  va_start(ap,zFormat);
25749  sqlite3VXPrintf(p, zFormat, ap);
25750  va_end(ap);
25751}
25752
25753/************** End of printf.c **********************************************/
25754/************** Begin file treeview.c ****************************************/
25755/*
25756** 2015-06-08
25757**
25758** The author disclaims copyright to this source code.  In place of
25759** a legal notice, here is a blessing:
25760**
25761**    May you do good and not evil.
25762**    May you find forgiveness for yourself and forgive others.
25763**    May you share freely, never taking more than you give.
25764**
25765*************************************************************************
25766**
25767** This file contains C code to implement the TreeView debugging routines.
25768** These routines print a parse tree to standard output for debugging and
25769** analysis.
25770**
25771** The interfaces in this file is only available when compiling
25772** with SQLITE_DEBUG.
25773*/
25774/* #include "sqliteInt.h" */
25775#ifdef SQLITE_DEBUG
25776
25777/*
25778** Add a new subitem to the tree.  The moreToFollow flag indicates that this
25779** is not the last item in the tree.
25780*/
25781static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
25782  if( p==0 ){
25783    p = sqlite3_malloc64( sizeof(*p) );
25784    if( p==0 ) return 0;
25785    memset(p, 0, sizeof(*p));
25786  }else{
25787    p->iLevel++;
25788  }
25789  assert( moreToFollow==0 || moreToFollow==1 );
25790  if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
25791  return p;
25792}
25793
25794/*
25795** Finished with one layer of the tree
25796*/
25797static void sqlite3TreeViewPop(TreeView *p){
25798  if( p==0 ) return;
25799  p->iLevel--;
25800  if( p->iLevel<0 ) sqlite3_free(p);
25801}
25802
25803/*
25804** Generate a single line of output for the tree, with a prefix that contains
25805** all the appropriate tree lines
25806*/
25807static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
25808  va_list ap;
25809  int i;
25810  StrAccum acc;
25811  char zBuf[500];
25812  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
25813  if( p ){
25814    for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
25815      sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|   " : "    ", 4);
25816    }
25817    sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
25818  }
25819  va_start(ap, zFormat);
25820  sqlite3VXPrintf(&acc, zFormat, ap);
25821  va_end(ap);
25822  if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
25823  sqlite3StrAccumFinish(&acc);
25824  fprintf(stdout,"%s", zBuf);
25825  fflush(stdout);
25826}
25827
25828/*
25829** Shorthand for starting a new tree item that consists of a single label
25830*/
25831static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
25832  p = sqlite3TreeViewPush(p, moreFollows);
25833  sqlite3TreeViewLine(p, "%s", zLabel);
25834}
25835
25836/*
25837** Generate a human-readable description of a WITH clause.
25838*/
25839SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
25840  int i;
25841  if( pWith==0 ) return;
25842  if( pWith->nCte==0 ) return;
25843  if( pWith->pOuter ){
25844    sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
25845  }else{
25846    sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
25847  }
25848  if( pWith->nCte>0 ){
25849    pView = sqlite3TreeViewPush(pView, 1);
25850    for(i=0; i<pWith->nCte; i++){
25851      StrAccum x;
25852      char zLine[1000];
25853      const struct Cte *pCte = &pWith->a[i];
25854      sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
25855      sqlite3XPrintf(&x, "%s", pCte->zName);
25856      if( pCte->pCols && pCte->pCols->nExpr>0 ){
25857        char cSep = '(';
25858        int j;
25859        for(j=0; j<pCte->pCols->nExpr; j++){
25860          sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
25861          cSep = ',';
25862        }
25863        sqlite3XPrintf(&x, ")");
25864      }
25865      sqlite3XPrintf(&x, " AS");
25866      sqlite3StrAccumFinish(&x);
25867      sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
25868      sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
25869      sqlite3TreeViewPop(pView);
25870    }
25871    sqlite3TreeViewPop(pView);
25872  }
25873}
25874
25875
25876/*
25877** Generate a human-readable description of a the Select object.
25878*/
25879SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
25880  int n = 0;
25881  int cnt = 0;
25882  pView = sqlite3TreeViewPush(pView, moreToFollow);
25883  if( p->pWith ){
25884    sqlite3TreeViewWith(pView, p->pWith, 1);
25885    cnt = 1;
25886    sqlite3TreeViewPush(pView, 1);
25887  }
25888  do{
25889    sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
25890      ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
25891      ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
25892      (int)p->nSelectRow
25893    );
25894    if( cnt++ ) sqlite3TreeViewPop(pView);
25895    if( p->pPrior ){
25896      n = 1000;
25897    }else{
25898      n = 0;
25899      if( p->pSrc && p->pSrc->nSrc ) n++;
25900      if( p->pWhere ) n++;
25901      if( p->pGroupBy ) n++;
25902      if( p->pHaving ) n++;
25903      if( p->pOrderBy ) n++;
25904      if( p->pLimit ) n++;
25905      if( p->pOffset ) n++;
25906    }
25907    sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
25908    if( p->pSrc && p->pSrc->nSrc ){
25909      int i;
25910      pView = sqlite3TreeViewPush(pView, (n--)>0);
25911      sqlite3TreeViewLine(pView, "FROM");
25912      for(i=0; i<p->pSrc->nSrc; i++){
25913        struct SrcList_item *pItem = &p->pSrc->a[i];
25914        StrAccum x;
25915        char zLine[100];
25916        sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
25917        sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor);
25918        if( pItem->zDatabase ){
25919          sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
25920        }else if( pItem->zName ){
25921          sqlite3XPrintf(&x, " %s", pItem->zName);
25922        }
25923        if( pItem->pTab ){
25924          sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName);
25925        }
25926        if( pItem->zAlias ){
25927          sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias);
25928        }
25929        if( pItem->fg.jointype & JT_LEFT ){
25930          sqlite3XPrintf(&x, " LEFT-JOIN");
25931        }
25932        sqlite3StrAccumFinish(&x);
25933        sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
25934        if( pItem->pSelect ){
25935          sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
25936        }
25937        if( pItem->fg.isTabFunc ){
25938          sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
25939        }
25940        sqlite3TreeViewPop(pView);
25941      }
25942      sqlite3TreeViewPop(pView);
25943    }
25944    if( p->pWhere ){
25945      sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
25946      sqlite3TreeViewExpr(pView, p->pWhere, 0);
25947      sqlite3TreeViewPop(pView);
25948    }
25949    if( p->pGroupBy ){
25950      sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
25951    }
25952    if( p->pHaving ){
25953      sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
25954      sqlite3TreeViewExpr(pView, p->pHaving, 0);
25955      sqlite3TreeViewPop(pView);
25956    }
25957    if( p->pOrderBy ){
25958      sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
25959    }
25960    if( p->pLimit ){
25961      sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
25962      sqlite3TreeViewExpr(pView, p->pLimit, 0);
25963      sqlite3TreeViewPop(pView);
25964    }
25965    if( p->pOffset ){
25966      sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
25967      sqlite3TreeViewExpr(pView, p->pOffset, 0);
25968      sqlite3TreeViewPop(pView);
25969    }
25970    if( p->pPrior ){
25971      const char *zOp = "UNION";
25972      switch( p->op ){
25973        case TK_ALL:         zOp = "UNION ALL";  break;
25974        case TK_INTERSECT:   zOp = "INTERSECT";  break;
25975        case TK_EXCEPT:      zOp = "EXCEPT";     break;
25976      }
25977      sqlite3TreeViewItem(pView, zOp, 1);
25978    }
25979    p = p->pPrior;
25980  }while( p!=0 );
25981  sqlite3TreeViewPop(pView);
25982}
25983
25984/*
25985** Generate a human-readable explanation of an expression tree.
25986*/
25987SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
25988  const char *zBinOp = 0;   /* Binary operator */
25989  const char *zUniOp = 0;   /* Unary operator */
25990  char zFlgs[30];
25991  pView = sqlite3TreeViewPush(pView, moreToFollow);
25992  if( pExpr==0 ){
25993    sqlite3TreeViewLine(pView, "nil");
25994    sqlite3TreeViewPop(pView);
25995    return;
25996  }
25997  if( pExpr->flags ){
25998    sqlite3_snprintf(sizeof(zFlgs),zFlgs,"  flags=0x%x",pExpr->flags);
25999  }else{
26000    zFlgs[0] = 0;
26001  }
26002  switch( pExpr->op ){
26003    case TK_AGG_COLUMN: {
26004      sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
26005            pExpr->iTable, pExpr->iColumn, zFlgs);
26006      break;
26007    }
26008    case TK_COLUMN: {
26009      if( pExpr->iTable<0 ){
26010        /* This only happens when coding check constraints */
26011        sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
26012      }else{
26013        sqlite3TreeViewLine(pView, "{%d:%d}%s",
26014                             pExpr->iTable, pExpr->iColumn, zFlgs);
26015      }
26016      break;
26017    }
26018    case TK_INTEGER: {
26019      if( pExpr->flags & EP_IntValue ){
26020        sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
26021      }else{
26022        sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
26023      }
26024      break;
26025    }
26026#ifndef SQLITE_OMIT_FLOATING_POINT
26027    case TK_FLOAT: {
26028      sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
26029      break;
26030    }
26031#endif
26032    case TK_STRING: {
26033      sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
26034      break;
26035    }
26036    case TK_NULL: {
26037      sqlite3TreeViewLine(pView,"NULL");
26038      break;
26039    }
26040#ifndef SQLITE_OMIT_BLOB_LITERAL
26041    case TK_BLOB: {
26042      sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
26043      break;
26044    }
26045#endif
26046    case TK_VARIABLE: {
26047      sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
26048                          pExpr->u.zToken, pExpr->iColumn);
26049      break;
26050    }
26051    case TK_REGISTER: {
26052      sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
26053      break;
26054    }
26055    case TK_ID: {
26056      sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
26057      break;
26058    }
26059#ifndef SQLITE_OMIT_CAST
26060    case TK_CAST: {
26061      /* Expressions of the form:   CAST(pLeft AS token) */
26062      sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
26063      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26064      break;
26065    }
26066#endif /* SQLITE_OMIT_CAST */
26067    case TK_LT:      zBinOp = "LT";     break;
26068    case TK_LE:      zBinOp = "LE";     break;
26069    case TK_GT:      zBinOp = "GT";     break;
26070    case TK_GE:      zBinOp = "GE";     break;
26071    case TK_NE:      zBinOp = "NE";     break;
26072    case TK_EQ:      zBinOp = "EQ";     break;
26073    case TK_IS:      zBinOp = "IS";     break;
26074    case TK_ISNOT:   zBinOp = "ISNOT";  break;
26075    case TK_AND:     zBinOp = "AND";    break;
26076    case TK_OR:      zBinOp = "OR";     break;
26077    case TK_PLUS:    zBinOp = "ADD";    break;
26078    case TK_STAR:    zBinOp = "MUL";    break;
26079    case TK_MINUS:   zBinOp = "SUB";    break;
26080    case TK_REM:     zBinOp = "REM";    break;
26081    case TK_BITAND:  zBinOp = "BITAND"; break;
26082    case TK_BITOR:   zBinOp = "BITOR";  break;
26083    case TK_SLASH:   zBinOp = "DIV";    break;
26084    case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
26085    case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
26086    case TK_CONCAT:  zBinOp = "CONCAT"; break;
26087    case TK_DOT:     zBinOp = "DOT";    break;
26088
26089    case TK_UMINUS:  zUniOp = "UMINUS"; break;
26090    case TK_UPLUS:   zUniOp = "UPLUS";  break;
26091    case TK_BITNOT:  zUniOp = "BITNOT"; break;
26092    case TK_NOT:     zUniOp = "NOT";    break;
26093    case TK_ISNULL:  zUniOp = "ISNULL"; break;
26094    case TK_NOTNULL: zUniOp = "NOTNULL"; break;
26095
26096    case TK_SPAN: {
26097      sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
26098      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26099      break;
26100    }
26101
26102    case TK_COLLATE: {
26103      sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
26104      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26105      break;
26106    }
26107
26108    case TK_AGG_FUNCTION:
26109    case TK_FUNCTION: {
26110      ExprList *pFarg;       /* List of function arguments */
26111      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
26112        pFarg = 0;
26113      }else{
26114        pFarg = pExpr->x.pList;
26115      }
26116      if( pExpr->op==TK_AGG_FUNCTION ){
26117        sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
26118                             pExpr->op2, pExpr->u.zToken);
26119      }else{
26120        sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
26121      }
26122      if( pFarg ){
26123        sqlite3TreeViewExprList(pView, pFarg, 0, 0);
26124      }
26125      break;
26126    }
26127#ifndef SQLITE_OMIT_SUBQUERY
26128    case TK_EXISTS: {
26129      sqlite3TreeViewLine(pView, "EXISTS-expr");
26130      sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26131      break;
26132    }
26133    case TK_SELECT: {
26134      sqlite3TreeViewLine(pView, "SELECT-expr");
26135      sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26136      break;
26137    }
26138    case TK_IN: {
26139      sqlite3TreeViewLine(pView, "IN");
26140      sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26141      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
26142        sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26143      }else{
26144        sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
26145      }
26146      break;
26147    }
26148#endif /* SQLITE_OMIT_SUBQUERY */
26149
26150    /*
26151    **    x BETWEEN y AND z
26152    **
26153    ** This is equivalent to
26154    **
26155    **    x>=y AND x<=z
26156    **
26157    ** X is stored in pExpr->pLeft.
26158    ** Y is stored in pExpr->pList->a[0].pExpr.
26159    ** Z is stored in pExpr->pList->a[1].pExpr.
26160    */
26161    case TK_BETWEEN: {
26162      Expr *pX = pExpr->pLeft;
26163      Expr *pY = pExpr->x.pList->a[0].pExpr;
26164      Expr *pZ = pExpr->x.pList->a[1].pExpr;
26165      sqlite3TreeViewLine(pView, "BETWEEN");
26166      sqlite3TreeViewExpr(pView, pX, 1);
26167      sqlite3TreeViewExpr(pView, pY, 1);
26168      sqlite3TreeViewExpr(pView, pZ, 0);
26169      break;
26170    }
26171    case TK_TRIGGER: {
26172      /* If the opcode is TK_TRIGGER, then the expression is a reference
26173      ** to a column in the new.* or old.* pseudo-tables available to
26174      ** trigger programs. In this case Expr.iTable is set to 1 for the
26175      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
26176      ** is set to the column of the pseudo-table to read, or to -1 to
26177      ** read the rowid field.
26178      */
26179      sqlite3TreeViewLine(pView, "%s(%d)",
26180          pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
26181      break;
26182    }
26183    case TK_CASE: {
26184      sqlite3TreeViewLine(pView, "CASE");
26185      sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26186      sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
26187      break;
26188    }
26189#ifndef SQLITE_OMIT_TRIGGER
26190    case TK_RAISE: {
26191      const char *zType = "unk";
26192      switch( pExpr->affinity ){
26193        case OE_Rollback:   zType = "rollback";  break;
26194        case OE_Abort:      zType = "abort";     break;
26195        case OE_Fail:       zType = "fail";      break;
26196        case OE_Ignore:     zType = "ignore";    break;
26197      }
26198      sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
26199      break;
26200    }
26201#endif
26202    case TK_MATCH: {
26203      sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
26204                          pExpr->iTable, pExpr->iColumn, zFlgs);
26205      sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
26206      break;
26207    }
26208    default: {
26209      sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
26210      break;
26211    }
26212  }
26213  if( zBinOp ){
26214    sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
26215    sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26216    sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
26217  }else if( zUniOp ){
26218    sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
26219    sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26220  }
26221  sqlite3TreeViewPop(pView);
26222}
26223
26224/*
26225** Generate a human-readable explanation of an expression list.
26226*/
26227SQLITE_PRIVATE void sqlite3TreeViewExprList(
26228  TreeView *pView,
26229  const ExprList *pList,
26230  u8 moreToFollow,
26231  const char *zLabel
26232){
26233  int i;
26234  pView = sqlite3TreeViewPush(pView, moreToFollow);
26235  if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
26236  if( pList==0 ){
26237    sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
26238  }else{
26239    sqlite3TreeViewLine(pView, "%s", zLabel);
26240    for(i=0; i<pList->nExpr; i++){
26241      int j = pList->a[i].u.x.iOrderByCol;
26242      if( j ){
26243        sqlite3TreeViewPush(pView, 0);
26244        sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
26245      }
26246      sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
26247      if( j ) sqlite3TreeViewPop(pView);
26248    }
26249  }
26250  sqlite3TreeViewPop(pView);
26251}
26252
26253#endif /* SQLITE_DEBUG */
26254
26255/************** End of treeview.c ********************************************/
26256/************** Begin file random.c ******************************************/
26257/*
26258** 2001 September 15
26259**
26260** The author disclaims copyright to this source code.  In place of
26261** a legal notice, here is a blessing:
26262**
26263**    May you do good and not evil.
26264**    May you find forgiveness for yourself and forgive others.
26265**    May you share freely, never taking more than you give.
26266**
26267*************************************************************************
26268** This file contains code to implement a pseudo-random number
26269** generator (PRNG) for SQLite.
26270**
26271** Random numbers are used by some of the database backends in order
26272** to generate random integer keys for tables or random filenames.
26273*/
26274/* #include "sqliteInt.h" */
26275
26276
26277/* All threads share a single random number generator.
26278** This structure is the current state of the generator.
26279*/
26280static SQLITE_WSD struct sqlite3PrngType {
26281  unsigned char isInit;          /* True if initialized */
26282  unsigned char i, j;            /* State variables */
26283  unsigned char s[256];          /* State variables */
26284} sqlite3Prng;
26285
26286/*
26287** Return N random bytes.
26288*/
26289SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *pBuf){
26290  unsigned char t;
26291  unsigned char *zBuf = pBuf;
26292
26293  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
26294  ** state vector.  If writable static data is unsupported on the target,
26295  ** we have to locate the state vector at run-time.  In the more common
26296  ** case where writable static data is supported, wsdPrng can refer directly
26297  ** to the "sqlite3Prng" state vector declared above.
26298  */
26299#ifdef SQLITE_OMIT_WSD
26300  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
26301# define wsdPrng p[0]
26302#else
26303# define wsdPrng sqlite3Prng
26304#endif
26305
26306#if SQLITE_THREADSAFE
26307  sqlite3_mutex *mutex;
26308#endif
26309
26310#ifndef SQLITE_OMIT_AUTOINIT
26311  if( sqlite3_initialize() ) return;
26312#endif
26313
26314#if SQLITE_THREADSAFE
26315  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
26316#endif
26317
26318  sqlite3_mutex_enter(mutex);
26319  if( N<=0 || pBuf==0 ){
26320    wsdPrng.isInit = 0;
26321    sqlite3_mutex_leave(mutex);
26322    return;
26323  }
26324
26325  /* Initialize the state of the random number generator once,
26326  ** the first time this routine is called.  The seed value does
26327  ** not need to contain a lot of randomness since we are not
26328  ** trying to do secure encryption or anything like that...
26329  **
26330  ** Nothing in this file or anywhere else in SQLite does any kind of
26331  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
26332  ** number generator) not as an encryption device.
26333  */
26334  if( !wsdPrng.isInit ){
26335    int i;
26336    char k[256];
26337    wsdPrng.j = 0;
26338    wsdPrng.i = 0;
26339    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
26340    for(i=0; i<256; i++){
26341      wsdPrng.s[i] = (u8)i;
26342    }
26343    for(i=0; i<256; i++){
26344      wsdPrng.j += wsdPrng.s[i] + k[i];
26345      t = wsdPrng.s[wsdPrng.j];
26346      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
26347      wsdPrng.s[i] = t;
26348    }
26349    wsdPrng.isInit = 1;
26350  }
26351
26352  assert( N>0 );
26353  do{
26354    wsdPrng.i++;
26355    t = wsdPrng.s[wsdPrng.i];
26356    wsdPrng.j += t;
26357    wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
26358    wsdPrng.s[wsdPrng.j] = t;
26359    t += wsdPrng.s[wsdPrng.i];
26360    *(zBuf++) = wsdPrng.s[t];
26361  }while( --N );
26362  sqlite3_mutex_leave(mutex);
26363}
26364
26365#ifndef SQLITE_OMIT_BUILTIN_TEST
26366/*
26367** For testing purposes, we sometimes want to preserve the state of
26368** PRNG and restore the PRNG to its saved state at a later time, or
26369** to reset the PRNG to its initial state.  These routines accomplish
26370** those tasks.
26371**
26372** The sqlite3_test_control() interface calls these routines to
26373** control the PRNG.
26374*/
26375static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
26376SQLITE_PRIVATE void sqlite3PrngSaveState(void){
26377  memcpy(
26378    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
26379    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
26380    sizeof(sqlite3Prng)
26381  );
26382}
26383SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
26384  memcpy(
26385    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
26386    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
26387    sizeof(sqlite3Prng)
26388  );
26389}
26390#endif /* SQLITE_OMIT_BUILTIN_TEST */
26391
26392/************** End of random.c **********************************************/
26393/************** Begin file threads.c *****************************************/
26394/*
26395** 2012 July 21
26396**
26397** The author disclaims copyright to this source code.  In place of
26398** a legal notice, here is a blessing:
26399**
26400**    May you do good and not evil.
26401**    May you find forgiveness for yourself and forgive others.
26402**    May you share freely, never taking more than you give.
26403**
26404******************************************************************************
26405**
26406** This file presents a simple cross-platform threading interface for
26407** use internally by SQLite.
26408**
26409** A "thread" can be created using sqlite3ThreadCreate().  This thread
26410** runs independently of its creator until it is joined using
26411** sqlite3ThreadJoin(), at which point it terminates.
26412**
26413** Threads do not have to be real.  It could be that the work of the
26414** "thread" is done by the main thread at either the sqlite3ThreadCreate()
26415** or sqlite3ThreadJoin() call.  This is, in fact, what happens in
26416** single threaded systems.  Nothing in SQLite requires multiple threads.
26417** This interface exists so that applications that want to take advantage
26418** of multiple cores can do so, while also allowing applications to stay
26419** single-threaded if desired.
26420*/
26421/* #include "sqliteInt.h" */
26422#if SQLITE_OS_WIN
26423/* #  include "os_win.h" */
26424#endif
26425
26426#if SQLITE_MAX_WORKER_THREADS>0
26427
26428/********************************* Unix Pthreads ****************************/
26429#if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
26430
26431#define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
26432/* #include <pthread.h> */
26433
26434/* A running thread */
26435struct SQLiteThread {
26436  pthread_t tid;                 /* Thread ID */
26437  int done;                      /* Set to true when thread finishes */
26438  void *pOut;                    /* Result returned by the thread */
26439  void *(*xTask)(void*);         /* The thread routine */
26440  void *pIn;                     /* Argument to the thread */
26441};
26442
26443/* Create a new thread */
26444SQLITE_PRIVATE int sqlite3ThreadCreate(
26445  SQLiteThread **ppThread,  /* OUT: Write the thread object here */
26446  void *(*xTask)(void*),    /* Routine to run in a separate thread */
26447  void *pIn                 /* Argument passed into xTask() */
26448){
26449  SQLiteThread *p;
26450  int rc;
26451
26452  assert( ppThread!=0 );
26453  assert( xTask!=0 );
26454  /* This routine is never used in single-threaded mode */
26455  assert( sqlite3GlobalConfig.bCoreMutex!=0 );
26456
26457  *ppThread = 0;
26458  p = sqlite3Malloc(sizeof(*p));
26459  if( p==0 ) return SQLITE_NOMEM_BKPT;
26460  memset(p, 0, sizeof(*p));
26461  p->xTask = xTask;
26462  p->pIn = pIn;
26463  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
26464  ** function that returns SQLITE_ERROR when passed the argument 200, that
26465  ** forces worker threads to run sequentially and deterministically
26466  ** for testing purposes. */
26467  if( sqlite3FaultSim(200) ){
26468    rc = 1;
26469  }else{
26470    rc = pthread_create(&p->tid, 0, xTask, pIn);
26471  }
26472  if( rc ){
26473    p->done = 1;
26474    p->pOut = xTask(pIn);
26475  }
26476  *ppThread = p;
26477  return SQLITE_OK;
26478}
26479
26480/* Get the results of the thread */
26481SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26482  int rc;
26483
26484  assert( ppOut!=0 );
26485  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26486  if( p->done ){
26487    *ppOut = p->pOut;
26488    rc = SQLITE_OK;
26489  }else{
26490    rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
26491  }
26492  sqlite3_free(p);
26493  return rc;
26494}
26495
26496#endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
26497/******************************** End Unix Pthreads *************************/
26498
26499
26500/********************************* Win32 Threads ****************************/
26501#if SQLITE_OS_WIN_THREADS
26502
26503#define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
26504#include <process.h>
26505
26506/* A running thread */
26507struct SQLiteThread {
26508  void *tid;               /* The thread handle */
26509  unsigned id;             /* The thread identifier */
26510  void *(*xTask)(void*);   /* The routine to run as a thread */
26511  void *pIn;               /* Argument to xTask */
26512  void *pResult;           /* Result of xTask */
26513};
26514
26515/* Thread procedure Win32 compatibility shim */
26516static unsigned __stdcall sqlite3ThreadProc(
26517  void *pArg  /* IN: Pointer to the SQLiteThread structure */
26518){
26519  SQLiteThread *p = (SQLiteThread *)pArg;
26520
26521  assert( p!=0 );
26522#if 0
26523  /*
26524  ** This assert appears to trigger spuriously on certain
26525  ** versions of Windows, possibly due to _beginthreadex()
26526  ** and/or CreateThread() not fully setting their thread
26527  ** ID parameter before starting the thread.
26528  */
26529  assert( p->id==GetCurrentThreadId() );
26530#endif
26531  assert( p->xTask!=0 );
26532  p->pResult = p->xTask(p->pIn);
26533
26534  _endthreadex(0);
26535  return 0; /* NOT REACHED */
26536}
26537
26538/* Create a new thread */
26539SQLITE_PRIVATE int sqlite3ThreadCreate(
26540  SQLiteThread **ppThread,  /* OUT: Write the thread object here */
26541  void *(*xTask)(void*),    /* Routine to run in a separate thread */
26542  void *pIn                 /* Argument passed into xTask() */
26543){
26544  SQLiteThread *p;
26545
26546  assert( ppThread!=0 );
26547  assert( xTask!=0 );
26548  *ppThread = 0;
26549  p = sqlite3Malloc(sizeof(*p));
26550  if( p==0 ) return SQLITE_NOMEM_BKPT;
26551  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
26552  ** function that returns SQLITE_ERROR when passed the argument 200, that
26553  ** forces worker threads to run sequentially and deterministically
26554  ** (via the sqlite3FaultSim() term of the conditional) for testing
26555  ** purposes. */
26556  if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
26557    memset(p, 0, sizeof(*p));
26558  }else{
26559    p->xTask = xTask;
26560    p->pIn = pIn;
26561    p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
26562    if( p->tid==0 ){
26563      memset(p, 0, sizeof(*p));
26564    }
26565  }
26566  if( p->xTask==0 ){
26567    p->id = GetCurrentThreadId();
26568    p->pResult = xTask(pIn);
26569  }
26570  *ppThread = p;
26571  return SQLITE_OK;
26572}
26573
26574SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
26575
26576/* Get the results of the thread */
26577SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26578  DWORD rc;
26579  BOOL bRc;
26580
26581  assert( ppOut!=0 );
26582  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26583  if( p->xTask==0 ){
26584    /* assert( p->id==GetCurrentThreadId() ); */
26585    rc = WAIT_OBJECT_0;
26586    assert( p->tid==0 );
26587  }else{
26588    assert( p->id!=0 && p->id!=GetCurrentThreadId() );
26589    rc = sqlite3Win32Wait((HANDLE)p->tid);
26590    assert( rc!=WAIT_IO_COMPLETION );
26591    bRc = CloseHandle((HANDLE)p->tid);
26592    assert( bRc );
26593  }
26594  if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
26595  sqlite3_free(p);
26596  return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
26597}
26598
26599#endif /* SQLITE_OS_WIN_THREADS */
26600/******************************** End Win32 Threads *************************/
26601
26602
26603/********************************* Single-Threaded **************************/
26604#ifndef SQLITE_THREADS_IMPLEMENTED
26605/*
26606** This implementation does not actually create a new thread.  It does the
26607** work of the thread in the main thread, when either the thread is created
26608** or when it is joined
26609*/
26610
26611/* A running thread */
26612struct SQLiteThread {
26613  void *(*xTask)(void*);   /* The routine to run as a thread */
26614  void *pIn;               /* Argument to xTask */
26615  void *pResult;           /* Result of xTask */
26616};
26617
26618/* Create a new thread */
26619SQLITE_PRIVATE int sqlite3ThreadCreate(
26620  SQLiteThread **ppThread,  /* OUT: Write the thread object here */
26621  void *(*xTask)(void*),    /* Routine to run in a separate thread */
26622  void *pIn                 /* Argument passed into xTask() */
26623){
26624  SQLiteThread *p;
26625
26626  assert( ppThread!=0 );
26627  assert( xTask!=0 );
26628  *ppThread = 0;
26629  p = sqlite3Malloc(sizeof(*p));
26630  if( p==0 ) return SQLITE_NOMEM_BKPT;
26631  if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
26632    p->xTask = xTask;
26633    p->pIn = pIn;
26634  }else{
26635    p->xTask = 0;
26636    p->pResult = xTask(pIn);
26637  }
26638  *ppThread = p;
26639  return SQLITE_OK;
26640}
26641
26642/* Get the results of the thread */
26643SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26644
26645  assert( ppOut!=0 );
26646  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26647  if( p->xTask ){
26648    *ppOut = p->xTask(p->pIn);
26649  }else{
26650    *ppOut = p->pResult;
26651  }
26652  sqlite3_free(p);
26653
26654#if defined(SQLITE_TEST)
26655  {
26656    void *pTstAlloc = sqlite3Malloc(10);
26657    if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
26658    sqlite3_free(pTstAlloc);
26659  }
26660#endif
26661
26662  return SQLITE_OK;
26663}
26664
26665#endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
26666/****************************** End Single-Threaded *************************/
26667#endif /* SQLITE_MAX_WORKER_THREADS>0 */
26668
26669/************** End of threads.c *********************************************/
26670/************** Begin file utf.c *********************************************/
26671/*
26672** 2004 April 13
26673**
26674** The author disclaims copyright to this source code.  In place of
26675** a legal notice, here is a blessing:
26676**
26677**    May you do good and not evil.
26678**    May you find forgiveness for yourself and forgive others.
26679**    May you share freely, never taking more than you give.
26680**
26681*************************************************************************
26682** This file contains routines used to translate between UTF-8,
26683** UTF-16, UTF-16BE, and UTF-16LE.
26684**
26685** Notes on UTF-8:
26686**
26687**   Byte-0    Byte-1    Byte-2    Byte-3    Value
26688**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
26689**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
26690**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
26691**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
26692**
26693**
26694** Notes on UTF-16:  (with wwww+1==uuuuu)
26695**
26696**      Word-0               Word-1          Value
26697**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
26698**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
26699**
26700**
26701** BOM or Byte Order Mark:
26702**     0xff 0xfe   little-endian utf-16 follows
26703**     0xfe 0xff   big-endian utf-16 follows
26704**
26705*/
26706/* #include "sqliteInt.h" */
26707/* #include <assert.h> */
26708/* #include "vdbeInt.h" */
26709
26710#if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
26711/*
26712** The following constant value is used by the SQLITE_BIGENDIAN and
26713** SQLITE_LITTLEENDIAN macros.
26714*/
26715SQLITE_PRIVATE const int sqlite3one = 1;
26716#endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
26717
26718/*
26719** This lookup table is used to help decode the first byte of
26720** a multi-byte UTF8 character.
26721*/
26722static const unsigned char sqlite3Utf8Trans1[] = {
26723  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26724  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
26725  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
26726  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
26727  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26728  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
26729  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26730  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
26731};
26732
26733
26734#define WRITE_UTF8(zOut, c) {                          \
26735  if( c<0x00080 ){                                     \
26736    *zOut++ = (u8)(c&0xFF);                            \
26737  }                                                    \
26738  else if( c<0x00800 ){                                \
26739    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
26740    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
26741  }                                                    \
26742  else if( c<0x10000 ){                                \
26743    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
26744    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
26745    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
26746  }else{                                               \
26747    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
26748    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
26749    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
26750    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
26751  }                                                    \
26752}
26753
26754#define WRITE_UTF16LE(zOut, c) {                                    \
26755  if( c<=0xFFFF ){                                                  \
26756    *zOut++ = (u8)(c&0x00FF);                                       \
26757    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
26758  }else{                                                            \
26759    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
26760    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
26761    *zOut++ = (u8)(c&0x00FF);                                       \
26762    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
26763  }                                                                 \
26764}
26765
26766#define WRITE_UTF16BE(zOut, c) {                                    \
26767  if( c<=0xFFFF ){                                                  \
26768    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
26769    *zOut++ = (u8)(c&0x00FF);                                       \
26770  }else{                                                            \
26771    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
26772    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
26773    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
26774    *zOut++ = (u8)(c&0x00FF);                                       \
26775  }                                                                 \
26776}
26777
26778#define READ_UTF16LE(zIn, TERM, c){                                   \
26779  c = (*zIn++);                                                       \
26780  c += ((*zIn++)<<8);                                                 \
26781  if( c>=0xD800 && c<0xE000 && TERM ){                                \
26782    int c2 = (*zIn++);                                                \
26783    c2 += ((*zIn++)<<8);                                              \
26784    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
26785  }                                                                   \
26786}
26787
26788#define READ_UTF16BE(zIn, TERM, c){                                   \
26789  c = ((*zIn++)<<8);                                                  \
26790  c += (*zIn++);                                                      \
26791  if( c>=0xD800 && c<0xE000 && TERM ){                                \
26792    int c2 = ((*zIn++)<<8);                                           \
26793    c2 += (*zIn++);                                                   \
26794    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
26795  }                                                                   \
26796}
26797
26798/*
26799** Translate a single UTF-8 character.  Return the unicode value.
26800**
26801** During translation, assume that the byte that zTerm points
26802** is a 0x00.
26803**
26804** Write a pointer to the next unread byte back into *pzNext.
26805**
26806** Notes On Invalid UTF-8:
26807**
26808**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
26809**     be encoded as a multi-byte character.  Any multi-byte character that
26810**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
26811**
26812**  *  This routine never allows a UTF16 surrogate value to be encoded.
26813**     If a multi-byte character attempts to encode a value between
26814**     0xd800 and 0xe000 then it is rendered as 0xfffd.
26815**
26816**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
26817**     byte of a character are interpreted as single-byte characters
26818**     and rendered as themselves even though they are technically
26819**     invalid characters.
26820**
26821**  *  This routine accepts over-length UTF8 encodings
26822**     for unicode values 0x80 and greater.  It does not change over-length
26823**     encodings to 0xfffd as some systems recommend.
26824*/
26825#define READ_UTF8(zIn, zTerm, c)                           \
26826  c = *(zIn++);                                            \
26827  if( c>=0xc0 ){                                           \
26828    c = sqlite3Utf8Trans1[c-0xc0];                         \
26829    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
26830      c = (c<<6) + (0x3f & *(zIn++));                      \
26831    }                                                      \
26832    if( c<0x80                                             \
26833        || (c&0xFFFFF800)==0xD800                          \
26834        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
26835  }
26836SQLITE_PRIVATE u32 sqlite3Utf8Read(
26837  const unsigned char **pz    /* Pointer to string from which to read char */
26838){
26839  unsigned int c;
26840
26841  /* Same as READ_UTF8() above but without the zTerm parameter.
26842  ** For this routine, we assume the UTF8 string is always zero-terminated.
26843  */
26844  c = *((*pz)++);
26845  if( c>=0xc0 ){
26846    c = sqlite3Utf8Trans1[c-0xc0];
26847    while( (*(*pz) & 0xc0)==0x80 ){
26848      c = (c<<6) + (0x3f & *((*pz)++));
26849    }
26850    if( c<0x80
26851        || (c&0xFFFFF800)==0xD800
26852        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
26853  }
26854  return c;
26855}
26856
26857
26858
26859
26860/*
26861** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
26862** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
26863*/
26864/* #define TRANSLATE_TRACE 1 */
26865
26866#ifndef SQLITE_OMIT_UTF16
26867/*
26868** This routine transforms the internal text encoding used by pMem to
26869** desiredEnc. It is an error if the string is already of the desired
26870** encoding, or if *pMem does not contain a string value.
26871*/
26872SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
26873  int len;                    /* Maximum length of output string in bytes */
26874  unsigned char *zOut;                  /* Output buffer */
26875  unsigned char *zIn;                   /* Input iterator */
26876  unsigned char *zTerm;                 /* End of input */
26877  unsigned char *z;                     /* Output iterator */
26878  unsigned int c;
26879
26880  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
26881  assert( pMem->flags&MEM_Str );
26882  assert( pMem->enc!=desiredEnc );
26883  assert( pMem->enc!=0 );
26884  assert( pMem->n>=0 );
26885
26886#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
26887  {
26888    char zBuf[100];
26889    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
26890    fprintf(stderr, "INPUT:  %s\n", zBuf);
26891  }
26892#endif
26893
26894  /* If the translation is between UTF-16 little and big endian, then
26895  ** all that is required is to swap the byte order. This case is handled
26896  ** differently from the others.
26897  */
26898  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
26899    u8 temp;
26900    int rc;
26901    rc = sqlite3VdbeMemMakeWriteable(pMem);
26902    if( rc!=SQLITE_OK ){
26903      assert( rc==SQLITE_NOMEM );
26904      return SQLITE_NOMEM_BKPT;
26905    }
26906    zIn = (u8*)pMem->z;
26907    zTerm = &zIn[pMem->n&~1];
26908    while( zIn<zTerm ){
26909      temp = *zIn;
26910      *zIn = *(zIn+1);
26911      zIn++;
26912      *zIn++ = temp;
26913    }
26914    pMem->enc = desiredEnc;
26915    goto translate_out;
26916  }
26917
26918  /* Set len to the maximum number of bytes required in the output buffer. */
26919  if( desiredEnc==SQLITE_UTF8 ){
26920    /* When converting from UTF-16, the maximum growth results from
26921    ** translating a 2-byte character to a 4-byte UTF-8 character.
26922    ** A single byte is required for the output string
26923    ** nul-terminator.
26924    */
26925    pMem->n &= ~1;
26926    len = pMem->n * 2 + 1;
26927  }else{
26928    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
26929    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
26930    ** character. Two bytes are required in the output buffer for the
26931    ** nul-terminator.
26932    */
26933    len = pMem->n * 2 + 2;
26934  }
26935
26936  /* Set zIn to point at the start of the input buffer and zTerm to point 1
26937  ** byte past the end.
26938  **
26939  ** Variable zOut is set to point at the output buffer, space obtained
26940  ** from sqlite3_malloc().
26941  */
26942  zIn = (u8*)pMem->z;
26943  zTerm = &zIn[pMem->n];
26944  zOut = sqlite3DbMallocRaw(pMem->db, len);
26945  if( !zOut ){
26946    return SQLITE_NOMEM_BKPT;
26947  }
26948  z = zOut;
26949
26950  if( pMem->enc==SQLITE_UTF8 ){
26951    if( desiredEnc==SQLITE_UTF16LE ){
26952      /* UTF-8 -> UTF-16 Little-endian */
26953      while( zIn<zTerm ){
26954        READ_UTF8(zIn, zTerm, c);
26955        WRITE_UTF16LE(z, c);
26956      }
26957    }else{
26958      assert( desiredEnc==SQLITE_UTF16BE );
26959      /* UTF-8 -> UTF-16 Big-endian */
26960      while( zIn<zTerm ){
26961        READ_UTF8(zIn, zTerm, c);
26962        WRITE_UTF16BE(z, c);
26963      }
26964    }
26965    pMem->n = (int)(z - zOut);
26966    *z++ = 0;
26967  }else{
26968    assert( desiredEnc==SQLITE_UTF8 );
26969    if( pMem->enc==SQLITE_UTF16LE ){
26970      /* UTF-16 Little-endian -> UTF-8 */
26971      while( zIn<zTerm ){
26972        READ_UTF16LE(zIn, zIn<zTerm, c);
26973        WRITE_UTF8(z, c);
26974      }
26975    }else{
26976      /* UTF-16 Big-endian -> UTF-8 */
26977      while( zIn<zTerm ){
26978        READ_UTF16BE(zIn, zIn<zTerm, c);
26979        WRITE_UTF8(z, c);
26980      }
26981    }
26982    pMem->n = (int)(z - zOut);
26983  }
26984  *z = 0;
26985  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
26986
26987  c = pMem->flags;
26988  sqlite3VdbeMemRelease(pMem);
26989  pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
26990  pMem->enc = desiredEnc;
26991  pMem->z = (char*)zOut;
26992  pMem->zMalloc = pMem->z;
26993  pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
26994
26995translate_out:
26996#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
26997  {
26998    char zBuf[100];
26999    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
27000    fprintf(stderr, "OUTPUT: %s\n", zBuf);
27001  }
27002#endif
27003  return SQLITE_OK;
27004}
27005
27006/*
27007** This routine checks for a byte-order mark at the beginning of the
27008** UTF-16 string stored in *pMem. If one is present, it is removed and
27009** the encoding of the Mem adjusted. This routine does not do any
27010** byte-swapping, it just sets Mem.enc appropriately.
27011**
27012** The allocation (static, dynamic etc.) and encoding of the Mem may be
27013** changed by this function.
27014*/
27015SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
27016  int rc = SQLITE_OK;
27017  u8 bom = 0;
27018
27019  assert( pMem->n>=0 );
27020  if( pMem->n>1 ){
27021    u8 b1 = *(u8 *)pMem->z;
27022    u8 b2 = *(((u8 *)pMem->z) + 1);
27023    if( b1==0xFE && b2==0xFF ){
27024      bom = SQLITE_UTF16BE;
27025    }
27026    if( b1==0xFF && b2==0xFE ){
27027      bom = SQLITE_UTF16LE;
27028    }
27029  }
27030
27031  if( bom ){
27032    rc = sqlite3VdbeMemMakeWriteable(pMem);
27033    if( rc==SQLITE_OK ){
27034      pMem->n -= 2;
27035      memmove(pMem->z, &pMem->z[2], pMem->n);
27036      pMem->z[pMem->n] = '\0';
27037      pMem->z[pMem->n+1] = '\0';
27038      pMem->flags |= MEM_Term;
27039      pMem->enc = bom;
27040    }
27041  }
27042  return rc;
27043}
27044#endif /* SQLITE_OMIT_UTF16 */
27045
27046/*
27047** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
27048** return the number of unicode characters in pZ up to (but not including)
27049** the first 0x00 byte. If nByte is not less than zero, return the
27050** number of unicode characters in the first nByte of pZ (or up to
27051** the first 0x00, whichever comes first).
27052*/
27053SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
27054  int r = 0;
27055  const u8 *z = (const u8*)zIn;
27056  const u8 *zTerm;
27057  if( nByte>=0 ){
27058    zTerm = &z[nByte];
27059  }else{
27060    zTerm = (const u8*)(-1);
27061  }
27062  assert( z<=zTerm );
27063  while( *z!=0 && z<zTerm ){
27064    SQLITE_SKIP_UTF8(z);
27065    r++;
27066  }
27067  return r;
27068}
27069
27070/* This test function is not currently used by the automated test-suite.
27071** Hence it is only available in debug builds.
27072*/
27073#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
27074/*
27075** Translate UTF-8 to UTF-8.
27076**
27077** This has the effect of making sure that the string is well-formed
27078** UTF-8.  Miscoded characters are removed.
27079**
27080** The translation is done in-place and aborted if the output
27081** overruns the input.
27082*/
27083SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
27084  unsigned char *zOut = zIn;
27085  unsigned char *zStart = zIn;
27086  u32 c;
27087
27088  while( zIn[0] && zOut<=zIn ){
27089    c = sqlite3Utf8Read((const u8**)&zIn);
27090    if( c!=0xfffd ){
27091      WRITE_UTF8(zOut, c);
27092    }
27093  }
27094  *zOut = 0;
27095  return (int)(zOut - zStart);
27096}
27097#endif
27098
27099#ifndef SQLITE_OMIT_UTF16
27100/*
27101** Convert a UTF-16 string in the native encoding into a UTF-8 string.
27102** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
27103** be freed by the calling function.
27104**
27105** NULL is returned if there is an allocation error.
27106*/
27107SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
27108  Mem m;
27109  memset(&m, 0, sizeof(m));
27110  m.db = db;
27111  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
27112  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
27113  if( db->mallocFailed ){
27114    sqlite3VdbeMemRelease(&m);
27115    m.z = 0;
27116  }
27117  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
27118  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
27119  assert( m.z || db->mallocFailed );
27120  return m.z;
27121}
27122
27123/*
27124** zIn is a UTF-16 encoded unicode string at least nChar characters long.
27125** Return the number of bytes in the first nChar unicode characters
27126** in pZ.  nChar must be non-negative.
27127*/
27128SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
27129  int c;
27130  unsigned char const *z = zIn;
27131  int n = 0;
27132
27133  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
27134    while( n<nChar ){
27135      READ_UTF16BE(z, 1, c);
27136      n++;
27137    }
27138  }else{
27139    while( n<nChar ){
27140      READ_UTF16LE(z, 1, c);
27141      n++;
27142    }
27143  }
27144  return (int)(z-(unsigned char const *)zIn);
27145}
27146
27147#if defined(SQLITE_TEST)
27148/*
27149** This routine is called from the TCL test function "translate_selftest".
27150** It checks that the primitives for serializing and deserializing
27151** characters in each encoding are inverses of each other.
27152*/
27153SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
27154  unsigned int i, t;
27155  unsigned char zBuf[20];
27156  unsigned char *z;
27157  int n;
27158  unsigned int c;
27159
27160  for(i=0; i<0x00110000; i++){
27161    z = zBuf;
27162    WRITE_UTF8(z, i);
27163    n = (int)(z-zBuf);
27164    assert( n>0 && n<=4 );
27165    z[0] = 0;
27166    z = zBuf;
27167    c = sqlite3Utf8Read((const u8**)&z);
27168    t = i;
27169    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
27170    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
27171    assert( c==t );
27172    assert( (z-zBuf)==n );
27173  }
27174  for(i=0; i<0x00110000; i++){
27175    if( i>=0xD800 && i<0xE000 ) continue;
27176    z = zBuf;
27177    WRITE_UTF16LE(z, i);
27178    n = (int)(z-zBuf);
27179    assert( n>0 && n<=4 );
27180    z[0] = 0;
27181    z = zBuf;
27182    READ_UTF16LE(z, 1, c);
27183    assert( c==i );
27184    assert( (z-zBuf)==n );
27185  }
27186  for(i=0; i<0x00110000; i++){
27187    if( i>=0xD800 && i<0xE000 ) continue;
27188    z = zBuf;
27189    WRITE_UTF16BE(z, i);
27190    n = (int)(z-zBuf);
27191    assert( n>0 && n<=4 );
27192    z[0] = 0;
27193    z = zBuf;
27194    READ_UTF16BE(z, 1, c);
27195    assert( c==i );
27196    assert( (z-zBuf)==n );
27197  }
27198}
27199#endif /* SQLITE_TEST */
27200#endif /* SQLITE_OMIT_UTF16 */
27201
27202/************** End of utf.c *************************************************/
27203/************** Begin file util.c ********************************************/
27204/*
27205** 2001 September 15
27206**
27207** The author disclaims copyright to this source code.  In place of
27208** a legal notice, here is a blessing:
27209**
27210**    May you do good and not evil.
27211**    May you find forgiveness for yourself and forgive others.
27212**    May you share freely, never taking more than you give.
27213**
27214*************************************************************************
27215** Utility functions used throughout sqlite.
27216**
27217** This file contains functions for allocating memory, comparing
27218** strings, and stuff like that.
27219**
27220*/
27221/* #include "sqliteInt.h" */
27222/* #include <stdarg.h> */
27223#if HAVE_ISNAN || SQLITE_HAVE_ISNAN
27224# include <math.h>
27225#endif
27226
27227/*
27228** Routine needed to support the testcase() macro.
27229*/
27230#ifdef SQLITE_COVERAGE_TEST
27231SQLITE_PRIVATE void sqlite3Coverage(int x){
27232  static unsigned dummy = 0;
27233  dummy += (unsigned)x;
27234}
27235#endif
27236
27237/*
27238** Give a callback to the test harness that can be used to simulate faults
27239** in places where it is difficult or expensive to do so purely by means
27240** of inputs.
27241**
27242** The intent of the integer argument is to let the fault simulator know
27243** which of multiple sqlite3FaultSim() calls has been hit.
27244**
27245** Return whatever integer value the test callback returns, or return
27246** SQLITE_OK if no test callback is installed.
27247*/
27248#ifndef SQLITE_OMIT_BUILTIN_TEST
27249SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
27250  int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
27251  return xCallback ? xCallback(iTest) : SQLITE_OK;
27252}
27253#endif
27254
27255#ifndef SQLITE_OMIT_FLOATING_POINT
27256/*
27257** Return true if the floating point value is Not a Number (NaN).
27258**
27259** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
27260** Otherwise, we have our own implementation that works on most systems.
27261*/
27262SQLITE_PRIVATE int sqlite3IsNaN(double x){
27263  int rc;   /* The value return */
27264#if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
27265  /*
27266  ** Systems that support the isnan() library function should probably
27267  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
27268  ** found that many systems do not have a working isnan() function so
27269  ** this implementation is provided as an alternative.
27270  **
27271  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
27272  ** On the other hand, the use of -ffast-math comes with the following
27273  ** warning:
27274  **
27275  **      This option [-ffast-math] should never be turned on by any
27276  **      -O option since it can result in incorrect output for programs
27277  **      which depend on an exact implementation of IEEE or ISO
27278  **      rules/specifications for math functions.
27279  **
27280  ** Under MSVC, this NaN test may fail if compiled with a floating-
27281  ** point precision mode other than /fp:precise.  From the MSDN
27282  ** documentation:
27283  **
27284  **      The compiler [with /fp:precise] will properly handle comparisons
27285  **      involving NaN. For example, x != x evaluates to true if x is NaN
27286  **      ...
27287  */
27288#ifdef __FAST_MATH__
27289# error SQLite will not work correctly with the -ffast-math option of GCC.
27290#endif
27291  volatile double y = x;
27292  volatile double z = y;
27293  rc = (y!=z);
27294#else  /* if HAVE_ISNAN */
27295  rc = isnan(x);
27296#endif /* HAVE_ISNAN */
27297  testcase( rc );
27298  return rc;
27299}
27300#endif /* SQLITE_OMIT_FLOATING_POINT */
27301
27302/*
27303** Compute a string length that is limited to what can be stored in
27304** lower 30 bits of a 32-bit signed integer.
27305**
27306** The value returned will never be negative.  Nor will it ever be greater
27307** than the actual length of the string.  For very long strings (greater
27308** than 1GiB) the value returned might be less than the true string length.
27309*/
27310SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
27311  if( z==0 ) return 0;
27312  return 0x3fffffff & (int)strlen(z);
27313}
27314
27315/*
27316** Return the declared type of a column.  Or return zDflt if the column
27317** has no declared type.
27318**
27319** The column type is an extra string stored after the zero-terminator on
27320** the column name if and only if the COLFLAG_HASTYPE flag is set.
27321*/
27322SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
27323  if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
27324  return pCol->zName + strlen(pCol->zName) + 1;
27325}
27326
27327/*
27328** Helper function for sqlite3Error() - called rarely.  Broken out into
27329** a separate routine to avoid unnecessary register saves on entry to
27330** sqlite3Error().
27331*/
27332static SQLITE_NOINLINE void  sqlite3ErrorFinish(sqlite3 *db, int err_code){
27333  if( db->pErr ) sqlite3ValueSetNull(db->pErr);
27334  sqlite3SystemError(db, err_code);
27335}
27336
27337/*
27338** Set the current error code to err_code and clear any prior error message.
27339** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
27340** that would be appropriate.
27341*/
27342SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
27343  assert( db!=0 );
27344  db->errCode = err_code;
27345  if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
27346}
27347
27348/*
27349** Load the sqlite3.iSysErrno field if that is an appropriate thing
27350** to do based on the SQLite error code in rc.
27351*/
27352SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
27353  if( rc==SQLITE_IOERR_NOMEM ) return;
27354  rc &= 0xff;
27355  if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
27356    db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
27357  }
27358}
27359
27360/*
27361** Set the most recent error code and error string for the sqlite
27362** handle "db". The error code is set to "err_code".
27363**
27364** If it is not NULL, string zFormat specifies the format of the
27365** error string in the style of the printf functions: The following
27366** format characters are allowed:
27367**
27368**      %s      Insert a string
27369**      %z      A string that should be freed after use
27370**      %d      Insert an integer
27371**      %T      Insert a token
27372**      %S      Insert the first element of a SrcList
27373**
27374** zFormat and any string tokens that follow it are assumed to be
27375** encoded in UTF-8.
27376**
27377** To clear the most recent error for sqlite handle "db", sqlite3Error
27378** should be called with err_code set to SQLITE_OK and zFormat set
27379** to NULL.
27380*/
27381SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
27382  assert( db!=0 );
27383  db->errCode = err_code;
27384  sqlite3SystemError(db, err_code);
27385  if( zFormat==0 ){
27386    sqlite3Error(db, err_code);
27387  }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
27388    char *z;
27389    va_list ap;
27390    va_start(ap, zFormat);
27391    z = sqlite3VMPrintf(db, zFormat, ap);
27392    va_end(ap);
27393    sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
27394  }
27395}
27396
27397/*
27398** Add an error message to pParse->zErrMsg and increment pParse->nErr.
27399** The following formatting characters are allowed:
27400**
27401**      %s      Insert a string
27402**      %z      A string that should be freed after use
27403**      %d      Insert an integer
27404**      %T      Insert a token
27405**      %S      Insert the first element of a SrcList
27406**
27407** This function should be used to report any error that occurs while
27408** compiling an SQL statement (i.e. within sqlite3_prepare()). The
27409** last thing the sqlite3_prepare() function does is copy the error
27410** stored by this function into the database handle using sqlite3Error().
27411** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
27412** during statement execution (sqlite3_step() etc.).
27413*/
27414SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
27415  char *zMsg;
27416  va_list ap;
27417  sqlite3 *db = pParse->db;
27418  va_start(ap, zFormat);
27419  zMsg = sqlite3VMPrintf(db, zFormat, ap);
27420  va_end(ap);
27421  if( db->suppressErr ){
27422    sqlite3DbFree(db, zMsg);
27423  }else{
27424    pParse->nErr++;
27425    sqlite3DbFree(db, pParse->zErrMsg);
27426    pParse->zErrMsg = zMsg;
27427    pParse->rc = SQLITE_ERROR;
27428  }
27429}
27430
27431/*
27432** Convert an SQL-style quoted string into a normal string by removing
27433** the quote characters.  The conversion is done in-place.  If the
27434** input does not begin with a quote character, then this routine
27435** is a no-op.
27436**
27437** The input string must be zero-terminated.  A new zero-terminator
27438** is added to the dequoted string.
27439**
27440** The return value is -1 if no dequoting occurs or the length of the
27441** dequoted string, exclusive of the zero terminator, if dequoting does
27442** occur.
27443**
27444** 2002-Feb-14: This routine is extended to remove MS-Access style
27445** brackets from around identifiers.  For example:  "[a-b-c]" becomes
27446** "a-b-c".
27447*/
27448SQLITE_PRIVATE void sqlite3Dequote(char *z){
27449  char quote;
27450  int i, j;
27451  if( z==0 ) return;
27452  quote = z[0];
27453  if( !sqlite3Isquote(quote) ) return;
27454  if( quote=='[' ) quote = ']';
27455  for(i=1, j=0;; i++){
27456    assert( z[i] );
27457    if( z[i]==quote ){
27458      if( z[i+1]==quote ){
27459        z[j++] = quote;
27460        i++;
27461      }else{
27462        break;
27463      }
27464    }else{
27465      z[j++] = z[i];
27466    }
27467  }
27468  z[j] = 0;
27469}
27470
27471/*
27472** Generate a Token object from a string
27473*/
27474SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
27475  p->z = z;
27476  p->n = sqlite3Strlen30(z);
27477}
27478
27479/* Convenient short-hand */
27480#define UpperToLower sqlite3UpperToLower
27481
27482/*
27483** Some systems have stricmp().  Others have strcasecmp().  Because
27484** there is no consistency, we will define our own.
27485**
27486** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
27487** sqlite3_strnicmp() APIs allow applications and extensions to compare
27488** the contents of two buffers containing UTF-8 strings in a
27489** case-independent fashion, using the same definition of "case
27490** independence" that SQLite uses internally when comparing identifiers.
27491*/
27492SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *zLeft, const char *zRight){
27493  if( zLeft==0 ){
27494    return zRight ? -1 : 0;
27495  }else if( zRight==0 ){
27496    return 1;
27497  }
27498  return sqlite3StrICmp(zLeft, zRight);
27499}
27500SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
27501  unsigned char *a, *b;
27502  int c;
27503  a = (unsigned char *)zLeft;
27504  b = (unsigned char *)zRight;
27505  for(;;){
27506    c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
27507    if( c || *a==0 ) break;
27508    a++;
27509    b++;
27510  }
27511  return c;
27512}
27513SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
27514  register unsigned char *a, *b;
27515  if( zLeft==0 ){
27516    return zRight ? -1 : 0;
27517  }else if( zRight==0 ){
27518    return 1;
27519  }
27520  a = (unsigned char *)zLeft;
27521  b = (unsigned char *)zRight;
27522  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
27523  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
27524}
27525
27526/*
27527** The string z[] is an text representation of a real number.
27528** Convert this string to a double and write it into *pResult.
27529**
27530** The string z[] is length bytes in length (bytes, not characters) and
27531** uses the encoding enc.  The string is not necessarily zero-terminated.
27532**
27533** Return TRUE if the result is a valid real number (or integer) and FALSE
27534** if the string is empty or contains extraneous text.  Valid numbers
27535** are in one of these formats:
27536**
27537**    [+-]digits[E[+-]digits]
27538**    [+-]digits.[digits][E[+-]digits]
27539**    [+-].digits[E[+-]digits]
27540**
27541** Leading and trailing whitespace is ignored for the purpose of determining
27542** validity.
27543**
27544** If some prefix of the input string is a valid number, this routine
27545** returns FALSE but it still converts the prefix and writes the result
27546** into *pResult.
27547*/
27548SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
27549#ifndef SQLITE_OMIT_FLOATING_POINT
27550  int incr;
27551  const char *zEnd = z + length;
27552  /* sign * significand * (10 ^ (esign * exponent)) */
27553  int sign = 1;    /* sign of significand */
27554  i64 s = 0;       /* significand */
27555  int d = 0;       /* adjust exponent for shifting decimal point */
27556  int esign = 1;   /* sign of exponent */
27557  int e = 0;       /* exponent */
27558  int eValid = 1;  /* True exponent is either not used or is well-formed */
27559  double result;
27560  int nDigits = 0;
27561  int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
27562
27563  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
27564  *pResult = 0.0;   /* Default return value, in case of an error */
27565
27566  if( enc==SQLITE_UTF8 ){
27567    incr = 1;
27568  }else{
27569    int i;
27570    incr = 2;
27571    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
27572    for(i=3-enc; i<length && z[i]==0; i+=2){}
27573    nonNum = i<length;
27574    zEnd = &z[i^1];
27575    z += (enc&1);
27576  }
27577
27578  /* skip leading spaces */
27579  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
27580  if( z>=zEnd ) return 0;
27581
27582  /* get sign of significand */
27583  if( *z=='-' ){
27584    sign = -1;
27585    z+=incr;
27586  }else if( *z=='+' ){
27587    z+=incr;
27588  }
27589
27590  /* copy max significant digits to significand */
27591  while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
27592    s = s*10 + (*z - '0');
27593    z+=incr, nDigits++;
27594  }
27595
27596  /* skip non-significant significand digits
27597  ** (increase exponent by d to shift decimal left) */
27598  while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
27599  if( z>=zEnd ) goto do_atof_calc;
27600
27601  /* if decimal point is present */
27602  if( *z=='.' ){
27603    z+=incr;
27604    /* copy digits from after decimal to significand
27605    ** (decrease exponent by d to shift decimal right) */
27606    while( z<zEnd && sqlite3Isdigit(*z) ){
27607      if( s<((LARGEST_INT64-9)/10) ){
27608        s = s*10 + (*z - '0');
27609        d--;
27610      }
27611      z+=incr, nDigits++;
27612    }
27613  }
27614  if( z>=zEnd ) goto do_atof_calc;
27615
27616  /* if exponent is present */
27617  if( *z=='e' || *z=='E' ){
27618    z+=incr;
27619    eValid = 0;
27620
27621    /* This branch is needed to avoid a (harmless) buffer overread.  The
27622    ** special comment alerts the mutation tester that the correct answer
27623    ** is obtained even if the branch is omitted */
27624    if( z>=zEnd ) goto do_atof_calc;              /*PREVENTS-HARMLESS-OVERREAD*/
27625
27626    /* get sign of exponent */
27627    if( *z=='-' ){
27628      esign = -1;
27629      z+=incr;
27630    }else if( *z=='+' ){
27631      z+=incr;
27632    }
27633    /* copy digits to exponent */
27634    while( z<zEnd && sqlite3Isdigit(*z) ){
27635      e = e<10000 ? (e*10 + (*z - '0')) : 10000;
27636      z+=incr;
27637      eValid = 1;
27638    }
27639  }
27640
27641  /* skip trailing spaces */
27642  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
27643
27644do_atof_calc:
27645  /* adjust exponent by d, and update sign */
27646  e = (e*esign) + d;
27647  if( e<0 ) {
27648    esign = -1;
27649    e *= -1;
27650  } else {
27651    esign = 1;
27652  }
27653
27654  if( s==0 ) {
27655    /* In the IEEE 754 standard, zero is signed. */
27656    result = sign<0 ? -(double)0 : (double)0;
27657  } else {
27658    /* Attempt to reduce exponent.
27659    **
27660    ** Branches that are not required for the correct answer but which only
27661    ** help to obtain the correct answer faster are marked with special
27662    ** comments, as a hint to the mutation tester.
27663    */
27664    while( e>0 ){                                       /*OPTIMIZATION-IF-TRUE*/
27665      if( esign>0 ){
27666        if( s>=(LARGEST_INT64/10) ) break;             /*OPTIMIZATION-IF-FALSE*/
27667        s *= 10;
27668      }else{
27669        if( s%10!=0 ) break;                           /*OPTIMIZATION-IF-FALSE*/
27670        s /= 10;
27671      }
27672      e--;
27673    }
27674
27675    /* adjust the sign of significand */
27676    s = sign<0 ? -s : s;
27677
27678    if( e==0 ){                                         /*OPTIMIZATION-IF-TRUE*/
27679      result = (double)s;
27680    }else{
27681      LONGDOUBLE_TYPE scale = 1.0;
27682      /* attempt to handle extremely small/large numbers better */
27683      if( e>307 ){                                      /*OPTIMIZATION-IF-TRUE*/
27684        if( e<342 ){                                    /*OPTIMIZATION-IF-TRUE*/
27685          while( e%308 ) { scale *= 1.0e+1; e -= 1; }
27686          if( esign<0 ){
27687            result = s / scale;
27688            result /= 1.0e+308;
27689          }else{
27690            result = s * scale;
27691            result *= 1.0e+308;
27692          }
27693        }else{ assert( e>=342 );
27694          if( esign<0 ){
27695            result = 0.0*s;
27696          }else{
27697            result = 1e308*1e308*s;  /* Infinity */
27698          }
27699        }
27700      }else{
27701        /* 1.0e+22 is the largest power of 10 than can be
27702        ** represented exactly. */
27703        while( e%22 ) { scale *= 1.0e+1; e -= 1; }
27704        while( e>0 ) { scale *= 1.0e+22; e -= 22; }
27705        if( esign<0 ){
27706          result = s / scale;
27707        }else{
27708          result = s * scale;
27709        }
27710      }
27711    }
27712  }
27713
27714  /* store the result */
27715  *pResult = result;
27716
27717  /* return true if number and no extra non-whitespace chracters after */
27718  return z==zEnd && nDigits>0 && eValid && nonNum==0;
27719#else
27720  return !sqlite3Atoi64(z, pResult, length, enc);
27721#endif /* SQLITE_OMIT_FLOATING_POINT */
27722}
27723
27724/*
27725** Compare the 19-character string zNum against the text representation
27726** value 2^63:  9223372036854775808.  Return negative, zero, or positive
27727** if zNum is less than, equal to, or greater than the string.
27728** Note that zNum must contain exactly 19 characters.
27729**
27730** Unlike memcmp() this routine is guaranteed to return the difference
27731** in the values of the last digit if the only difference is in the
27732** last digit.  So, for example,
27733**
27734**      compare2pow63("9223372036854775800", 1)
27735**
27736** will return -8.
27737*/
27738static int compare2pow63(const char *zNum, int incr){
27739  int c = 0;
27740  int i;
27741                    /* 012345678901234567 */
27742  const char *pow63 = "922337203685477580";
27743  for(i=0; c==0 && i<18; i++){
27744    c = (zNum[i*incr]-pow63[i])*10;
27745  }
27746  if( c==0 ){
27747    c = zNum[18*incr] - '8';
27748    testcase( c==(-1) );
27749    testcase( c==0 );
27750    testcase( c==(+1) );
27751  }
27752  return c;
27753}
27754
27755/*
27756** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This
27757** routine does *not* accept hexadecimal notation.
27758**
27759** If the zNum value is representable as a 64-bit twos-complement
27760** integer, then write that value into *pNum and return 0.
27761**
27762** If zNum is exactly 9223372036854775808, return 2.  This special
27763** case is broken out because while 9223372036854775808 cannot be a
27764** signed 64-bit integer, its negative -9223372036854775808 can be.
27765**
27766** If zNum is too big for a 64-bit integer and is not
27767** 9223372036854775808  or if zNum contains any non-numeric text,
27768** then return 1.
27769**
27770** length is the number of bytes in the string (bytes, not characters).
27771** The string is not necessarily zero-terminated.  The encoding is
27772** given by enc.
27773*/
27774SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
27775  int incr;
27776  u64 u = 0;
27777  int neg = 0; /* assume positive */
27778  int i;
27779  int c = 0;
27780  int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
27781  const char *zStart;
27782  const char *zEnd = zNum + length;
27783  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
27784  if( enc==SQLITE_UTF8 ){
27785    incr = 1;
27786  }else{
27787    incr = 2;
27788    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
27789    for(i=3-enc; i<length && zNum[i]==0; i+=2){}
27790    nonNum = i<length;
27791    zEnd = &zNum[i^1];
27792    zNum += (enc&1);
27793  }
27794  while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
27795  if( zNum<zEnd ){
27796    if( *zNum=='-' ){
27797      neg = 1;
27798      zNum+=incr;
27799    }else if( *zNum=='+' ){
27800      zNum+=incr;
27801    }
27802  }
27803  zStart = zNum;
27804  while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
27805  for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
27806    u = u*10 + c - '0';
27807  }
27808  if( u>LARGEST_INT64 ){
27809    *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
27810  }else if( neg ){
27811    *pNum = -(i64)u;
27812  }else{
27813    *pNum = (i64)u;
27814  }
27815  testcase( i==18 );
27816  testcase( i==19 );
27817  testcase( i==20 );
27818  if( &zNum[i]<zEnd              /* Extra bytes at the end */
27819   || (i==0 && zStart==zNum)     /* No digits */
27820   || i>19*incr                  /* Too many digits */
27821   || nonNum                     /* UTF16 with high-order bytes non-zero */
27822  ){
27823    /* zNum is empty or contains non-numeric text or is longer
27824    ** than 19 digits (thus guaranteeing that it is too large) */
27825    return 1;
27826  }else if( i<19*incr ){
27827    /* Less than 19 digits, so we know that it fits in 64 bits */
27828    assert( u<=LARGEST_INT64 );
27829    return 0;
27830  }else{
27831    /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
27832    c = compare2pow63(zNum, incr);
27833    if( c<0 ){
27834      /* zNum is less than 9223372036854775808 so it fits */
27835      assert( u<=LARGEST_INT64 );
27836      return 0;
27837    }else if( c>0 ){
27838      /* zNum is greater than 9223372036854775808 so it overflows */
27839      return 1;
27840    }else{
27841      /* zNum is exactly 9223372036854775808.  Fits if negative.  The
27842      ** special case 2 overflow if positive */
27843      assert( u-1==LARGEST_INT64 );
27844      return neg ? 0 : 2;
27845    }
27846  }
27847}
27848
27849/*
27850** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
27851** into a 64-bit signed integer.  This routine accepts hexadecimal literals,
27852** whereas sqlite3Atoi64() does not.
27853**
27854** Returns:
27855**
27856**     0    Successful transformation.  Fits in a 64-bit signed integer.
27857**     1    Integer too large for a 64-bit signed integer or is malformed
27858**     2    Special case of 9223372036854775808
27859*/
27860SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
27861#ifndef SQLITE_OMIT_HEX_INTEGER
27862  if( z[0]=='0'
27863   && (z[1]=='x' || z[1]=='X')
27864  ){
27865    u64 u = 0;
27866    int i, k;
27867    for(i=2; z[i]=='0'; i++){}
27868    for(k=i; sqlite3Isxdigit(z[k]); k++){
27869      u = u*16 + sqlite3HexToInt(z[k]);
27870    }
27871    memcpy(pOut, &u, 8);
27872    return (z[k]==0 && k-i<=16) ? 0 : 1;
27873  }else
27874#endif /* SQLITE_OMIT_HEX_INTEGER */
27875  {
27876    return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
27877  }
27878}
27879
27880/*
27881** If zNum represents an integer that will fit in 32-bits, then set
27882** *pValue to that integer and return true.  Otherwise return false.
27883**
27884** This routine accepts both decimal and hexadecimal notation for integers.
27885**
27886** Any non-numeric characters that following zNum are ignored.
27887** This is different from sqlite3Atoi64() which requires the
27888** input number to be zero-terminated.
27889*/
27890SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
27891  sqlite_int64 v = 0;
27892  int i, c;
27893  int neg = 0;
27894  if( zNum[0]=='-' ){
27895    neg = 1;
27896    zNum++;
27897  }else if( zNum[0]=='+' ){
27898    zNum++;
27899  }
27900#ifndef SQLITE_OMIT_HEX_INTEGER
27901  else if( zNum[0]=='0'
27902        && (zNum[1]=='x' || zNum[1]=='X')
27903        && sqlite3Isxdigit(zNum[2])
27904  ){
27905    u32 u = 0;
27906    zNum += 2;
27907    while( zNum[0]=='0' ) zNum++;
27908    for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
27909      u = u*16 + sqlite3HexToInt(zNum[i]);
27910    }
27911    if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
27912      memcpy(pValue, &u, 4);
27913      return 1;
27914    }else{
27915      return 0;
27916    }
27917  }
27918#endif
27919  while( zNum[0]=='0' ) zNum++;
27920  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
27921    v = v*10 + c;
27922  }
27923
27924  /* The longest decimal representation of a 32 bit integer is 10 digits:
27925  **
27926  **             1234567890
27927  **     2^31 -> 2147483648
27928  */
27929  testcase( i==10 );
27930  if( i>10 ){
27931    return 0;
27932  }
27933  testcase( v-neg==2147483647 );
27934  if( v-neg>2147483647 ){
27935    return 0;
27936  }
27937  if( neg ){
27938    v = -v;
27939  }
27940  *pValue = (int)v;
27941  return 1;
27942}
27943
27944/*
27945** Return a 32-bit integer value extracted from a string.  If the
27946** string is not an integer, just return 0.
27947*/
27948SQLITE_PRIVATE int sqlite3Atoi(const char *z){
27949  int x = 0;
27950  if( z ) sqlite3GetInt32(z, &x);
27951  return x;
27952}
27953
27954/*
27955** The variable-length integer encoding is as follows:
27956**
27957** KEY:
27958**         A = 0xxxxxxx    7 bits of data and one flag bit
27959**         B = 1xxxxxxx    7 bits of data and one flag bit
27960**         C = xxxxxxxx    8 bits of data
27961**
27962**  7 bits - A
27963** 14 bits - BA
27964** 21 bits - BBA
27965** 28 bits - BBBA
27966** 35 bits - BBBBA
27967** 42 bits - BBBBBA
27968** 49 bits - BBBBBBA
27969** 56 bits - BBBBBBBA
27970** 64 bits - BBBBBBBBC
27971*/
27972
27973/*
27974** Write a 64-bit variable-length integer to memory starting at p[0].
27975** The length of data write will be between 1 and 9 bytes.  The number
27976** of bytes written is returned.
27977**
27978** A variable-length integer consists of the lower 7 bits of each byte
27979** for all bytes that have the 8th bit set and one byte with the 8th
27980** bit clear.  Except, if we get to the 9th byte, it stores the full
27981** 8 bits and is the last byte.
27982*/
27983static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
27984  int i, j, n;
27985  u8 buf[10];
27986  if( v & (((u64)0xff000000)<<32) ){
27987    p[8] = (u8)v;
27988    v >>= 8;
27989    for(i=7; i>=0; i--){
27990      p[i] = (u8)((v & 0x7f) | 0x80);
27991      v >>= 7;
27992    }
27993    return 9;
27994  }
27995  n = 0;
27996  do{
27997    buf[n++] = (u8)((v & 0x7f) | 0x80);
27998    v >>= 7;
27999  }while( v!=0 );
28000  buf[0] &= 0x7f;
28001  assert( n<=9 );
28002  for(i=0, j=n-1; j>=0; j--, i++){
28003    p[i] = buf[j];
28004  }
28005  return n;
28006}
28007SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
28008  if( v<=0x7f ){
28009    p[0] = v&0x7f;
28010    return 1;
28011  }
28012  if( v<=0x3fff ){
28013    p[0] = ((v>>7)&0x7f)|0x80;
28014    p[1] = v&0x7f;
28015    return 2;
28016  }
28017  return putVarint64(p,v);
28018}
28019
28020/*
28021** Bitmasks used by sqlite3GetVarint().  These precomputed constants
28022** are defined here rather than simply putting the constant expressions
28023** inline in order to work around bugs in the RVT compiler.
28024**
28025** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
28026**
28027** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
28028*/
28029#define SLOT_2_0     0x001fc07f
28030#define SLOT_4_2_0   0xf01fc07f
28031
28032
28033/*
28034** Read a 64-bit variable-length integer from memory starting at p[0].
28035** Return the number of bytes read.  The value is stored in *v.
28036*/
28037SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
28038  u32 a,b,s;
28039
28040  a = *p;
28041  /* a: p0 (unmasked) */
28042  if (!(a&0x80))
28043  {
28044    *v = a;
28045    return 1;
28046  }
28047
28048  p++;
28049  b = *p;
28050  /* b: p1 (unmasked) */
28051  if (!(b&0x80))
28052  {
28053    a &= 0x7f;
28054    a = a<<7;
28055    a |= b;
28056    *v = a;
28057    return 2;
28058  }
28059
28060  /* Verify that constants are precomputed correctly */
28061  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
28062  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
28063
28064  p++;
28065  a = a<<14;
28066  a |= *p;
28067  /* a: p0<<14 | p2 (unmasked) */
28068  if (!(a&0x80))
28069  {
28070    a &= SLOT_2_0;
28071    b &= 0x7f;
28072    b = b<<7;
28073    a |= b;
28074    *v = a;
28075    return 3;
28076  }
28077
28078  /* CSE1 from below */
28079  a &= SLOT_2_0;
28080  p++;
28081  b = b<<14;
28082  b |= *p;
28083  /* b: p1<<14 | p3 (unmasked) */
28084  if (!(b&0x80))
28085  {
28086    b &= SLOT_2_0;
28087    /* moved CSE1 up */
28088    /* a &= (0x7f<<14)|(0x7f); */
28089    a = a<<7;
28090    a |= b;
28091    *v = a;
28092    return 4;
28093  }
28094
28095  /* a: p0<<14 | p2 (masked) */
28096  /* b: p1<<14 | p3 (unmasked) */
28097  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28098  /* moved CSE1 up */
28099  /* a &= (0x7f<<14)|(0x7f); */
28100  b &= SLOT_2_0;
28101  s = a;
28102  /* s: p0<<14 | p2 (masked) */
28103
28104  p++;
28105  a = a<<14;
28106  a |= *p;
28107  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
28108  if (!(a&0x80))
28109  {
28110    /* we can skip these cause they were (effectively) done above
28111    ** while calculating s */
28112    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
28113    /* b &= (0x7f<<14)|(0x7f); */
28114    b = b<<7;
28115    a |= b;
28116    s = s>>18;
28117    *v = ((u64)s)<<32 | a;
28118    return 5;
28119  }
28120
28121  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28122  s = s<<7;
28123  s |= b;
28124  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28125
28126  p++;
28127  b = b<<14;
28128  b |= *p;
28129  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
28130  if (!(b&0x80))
28131  {
28132    /* we can skip this cause it was (effectively) done above in calc'ing s */
28133    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
28134    a &= SLOT_2_0;
28135    a = a<<7;
28136    a |= b;
28137    s = s>>18;
28138    *v = ((u64)s)<<32 | a;
28139    return 6;
28140  }
28141
28142  p++;
28143  a = a<<14;
28144  a |= *p;
28145  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
28146  if (!(a&0x80))
28147  {
28148    a &= SLOT_4_2_0;
28149    b &= SLOT_2_0;
28150    b = b<<7;
28151    a |= b;
28152    s = s>>11;
28153    *v = ((u64)s)<<32 | a;
28154    return 7;
28155  }
28156
28157  /* CSE2 from below */
28158  a &= SLOT_2_0;
28159  p++;
28160  b = b<<14;
28161  b |= *p;
28162  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
28163  if (!(b&0x80))
28164  {
28165    b &= SLOT_4_2_0;
28166    /* moved CSE2 up */
28167    /* a &= (0x7f<<14)|(0x7f); */
28168    a = a<<7;
28169    a |= b;
28170    s = s>>4;
28171    *v = ((u64)s)<<32 | a;
28172    return 8;
28173  }
28174
28175  p++;
28176  a = a<<15;
28177  a |= *p;
28178  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
28179
28180  /* moved CSE2 up */
28181  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
28182  b &= SLOT_2_0;
28183  b = b<<8;
28184  a |= b;
28185
28186  s = s<<4;
28187  b = p[-4];
28188  b &= 0x7f;
28189  b = b>>3;
28190  s |= b;
28191
28192  *v = ((u64)s)<<32 | a;
28193
28194  return 9;
28195}
28196
28197/*
28198** Read a 32-bit variable-length integer from memory starting at p[0].
28199** Return the number of bytes read.  The value is stored in *v.
28200**
28201** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
28202** integer, then set *v to 0xffffffff.
28203**
28204** A MACRO version, getVarint32, is provided which inlines the
28205** single-byte case.  All code should use the MACRO version as
28206** this function assumes the single-byte case has already been handled.
28207*/
28208SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
28209  u32 a,b;
28210
28211  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
28212  ** by the getVarin32() macro */
28213  a = *p;
28214  /* a: p0 (unmasked) */
28215#ifndef getVarint32
28216  if (!(a&0x80))
28217  {
28218    /* Values between 0 and 127 */
28219    *v = a;
28220    return 1;
28221  }
28222#endif
28223
28224  /* The 2-byte case */
28225  p++;
28226  b = *p;
28227  /* b: p1 (unmasked) */
28228  if (!(b&0x80))
28229  {
28230    /* Values between 128 and 16383 */
28231    a &= 0x7f;
28232    a = a<<7;
28233    *v = a | b;
28234    return 2;
28235  }
28236
28237  /* The 3-byte case */
28238  p++;
28239  a = a<<14;
28240  a |= *p;
28241  /* a: p0<<14 | p2 (unmasked) */
28242  if (!(a&0x80))
28243  {
28244    /* Values between 16384 and 2097151 */
28245    a &= (0x7f<<14)|(0x7f);
28246    b &= 0x7f;
28247    b = b<<7;
28248    *v = a | b;
28249    return 3;
28250  }
28251
28252  /* A 32-bit varint is used to store size information in btrees.
28253  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
28254  ** A 3-byte varint is sufficient, for example, to record the size
28255  ** of a 1048569-byte BLOB or string.
28256  **
28257  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
28258  ** rare larger cases can be handled by the slower 64-bit varint
28259  ** routine.
28260  */
28261#if 1
28262  {
28263    u64 v64;
28264    u8 n;
28265
28266    p -= 2;
28267    n = sqlite3GetVarint(p, &v64);
28268    assert( n>3 && n<=9 );
28269    if( (v64 & SQLITE_MAX_U32)!=v64 ){
28270      *v = 0xffffffff;
28271    }else{
28272      *v = (u32)v64;
28273    }
28274    return n;
28275  }
28276
28277#else
28278  /* For following code (kept for historical record only) shows an
28279  ** unrolling for the 3- and 4-byte varint cases.  This code is
28280  ** slightly faster, but it is also larger and much harder to test.
28281  */
28282  p++;
28283  b = b<<14;
28284  b |= *p;
28285  /* b: p1<<14 | p3 (unmasked) */
28286  if (!(b&0x80))
28287  {
28288    /* Values between 2097152 and 268435455 */
28289    b &= (0x7f<<14)|(0x7f);
28290    a &= (0x7f<<14)|(0x7f);
28291    a = a<<7;
28292    *v = a | b;
28293    return 4;
28294  }
28295
28296  p++;
28297  a = a<<14;
28298  a |= *p;
28299  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
28300  if (!(a&0x80))
28301  {
28302    /* Values  between 268435456 and 34359738367 */
28303    a &= SLOT_4_2_0;
28304    b &= SLOT_4_2_0;
28305    b = b<<7;
28306    *v = a | b;
28307    return 5;
28308  }
28309
28310  /* We can only reach this point when reading a corrupt database
28311  ** file.  In that case we are not in any hurry.  Use the (relatively
28312  ** slow) general-purpose sqlite3GetVarint() routine to extract the
28313  ** value. */
28314  {
28315    u64 v64;
28316    u8 n;
28317
28318    p -= 4;
28319    n = sqlite3GetVarint(p, &v64);
28320    assert( n>5 && n<=9 );
28321    *v = (u32)v64;
28322    return n;
28323  }
28324#endif
28325}
28326
28327/*
28328** Return the number of bytes that will be needed to store the given
28329** 64-bit integer.
28330*/
28331SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
28332  int i;
28333  for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
28334  return i;
28335}
28336
28337
28338/*
28339** Read or write a four-byte big-endian integer value.
28340*/
28341SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
28342#if SQLITE_BYTEORDER==4321
28343  u32 x;
28344  memcpy(&x,p,4);
28345  return x;
28346#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28347    && defined(__GNUC__) && GCC_VERSION>=4003000
28348  u32 x;
28349  memcpy(&x,p,4);
28350  return __builtin_bswap32(x);
28351#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28352    && defined(_MSC_VER) && _MSC_VER>=1300
28353  u32 x;
28354  memcpy(&x,p,4);
28355  return _byteswap_ulong(x);
28356#else
28357  testcase( p[0]&0x80 );
28358  return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
28359#endif
28360}
28361SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
28362#if SQLITE_BYTEORDER==4321
28363  memcpy(p,&v,4);
28364#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28365    && defined(__GNUC__) && GCC_VERSION>=4003000
28366  u32 x = __builtin_bswap32(v);
28367  memcpy(p,&x,4);
28368#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28369    && defined(_MSC_VER) && _MSC_VER>=1300
28370  u32 x = _byteswap_ulong(v);
28371  memcpy(p,&x,4);
28372#else
28373  p[0] = (u8)(v>>24);
28374  p[1] = (u8)(v>>16);
28375  p[2] = (u8)(v>>8);
28376  p[3] = (u8)v;
28377#endif
28378}
28379
28380
28381
28382/*
28383** Translate a single byte of Hex into an integer.
28384** This routine only works if h really is a valid hexadecimal
28385** character:  0..9a..fA..F
28386*/
28387SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
28388  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
28389#ifdef SQLITE_ASCII
28390  h += 9*(1&(h>>6));
28391#endif
28392#ifdef SQLITE_EBCDIC
28393  h += 9*(1&~(h>>4));
28394#endif
28395  return (u8)(h & 0xf);
28396}
28397
28398#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
28399/*
28400** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
28401** value.  Return a pointer to its binary value.  Space to hold the
28402** binary value has been obtained from malloc and must be freed by
28403** the calling routine.
28404*/
28405SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
28406  char *zBlob;
28407  int i;
28408
28409  zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
28410  n--;
28411  if( zBlob ){
28412    for(i=0; i<n; i+=2){
28413      zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
28414    }
28415    zBlob[i/2] = 0;
28416  }
28417  return zBlob;
28418}
28419#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
28420
28421/*
28422** Log an error that is an API call on a connection pointer that should
28423** not have been used.  The "type" of connection pointer is given as the
28424** argument.  The zType is a word like "NULL" or "closed" or "invalid".
28425*/
28426static void logBadConnection(const char *zType){
28427  sqlite3_log(SQLITE_MISUSE,
28428     "API call with %s database connection pointer",
28429     zType
28430  );
28431}
28432
28433/*
28434** Check to make sure we have a valid db pointer.  This test is not
28435** foolproof but it does provide some measure of protection against
28436** misuse of the interface such as passing in db pointers that are
28437** NULL or which have been previously closed.  If this routine returns
28438** 1 it means that the db pointer is valid and 0 if it should not be
28439** dereferenced for any reason.  The calling function should invoke
28440** SQLITE_MISUSE immediately.
28441**
28442** sqlite3SafetyCheckOk() requires that the db pointer be valid for
28443** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
28444** open properly and is not fit for general use but which can be
28445** used as an argument to sqlite3_errmsg() or sqlite3_close().
28446*/
28447SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
28448  u32 magic;
28449  if( db==0 ){
28450    logBadConnection("NULL");
28451    return 0;
28452  }
28453  magic = db->magic;
28454  if( magic!=SQLITE_MAGIC_OPEN ){
28455    if( sqlite3SafetyCheckSickOrOk(db) ){
28456      testcase( sqlite3GlobalConfig.xLog!=0 );
28457      logBadConnection("unopened");
28458    }
28459    return 0;
28460  }else{
28461    return 1;
28462  }
28463}
28464SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
28465  u32 magic;
28466  magic = db->magic;
28467  if( magic!=SQLITE_MAGIC_SICK &&
28468      magic!=SQLITE_MAGIC_OPEN &&
28469      magic!=SQLITE_MAGIC_BUSY ){
28470    testcase( sqlite3GlobalConfig.xLog!=0 );
28471    logBadConnection("invalid");
28472    return 0;
28473  }else{
28474    return 1;
28475  }
28476}
28477
28478/*
28479** Attempt to add, substract, or multiply the 64-bit signed value iB against
28480** the other 64-bit signed integer at *pA and store the result in *pA.
28481** Return 0 on success.  Or if the operation would have resulted in an
28482** overflow, leave *pA unchanged and return 1.
28483*/
28484SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
28485  i64 iA = *pA;
28486  testcase( iA==0 ); testcase( iA==1 );
28487  testcase( iB==-1 ); testcase( iB==0 );
28488  if( iB>=0 ){
28489    testcase( iA>0 && LARGEST_INT64 - iA == iB );
28490    testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
28491    if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
28492  }else{
28493    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
28494    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
28495    if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
28496  }
28497  *pA += iB;
28498  return 0;
28499}
28500SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
28501  testcase( iB==SMALLEST_INT64+1 );
28502  if( iB==SMALLEST_INT64 ){
28503    testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
28504    if( (*pA)>=0 ) return 1;
28505    *pA -= iB;
28506    return 0;
28507  }else{
28508    return sqlite3AddInt64(pA, -iB);
28509  }
28510}
28511#define TWOPOWER32 (((i64)1)<<32)
28512#define TWOPOWER31 (((i64)1)<<31)
28513SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
28514  i64 iA = *pA;
28515  i64 iA1, iA0, iB1, iB0, r;
28516
28517  iA1 = iA/TWOPOWER32;
28518  iA0 = iA % TWOPOWER32;
28519  iB1 = iB/TWOPOWER32;
28520  iB0 = iB % TWOPOWER32;
28521  if( iA1==0 ){
28522    if( iB1==0 ){
28523      *pA *= iB;
28524      return 0;
28525    }
28526    r = iA0*iB1;
28527  }else if( iB1==0 ){
28528    r = iA1*iB0;
28529  }else{
28530    /* If both iA1 and iB1 are non-zero, overflow will result */
28531    return 1;
28532  }
28533  testcase( r==(-TWOPOWER31)-1 );
28534  testcase( r==(-TWOPOWER31) );
28535  testcase( r==TWOPOWER31 );
28536  testcase( r==TWOPOWER31-1 );
28537  if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
28538  r *= TWOPOWER32;
28539  if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
28540  *pA = r;
28541  return 0;
28542}
28543
28544/*
28545** Compute the absolute value of a 32-bit signed integer, of possible.  Or
28546** if the integer has a value of -2147483648, return +2147483647
28547*/
28548SQLITE_PRIVATE int sqlite3AbsInt32(int x){
28549  if( x>=0 ) return x;
28550  if( x==(int)0x80000000 ) return 0x7fffffff;
28551  return -x;
28552}
28553
28554#ifdef SQLITE_ENABLE_8_3_NAMES
28555/*
28556** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
28557** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
28558** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
28559** three characters, then shorten the suffix on z[] to be the last three
28560** characters of the original suffix.
28561**
28562** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
28563** do the suffix shortening regardless of URI parameter.
28564**
28565** Examples:
28566**
28567**     test.db-journal    =>   test.nal
28568**     test.db-wal        =>   test.wal
28569**     test.db-shm        =>   test.shm
28570**     test.db-mj7f3319fa =>   test.9fa
28571*/
28572SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
28573#if SQLITE_ENABLE_8_3_NAMES<2
28574  if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
28575#endif
28576  {
28577    int i, sz;
28578    sz = sqlite3Strlen30(z);
28579    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
28580    if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
28581  }
28582}
28583#endif
28584
28585/*
28586** Find (an approximate) sum of two LogEst values.  This computation is
28587** not a simple "+" operator because LogEst is stored as a logarithmic
28588** value.
28589**
28590*/
28591SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
28592  static const unsigned char x[] = {
28593     10, 10,                         /* 0,1 */
28594      9, 9,                          /* 2,3 */
28595      8, 8,                          /* 4,5 */
28596      7, 7, 7,                       /* 6,7,8 */
28597      6, 6, 6,                       /* 9,10,11 */
28598      5, 5, 5,                       /* 12-14 */
28599      4, 4, 4, 4,                    /* 15-18 */
28600      3, 3, 3, 3, 3, 3,              /* 19-24 */
28601      2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
28602  };
28603  if( a>=b ){
28604    if( a>b+49 ) return a;
28605    if( a>b+31 ) return a+1;
28606    return a+x[a-b];
28607  }else{
28608    if( b>a+49 ) return b;
28609    if( b>a+31 ) return b+1;
28610    return b+x[b-a];
28611  }
28612}
28613
28614/*
28615** Convert an integer into a LogEst.  In other words, compute an
28616** approximation for 10*log2(x).
28617*/
28618SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
28619  static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
28620  LogEst y = 40;
28621  if( x<8 ){
28622    if( x<2 ) return 0;
28623    while( x<8 ){  y -= 10; x <<= 1; }
28624  }else{
28625    while( x>255 ){ y += 40; x >>= 4; }  /*OPTIMIZATION-IF-TRUE*/
28626    while( x>15 ){  y += 10; x >>= 1; }
28627  }
28628  return a[x&7] + y - 10;
28629}
28630
28631#ifndef SQLITE_OMIT_VIRTUALTABLE
28632/*
28633** Convert a double into a LogEst
28634** In other words, compute an approximation for 10*log2(x).
28635*/
28636SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
28637  u64 a;
28638  LogEst e;
28639  assert( sizeof(x)==8 && sizeof(a)==8 );
28640  if( x<=1 ) return 0;
28641  if( x<=2000000000 ) return sqlite3LogEst((u64)x);
28642  memcpy(&a, &x, 8);
28643  e = (a>>52) - 1022;
28644  return e*10;
28645}
28646#endif /* SQLITE_OMIT_VIRTUALTABLE */
28647
28648#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
28649    defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
28650    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
28651/*
28652** Convert a LogEst into an integer.
28653**
28654** Note that this routine is only used when one or more of various
28655** non-standard compile-time options is enabled.
28656*/
28657SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
28658  u64 n;
28659  n = x%10;
28660  x /= 10;
28661  if( n>=5 ) n -= 2;
28662  else if( n>=1 ) n -= 1;
28663#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
28664    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
28665  if( x>60 ) return (u64)LARGEST_INT64;
28666#else
28667  /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
28668  ** possible to this routine is 310, resulting in a maximum x of 31 */
28669  assert( x<=60 );
28670#endif
28671  return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
28672}
28673#endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
28674
28675/************** End of util.c ************************************************/
28676/************** Begin file hash.c ********************************************/
28677/*
28678** 2001 September 22
28679**
28680** The author disclaims copyright to this source code.  In place of
28681** a legal notice, here is a blessing:
28682**
28683**    May you do good and not evil.
28684**    May you find forgiveness for yourself and forgive others.
28685**    May you share freely, never taking more than you give.
28686**
28687*************************************************************************
28688** This is the implementation of generic hash-tables
28689** used in SQLite.
28690*/
28691/* #include "sqliteInt.h" */
28692/* #include <assert.h> */
28693
28694/* Turn bulk memory into a hash table object by initializing the
28695** fields of the Hash structure.
28696**
28697** "pNew" is a pointer to the hash table that is to be initialized.
28698*/
28699SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
28700  assert( pNew!=0 );
28701  pNew->first = 0;
28702  pNew->count = 0;
28703  pNew->htsize = 0;
28704  pNew->ht = 0;
28705}
28706
28707/* Remove all entries from a hash table.  Reclaim all memory.
28708** Call this routine to delete a hash table or to reset a hash table
28709** to the empty state.
28710*/
28711SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
28712  HashElem *elem;         /* For looping over all elements of the table */
28713
28714  assert( pH!=0 );
28715  elem = pH->first;
28716  pH->first = 0;
28717  sqlite3_free(pH->ht);
28718  pH->ht = 0;
28719  pH->htsize = 0;
28720  while( elem ){
28721    HashElem *next_elem = elem->next;
28722    sqlite3_free(elem);
28723    elem = next_elem;
28724  }
28725  pH->count = 0;
28726}
28727
28728/*
28729** The hashing function.
28730*/
28731static unsigned int strHash(const char *z){
28732  unsigned int h = 0;
28733  unsigned char c;
28734  while( (c = (unsigned char)*z++)!=0 ){     /*OPTIMIZATION-IF-TRUE*/
28735    h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
28736  }
28737  return h;
28738}
28739
28740
28741/* Link pNew element into the hash table pH.  If pEntry!=0 then also
28742** insert pNew into the pEntry hash bucket.
28743*/
28744static void insertElement(
28745  Hash *pH,              /* The complete hash table */
28746  struct _ht *pEntry,    /* The entry into which pNew is inserted */
28747  HashElem *pNew         /* The element to be inserted */
28748){
28749  HashElem *pHead;       /* First element already in pEntry */
28750  if( pEntry ){
28751    pHead = pEntry->count ? pEntry->chain : 0;
28752    pEntry->count++;
28753    pEntry->chain = pNew;
28754  }else{
28755    pHead = 0;
28756  }
28757  if( pHead ){
28758    pNew->next = pHead;
28759    pNew->prev = pHead->prev;
28760    if( pHead->prev ){ pHead->prev->next = pNew; }
28761    else             { pH->first = pNew; }
28762    pHead->prev = pNew;
28763  }else{
28764    pNew->next = pH->first;
28765    if( pH->first ){ pH->first->prev = pNew; }
28766    pNew->prev = 0;
28767    pH->first = pNew;
28768  }
28769}
28770
28771
28772/* Resize the hash table so that it cantains "new_size" buckets.
28773**
28774** The hash table might fail to resize if sqlite3_malloc() fails or
28775** if the new size is the same as the prior size.
28776** Return TRUE if the resize occurs and false if not.
28777*/
28778static int rehash(Hash *pH, unsigned int new_size){
28779  struct _ht *new_ht;            /* The new hash table */
28780  HashElem *elem, *next_elem;    /* For looping over existing elements */
28781
28782#if SQLITE_MALLOC_SOFT_LIMIT>0
28783  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
28784    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
28785  }
28786  if( new_size==pH->htsize ) return 0;
28787#endif
28788
28789  /* The inability to allocates space for a larger hash table is
28790  ** a performance hit but it is not a fatal error.  So mark the
28791  ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
28792  ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
28793  ** only zeroes the requested number of bytes whereas this module will
28794  ** use the actual amount of space allocated for the hash table (which
28795  ** may be larger than the requested amount).
28796  */
28797  sqlite3BeginBenignMalloc();
28798  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
28799  sqlite3EndBenignMalloc();
28800
28801  if( new_ht==0 ) return 0;
28802  sqlite3_free(pH->ht);
28803  pH->ht = new_ht;
28804  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
28805  memset(new_ht, 0, new_size*sizeof(struct _ht));
28806  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
28807    unsigned int h = strHash(elem->pKey) % new_size;
28808    next_elem = elem->next;
28809    insertElement(pH, &new_ht[h], elem);
28810  }
28811  return 1;
28812}
28813
28814/* This function (for internal use only) locates an element in an
28815** hash table that matches the given key.  The hash for this key is
28816** also computed and returned in the *pH parameter.
28817*/
28818static HashElem *findElementWithHash(
28819  const Hash *pH,     /* The pH to be searched */
28820  const char *pKey,   /* The key we are searching for */
28821  unsigned int *pHash /* Write the hash value here */
28822){
28823  HashElem *elem;                /* Used to loop thru the element list */
28824  int count;                     /* Number of elements left to test */
28825  unsigned int h;                /* The computed hash */
28826
28827  if( pH->ht ){   /*OPTIMIZATION-IF-TRUE*/
28828    struct _ht *pEntry;
28829    h = strHash(pKey) % pH->htsize;
28830    pEntry = &pH->ht[h];
28831    elem = pEntry->chain;
28832    count = pEntry->count;
28833  }else{
28834    h = 0;
28835    elem = pH->first;
28836    count = pH->count;
28837  }
28838  *pHash = h;
28839  while( count-- ){
28840    assert( elem!=0 );
28841    if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
28842      return elem;
28843    }
28844    elem = elem->next;
28845  }
28846  return 0;
28847}
28848
28849/* Remove a single entry from the hash table given a pointer to that
28850** element and a hash on the element's key.
28851*/
28852static void removeElementGivenHash(
28853  Hash *pH,         /* The pH containing "elem" */
28854  HashElem* elem,   /* The element to be removed from the pH */
28855  unsigned int h    /* Hash value for the element */
28856){
28857  struct _ht *pEntry;
28858  if( elem->prev ){
28859    elem->prev->next = elem->next;
28860  }else{
28861    pH->first = elem->next;
28862  }
28863  if( elem->next ){
28864    elem->next->prev = elem->prev;
28865  }
28866  if( pH->ht ){
28867    pEntry = &pH->ht[h];
28868    if( pEntry->chain==elem ){
28869      pEntry->chain = elem->next;
28870    }
28871    pEntry->count--;
28872    assert( pEntry->count>=0 );
28873  }
28874  sqlite3_free( elem );
28875  pH->count--;
28876  if( pH->count==0 ){
28877    assert( pH->first==0 );
28878    assert( pH->count==0 );
28879    sqlite3HashClear(pH);
28880  }
28881}
28882
28883/* Attempt to locate an element of the hash table pH with a key
28884** that matches pKey.  Return the data for this element if it is
28885** found, or NULL if there is no match.
28886*/
28887SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
28888  HashElem *elem;    /* The element that matches key */
28889  unsigned int h;    /* A hash on key */
28890
28891  assert( pH!=0 );
28892  assert( pKey!=0 );
28893  elem = findElementWithHash(pH, pKey, &h);
28894  return elem ? elem->data : 0;
28895}
28896
28897/* Insert an element into the hash table pH.  The key is pKey
28898** and the data is "data".
28899**
28900** If no element exists with a matching key, then a new
28901** element is created and NULL is returned.
28902**
28903** If another element already exists with the same key, then the
28904** new data replaces the old data and the old data is returned.
28905** The key is not copied in this instance.  If a malloc fails, then
28906** the new data is returned and the hash table is unchanged.
28907**
28908** If the "data" parameter to this function is NULL, then the
28909** element corresponding to "key" is removed from the hash table.
28910*/
28911SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
28912  unsigned int h;       /* the hash of the key modulo hash table size */
28913  HashElem *elem;       /* Used to loop thru the element list */
28914  HashElem *new_elem;   /* New element added to the pH */
28915
28916  assert( pH!=0 );
28917  assert( pKey!=0 );
28918  elem = findElementWithHash(pH,pKey,&h);
28919  if( elem ){
28920    void *old_data = elem->data;
28921    if( data==0 ){
28922      removeElementGivenHash(pH,elem,h);
28923    }else{
28924      elem->data = data;
28925      elem->pKey = pKey;
28926    }
28927    return old_data;
28928  }
28929  if( data==0 ) return 0;
28930  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
28931  if( new_elem==0 ) return data;
28932  new_elem->pKey = pKey;
28933  new_elem->data = data;
28934  pH->count++;
28935  if( pH->count>=10 && pH->count > 2*pH->htsize ){
28936    if( rehash(pH, pH->count*2) ){
28937      assert( pH->htsize>0 );
28938      h = strHash(pKey) % pH->htsize;
28939    }
28940  }
28941  insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
28942  return 0;
28943}
28944
28945/************** End of hash.c ************************************************/
28946/************** Begin file opcodes.c *****************************************/
28947/* Automatically generated.  Do not edit */
28948/* See the tool/mkopcodec.tcl script for details. */
28949#if !defined(SQLITE_OMIT_EXPLAIN) \
28950 || defined(VDBE_PROFILE) \
28951 || defined(SQLITE_DEBUG)
28952#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
28953# define OpHelp(X) "\0" X
28954#else
28955# define OpHelp(X)
28956#endif
28957SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
28958 static const char *const azName[] = {
28959    /*   0 */ "Savepoint"        OpHelp(""),
28960    /*   1 */ "AutoCommit"       OpHelp(""),
28961    /*   2 */ "Transaction"      OpHelp(""),
28962    /*   3 */ "SorterNext"       OpHelp(""),
28963    /*   4 */ "PrevIfOpen"       OpHelp(""),
28964    /*   5 */ "NextIfOpen"       OpHelp(""),
28965    /*   6 */ "Prev"             OpHelp(""),
28966    /*   7 */ "Next"             OpHelp(""),
28967    /*   8 */ "Checkpoint"       OpHelp(""),
28968    /*   9 */ "JournalMode"      OpHelp(""),
28969    /*  10 */ "Vacuum"           OpHelp(""),
28970    /*  11 */ "VFilter"          OpHelp("iplan=r[P3] zplan='P4'"),
28971    /*  12 */ "VUpdate"          OpHelp("data=r[P3@P2]"),
28972    /*  13 */ "Goto"             OpHelp(""),
28973    /*  14 */ "Gosub"            OpHelp(""),
28974    /*  15 */ "InitCoroutine"    OpHelp(""),
28975    /*  16 */ "Yield"            OpHelp(""),
28976    /*  17 */ "MustBeInt"        OpHelp(""),
28977    /*  18 */ "Jump"             OpHelp(""),
28978    /*  19 */ "Not"              OpHelp("r[P2]= !r[P1]"),
28979    /*  20 */ "Once"             OpHelp(""),
28980    /*  21 */ "If"               OpHelp(""),
28981    /*  22 */ "IfNot"            OpHelp(""),
28982    /*  23 */ "SeekLT"           OpHelp("key=r[P3@P4]"),
28983    /*  24 */ "SeekLE"           OpHelp("key=r[P3@P4]"),
28984    /*  25 */ "SeekGE"           OpHelp("key=r[P3@P4]"),
28985    /*  26 */ "SeekGT"           OpHelp("key=r[P3@P4]"),
28986    /*  27 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
28987    /*  28 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
28988    /*  29 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
28989    /*  30 */ "NotFound"         OpHelp("key=r[P3@P4]"),
28990    /*  31 */ "Found"            OpHelp("key=r[P3@P4]"),
28991    /*  32 */ "SeekRowid"        OpHelp("intkey=r[P3]"),
28992    /*  33 */ "NotExists"        OpHelp("intkey=r[P3]"),
28993    /*  34 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
28994    /*  35 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
28995    /*  36 */ "Ne"               OpHelp("if r[P1]!=r[P3] goto P2"),
28996    /*  37 */ "Eq"               OpHelp("if r[P1]==r[P3] goto P2"),
28997    /*  38 */ "Gt"               OpHelp("if r[P1]>r[P3] goto P2"),
28998    /*  39 */ "Le"               OpHelp("if r[P1]<=r[P3] goto P2"),
28999    /*  40 */ "Lt"               OpHelp("if r[P1]<r[P3] goto P2"),
29000    /*  41 */ "Ge"               OpHelp("if r[P1]>=r[P3] goto P2"),
29001    /*  42 */ "Last"             OpHelp(""),
29002    /*  43 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
29003    /*  44 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
29004    /*  45 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
29005    /*  46 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
29006    /*  47 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
29007    /*  48 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
29008    /*  49 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
29009    /*  50 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
29010    /*  51 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
29011    /*  52 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
29012    /*  53 */ "SorterSort"       OpHelp(""),
29013    /*  54 */ "BitNot"           OpHelp("r[P1]= ~r[P1]"),
29014    /*  55 */ "Sort"             OpHelp(""),
29015    /*  56 */ "Rewind"           OpHelp(""),
29016    /*  57 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
29017    /*  58 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
29018    /*  59 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
29019    /*  60 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
29020    /*  61 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
29021    /*  62 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
29022    /*  63 */ "Program"          OpHelp(""),
29023    /*  64 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
29024    /*  65 */ "IfPos"            OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
29025    /*  66 */ "IfNotZero"        OpHelp("if r[P1]!=0 then r[P1]-=P3, goto P2"),
29026    /*  67 */ "DecrJumpZero"     OpHelp("if (--r[P1])==0 goto P2"),
29027    /*  68 */ "IncrVacuum"       OpHelp(""),
29028    /*  69 */ "VNext"            OpHelp(""),
29029    /*  70 */ "Init"             OpHelp("Start at P2"),
29030    /*  71 */ "Return"           OpHelp(""),
29031    /*  72 */ "EndCoroutine"     OpHelp(""),
29032    /*  73 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
29033    /*  74 */ "Halt"             OpHelp(""),
29034    /*  75 */ "Integer"          OpHelp("r[P2]=P1"),
29035    /*  76 */ "Int64"            OpHelp("r[P2]=P4"),
29036    /*  77 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
29037    /*  78 */ "Null"             OpHelp("r[P2..P3]=NULL"),
29038    /*  79 */ "SoftNull"         OpHelp("r[P1]=NULL"),
29039    /*  80 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
29040    /*  81 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
29041    /*  82 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
29042    /*  83 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
29043    /*  84 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
29044    /*  85 */ "IntCopy"          OpHelp("r[P2]=r[P1]"),
29045    /*  86 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
29046    /*  87 */ "CollSeq"          OpHelp(""),
29047    /*  88 */ "Function0"        OpHelp("r[P3]=func(r[P2@P5])"),
29048    /*  89 */ "Function"         OpHelp("r[P3]=func(r[P2@P5])"),
29049    /*  90 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
29050    /*  91 */ "RealAffinity"     OpHelp(""),
29051    /*  92 */ "Cast"             OpHelp("affinity(r[P1])"),
29052    /*  93 */ "Permutation"      OpHelp(""),
29053    /*  94 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
29054    /*  95 */ "Column"           OpHelp("r[P3]=PX"),
29055    /*  96 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
29056    /*  97 */ "String8"          OpHelp("r[P2]='P4'"),
29057    /*  98 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
29058    /*  99 */ "Count"            OpHelp("r[P2]=count()"),
29059    /* 100 */ "ReadCookie"       OpHelp(""),
29060    /* 101 */ "SetCookie"        OpHelp(""),
29061    /* 102 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
29062    /* 103 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
29063    /* 104 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
29064    /* 105 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
29065    /* 106 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
29066    /* 107 */ "SorterOpen"       OpHelp(""),
29067    /* 108 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
29068    /* 109 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
29069    /* 110 */ "Close"            OpHelp(""),
29070    /* 111 */ "ColumnsUsed"      OpHelp(""),
29071    /* 112 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
29072    /* 113 */ "NewRowid"         OpHelp("r[P2]=rowid"),
29073    /* 114 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
29074    /* 115 */ "InsertInt"        OpHelp("intkey=P3 data=r[P2]"),
29075    /* 116 */ "Delete"           OpHelp(""),
29076    /* 117 */ "ResetCount"       OpHelp(""),
29077    /* 118 */ "SorterCompare"    OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
29078    /* 119 */ "SorterData"       OpHelp("r[P2]=data"),
29079    /* 120 */ "RowKey"           OpHelp("r[P2]=key"),
29080    /* 121 */ "RowData"          OpHelp("r[P2]=data"),
29081    /* 122 */ "Rowid"            OpHelp("r[P2]=rowid"),
29082    /* 123 */ "NullRow"          OpHelp(""),
29083    /* 124 */ "SorterInsert"     OpHelp(""),
29084    /* 125 */ "IdxInsert"        OpHelp("key=r[P2]"),
29085    /* 126 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
29086    /* 127 */ "Seek"             OpHelp("Move P3 to P1.rowid"),
29087    /* 128 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
29088    /* 129 */ "Destroy"          OpHelp(""),
29089    /* 130 */ "Clear"            OpHelp(""),
29090    /* 131 */ "ResetSorter"      OpHelp(""),
29091    /* 132 */ "CreateIndex"      OpHelp("r[P2]=root iDb=P1"),
29092    /* 133 */ "Real"             OpHelp("r[P2]=P4"),
29093    /* 134 */ "CreateTable"      OpHelp("r[P2]=root iDb=P1"),
29094    /* 135 */ "ParseSchema"      OpHelp(""),
29095    /* 136 */ "LoadAnalysis"     OpHelp(""),
29096    /* 137 */ "DropTable"        OpHelp(""),
29097    /* 138 */ "DropIndex"        OpHelp(""),
29098    /* 139 */ "DropTrigger"      OpHelp(""),
29099    /* 140 */ "IntegrityCk"      OpHelp(""),
29100    /* 141 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
29101    /* 142 */ "Param"            OpHelp(""),
29102    /* 143 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
29103    /* 144 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
29104    /* 145 */ "OffsetLimit"      OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
29105    /* 146 */ "AggStep0"         OpHelp("accum=r[P3] step(r[P2@P5])"),
29106    /* 147 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
29107    /* 148 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
29108    /* 149 */ "Expire"           OpHelp(""),
29109    /* 150 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
29110    /* 151 */ "VBegin"           OpHelp(""),
29111    /* 152 */ "VCreate"          OpHelp(""),
29112    /* 153 */ "VDestroy"         OpHelp(""),
29113    /* 154 */ "VOpen"            OpHelp(""),
29114    /* 155 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
29115    /* 156 */ "VRename"          OpHelp(""),
29116    /* 157 */ "Pagecount"        OpHelp(""),
29117    /* 158 */ "MaxPgcnt"         OpHelp(""),
29118    /* 159 */ "CursorHint"       OpHelp(""),
29119    /* 160 */ "Noop"             OpHelp(""),
29120    /* 161 */ "Explain"          OpHelp(""),
29121  };
29122  return azName[i];
29123}
29124#endif
29125
29126/************** End of opcodes.c *********************************************/
29127/************** Begin file os_unix.c *****************************************/
29128/*
29129** 2004 May 22
29130**
29131** The author disclaims copyright to this source code.  In place of
29132** a legal notice, here is a blessing:
29133**
29134**    May you do good and not evil.
29135**    May you find forgiveness for yourself and forgive others.
29136**    May you share freely, never taking more than you give.
29137**
29138******************************************************************************
29139**
29140** This file contains the VFS implementation for unix-like operating systems
29141** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
29142**
29143** There are actually several different VFS implementations in this file.
29144** The differences are in the way that file locking is done.  The default
29145** implementation uses Posix Advisory Locks.  Alternative implementations
29146** use flock(), dot-files, various proprietary locking schemas, or simply
29147** skip locking all together.
29148**
29149** This source file is organized into divisions where the logic for various
29150** subfunctions is contained within the appropriate division.  PLEASE
29151** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
29152** in the correct division and should be clearly labeled.
29153**
29154** The layout of divisions is as follows:
29155**
29156**   *  General-purpose declarations and utility functions.
29157**   *  Unique file ID logic used by VxWorks.
29158**   *  Various locking primitive implementations (all except proxy locking):
29159**      + for Posix Advisory Locks
29160**      + for no-op locks
29161**      + for dot-file locks
29162**      + for flock() locking
29163**      + for named semaphore locks (VxWorks only)
29164**      + for AFP filesystem locks (MacOSX only)
29165**   *  sqlite3_file methods not associated with locking.
29166**   *  Definitions of sqlite3_io_methods objects for all locking
29167**      methods plus "finder" functions for each locking method.
29168**   *  sqlite3_vfs method implementations.
29169**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
29170**   *  Definitions of sqlite3_vfs objects for all locking methods
29171**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
29172*/
29173/* #include "sqliteInt.h" */
29174#if SQLITE_OS_UNIX              /* This file is used on unix only */
29175
29176/*
29177** There are various methods for file locking used for concurrency
29178** control:
29179**
29180**   1. POSIX locking (the default),
29181**   2. No locking,
29182**   3. Dot-file locking,
29183**   4. flock() locking,
29184**   5. AFP locking (OSX only),
29185**   6. Named POSIX semaphores (VXWorks only),
29186**   7. proxy locking. (OSX only)
29187**
29188** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
29189** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
29190** selection of the appropriate locking style based on the filesystem
29191** where the database is located.
29192*/
29193#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
29194#  if defined(__APPLE__)
29195#    define SQLITE_ENABLE_LOCKING_STYLE 1
29196#  else
29197#    define SQLITE_ENABLE_LOCKING_STYLE 0
29198#  endif
29199#endif
29200
29201/* Use pread() and pwrite() if they are available */
29202#if defined(__APPLE__)
29203# define HAVE_PREAD 1
29204# define HAVE_PWRITE 1
29205#endif
29206#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
29207# undef USE_PREAD
29208# define USE_PREAD64 1
29209#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
29210# undef USE_PREAD64
29211# define USE_PREAD 1
29212#endif
29213
29214/*
29215** standard include files.
29216*/
29217#include <sys/types.h>
29218#include <sys/stat.h>
29219#include <fcntl.h>
29220#include <unistd.h>
29221/* #include <time.h> */
29222#include <sys/time.h>
29223#include <errno.h>
29224#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29225# include <sys/mman.h>
29226#endif
29227
29228#if SQLITE_ENABLE_LOCKING_STYLE
29229# include <sys/ioctl.h>
29230# include <sys/file.h>
29231# include <sys/param.h>
29232#endif /* SQLITE_ENABLE_LOCKING_STYLE */
29233
29234#if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
29235                           (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
29236#  if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
29237       && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
29238#    define HAVE_GETHOSTUUID 1
29239#  else
29240#    warning "gethostuuid() is disabled."
29241#  endif
29242#endif
29243
29244
29245#if OS_VXWORKS
29246/* # include <sys/ioctl.h> */
29247# include <semaphore.h>
29248# include <limits.h>
29249#endif /* OS_VXWORKS */
29250
29251#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29252# include <sys/mount.h>
29253#endif
29254
29255#ifdef HAVE_UTIME
29256# include <utime.h>
29257#endif
29258
29259/*
29260** Allowed values of unixFile.fsFlags
29261*/
29262#define SQLITE_FSFLAGS_IS_MSDOS     0x1
29263
29264/*
29265** If we are to be thread-safe, include the pthreads header and define
29266** the SQLITE_UNIX_THREADS macro.
29267*/
29268#if SQLITE_THREADSAFE
29269/* # include <pthread.h> */
29270# define SQLITE_UNIX_THREADS 1
29271#endif
29272
29273/*
29274** Default permissions when creating a new file
29275*/
29276#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
29277# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
29278#endif
29279
29280/*
29281** Default permissions when creating auto proxy dir
29282*/
29283#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
29284# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
29285#endif
29286
29287/*
29288** Maximum supported path-length.
29289*/
29290#define MAX_PATHNAME 512
29291
29292/*
29293** Maximum supported symbolic links
29294*/
29295#define SQLITE_MAX_SYMLINKS 100
29296
29297/* Always cast the getpid() return type for compatibility with
29298** kernel modules in VxWorks. */
29299#define osGetpid(X) (pid_t)getpid()
29300
29301/*
29302** Only set the lastErrno if the error code is a real error and not
29303** a normal expected return code of SQLITE_BUSY or SQLITE_OK
29304*/
29305#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
29306
29307/* Forward references */
29308typedef struct unixShm unixShm;               /* Connection shared memory */
29309typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
29310typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
29311typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
29312
29313/*
29314** Sometimes, after a file handle is closed by SQLite, the file descriptor
29315** cannot be closed immediately. In these cases, instances of the following
29316** structure are used to store the file descriptor while waiting for an
29317** opportunity to either close or reuse it.
29318*/
29319struct UnixUnusedFd {
29320  int fd;                   /* File descriptor to close */
29321  int flags;                /* Flags this file descriptor was opened with */
29322  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
29323};
29324
29325/*
29326** The unixFile structure is subclass of sqlite3_file specific to the unix
29327** VFS implementations.
29328*/
29329typedef struct unixFile unixFile;
29330struct unixFile {
29331  sqlite3_io_methods const *pMethod;  /* Always the first entry */
29332  sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
29333  unixInodeInfo *pInode;              /* Info about locks on this inode */
29334  int h;                              /* The file descriptor */
29335  unsigned char eFileLock;            /* The type of lock held on this fd */
29336  unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
29337  int lastErrno;                      /* The unix errno from last I/O error */
29338  void *lockingContext;               /* Locking style specific state */
29339  UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
29340  const char *zPath;                  /* Name of the file */
29341  unixShm *pShm;                      /* Shared memory segment information */
29342  int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
29343#if SQLITE_MAX_MMAP_SIZE>0
29344  int nFetchOut;                      /* Number of outstanding xFetch refs */
29345  sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
29346  sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
29347  sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
29348  void *pMapRegion;                   /* Memory mapped region */
29349#endif
29350#ifdef __QNXNTO__
29351  int sectorSize;                     /* Device sector size */
29352  int deviceCharacteristics;          /* Precomputed device characteristics */
29353#endif
29354#if SQLITE_ENABLE_LOCKING_STYLE
29355  int openFlags;                      /* The flags specified at open() */
29356#endif
29357#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
29358  unsigned fsFlags;                   /* cached details from statfs() */
29359#endif
29360#if OS_VXWORKS
29361  struct vxworksFileId *pId;          /* Unique file ID */
29362#endif
29363#ifdef SQLITE_DEBUG
29364  /* The next group of variables are used to track whether or not the
29365  ** transaction counter in bytes 24-27 of database files are updated
29366  ** whenever any part of the database changes.  An assertion fault will
29367  ** occur if a file is updated without also updating the transaction
29368  ** counter.  This test is made to avoid new problems similar to the
29369  ** one described by ticket #3584.
29370  */
29371  unsigned char transCntrChng;   /* True if the transaction counter changed */
29372  unsigned char dbUpdate;        /* True if any part of database file changed */
29373  unsigned char inNormalWrite;   /* True if in a normal write operation */
29374
29375#endif
29376
29377#ifdef SQLITE_TEST
29378  /* In test mode, increase the size of this structure a bit so that
29379  ** it is larger than the struct CrashFile defined in test6.c.
29380  */
29381  char aPadding[32];
29382#endif
29383};
29384
29385/* This variable holds the process id (pid) from when the xRandomness()
29386** method was called.  If xOpen() is called from a different process id,
29387** indicating that a fork() has occurred, the PRNG will be reset.
29388*/
29389static pid_t randomnessPid = 0;
29390
29391/*
29392** Allowed values for the unixFile.ctrlFlags bitmask:
29393*/
29394#define UNIXFILE_EXCL        0x01     /* Connections from one process only */
29395#define UNIXFILE_RDONLY      0x02     /* Connection is read only */
29396#define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
29397#ifndef SQLITE_DISABLE_DIRSYNC
29398# define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
29399#else
29400# define UNIXFILE_DIRSYNC    0x00
29401#endif
29402#define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
29403#define UNIXFILE_DELETE      0x20     /* Delete on close */
29404#define UNIXFILE_URI         0x40     /* Filename might have query parameters */
29405#define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
29406
29407/*
29408** Include code that is common to all os_*.c files
29409*/
29410/************** Include os_common.h in the middle of os_unix.c ***************/
29411/************** Begin file os_common.h ***************************************/
29412/*
29413** 2004 May 22
29414**
29415** The author disclaims copyright to this source code.  In place of
29416** a legal notice, here is a blessing:
29417**
29418**    May you do good and not evil.
29419**    May you find forgiveness for yourself and forgive others.
29420**    May you share freely, never taking more than you give.
29421**
29422******************************************************************************
29423**
29424** This file contains macros and a little bit of code that is common to
29425** all of the platform-specific files (os_*.c) and is #included into those
29426** files.
29427**
29428** This file should be #included by the os_*.c files only.  It is not a
29429** general purpose header file.
29430*/
29431#ifndef _OS_COMMON_H_
29432#define _OS_COMMON_H_
29433
29434/*
29435** At least two bugs have slipped in because we changed the MEMORY_DEBUG
29436** macro to SQLITE_DEBUG and some older makefiles have not yet made the
29437** switch.  The following code should catch this problem at compile-time.
29438*/
29439#ifdef MEMORY_DEBUG
29440# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
29441#endif
29442
29443/*
29444** Macros for performance tracing.  Normally turned off.  Only works
29445** on i486 hardware.
29446*/
29447#ifdef SQLITE_PERFORMANCE_TRACE
29448
29449/*
29450** hwtime.h contains inline assembler code for implementing
29451** high-performance timing routines.
29452*/
29453/************** Include hwtime.h in the middle of os_common.h ****************/
29454/************** Begin file hwtime.h ******************************************/
29455/*
29456** 2008 May 27
29457**
29458** The author disclaims copyright to this source code.  In place of
29459** a legal notice, here is a blessing:
29460**
29461**    May you do good and not evil.
29462**    May you find forgiveness for yourself and forgive others.
29463**    May you share freely, never taking more than you give.
29464**
29465******************************************************************************
29466**
29467** This file contains inline asm code for retrieving "high-performance"
29468** counters for x86 class CPUs.
29469*/
29470#ifndef SQLITE_HWTIME_H
29471#define SQLITE_HWTIME_H
29472
29473/*
29474** The following routine only works on pentium-class (or newer) processors.
29475** It uses the RDTSC opcode to read the cycle count value out of the
29476** processor and returns that value.  This can be used for high-res
29477** profiling.
29478*/
29479#if (defined(__GNUC__) || defined(_MSC_VER)) && \
29480      (defined(i386) || defined(__i386__) || defined(_M_IX86))
29481
29482  #if defined(__GNUC__)
29483
29484  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29485     unsigned int lo, hi;
29486     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
29487     return (sqlite_uint64)hi << 32 | lo;
29488  }
29489
29490  #elif defined(_MSC_VER)
29491
29492  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
29493     __asm {
29494        rdtsc
29495        ret       ; return value at EDX:EAX
29496     }
29497  }
29498
29499  #endif
29500
29501#elif (defined(__GNUC__) && defined(__x86_64__))
29502
29503  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29504      unsigned long val;
29505      __asm__ __volatile__ ("rdtsc" : "=A" (val));
29506      return val;
29507  }
29508
29509#elif (defined(__GNUC__) && defined(__ppc__))
29510
29511  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29512      unsigned long long retval;
29513      unsigned long junk;
29514      __asm__ __volatile__ ("\n\
29515          1:      mftbu   %1\n\
29516                  mftb    %L0\n\
29517                  mftbu   %0\n\
29518                  cmpw    %0,%1\n\
29519                  bne     1b"
29520                  : "=r" (retval), "=r" (junk));
29521      return retval;
29522  }
29523
29524#else
29525
29526  #error Need implementation of sqlite3Hwtime() for your platform.
29527
29528  /*
29529  ** To compile without implementing sqlite3Hwtime() for your platform,
29530  ** you can remove the above #error and use the following
29531  ** stub function.  You will lose timing support for many
29532  ** of the debugging and testing utilities, but it should at
29533  ** least compile and run.
29534  */
29535SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
29536
29537#endif
29538
29539#endif /* !defined(SQLITE_HWTIME_H) */
29540
29541/************** End of hwtime.h **********************************************/
29542/************** Continuing where we left off in os_common.h ******************/
29543
29544static sqlite_uint64 g_start;
29545static sqlite_uint64 g_elapsed;
29546#define TIMER_START       g_start=sqlite3Hwtime()
29547#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
29548#define TIMER_ELAPSED     g_elapsed
29549#else
29550#define TIMER_START
29551#define TIMER_END
29552#define TIMER_ELAPSED     ((sqlite_uint64)0)
29553#endif
29554
29555/*
29556** If we compile with the SQLITE_TEST macro set, then the following block
29557** of code will give us the ability to simulate a disk I/O error.  This
29558** is used for testing the I/O recovery logic.
29559*/
29560#if defined(SQLITE_TEST)
29561SQLITE_API extern int sqlite3_io_error_hit;
29562SQLITE_API extern int sqlite3_io_error_hardhit;
29563SQLITE_API extern int sqlite3_io_error_pending;
29564SQLITE_API extern int sqlite3_io_error_persist;
29565SQLITE_API extern int sqlite3_io_error_benign;
29566SQLITE_API extern int sqlite3_diskfull_pending;
29567SQLITE_API extern int sqlite3_diskfull;
29568#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
29569#define SimulateIOError(CODE)  \
29570  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
29571       || sqlite3_io_error_pending-- == 1 )  \
29572              { local_ioerr(); CODE; }
29573static void local_ioerr(){
29574  IOTRACE(("IOERR\n"));
29575  sqlite3_io_error_hit++;
29576  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
29577}
29578#define SimulateDiskfullError(CODE) \
29579   if( sqlite3_diskfull_pending ){ \
29580     if( sqlite3_diskfull_pending == 1 ){ \
29581       local_ioerr(); \
29582       sqlite3_diskfull = 1; \
29583       sqlite3_io_error_hit = 1; \
29584       CODE; \
29585     }else{ \
29586       sqlite3_diskfull_pending--; \
29587     } \
29588   }
29589#else
29590#define SimulateIOErrorBenign(X)
29591#define SimulateIOError(A)
29592#define SimulateDiskfullError(A)
29593#endif /* defined(SQLITE_TEST) */
29594
29595/*
29596** When testing, keep a count of the number of open files.
29597*/
29598#if defined(SQLITE_TEST)
29599SQLITE_API extern int sqlite3_open_file_count;
29600#define OpenCounter(X)  sqlite3_open_file_count+=(X)
29601#else
29602#define OpenCounter(X)
29603#endif /* defined(SQLITE_TEST) */
29604
29605#endif /* !defined(_OS_COMMON_H_) */
29606
29607/************** End of os_common.h *******************************************/
29608/************** Continuing where we left off in os_unix.c ********************/
29609
29610/*
29611** Define various macros that are missing from some systems.
29612*/
29613#ifndef O_LARGEFILE
29614# define O_LARGEFILE 0
29615#endif
29616#ifdef SQLITE_DISABLE_LFS
29617# undef O_LARGEFILE
29618# define O_LARGEFILE 0
29619#endif
29620#ifndef O_NOFOLLOW
29621# define O_NOFOLLOW 0
29622#endif
29623#ifndef O_BINARY
29624# define O_BINARY 0
29625#endif
29626
29627/*
29628** The threadid macro resolves to the thread-id or to 0.  Used for
29629** testing and debugging only.
29630*/
29631#if SQLITE_THREADSAFE
29632#define threadid pthread_self()
29633#else
29634#define threadid 0
29635#endif
29636
29637/*
29638** HAVE_MREMAP defaults to true on Linux and false everywhere else.
29639*/
29640#if !defined(HAVE_MREMAP)
29641# if defined(__linux__) && defined(_GNU_SOURCE)
29642#  define HAVE_MREMAP 1
29643# else
29644#  define HAVE_MREMAP 0
29645# endif
29646#endif
29647
29648/*
29649** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
29650** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
29651*/
29652#ifdef __ANDROID__
29653# define lseek lseek64
29654#endif
29655
29656/*
29657** Different Unix systems declare open() in different ways.  Same use
29658** open(const char*,int,mode_t).  Others use open(const char*,int,...).
29659** The difference is important when using a pointer to the function.
29660**
29661** The safest way to deal with the problem is to always use this wrapper
29662** which always has the same well-defined interface.
29663*/
29664static int posixOpen(const char *zFile, int flags, int mode){
29665  return open(zFile, flags, mode);
29666}
29667
29668/* Forward reference */
29669static int openDirectory(const char*, int*);
29670static int unixGetpagesize(void);
29671
29672/*
29673** Many system calls are accessed through pointer-to-functions so that
29674** they may be overridden at runtime to facilitate fault injection during
29675** testing and sandboxing.  The following array holds the names and pointers
29676** to all overrideable system calls.
29677*/
29678static struct unix_syscall {
29679  const char *zName;            /* Name of the system call */
29680  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
29681  sqlite3_syscall_ptr pDefault; /* Default value */
29682} aSyscall[] = {
29683  { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
29684#define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
29685
29686  { "close",        (sqlite3_syscall_ptr)close,      0  },
29687#define osClose     ((int(*)(int))aSyscall[1].pCurrent)
29688
29689  { "access",       (sqlite3_syscall_ptr)access,     0  },
29690#define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
29691
29692  { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
29693#define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
29694
29695  { "stat",         (sqlite3_syscall_ptr)stat,       0  },
29696#define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
29697
29698/*
29699** The DJGPP compiler environment looks mostly like Unix, but it
29700** lacks the fcntl() system call.  So redefine fcntl() to be something
29701** that always succeeds.  This means that locking does not occur under
29702** DJGPP.  But it is DOS - what did you expect?
29703*/
29704#ifdef __DJGPP__
29705  { "fstat",        0,                 0  },
29706#define osFstat(a,b,c)    0
29707#else
29708  { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
29709#define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
29710#endif
29711
29712  { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
29713#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
29714
29715  { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
29716#define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
29717
29718  { "read",         (sqlite3_syscall_ptr)read,       0  },
29719#define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
29720
29721#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
29722  { "pread",        (sqlite3_syscall_ptr)pread,      0  },
29723#else
29724  { "pread",        (sqlite3_syscall_ptr)0,          0  },
29725#endif
29726#define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
29727
29728#if defined(USE_PREAD64)
29729  { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
29730#else
29731  { "pread64",      (sqlite3_syscall_ptr)0,          0  },
29732#endif
29733#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
29734
29735  { "write",        (sqlite3_syscall_ptr)write,      0  },
29736#define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
29737
29738#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
29739  { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
29740#else
29741  { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
29742#endif
29743#define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
29744                    aSyscall[12].pCurrent)
29745
29746#if defined(USE_PREAD64)
29747  { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
29748#else
29749  { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
29750#endif
29751#define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off64_t))\
29752                    aSyscall[13].pCurrent)
29753
29754  { "fchmod",       (sqlite3_syscall_ptr)fchmod,          0  },
29755#define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
29756
29757#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
29758  { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
29759#else
29760  { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
29761#endif
29762#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
29763
29764  { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
29765#define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
29766
29767  { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
29768#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
29769
29770  { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
29771#define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
29772
29773  { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
29774#define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
29775
29776#if defined(HAVE_FCHOWN)
29777  { "fchown",       (sqlite3_syscall_ptr)fchown,          0 },
29778#else
29779  { "fchown",       (sqlite3_syscall_ptr)0,               0 },
29780#endif
29781#define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
29782
29783  { "geteuid",      (sqlite3_syscall_ptr)geteuid,         0 },
29784#define osGeteuid   ((uid_t(*)(void))aSyscall[21].pCurrent)
29785
29786#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29787  { "mmap",         (sqlite3_syscall_ptr)mmap,            0 },
29788#else
29789  { "mmap",         (sqlite3_syscall_ptr)0,               0 },
29790#endif
29791#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
29792
29793#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29794  { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
29795#else
29796  { "munmap",       (sqlite3_syscall_ptr)0,               0 },
29797#endif
29798#define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
29799
29800#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
29801  { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
29802#else
29803  { "mremap",       (sqlite3_syscall_ptr)0,               0 },
29804#endif
29805#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
29806
29807#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29808  { "getpagesize",  (sqlite3_syscall_ptr)unixGetpagesize, 0 },
29809#else
29810  { "getpagesize",  (sqlite3_syscall_ptr)0,               0 },
29811#endif
29812#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
29813
29814#if defined(HAVE_READLINK)
29815  { "readlink",     (sqlite3_syscall_ptr)readlink,        0 },
29816#else
29817  { "readlink",     (sqlite3_syscall_ptr)0,               0 },
29818#endif
29819#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
29820
29821#if defined(HAVE_LSTAT)
29822  { "lstat",         (sqlite3_syscall_ptr)lstat,          0 },
29823#else
29824  { "lstat",         (sqlite3_syscall_ptr)0,              0 },
29825#endif
29826#define osLstat      ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
29827
29828}; /* End of the overrideable system calls */
29829
29830
29831/*
29832** On some systems, calls to fchown() will trigger a message in a security
29833** log if they come from non-root processes.  So avoid calling fchown() if
29834** we are not running as root.
29835*/
29836static int robustFchown(int fd, uid_t uid, gid_t gid){
29837#if defined(HAVE_FCHOWN)
29838  return osGeteuid() ? 0 : osFchown(fd,uid,gid);
29839#else
29840  return 0;
29841#endif
29842}
29843
29844/*
29845** This is the xSetSystemCall() method of sqlite3_vfs for all of the
29846** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
29847** system call pointer, or SQLITE_NOTFOUND if there is no configurable
29848** system call named zName.
29849*/
29850static int unixSetSystemCall(
29851  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
29852  const char *zName,            /* Name of system call to override */
29853  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
29854){
29855  unsigned int i;
29856  int rc = SQLITE_NOTFOUND;
29857
29858  UNUSED_PARAMETER(pNotUsed);
29859  if( zName==0 ){
29860    /* If no zName is given, restore all system calls to their default
29861    ** settings and return NULL
29862    */
29863    rc = SQLITE_OK;
29864    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29865      if( aSyscall[i].pDefault ){
29866        aSyscall[i].pCurrent = aSyscall[i].pDefault;
29867      }
29868    }
29869  }else{
29870    /* If zName is specified, operate on only the one system call
29871    ** specified.
29872    */
29873    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29874      if( strcmp(zName, aSyscall[i].zName)==0 ){
29875        if( aSyscall[i].pDefault==0 ){
29876          aSyscall[i].pDefault = aSyscall[i].pCurrent;
29877        }
29878        rc = SQLITE_OK;
29879        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
29880        aSyscall[i].pCurrent = pNewFunc;
29881        break;
29882      }
29883    }
29884  }
29885  return rc;
29886}
29887
29888/*
29889** Return the value of a system call.  Return NULL if zName is not a
29890** recognized system call name.  NULL is also returned if the system call
29891** is currently undefined.
29892*/
29893static sqlite3_syscall_ptr unixGetSystemCall(
29894  sqlite3_vfs *pNotUsed,
29895  const char *zName
29896){
29897  unsigned int i;
29898
29899  UNUSED_PARAMETER(pNotUsed);
29900  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29901    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
29902  }
29903  return 0;
29904}
29905
29906/*
29907** Return the name of the first system call after zName.  If zName==NULL
29908** then return the name of the first system call.  Return NULL if zName
29909** is the last system call or if zName is not the name of a valid
29910** system call.
29911*/
29912static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
29913  int i = -1;
29914
29915  UNUSED_PARAMETER(p);
29916  if( zName ){
29917    for(i=0; i<ArraySize(aSyscall)-1; i++){
29918      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
29919    }
29920  }
29921  for(i++; i<ArraySize(aSyscall); i++){
29922    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
29923  }
29924  return 0;
29925}
29926
29927/*
29928** Do not accept any file descriptor less than this value, in order to avoid
29929** opening database file using file descriptors that are commonly used for
29930** standard input, output, and error.
29931*/
29932#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
29933# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
29934#endif
29935
29936/*
29937** Invoke open().  Do so multiple times, until it either succeeds or
29938** fails for some reason other than EINTR.
29939**
29940** If the file creation mode "m" is 0 then set it to the default for
29941** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
29942** 0644) as modified by the system umask.  If m is not 0, then
29943** make the file creation mode be exactly m ignoring the umask.
29944**
29945** The m parameter will be non-zero only when creating -wal, -journal,
29946** and -shm files.  We want those files to have *exactly* the same
29947** permissions as their original database, unadulterated by the umask.
29948** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
29949** transaction crashes and leaves behind hot journals, then any
29950** process that is able to write to the database will also be able to
29951** recover the hot journals.
29952*/
29953static int robust_open(const char *z, int f, mode_t m){
29954  int fd;
29955  mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
29956  while(1){
29957#if defined(O_CLOEXEC)
29958    fd = osOpen(z,f|O_CLOEXEC,m2);
29959#else
29960    fd = osOpen(z,f,m2);
29961#endif
29962    if( fd<0 ){
29963      if( errno==EINTR ) continue;
29964      break;
29965    }
29966    if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
29967    osClose(fd);
29968    sqlite3_log(SQLITE_WARNING,
29969                "attempt to open \"%s\" as file descriptor %d", z, fd);
29970    fd = -1;
29971    if( osOpen("/dev/null", f, m)<0 ) break;
29972  }
29973  if( fd>=0 ){
29974    if( m!=0 ){
29975      struct stat statbuf;
29976      if( osFstat(fd, &statbuf)==0
29977       && statbuf.st_size==0
29978       && (statbuf.st_mode&0777)!=m
29979      ){
29980        osFchmod(fd, m);
29981      }
29982    }
29983#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
29984    osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
29985#endif
29986  }
29987  return fd;
29988}
29989
29990/*
29991** Helper functions to obtain and relinquish the global mutex. The
29992** global mutex is used to protect the unixInodeInfo and
29993** vxworksFileId objects used by this file, all of which may be
29994** shared by multiple threads.
29995**
29996** Function unixMutexHeld() is used to assert() that the global mutex
29997** is held when required. This function is only used as part of assert()
29998** statements. e.g.
29999**
30000**   unixEnterMutex()
30001**     assert( unixMutexHeld() );
30002**   unixEnterLeave()
30003*/
30004static void unixEnterMutex(void){
30005  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
30006}
30007static void unixLeaveMutex(void){
30008  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
30009}
30010#ifdef SQLITE_DEBUG
30011static int unixMutexHeld(void) {
30012  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
30013}
30014#endif
30015
30016
30017#ifdef SQLITE_HAVE_OS_TRACE
30018/*
30019** Helper function for printing out trace information from debugging
30020** binaries. This returns the string representation of the supplied
30021** integer lock-type.
30022*/
30023static const char *azFileLock(int eFileLock){
30024  switch( eFileLock ){
30025    case NO_LOCK: return "NONE";
30026    case SHARED_LOCK: return "SHARED";
30027    case RESERVED_LOCK: return "RESERVED";
30028    case PENDING_LOCK: return "PENDING";
30029    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
30030  }
30031  return "ERROR";
30032}
30033#endif
30034
30035#ifdef SQLITE_LOCK_TRACE
30036/*
30037** Print out information about all locking operations.
30038**
30039** This routine is used for troubleshooting locks on multithreaded
30040** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
30041** command-line option on the compiler.  This code is normally
30042** turned off.
30043*/
30044static int lockTrace(int fd, int op, struct flock *p){
30045  char *zOpName, *zType;
30046  int s;
30047  int savedErrno;
30048  if( op==F_GETLK ){
30049    zOpName = "GETLK";
30050  }else if( op==F_SETLK ){
30051    zOpName = "SETLK";
30052  }else{
30053    s = osFcntl(fd, op, p);
30054    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
30055    return s;
30056  }
30057  if( p->l_type==F_RDLCK ){
30058    zType = "RDLCK";
30059  }else if( p->l_type==F_WRLCK ){
30060    zType = "WRLCK";
30061  }else if( p->l_type==F_UNLCK ){
30062    zType = "UNLCK";
30063  }else{
30064    assert( 0 );
30065  }
30066  assert( p->l_whence==SEEK_SET );
30067  s = osFcntl(fd, op, p);
30068  savedErrno = errno;
30069  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
30070     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
30071     (int)p->l_pid, s);
30072  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
30073    struct flock l2;
30074    l2 = *p;
30075    osFcntl(fd, F_GETLK, &l2);
30076    if( l2.l_type==F_RDLCK ){
30077      zType = "RDLCK";
30078    }else if( l2.l_type==F_WRLCK ){
30079      zType = "WRLCK";
30080    }else if( l2.l_type==F_UNLCK ){
30081      zType = "UNLCK";
30082    }else{
30083      assert( 0 );
30084    }
30085    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
30086       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
30087  }
30088  errno = savedErrno;
30089  return s;
30090}
30091#undef osFcntl
30092#define osFcntl lockTrace
30093#endif /* SQLITE_LOCK_TRACE */
30094
30095/*
30096** Retry ftruncate() calls that fail due to EINTR
30097**
30098** All calls to ftruncate() within this file should be made through
30099** this wrapper.  On the Android platform, bypassing the logic below
30100** could lead to a corrupt database.
30101*/
30102static int robust_ftruncate(int h, sqlite3_int64 sz){
30103  int rc;
30104#ifdef __ANDROID__
30105  /* On Android, ftruncate() always uses 32-bit offsets, even if
30106  ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
30107  ** truncate a file to any size larger than 2GiB. Silently ignore any
30108  ** such attempts.  */
30109  if( sz>(sqlite3_int64)0x7FFFFFFF ){
30110    rc = SQLITE_OK;
30111  }else
30112#endif
30113  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
30114  return rc;
30115}
30116
30117/*
30118** This routine translates a standard POSIX errno code into something
30119** useful to the clients of the sqlite3 functions.  Specifically, it is
30120** intended to translate a variety of "try again" errors into SQLITE_BUSY
30121** and a variety of "please close the file descriptor NOW" errors into
30122** SQLITE_IOERR
30123**
30124** Errors during initialization of locks, or file system support for locks,
30125** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
30126*/
30127static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
30128  assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
30129          (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
30130          (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
30131          (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
30132  switch (posixError) {
30133  case EACCES:
30134  case EAGAIN:
30135  case ETIMEDOUT:
30136  case EBUSY:
30137  case EINTR:
30138  case ENOLCK:
30139    /* random NFS retry error, unless during file system support
30140     * introspection, in which it actually means what it says */
30141    return SQLITE_BUSY;
30142
30143  case EPERM:
30144    return SQLITE_PERM;
30145
30146  default:
30147    return sqliteIOErr;
30148  }
30149}
30150
30151
30152/******************************************************************************
30153****************** Begin Unique File ID Utility Used By VxWorks ***************
30154**
30155** On most versions of unix, we can get a unique ID for a file by concatenating
30156** the device number and the inode number.  But this does not work on VxWorks.
30157** On VxWorks, a unique file id must be based on the canonical filename.
30158**
30159** A pointer to an instance of the following structure can be used as a
30160** unique file ID in VxWorks.  Each instance of this structure contains
30161** a copy of the canonical filename.  There is also a reference count.
30162** The structure is reclaimed when the number of pointers to it drops to
30163** zero.
30164**
30165** There are never very many files open at one time and lookups are not
30166** a performance-critical path, so it is sufficient to put these
30167** structures on a linked list.
30168*/
30169struct vxworksFileId {
30170  struct vxworksFileId *pNext;  /* Next in a list of them all */
30171  int nRef;                     /* Number of references to this one */
30172  int nName;                    /* Length of the zCanonicalName[] string */
30173  char *zCanonicalName;         /* Canonical filename */
30174};
30175
30176#if OS_VXWORKS
30177/*
30178** All unique filenames are held on a linked list headed by this
30179** variable:
30180*/
30181static struct vxworksFileId *vxworksFileList = 0;
30182
30183/*
30184** Simplify a filename into its canonical form
30185** by making the following changes:
30186**
30187**  * removing any trailing and duplicate /
30188**  * convert /./ into just /
30189**  * convert /A/../ where A is any simple name into just /
30190**
30191** Changes are made in-place.  Return the new name length.
30192**
30193** The original filename is in z[0..n-1].  Return the number of
30194** characters in the simplified name.
30195*/
30196static int vxworksSimplifyName(char *z, int n){
30197  int i, j;
30198  while( n>1 && z[n-1]=='/' ){ n--; }
30199  for(i=j=0; i<n; i++){
30200    if( z[i]=='/' ){
30201      if( z[i+1]=='/' ) continue;
30202      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
30203        i += 1;
30204        continue;
30205      }
30206      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
30207        while( j>0 && z[j-1]!='/' ){ j--; }
30208        if( j>0 ){ j--; }
30209        i += 2;
30210        continue;
30211      }
30212    }
30213    z[j++] = z[i];
30214  }
30215  z[j] = 0;
30216  return j;
30217}
30218
30219/*
30220** Find a unique file ID for the given absolute pathname.  Return
30221** a pointer to the vxworksFileId object.  This pointer is the unique
30222** file ID.
30223**
30224** The nRef field of the vxworksFileId object is incremented before
30225** the object is returned.  A new vxworksFileId object is created
30226** and added to the global list if necessary.
30227**
30228** If a memory allocation error occurs, return NULL.
30229*/
30230static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
30231  struct vxworksFileId *pNew;         /* search key and new file ID */
30232  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
30233  int n;                              /* Length of zAbsoluteName string */
30234
30235  assert( zAbsoluteName[0]=='/' );
30236  n = (int)strlen(zAbsoluteName);
30237  pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
30238  if( pNew==0 ) return 0;
30239  pNew->zCanonicalName = (char*)&pNew[1];
30240  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
30241  n = vxworksSimplifyName(pNew->zCanonicalName, n);
30242
30243  /* Search for an existing entry that matching the canonical name.
30244  ** If found, increment the reference count and return a pointer to
30245  ** the existing file ID.
30246  */
30247  unixEnterMutex();
30248  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
30249    if( pCandidate->nName==n
30250     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
30251    ){
30252       sqlite3_free(pNew);
30253       pCandidate->nRef++;
30254       unixLeaveMutex();
30255       return pCandidate;
30256    }
30257  }
30258
30259  /* No match was found.  We will make a new file ID */
30260  pNew->nRef = 1;
30261  pNew->nName = n;
30262  pNew->pNext = vxworksFileList;
30263  vxworksFileList = pNew;
30264  unixLeaveMutex();
30265  return pNew;
30266}
30267
30268/*
30269** Decrement the reference count on a vxworksFileId object.  Free
30270** the object when the reference count reaches zero.
30271*/
30272static void vxworksReleaseFileId(struct vxworksFileId *pId){
30273  unixEnterMutex();
30274  assert( pId->nRef>0 );
30275  pId->nRef--;
30276  if( pId->nRef==0 ){
30277    struct vxworksFileId **pp;
30278    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
30279    assert( *pp==pId );
30280    *pp = pId->pNext;
30281    sqlite3_free(pId);
30282  }
30283  unixLeaveMutex();
30284}
30285#endif /* OS_VXWORKS */
30286/*************** End of Unique File ID Utility Used By VxWorks ****************
30287******************************************************************************/
30288
30289
30290/******************************************************************************
30291*************************** Posix Advisory Locking ****************************
30292**
30293** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
30294** section 6.5.2.2 lines 483 through 490 specify that when a process
30295** sets or clears a lock, that operation overrides any prior locks set
30296** by the same process.  It does not explicitly say so, but this implies
30297** that it overrides locks set by the same process using a different
30298** file descriptor.  Consider this test case:
30299**
30300**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
30301**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
30302**
30303** Suppose ./file1 and ./file2 are really the same file (because
30304** one is a hard or symbolic link to the other) then if you set
30305** an exclusive lock on fd1, then try to get an exclusive lock
30306** on fd2, it works.  I would have expected the second lock to
30307** fail since there was already a lock on the file due to fd1.
30308** But not so.  Since both locks came from the same process, the
30309** second overrides the first, even though they were on different
30310** file descriptors opened on different file names.
30311**
30312** This means that we cannot use POSIX locks to synchronize file access
30313** among competing threads of the same process.  POSIX locks will work fine
30314** to synchronize access for threads in separate processes, but not
30315** threads within the same process.
30316**
30317** To work around the problem, SQLite has to manage file locks internally
30318** on its own.  Whenever a new database is opened, we have to find the
30319** specific inode of the database file (the inode is determined by the
30320** st_dev and st_ino fields of the stat structure that fstat() fills in)
30321** and check for locks already existing on that inode.  When locks are
30322** created or removed, we have to look at our own internal record of the
30323** locks to see if another thread has previously set a lock on that same
30324** inode.
30325**
30326** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
30327** For VxWorks, we have to use the alternative unique ID system based on
30328** canonical filename and implemented in the previous division.)
30329**
30330** The sqlite3_file structure for POSIX is no longer just an integer file
30331** descriptor.  It is now a structure that holds the integer file
30332** descriptor and a pointer to a structure that describes the internal
30333** locks on the corresponding inode.  There is one locking structure
30334** per inode, so if the same inode is opened twice, both unixFile structures
30335** point to the same locking structure.  The locking structure keeps
30336** a reference count (so we will know when to delete it) and a "cnt"
30337** field that tells us its internal lock status.  cnt==0 means the
30338** file is unlocked.  cnt==-1 means the file has an exclusive lock.
30339** cnt>0 means there are cnt shared locks on the file.
30340**
30341** Any attempt to lock or unlock a file first checks the locking
30342** structure.  The fcntl() system call is only invoked to set a
30343** POSIX lock if the internal lock structure transitions between
30344** a locked and an unlocked state.
30345**
30346** But wait:  there are yet more problems with POSIX advisory locks.
30347**
30348** If you close a file descriptor that points to a file that has locks,
30349** all locks on that file that are owned by the current process are
30350** released.  To work around this problem, each unixInodeInfo object
30351** maintains a count of the number of pending locks on tha inode.
30352** When an attempt is made to close an unixFile, if there are
30353** other unixFile open on the same inode that are holding locks, the call
30354** to close() the file descriptor is deferred until all of the locks clear.
30355** The unixInodeInfo structure keeps a list of file descriptors that need to
30356** be closed and that list is walked (and cleared) when the last lock
30357** clears.
30358**
30359** Yet another problem:  LinuxThreads do not play well with posix locks.
30360**
30361** Many older versions of linux use the LinuxThreads library which is
30362** not posix compliant.  Under LinuxThreads, a lock created by thread
30363** A cannot be modified or overridden by a different thread B.
30364** Only thread A can modify the lock.  Locking behavior is correct
30365** if the appliation uses the newer Native Posix Thread Library (NPTL)
30366** on linux - with NPTL a lock created by thread A can override locks
30367** in thread B.  But there is no way to know at compile-time which
30368** threading library is being used.  So there is no way to know at
30369** compile-time whether or not thread A can override locks on thread B.
30370** One has to do a run-time check to discover the behavior of the
30371** current process.
30372**
30373** SQLite used to support LinuxThreads.  But support for LinuxThreads
30374** was dropped beginning with version 3.7.0.  SQLite will still work with
30375** LinuxThreads provided that (1) there is no more than one connection
30376** per database file in the same process and (2) database connections
30377** do not move across threads.
30378*/
30379
30380/*
30381** An instance of the following structure serves as the key used
30382** to locate a particular unixInodeInfo object.
30383*/
30384struct unixFileId {
30385  dev_t dev;                  /* Device number */
30386#if OS_VXWORKS
30387  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
30388#else
30389  ino_t ino;                  /* Inode number */
30390#endif
30391};
30392
30393/*
30394** An instance of the following structure is allocated for each open
30395** inode.  Or, on LinuxThreads, there is one of these structures for
30396** each inode opened by each thread.
30397**
30398** A single inode can have multiple file descriptors, so each unixFile
30399** structure contains a pointer to an instance of this object and this
30400** object keeps a count of the number of unixFile pointing to it.
30401*/
30402struct unixInodeInfo {
30403  struct unixFileId fileId;       /* The lookup key */
30404  int nShared;                    /* Number of SHARED locks held */
30405  unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
30406  unsigned char bProcessLock;     /* An exclusive process lock is held */
30407  int nRef;                       /* Number of pointers to this structure */
30408  unixShmNode *pShmNode;          /* Shared memory associated with this inode */
30409  int nLock;                      /* Number of outstanding file locks */
30410  UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
30411  unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
30412  unixInodeInfo *pPrev;           /*    .... doubly linked */
30413#if SQLITE_ENABLE_LOCKING_STYLE
30414  unsigned long long sharedByte;  /* for AFP simulated shared lock */
30415#endif
30416#if OS_VXWORKS
30417  sem_t *pSem;                    /* Named POSIX semaphore */
30418  char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
30419#endif
30420};
30421
30422/*
30423** A lists of all unixInodeInfo objects.
30424*/
30425static unixInodeInfo *inodeList = 0;
30426
30427/*
30428**
30429** This function - unixLogErrorAtLine(), is only ever called via the macro
30430** unixLogError().
30431**
30432** It is invoked after an error occurs in an OS function and errno has been
30433** set. It logs a message using sqlite3_log() containing the current value of
30434** errno and, if possible, the human-readable equivalent from strerror() or
30435** strerror_r().
30436**
30437** The first argument passed to the macro should be the error code that
30438** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
30439** The two subsequent arguments should be the name of the OS function that
30440** failed (e.g. "unlink", "open") and the associated file-system path,
30441** if any.
30442*/
30443#define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
30444static int unixLogErrorAtLine(
30445  int errcode,                    /* SQLite error code */
30446  const char *zFunc,              /* Name of OS function that failed */
30447  const char *zPath,              /* File path associated with error */
30448  int iLine                       /* Source line number where error occurred */
30449){
30450  char *zErr;                     /* Message from strerror() or equivalent */
30451  int iErrno = errno;             /* Saved syscall error number */
30452
30453  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
30454  ** the strerror() function to obtain the human-readable error message
30455  ** equivalent to errno. Otherwise, use strerror_r().
30456  */
30457#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
30458  char aErr[80];
30459  memset(aErr, 0, sizeof(aErr));
30460  zErr = aErr;
30461
30462  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
30463  ** assume that the system provides the GNU version of strerror_r() that
30464  ** returns a pointer to a buffer containing the error message. That pointer
30465  ** may point to aErr[], or it may point to some static storage somewhere.
30466  ** Otherwise, assume that the system provides the POSIX version of
30467  ** strerror_r(), which always writes an error message into aErr[].
30468  **
30469  ** If the code incorrectly assumes that it is the POSIX version that is
30470  ** available, the error message will often be an empty string. Not a
30471  ** huge problem. Incorrectly concluding that the GNU version is available
30472  ** could lead to a segfault though.
30473  */
30474#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
30475  zErr =
30476# endif
30477  strerror_r(iErrno, aErr, sizeof(aErr)-1);
30478
30479#elif SQLITE_THREADSAFE
30480  /* This is a threadsafe build, but strerror_r() is not available. */
30481  zErr = "";
30482#else
30483  /* Non-threadsafe build, use strerror(). */
30484  zErr = strerror(iErrno);
30485#endif
30486
30487  if( zPath==0 ) zPath = "";
30488  sqlite3_log(errcode,
30489      "os_unix.c:%d: (%d) %s(%s) - %s",
30490      iLine, iErrno, zFunc, zPath, zErr
30491  );
30492
30493  return errcode;
30494}
30495
30496/*
30497** Close a file descriptor.
30498**
30499** We assume that close() almost always works, since it is only in a
30500** very sick application or on a very sick platform that it might fail.
30501** If it does fail, simply leak the file descriptor, but do log the
30502** error.
30503**
30504** Note that it is not safe to retry close() after EINTR since the
30505** file descriptor might have already been reused by another thread.
30506** So we don't even try to recover from an EINTR.  Just log the error
30507** and move on.
30508*/
30509static void robust_close(unixFile *pFile, int h, int lineno){
30510  if( osClose(h) ){
30511    unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
30512                       pFile ? pFile->zPath : 0, lineno);
30513  }
30514}
30515
30516/*
30517** Set the pFile->lastErrno.  Do this in a subroutine as that provides
30518** a convenient place to set a breakpoint.
30519*/
30520static void storeLastErrno(unixFile *pFile, int error){
30521  pFile->lastErrno = error;
30522}
30523
30524/*
30525** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
30526*/
30527static void closePendingFds(unixFile *pFile){
30528  unixInodeInfo *pInode = pFile->pInode;
30529  UnixUnusedFd *p;
30530  UnixUnusedFd *pNext;
30531  for(p=pInode->pUnused; p; p=pNext){
30532    pNext = p->pNext;
30533    robust_close(pFile, p->fd, __LINE__);
30534    sqlite3_free(p);
30535  }
30536  pInode->pUnused = 0;
30537}
30538
30539/*
30540** Release a unixInodeInfo structure previously allocated by findInodeInfo().
30541**
30542** The mutex entered using the unixEnterMutex() function must be held
30543** when this function is called.
30544*/
30545static void releaseInodeInfo(unixFile *pFile){
30546  unixInodeInfo *pInode = pFile->pInode;
30547  assert( unixMutexHeld() );
30548  if( ALWAYS(pInode) ){
30549    pInode->nRef--;
30550    if( pInode->nRef==0 ){
30551      assert( pInode->pShmNode==0 );
30552      closePendingFds(pFile);
30553      if( pInode->pPrev ){
30554        assert( pInode->pPrev->pNext==pInode );
30555        pInode->pPrev->pNext = pInode->pNext;
30556      }else{
30557        assert( inodeList==pInode );
30558        inodeList = pInode->pNext;
30559      }
30560      if( pInode->pNext ){
30561        assert( pInode->pNext->pPrev==pInode );
30562        pInode->pNext->pPrev = pInode->pPrev;
30563      }
30564      sqlite3_free(pInode);
30565    }
30566  }
30567}
30568
30569/*
30570** Given a file descriptor, locate the unixInodeInfo object that
30571** describes that file descriptor.  Create a new one if necessary.  The
30572** return value might be uninitialized if an error occurs.
30573**
30574** The mutex entered using the unixEnterMutex() function must be held
30575** when this function is called.
30576**
30577** Return an appropriate error code.
30578*/
30579static int findInodeInfo(
30580  unixFile *pFile,               /* Unix file with file desc used in the key */
30581  unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
30582){
30583  int rc;                        /* System call return code */
30584  int fd;                        /* The file descriptor for pFile */
30585  struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
30586  struct stat statbuf;           /* Low-level file information */
30587  unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
30588
30589  assert( unixMutexHeld() );
30590
30591  /* Get low-level information about the file that we can used to
30592  ** create a unique name for the file.
30593  */
30594  fd = pFile->h;
30595  rc = osFstat(fd, &statbuf);
30596  if( rc!=0 ){
30597    storeLastErrno(pFile, errno);
30598#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
30599    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
30600#endif
30601    return SQLITE_IOERR;
30602  }
30603
30604#ifdef __APPLE__
30605  /* On OS X on an msdos filesystem, the inode number is reported
30606  ** incorrectly for zero-size files.  See ticket #3260.  To work
30607  ** around this problem (we consider it a bug in OS X, not SQLite)
30608  ** we always increase the file size to 1 by writing a single byte
30609  ** prior to accessing the inode number.  The one byte written is
30610  ** an ASCII 'S' character which also happens to be the first byte
30611  ** in the header of every SQLite database.  In this way, if there
30612  ** is a race condition such that another thread has already populated
30613  ** the first page of the database, no damage is done.
30614  */
30615  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
30616    do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
30617    if( rc!=1 ){
30618      storeLastErrno(pFile, errno);
30619      return SQLITE_IOERR;
30620    }
30621    rc = osFstat(fd, &statbuf);
30622    if( rc!=0 ){
30623      storeLastErrno(pFile, errno);
30624      return SQLITE_IOERR;
30625    }
30626  }
30627#endif
30628
30629  memset(&fileId, 0, sizeof(fileId));
30630  fileId.dev = statbuf.st_dev;
30631#if OS_VXWORKS
30632  fileId.pId = pFile->pId;
30633#else
30634  fileId.ino = statbuf.st_ino;
30635#endif
30636  pInode = inodeList;
30637  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
30638    pInode = pInode->pNext;
30639  }
30640  if( pInode==0 ){
30641    pInode = sqlite3_malloc64( sizeof(*pInode) );
30642    if( pInode==0 ){
30643      return SQLITE_NOMEM_BKPT;
30644    }
30645    memset(pInode, 0, sizeof(*pInode));
30646    memcpy(&pInode->fileId, &fileId, sizeof(fileId));
30647    pInode->nRef = 1;
30648    pInode->pNext = inodeList;
30649    pInode->pPrev = 0;
30650    if( inodeList ) inodeList->pPrev = pInode;
30651    inodeList = pInode;
30652  }else{
30653    pInode->nRef++;
30654  }
30655  *ppInode = pInode;
30656  return SQLITE_OK;
30657}
30658
30659/*
30660** Return TRUE if pFile has been renamed or unlinked since it was first opened.
30661*/
30662static int fileHasMoved(unixFile *pFile){
30663#if OS_VXWORKS
30664  return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
30665#else
30666  struct stat buf;
30667  return pFile->pInode!=0 &&
30668      (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
30669#endif
30670}
30671
30672
30673/*
30674** Check a unixFile that is a database.  Verify the following:
30675**
30676** (1) There is exactly one hard link on the file
30677** (2) The file is not a symbolic link
30678** (3) The file has not been renamed or unlinked
30679**
30680** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
30681*/
30682static void verifyDbFile(unixFile *pFile){
30683  struct stat buf;
30684  int rc;
30685
30686  /* These verifications occurs for the main database only */
30687  if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
30688
30689  rc = osFstat(pFile->h, &buf);
30690  if( rc!=0 ){
30691    sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
30692    return;
30693  }
30694  if( buf.st_nlink==0 ){
30695    sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
30696    return;
30697  }
30698  if( buf.st_nlink>1 ){
30699    sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
30700    return;
30701  }
30702  if( fileHasMoved(pFile) ){
30703    sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
30704    return;
30705  }
30706}
30707
30708
30709/*
30710** This routine checks if there is a RESERVED lock held on the specified
30711** file by this or any other process. If such a lock is held, set *pResOut
30712** to a non-zero value otherwise *pResOut is set to zero.  The return value
30713** is set to SQLITE_OK unless an I/O error occurs during lock checking.
30714*/
30715static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
30716  int rc = SQLITE_OK;
30717  int reserved = 0;
30718  unixFile *pFile = (unixFile*)id;
30719
30720  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
30721
30722  assert( pFile );
30723  assert( pFile->eFileLock<=SHARED_LOCK );
30724  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
30725
30726  /* Check if a thread in this process holds such a lock */
30727  if( pFile->pInode->eFileLock>SHARED_LOCK ){
30728    reserved = 1;
30729  }
30730
30731  /* Otherwise see if some other process holds it.
30732  */
30733#ifndef __DJGPP__
30734  if( !reserved && !pFile->pInode->bProcessLock ){
30735    struct flock lock;
30736    lock.l_whence = SEEK_SET;
30737    lock.l_start = RESERVED_BYTE;
30738    lock.l_len = 1;
30739    lock.l_type = F_WRLCK;
30740    if( osFcntl(pFile->h, F_GETLK, &lock) ){
30741      rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
30742      storeLastErrno(pFile, errno);
30743    } else if( lock.l_type!=F_UNLCK ){
30744      reserved = 1;
30745    }
30746  }
30747#endif
30748
30749  unixLeaveMutex();
30750  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
30751
30752  *pResOut = reserved;
30753  return rc;
30754}
30755
30756/*
30757** Attempt to set a system-lock on the file pFile.  The lock is
30758** described by pLock.
30759**
30760** If the pFile was opened read/write from unix-excl, then the only lock
30761** ever obtained is an exclusive lock, and it is obtained exactly once
30762** the first time any lock is attempted.  All subsequent system locking
30763** operations become no-ops.  Locking operations still happen internally,
30764** in order to coordinate access between separate database connections
30765** within this process, but all of that is handled in memory and the
30766** operating system does not participate.
30767**
30768** This function is a pass-through to fcntl(F_SETLK) if pFile is using
30769** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
30770** and is read-only.
30771**
30772** Zero is returned if the call completes successfully, or -1 if a call
30773** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
30774*/
30775static int unixFileLock(unixFile *pFile, struct flock *pLock){
30776  int rc;
30777  unixInodeInfo *pInode = pFile->pInode;
30778  assert( unixMutexHeld() );
30779  assert( pInode!=0 );
30780  if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
30781    if( pInode->bProcessLock==0 ){
30782      struct flock lock;
30783      assert( pInode->nLock==0 );
30784      lock.l_whence = SEEK_SET;
30785      lock.l_start = SHARED_FIRST;
30786      lock.l_len = SHARED_SIZE;
30787      lock.l_type = F_WRLCK;
30788      rc = osFcntl(pFile->h, F_SETLK, &lock);
30789      if( rc<0 ) return rc;
30790      pInode->bProcessLock = 1;
30791      pInode->nLock++;
30792    }else{
30793      rc = 0;
30794    }
30795  }else{
30796    rc = osFcntl(pFile->h, F_SETLK, pLock);
30797  }
30798  return rc;
30799}
30800
30801/*
30802** Lock the file with the lock specified by parameter eFileLock - one
30803** of the following:
30804**
30805**     (1) SHARED_LOCK
30806**     (2) RESERVED_LOCK
30807**     (3) PENDING_LOCK
30808**     (4) EXCLUSIVE_LOCK
30809**
30810** Sometimes when requesting one lock state, additional lock states
30811** are inserted in between.  The locking might fail on one of the later
30812** transitions leaving the lock state different from what it started but
30813** still short of its goal.  The following chart shows the allowed
30814** transitions and the inserted intermediate states:
30815**
30816**    UNLOCKED -> SHARED
30817**    SHARED -> RESERVED
30818**    SHARED -> (PENDING) -> EXCLUSIVE
30819**    RESERVED -> (PENDING) -> EXCLUSIVE
30820**    PENDING -> EXCLUSIVE
30821**
30822** This routine will only increase a lock.  Use the sqlite3OsUnlock()
30823** routine to lower a locking level.
30824*/
30825static int unixLock(sqlite3_file *id, int eFileLock){
30826  /* The following describes the implementation of the various locks and
30827  ** lock transitions in terms of the POSIX advisory shared and exclusive
30828  ** lock primitives (called read-locks and write-locks below, to avoid
30829  ** confusion with SQLite lock names). The algorithms are complicated
30830  ** slightly in order to be compatible with Windows95 systems simultaneously
30831  ** accessing the same database file, in case that is ever required.
30832  **
30833  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
30834  ** byte', each single bytes at well known offsets, and the 'shared byte
30835  ** range', a range of 510 bytes at a well known offset.
30836  **
30837  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
30838  ** byte'.  If this is successful, 'shared byte range' is read-locked
30839  ** and the lock on the 'pending byte' released.  (Legacy note:  When
30840  ** SQLite was first developed, Windows95 systems were still very common,
30841  ** and Widnows95 lacks a shared-lock capability.  So on Windows95, a
30842  ** single randomly selected by from the 'shared byte range' is locked.
30843  ** Windows95 is now pretty much extinct, but this work-around for the
30844  ** lack of shared-locks on Windows95 lives on, for backwards
30845  ** compatibility.)
30846  **
30847  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
30848  ** A RESERVED lock is implemented by grabbing a write-lock on the
30849  ** 'reserved byte'.
30850  **
30851  ** A process may only obtain a PENDING lock after it has obtained a
30852  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
30853  ** on the 'pending byte'. This ensures that no new SHARED locks can be
30854  ** obtained, but existing SHARED locks are allowed to persist. A process
30855  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
30856  ** This property is used by the algorithm for rolling back a journal file
30857  ** after a crash.
30858  **
30859  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
30860  ** implemented by obtaining a write-lock on the entire 'shared byte
30861  ** range'. Since all other locks require a read-lock on one of the bytes
30862  ** within this range, this ensures that no other locks are held on the
30863  ** database.
30864  */
30865  int rc = SQLITE_OK;
30866  unixFile *pFile = (unixFile*)id;
30867  unixInodeInfo *pInode;
30868  struct flock lock;
30869  int tErrno = 0;
30870
30871  assert( pFile );
30872  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
30873      azFileLock(eFileLock), azFileLock(pFile->eFileLock),
30874      azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
30875      osGetpid(0)));
30876
30877  /* If there is already a lock of this type or more restrictive on the
30878  ** unixFile, do nothing. Don't use the end_lock: exit path, as
30879  ** unixEnterMutex() hasn't been called yet.
30880  */
30881  if( pFile->eFileLock>=eFileLock ){
30882    OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
30883            azFileLock(eFileLock)));
30884    return SQLITE_OK;
30885  }
30886
30887  /* Make sure the locking sequence is correct.
30888  **  (1) We never move from unlocked to anything higher than shared lock.
30889  **  (2) SQLite never explicitly requests a pendig lock.
30890  **  (3) A shared lock is always held when a reserve lock is requested.
30891  */
30892  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
30893  assert( eFileLock!=PENDING_LOCK );
30894  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
30895
30896  /* This mutex is needed because pFile->pInode is shared across threads
30897  */
30898  unixEnterMutex();
30899  pInode = pFile->pInode;
30900
30901  /* If some thread using this PID has a lock via a different unixFile*
30902  ** handle that precludes the requested lock, return BUSY.
30903  */
30904  if( (pFile->eFileLock!=pInode->eFileLock &&
30905          (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
30906  ){
30907    rc = SQLITE_BUSY;
30908    goto end_lock;
30909  }
30910
30911  /* If a SHARED lock is requested, and some thread using this PID already
30912  ** has a SHARED or RESERVED lock, then increment reference counts and
30913  ** return SQLITE_OK.
30914  */
30915  if( eFileLock==SHARED_LOCK &&
30916      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
30917    assert( eFileLock==SHARED_LOCK );
30918    assert( pFile->eFileLock==0 );
30919    assert( pInode->nShared>0 );
30920    pFile->eFileLock = SHARED_LOCK;
30921    pInode->nShared++;
30922    pInode->nLock++;
30923    goto end_lock;
30924  }
30925
30926
30927  /* A PENDING lock is needed before acquiring a SHARED lock and before
30928  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
30929  ** be released.
30930  */
30931  lock.l_len = 1L;
30932  lock.l_whence = SEEK_SET;
30933  if( eFileLock==SHARED_LOCK
30934      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
30935  ){
30936    lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
30937    lock.l_start = PENDING_BYTE;
30938    if( unixFileLock(pFile, &lock) ){
30939      tErrno = errno;
30940      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
30941      if( rc!=SQLITE_BUSY ){
30942        storeLastErrno(pFile, tErrno);
30943      }
30944      goto end_lock;
30945    }
30946  }
30947
30948
30949  /* If control gets to this point, then actually go ahead and make
30950  ** operating system calls for the specified lock.
30951  */
30952  if( eFileLock==SHARED_LOCK ){
30953    assert( pInode->nShared==0 );
30954    assert( pInode->eFileLock==0 );
30955    assert( rc==SQLITE_OK );
30956
30957    /* Now get the read-lock */
30958    lock.l_start = SHARED_FIRST;
30959    lock.l_len = SHARED_SIZE;
30960    if( unixFileLock(pFile, &lock) ){
30961      tErrno = errno;
30962      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
30963    }
30964
30965    /* Drop the temporary PENDING lock */
30966    lock.l_start = PENDING_BYTE;
30967    lock.l_len = 1L;
30968    lock.l_type = F_UNLCK;
30969    if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
30970      /* This could happen with a network mount */
30971      tErrno = errno;
30972      rc = SQLITE_IOERR_UNLOCK;
30973    }
30974
30975    if( rc ){
30976      if( rc!=SQLITE_BUSY ){
30977        storeLastErrno(pFile, tErrno);
30978      }
30979      goto end_lock;
30980    }else{
30981      pFile->eFileLock = SHARED_LOCK;
30982      pInode->nLock++;
30983      pInode->nShared = 1;
30984    }
30985  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
30986    /* We are trying for an exclusive lock but another thread in this
30987    ** same process is still holding a shared lock. */
30988    rc = SQLITE_BUSY;
30989  }else{
30990    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
30991    ** assumed that there is a SHARED or greater lock on the file
30992    ** already.
30993    */
30994    assert( 0!=pFile->eFileLock );
30995    lock.l_type = F_WRLCK;
30996
30997    assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
30998    if( eFileLock==RESERVED_LOCK ){
30999      lock.l_start = RESERVED_BYTE;
31000      lock.l_len = 1L;
31001    }else{
31002      lock.l_start = SHARED_FIRST;
31003      lock.l_len = SHARED_SIZE;
31004    }
31005
31006    if( unixFileLock(pFile, &lock) ){
31007      tErrno = errno;
31008      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31009      if( rc!=SQLITE_BUSY ){
31010        storeLastErrno(pFile, tErrno);
31011      }
31012    }
31013  }
31014
31015
31016#ifdef SQLITE_DEBUG
31017  /* Set up the transaction-counter change checking flags when
31018  ** transitioning from a SHARED to a RESERVED lock.  The change
31019  ** from SHARED to RESERVED marks the beginning of a normal
31020  ** write operation (not a hot journal rollback).
31021  */
31022  if( rc==SQLITE_OK
31023   && pFile->eFileLock<=SHARED_LOCK
31024   && eFileLock==RESERVED_LOCK
31025  ){
31026    pFile->transCntrChng = 0;
31027    pFile->dbUpdate = 0;
31028    pFile->inNormalWrite = 1;
31029  }
31030#endif
31031
31032
31033  if( rc==SQLITE_OK ){
31034    pFile->eFileLock = eFileLock;
31035    pInode->eFileLock = eFileLock;
31036  }else if( eFileLock==EXCLUSIVE_LOCK ){
31037    pFile->eFileLock = PENDING_LOCK;
31038    pInode->eFileLock = PENDING_LOCK;
31039  }
31040
31041end_lock:
31042  unixLeaveMutex();
31043  OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
31044      rc==SQLITE_OK ? "ok" : "failed"));
31045  return rc;
31046}
31047
31048/*
31049** Add the file descriptor used by file handle pFile to the corresponding
31050** pUnused list.
31051*/
31052static void setPendingFd(unixFile *pFile){
31053  unixInodeInfo *pInode = pFile->pInode;
31054  UnixUnusedFd *p = pFile->pUnused;
31055  p->pNext = pInode->pUnused;
31056  pInode->pUnused = p;
31057  pFile->h = -1;
31058  pFile->pUnused = 0;
31059}
31060
31061/*
31062** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31063** must be either NO_LOCK or SHARED_LOCK.
31064**
31065** If the locking level of the file descriptor is already at or below
31066** the requested locking level, this routine is a no-op.
31067**
31068** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
31069** the byte range is divided into 2 parts and the first part is unlocked then
31070** set to a read lock, then the other part is simply unlocked.  This works
31071** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
31072** remove the write lock on a region when a read lock is set.
31073*/
31074static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
31075  unixFile *pFile = (unixFile*)id;
31076  unixInodeInfo *pInode;
31077  struct flock lock;
31078  int rc = SQLITE_OK;
31079
31080  assert( pFile );
31081  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
31082      pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
31083      osGetpid(0)));
31084
31085  assert( eFileLock<=SHARED_LOCK );
31086  if( pFile->eFileLock<=eFileLock ){
31087    return SQLITE_OK;
31088  }
31089  unixEnterMutex();
31090  pInode = pFile->pInode;
31091  assert( pInode->nShared!=0 );
31092  if( pFile->eFileLock>SHARED_LOCK ){
31093    assert( pInode->eFileLock==pFile->eFileLock );
31094
31095#ifdef SQLITE_DEBUG
31096    /* When reducing a lock such that other processes can start
31097    ** reading the database file again, make sure that the
31098    ** transaction counter was updated if any part of the database
31099    ** file changed.  If the transaction counter is not updated,
31100    ** other connections to the same file might not realize that
31101    ** the file has changed and hence might not know to flush their
31102    ** cache.  The use of a stale cache can lead to database corruption.
31103    */
31104    pFile->inNormalWrite = 0;
31105#endif
31106
31107    /* downgrading to a shared lock on NFS involves clearing the write lock
31108    ** before establishing the readlock - to avoid a race condition we downgrade
31109    ** the lock in 2 blocks, so that part of the range will be covered by a
31110    ** write lock until the rest is covered by a read lock:
31111    **  1:   [WWWWW]
31112    **  2:   [....W]
31113    **  3:   [RRRRW]
31114    **  4:   [RRRR.]
31115    */
31116    if( eFileLock==SHARED_LOCK ){
31117#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
31118      (void)handleNFSUnlock;
31119      assert( handleNFSUnlock==0 );
31120#endif
31121#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31122      if( handleNFSUnlock ){
31123        int tErrno;               /* Error code from system call errors */
31124        off_t divSize = SHARED_SIZE - 1;
31125
31126        lock.l_type = F_UNLCK;
31127        lock.l_whence = SEEK_SET;
31128        lock.l_start = SHARED_FIRST;
31129        lock.l_len = divSize;
31130        if( unixFileLock(pFile, &lock)==(-1) ){
31131          tErrno = errno;
31132          rc = SQLITE_IOERR_UNLOCK;
31133          storeLastErrno(pFile, tErrno);
31134          goto end_unlock;
31135        }
31136        lock.l_type = F_RDLCK;
31137        lock.l_whence = SEEK_SET;
31138        lock.l_start = SHARED_FIRST;
31139        lock.l_len = divSize;
31140        if( unixFileLock(pFile, &lock)==(-1) ){
31141          tErrno = errno;
31142          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
31143          if( IS_LOCK_ERROR(rc) ){
31144            storeLastErrno(pFile, tErrno);
31145          }
31146          goto end_unlock;
31147        }
31148        lock.l_type = F_UNLCK;
31149        lock.l_whence = SEEK_SET;
31150        lock.l_start = SHARED_FIRST+divSize;
31151        lock.l_len = SHARED_SIZE-divSize;
31152        if( unixFileLock(pFile, &lock)==(-1) ){
31153          tErrno = errno;
31154          rc = SQLITE_IOERR_UNLOCK;
31155          storeLastErrno(pFile, tErrno);
31156          goto end_unlock;
31157        }
31158      }else
31159#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
31160      {
31161        lock.l_type = F_RDLCK;
31162        lock.l_whence = SEEK_SET;
31163        lock.l_start = SHARED_FIRST;
31164        lock.l_len = SHARED_SIZE;
31165        if( unixFileLock(pFile, &lock) ){
31166          /* In theory, the call to unixFileLock() cannot fail because another
31167          ** process is holding an incompatible lock. If it does, this
31168          ** indicates that the other process is not following the locking
31169          ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
31170          ** SQLITE_BUSY would confuse the upper layer (in practice it causes
31171          ** an assert to fail). */
31172          rc = SQLITE_IOERR_RDLOCK;
31173          storeLastErrno(pFile, errno);
31174          goto end_unlock;
31175        }
31176      }
31177    }
31178    lock.l_type = F_UNLCK;
31179    lock.l_whence = SEEK_SET;
31180    lock.l_start = PENDING_BYTE;
31181    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
31182    if( unixFileLock(pFile, &lock)==0 ){
31183      pInode->eFileLock = SHARED_LOCK;
31184    }else{
31185      rc = SQLITE_IOERR_UNLOCK;
31186      storeLastErrno(pFile, errno);
31187      goto end_unlock;
31188    }
31189  }
31190  if( eFileLock==NO_LOCK ){
31191    /* Decrement the shared lock counter.  Release the lock using an
31192    ** OS call only when all threads in this same process have released
31193    ** the lock.
31194    */
31195    pInode->nShared--;
31196    if( pInode->nShared==0 ){
31197      lock.l_type = F_UNLCK;
31198      lock.l_whence = SEEK_SET;
31199      lock.l_start = lock.l_len = 0L;
31200      if( unixFileLock(pFile, &lock)==0 ){
31201        pInode->eFileLock = NO_LOCK;
31202      }else{
31203        rc = SQLITE_IOERR_UNLOCK;
31204        storeLastErrno(pFile, errno);
31205        pInode->eFileLock = NO_LOCK;
31206        pFile->eFileLock = NO_LOCK;
31207      }
31208    }
31209
31210    /* Decrement the count of locks against this same file.  When the
31211    ** count reaches zero, close any other file descriptors whose close
31212    ** was deferred because of outstanding locks.
31213    */
31214    pInode->nLock--;
31215    assert( pInode->nLock>=0 );
31216    if( pInode->nLock==0 ){
31217      closePendingFds(pFile);
31218    }
31219  }
31220
31221end_unlock:
31222  unixLeaveMutex();
31223  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
31224  return rc;
31225}
31226
31227/*
31228** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31229** must be either NO_LOCK or SHARED_LOCK.
31230**
31231** If the locking level of the file descriptor is already at or below
31232** the requested locking level, this routine is a no-op.
31233*/
31234static int unixUnlock(sqlite3_file *id, int eFileLock){
31235#if SQLITE_MAX_MMAP_SIZE>0
31236  assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
31237#endif
31238  return posixUnlock(id, eFileLock, 0);
31239}
31240
31241#if SQLITE_MAX_MMAP_SIZE>0
31242static int unixMapfile(unixFile *pFd, i64 nByte);
31243static void unixUnmapfile(unixFile *pFd);
31244#endif
31245
31246/*
31247** This function performs the parts of the "close file" operation
31248** common to all locking schemes. It closes the directory and file
31249** handles, if they are valid, and sets all fields of the unixFile
31250** structure to 0.
31251**
31252** It is *not* necessary to hold the mutex when this routine is called,
31253** even on VxWorks.  A mutex will be acquired on VxWorks by the
31254** vxworksReleaseFileId() routine.
31255*/
31256static int closeUnixFile(sqlite3_file *id){
31257  unixFile *pFile = (unixFile*)id;
31258#if SQLITE_MAX_MMAP_SIZE>0
31259  unixUnmapfile(pFile);
31260#endif
31261  if( pFile->h>=0 ){
31262    robust_close(pFile, pFile->h, __LINE__);
31263    pFile->h = -1;
31264  }
31265#if OS_VXWORKS
31266  if( pFile->pId ){
31267    if( pFile->ctrlFlags & UNIXFILE_DELETE ){
31268      osUnlink(pFile->pId->zCanonicalName);
31269    }
31270    vxworksReleaseFileId(pFile->pId);
31271    pFile->pId = 0;
31272  }
31273#endif
31274#ifdef SQLITE_UNLINK_AFTER_CLOSE
31275  if( pFile->ctrlFlags & UNIXFILE_DELETE ){
31276    osUnlink(pFile->zPath);
31277    sqlite3_free(*(char**)&pFile->zPath);
31278    pFile->zPath = 0;
31279  }
31280#endif
31281  OSTRACE(("CLOSE   %-3d\n", pFile->h));
31282  OpenCounter(-1);
31283  sqlite3_free(pFile->pUnused);
31284  memset(pFile, 0, sizeof(unixFile));
31285  return SQLITE_OK;
31286}
31287
31288/*
31289** Close a file.
31290*/
31291static int unixClose(sqlite3_file *id){
31292  int rc = SQLITE_OK;
31293  unixFile *pFile = (unixFile *)id;
31294  verifyDbFile(pFile);
31295  unixUnlock(id, NO_LOCK);
31296  unixEnterMutex();
31297
31298  /* unixFile.pInode is always valid here. Otherwise, a different close
31299  ** routine (e.g. nolockClose()) would be called instead.
31300  */
31301  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
31302  if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
31303    /* If there are outstanding locks, do not actually close the file just
31304    ** yet because that would clear those locks.  Instead, add the file
31305    ** descriptor to pInode->pUnused list.  It will be automatically closed
31306    ** when the last lock is cleared.
31307    */
31308    setPendingFd(pFile);
31309  }
31310  releaseInodeInfo(pFile);
31311  rc = closeUnixFile(id);
31312  unixLeaveMutex();
31313  return rc;
31314}
31315
31316/************** End of the posix advisory lock implementation *****************
31317******************************************************************************/
31318
31319/******************************************************************************
31320****************************** No-op Locking **********************************
31321**
31322** Of the various locking implementations available, this is by far the
31323** simplest:  locking is ignored.  No attempt is made to lock the database
31324** file for reading or writing.
31325**
31326** This locking mode is appropriate for use on read-only databases
31327** (ex: databases that are burned into CD-ROM, for example.)  It can
31328** also be used if the application employs some external mechanism to
31329** prevent simultaneous access of the same database by two or more
31330** database connections.  But there is a serious risk of database
31331** corruption if this locking mode is used in situations where multiple
31332** database connections are accessing the same database file at the same
31333** time and one or more of those connections are writing.
31334*/
31335
31336static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
31337  UNUSED_PARAMETER(NotUsed);
31338  *pResOut = 0;
31339  return SQLITE_OK;
31340}
31341static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
31342  UNUSED_PARAMETER2(NotUsed, NotUsed2);
31343  return SQLITE_OK;
31344}
31345static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
31346  UNUSED_PARAMETER2(NotUsed, NotUsed2);
31347  return SQLITE_OK;
31348}
31349
31350/*
31351** Close the file.
31352*/
31353static int nolockClose(sqlite3_file *id) {
31354  return closeUnixFile(id);
31355}
31356
31357/******************* End of the no-op lock implementation *********************
31358******************************************************************************/
31359
31360/******************************************************************************
31361************************* Begin dot-file Locking ******************************
31362**
31363** The dotfile locking implementation uses the existence of separate lock
31364** files (really a directory) to control access to the database.  This works
31365** on just about every filesystem imaginable.  But there are serious downsides:
31366**
31367**    (1)  There is zero concurrency.  A single reader blocks all other
31368**         connections from reading or writing the database.
31369**
31370**    (2)  An application crash or power loss can leave stale lock files
31371**         sitting around that need to be cleared manually.
31372**
31373** Nevertheless, a dotlock is an appropriate locking mode for use if no
31374** other locking strategy is available.
31375**
31376** Dotfile locking works by creating a subdirectory in the same directory as
31377** the database and with the same name but with a ".lock" extension added.
31378** The existence of a lock directory implies an EXCLUSIVE lock.  All other
31379** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
31380*/
31381
31382/*
31383** The file suffix added to the data base filename in order to create the
31384** lock directory.
31385*/
31386#define DOTLOCK_SUFFIX ".lock"
31387
31388/*
31389** This routine checks if there is a RESERVED lock held on the specified
31390** file by this or any other process. If such a lock is held, set *pResOut
31391** to a non-zero value otherwise *pResOut is set to zero.  The return value
31392** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31393**
31394** In dotfile locking, either a lock exists or it does not.  So in this
31395** variation of CheckReservedLock(), *pResOut is set to true if any lock
31396** is held on the file and false if the file is unlocked.
31397*/
31398static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
31399  int rc = SQLITE_OK;
31400  int reserved = 0;
31401  unixFile *pFile = (unixFile*)id;
31402
31403  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
31404
31405  assert( pFile );
31406  reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
31407  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
31408  *pResOut = reserved;
31409  return rc;
31410}
31411
31412/*
31413** Lock the file with the lock specified by parameter eFileLock - one
31414** of the following:
31415**
31416**     (1) SHARED_LOCK
31417**     (2) RESERVED_LOCK
31418**     (3) PENDING_LOCK
31419**     (4) EXCLUSIVE_LOCK
31420**
31421** Sometimes when requesting one lock state, additional lock states
31422** are inserted in between.  The locking might fail on one of the later
31423** transitions leaving the lock state different from what it started but
31424** still short of its goal.  The following chart shows the allowed
31425** transitions and the inserted intermediate states:
31426**
31427**    UNLOCKED -> SHARED
31428**    SHARED -> RESERVED
31429**    SHARED -> (PENDING) -> EXCLUSIVE
31430**    RESERVED -> (PENDING) -> EXCLUSIVE
31431**    PENDING -> EXCLUSIVE
31432**
31433** This routine will only increase a lock.  Use the sqlite3OsUnlock()
31434** routine to lower a locking level.
31435**
31436** With dotfile locking, we really only support state (4): EXCLUSIVE.
31437** But we track the other locking levels internally.
31438*/
31439static int dotlockLock(sqlite3_file *id, int eFileLock) {
31440  unixFile *pFile = (unixFile*)id;
31441  char *zLockFile = (char *)pFile->lockingContext;
31442  int rc = SQLITE_OK;
31443
31444
31445  /* If we have any lock, then the lock file already exists.  All we have
31446  ** to do is adjust our internal record of the lock level.
31447  */
31448  if( pFile->eFileLock > NO_LOCK ){
31449    pFile->eFileLock = eFileLock;
31450    /* Always update the timestamp on the old file */
31451#ifdef HAVE_UTIME
31452    utime(zLockFile, NULL);
31453#else
31454    utimes(zLockFile, NULL);
31455#endif
31456    return SQLITE_OK;
31457  }
31458
31459  /* grab an exclusive lock */
31460  rc = osMkdir(zLockFile, 0777);
31461  if( rc<0 ){
31462    /* failed to open/create the lock directory */
31463    int tErrno = errno;
31464    if( EEXIST == tErrno ){
31465      rc = SQLITE_BUSY;
31466    } else {
31467      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31468      if( rc!=SQLITE_BUSY ){
31469        storeLastErrno(pFile, tErrno);
31470      }
31471    }
31472    return rc;
31473  }
31474
31475  /* got it, set the type and return ok */
31476  pFile->eFileLock = eFileLock;
31477  return rc;
31478}
31479
31480/*
31481** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31482** must be either NO_LOCK or SHARED_LOCK.
31483**
31484** If the locking level of the file descriptor is already at or below
31485** the requested locking level, this routine is a no-op.
31486**
31487** When the locking level reaches NO_LOCK, delete the lock file.
31488*/
31489static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
31490  unixFile *pFile = (unixFile*)id;
31491  char *zLockFile = (char *)pFile->lockingContext;
31492  int rc;
31493
31494  assert( pFile );
31495  OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
31496           pFile->eFileLock, osGetpid(0)));
31497  assert( eFileLock<=SHARED_LOCK );
31498
31499  /* no-op if possible */
31500  if( pFile->eFileLock==eFileLock ){
31501    return SQLITE_OK;
31502  }
31503
31504  /* To downgrade to shared, simply update our internal notion of the
31505  ** lock state.  No need to mess with the file on disk.
31506  */
31507  if( eFileLock==SHARED_LOCK ){
31508    pFile->eFileLock = SHARED_LOCK;
31509    return SQLITE_OK;
31510  }
31511
31512  /* To fully unlock the database, delete the lock file */
31513  assert( eFileLock==NO_LOCK );
31514  rc = osRmdir(zLockFile);
31515  if( rc<0 ){
31516    int tErrno = errno;
31517    if( tErrno==ENOENT ){
31518      rc = SQLITE_OK;
31519    }else{
31520      rc = SQLITE_IOERR_UNLOCK;
31521      storeLastErrno(pFile, tErrno);
31522    }
31523    return rc;
31524  }
31525  pFile->eFileLock = NO_LOCK;
31526  return SQLITE_OK;
31527}
31528
31529/*
31530** Close a file.  Make sure the lock has been released before closing.
31531*/
31532static int dotlockClose(sqlite3_file *id) {
31533  unixFile *pFile = (unixFile*)id;
31534  assert( id!=0 );
31535  dotlockUnlock(id, NO_LOCK);
31536  sqlite3_free(pFile->lockingContext);
31537  return closeUnixFile(id);
31538}
31539/****************** End of the dot-file lock implementation *******************
31540******************************************************************************/
31541
31542/******************************************************************************
31543************************** Begin flock Locking ********************************
31544**
31545** Use the flock() system call to do file locking.
31546**
31547** flock() locking is like dot-file locking in that the various
31548** fine-grain locking levels supported by SQLite are collapsed into
31549** a single exclusive lock.  In other words, SHARED, RESERVED, and
31550** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
31551** still works when you do this, but concurrency is reduced since
31552** only a single process can be reading the database at a time.
31553**
31554** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
31555*/
31556#if SQLITE_ENABLE_LOCKING_STYLE
31557
31558/*
31559** Retry flock() calls that fail with EINTR
31560*/
31561#ifdef EINTR
31562static int robust_flock(int fd, int op){
31563  int rc;
31564  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
31565  return rc;
31566}
31567#else
31568# define robust_flock(a,b) flock(a,b)
31569#endif
31570
31571
31572/*
31573** This routine checks if there is a RESERVED lock held on the specified
31574** file by this or any other process. If such a lock is held, set *pResOut
31575** to a non-zero value otherwise *pResOut is set to zero.  The return value
31576** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31577*/
31578static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
31579  int rc = SQLITE_OK;
31580  int reserved = 0;
31581  unixFile *pFile = (unixFile*)id;
31582
31583  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
31584
31585  assert( pFile );
31586
31587  /* Check if a thread in this process holds such a lock */
31588  if( pFile->eFileLock>SHARED_LOCK ){
31589    reserved = 1;
31590  }
31591
31592  /* Otherwise see if some other process holds it. */
31593  if( !reserved ){
31594    /* attempt to get the lock */
31595    int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
31596    if( !lrc ){
31597      /* got the lock, unlock it */
31598      lrc = robust_flock(pFile->h, LOCK_UN);
31599      if ( lrc ) {
31600        int tErrno = errno;
31601        /* unlock failed with an error */
31602        lrc = SQLITE_IOERR_UNLOCK;
31603        storeLastErrno(pFile, tErrno);
31604        rc = lrc;
31605      }
31606    } else {
31607      int tErrno = errno;
31608      reserved = 1;
31609      /* someone else might have it reserved */
31610      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31611      if( IS_LOCK_ERROR(lrc) ){
31612        storeLastErrno(pFile, tErrno);
31613        rc = lrc;
31614      }
31615    }
31616  }
31617  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
31618
31619#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31620  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
31621    rc = SQLITE_OK;
31622    reserved=1;
31623  }
31624#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31625  *pResOut = reserved;
31626  return rc;
31627}
31628
31629/*
31630** Lock the file with the lock specified by parameter eFileLock - one
31631** of the following:
31632**
31633**     (1) SHARED_LOCK
31634**     (2) RESERVED_LOCK
31635**     (3) PENDING_LOCK
31636**     (4) EXCLUSIVE_LOCK
31637**
31638** Sometimes when requesting one lock state, additional lock states
31639** are inserted in between.  The locking might fail on one of the later
31640** transitions leaving the lock state different from what it started but
31641** still short of its goal.  The following chart shows the allowed
31642** transitions and the inserted intermediate states:
31643**
31644**    UNLOCKED -> SHARED
31645**    SHARED -> RESERVED
31646**    SHARED -> (PENDING) -> EXCLUSIVE
31647**    RESERVED -> (PENDING) -> EXCLUSIVE
31648**    PENDING -> EXCLUSIVE
31649**
31650** flock() only really support EXCLUSIVE locks.  We track intermediate
31651** lock states in the sqlite3_file structure, but all locks SHARED or
31652** above are really EXCLUSIVE locks and exclude all other processes from
31653** access the file.
31654**
31655** This routine will only increase a lock.  Use the sqlite3OsUnlock()
31656** routine to lower a locking level.
31657*/
31658static int flockLock(sqlite3_file *id, int eFileLock) {
31659  int rc = SQLITE_OK;
31660  unixFile *pFile = (unixFile*)id;
31661
31662  assert( pFile );
31663
31664  /* if we already have a lock, it is exclusive.
31665  ** Just adjust level and punt on outta here. */
31666  if (pFile->eFileLock > NO_LOCK) {
31667    pFile->eFileLock = eFileLock;
31668    return SQLITE_OK;
31669  }
31670
31671  /* grab an exclusive lock */
31672
31673  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
31674    int tErrno = errno;
31675    /* didn't get, must be busy */
31676    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31677    if( IS_LOCK_ERROR(rc) ){
31678      storeLastErrno(pFile, tErrno);
31679    }
31680  } else {
31681    /* got it, set the type and return ok */
31682    pFile->eFileLock = eFileLock;
31683  }
31684  OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
31685           rc==SQLITE_OK ? "ok" : "failed"));
31686#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31687  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
31688    rc = SQLITE_BUSY;
31689  }
31690#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31691  return rc;
31692}
31693
31694
31695/*
31696** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31697** must be either NO_LOCK or SHARED_LOCK.
31698**
31699** If the locking level of the file descriptor is already at or below
31700** the requested locking level, this routine is a no-op.
31701*/
31702static int flockUnlock(sqlite3_file *id, int eFileLock) {
31703  unixFile *pFile = (unixFile*)id;
31704
31705  assert( pFile );
31706  OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
31707           pFile->eFileLock, osGetpid(0)));
31708  assert( eFileLock<=SHARED_LOCK );
31709
31710  /* no-op if possible */
31711  if( pFile->eFileLock==eFileLock ){
31712    return SQLITE_OK;
31713  }
31714
31715  /* shared can just be set because we always have an exclusive */
31716  if (eFileLock==SHARED_LOCK) {
31717    pFile->eFileLock = eFileLock;
31718    return SQLITE_OK;
31719  }
31720
31721  /* no, really, unlock. */
31722  if( robust_flock(pFile->h, LOCK_UN) ){
31723#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31724    return SQLITE_OK;
31725#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31726    return SQLITE_IOERR_UNLOCK;
31727  }else{
31728    pFile->eFileLock = NO_LOCK;
31729    return SQLITE_OK;
31730  }
31731}
31732
31733/*
31734** Close a file.
31735*/
31736static int flockClose(sqlite3_file *id) {
31737  assert( id!=0 );
31738  flockUnlock(id, NO_LOCK);
31739  return closeUnixFile(id);
31740}
31741
31742#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
31743
31744/******************* End of the flock lock implementation *********************
31745******************************************************************************/
31746
31747/******************************************************************************
31748************************ Begin Named Semaphore Locking ************************
31749**
31750** Named semaphore locking is only supported on VxWorks.
31751**
31752** Semaphore locking is like dot-lock and flock in that it really only
31753** supports EXCLUSIVE locking.  Only a single process can read or write
31754** the database file at a time.  This reduces potential concurrency, but
31755** makes the lock implementation much easier.
31756*/
31757#if OS_VXWORKS
31758
31759/*
31760** This routine checks if there is a RESERVED lock held on the specified
31761** file by this or any other process. If such a lock is held, set *pResOut
31762** to a non-zero value otherwise *pResOut is set to zero.  The return value
31763** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31764*/
31765static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
31766  int rc = SQLITE_OK;
31767  int reserved = 0;
31768  unixFile *pFile = (unixFile*)id;
31769
31770  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
31771
31772  assert( pFile );
31773
31774  /* Check if a thread in this process holds such a lock */
31775  if( pFile->eFileLock>SHARED_LOCK ){
31776    reserved = 1;
31777  }
31778
31779  /* Otherwise see if some other process holds it. */
31780  if( !reserved ){
31781    sem_t *pSem = pFile->pInode->pSem;
31782
31783    if( sem_trywait(pSem)==-1 ){
31784      int tErrno = errno;
31785      if( EAGAIN != tErrno ){
31786        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
31787        storeLastErrno(pFile, tErrno);
31788      } else {
31789        /* someone else has the lock when we are in NO_LOCK */
31790        reserved = (pFile->eFileLock < SHARED_LOCK);
31791      }
31792    }else{
31793      /* we could have it if we want it */
31794      sem_post(pSem);
31795    }
31796  }
31797  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
31798
31799  *pResOut = reserved;
31800  return rc;
31801}
31802
31803/*
31804** Lock the file with the lock specified by parameter eFileLock - one
31805** of the following:
31806**
31807**     (1) SHARED_LOCK
31808**     (2) RESERVED_LOCK
31809**     (3) PENDING_LOCK
31810**     (4) EXCLUSIVE_LOCK
31811**
31812** Sometimes when requesting one lock state, additional lock states
31813** are inserted in between.  The locking might fail on one of the later
31814** transitions leaving the lock state different from what it started but
31815** still short of its goal.  The following chart shows the allowed
31816** transitions and the inserted intermediate states:
31817**
31818**    UNLOCKED -> SHARED
31819**    SHARED -> RESERVED
31820**    SHARED -> (PENDING) -> EXCLUSIVE
31821**    RESERVED -> (PENDING) -> EXCLUSIVE
31822**    PENDING -> EXCLUSIVE
31823**
31824** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
31825** lock states in the sqlite3_file structure, but all locks SHARED or
31826** above are really EXCLUSIVE locks and exclude all other processes from
31827** access the file.
31828**
31829** This routine will only increase a lock.  Use the sqlite3OsUnlock()
31830** routine to lower a locking level.
31831*/
31832static int semXLock(sqlite3_file *id, int eFileLock) {
31833  unixFile *pFile = (unixFile*)id;
31834  sem_t *pSem = pFile->pInode->pSem;
31835  int rc = SQLITE_OK;
31836
31837  /* if we already have a lock, it is exclusive.
31838  ** Just adjust level and punt on outta here. */
31839  if (pFile->eFileLock > NO_LOCK) {
31840    pFile->eFileLock = eFileLock;
31841    rc = SQLITE_OK;
31842    goto sem_end_lock;
31843  }
31844
31845  /* lock semaphore now but bail out when already locked. */
31846  if( sem_trywait(pSem)==-1 ){
31847    rc = SQLITE_BUSY;
31848    goto sem_end_lock;
31849  }
31850
31851  /* got it, set the type and return ok */
31852  pFile->eFileLock = eFileLock;
31853
31854 sem_end_lock:
31855  return rc;
31856}
31857
31858/*
31859** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31860** must be either NO_LOCK or SHARED_LOCK.
31861**
31862** If the locking level of the file descriptor is already at or below
31863** the requested locking level, this routine is a no-op.
31864*/
31865static int semXUnlock(sqlite3_file *id, int eFileLock) {
31866  unixFile *pFile = (unixFile*)id;
31867  sem_t *pSem = pFile->pInode->pSem;
31868
31869  assert( pFile );
31870  assert( pSem );
31871  OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
31872           pFile->eFileLock, osGetpid(0)));
31873  assert( eFileLock<=SHARED_LOCK );
31874
31875  /* no-op if possible */
31876  if( pFile->eFileLock==eFileLock ){
31877    return SQLITE_OK;
31878  }
31879
31880  /* shared can just be set because we always have an exclusive */
31881  if (eFileLock==SHARED_LOCK) {
31882    pFile->eFileLock = eFileLock;
31883    return SQLITE_OK;
31884  }
31885
31886  /* no, really unlock. */
31887  if ( sem_post(pSem)==-1 ) {
31888    int rc, tErrno = errno;
31889    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
31890    if( IS_LOCK_ERROR(rc) ){
31891      storeLastErrno(pFile, tErrno);
31892    }
31893    return rc;
31894  }
31895  pFile->eFileLock = NO_LOCK;
31896  return SQLITE_OK;
31897}
31898
31899/*
31900 ** Close a file.
31901 */
31902static int semXClose(sqlite3_file *id) {
31903  if( id ){
31904    unixFile *pFile = (unixFile*)id;
31905    semXUnlock(id, NO_LOCK);
31906    assert( pFile );
31907    unixEnterMutex();
31908    releaseInodeInfo(pFile);
31909    unixLeaveMutex();
31910    closeUnixFile(id);
31911  }
31912  return SQLITE_OK;
31913}
31914
31915#endif /* OS_VXWORKS */
31916/*
31917** Named semaphore locking is only available on VxWorks.
31918**
31919*************** End of the named semaphore lock implementation ****************
31920******************************************************************************/
31921
31922
31923/******************************************************************************
31924*************************** Begin AFP Locking *********************************
31925**
31926** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
31927** on Apple Macintosh computers - both OS9 and OSX.
31928**
31929** Third-party implementations of AFP are available.  But this code here
31930** only works on OSX.
31931*/
31932
31933#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31934/*
31935** The afpLockingContext structure contains all afp lock specific state
31936*/
31937typedef struct afpLockingContext afpLockingContext;
31938struct afpLockingContext {
31939  int reserved;
31940  const char *dbPath;             /* Name of the open file */
31941};
31942
31943struct ByteRangeLockPB2
31944{
31945  unsigned long long offset;        /* offset to first byte to lock */
31946  unsigned long long length;        /* nbr of bytes to lock */
31947  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
31948  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
31949  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
31950  int fd;                           /* file desc to assoc this lock with */
31951};
31952
31953#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
31954
31955/*
31956** This is a utility for setting or clearing a bit-range lock on an
31957** AFP filesystem.
31958**
31959** Return SQLITE_OK on success, SQLITE_BUSY on failure.
31960*/
31961static int afpSetLock(
31962  const char *path,              /* Name of the file to be locked or unlocked */
31963  unixFile *pFile,               /* Open file descriptor on path */
31964  unsigned long long offset,     /* First byte to be locked */
31965  unsigned long long length,     /* Number of bytes to lock */
31966  int setLockFlag                /* True to set lock.  False to clear lock */
31967){
31968  struct ByteRangeLockPB2 pb;
31969  int err;
31970
31971  pb.unLockFlag = setLockFlag ? 0 : 1;
31972  pb.startEndFlag = 0;
31973  pb.offset = offset;
31974  pb.length = length;
31975  pb.fd = pFile->h;
31976
31977  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
31978    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
31979    offset, length));
31980  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
31981  if ( err==-1 ) {
31982    int rc;
31983    int tErrno = errno;
31984    OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
31985             path, tErrno, strerror(tErrno)));
31986#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
31987    rc = SQLITE_BUSY;
31988#else
31989    rc = sqliteErrorFromPosixError(tErrno,
31990                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
31991#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
31992    if( IS_LOCK_ERROR(rc) ){
31993      storeLastErrno(pFile, tErrno);
31994    }
31995    return rc;
31996  } else {
31997    return SQLITE_OK;
31998  }
31999}
32000
32001/*
32002** This routine checks if there is a RESERVED lock held on the specified
32003** file by this or any other process. If such a lock is held, set *pResOut
32004** to a non-zero value otherwise *pResOut is set to zero.  The return value
32005** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32006*/
32007static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
32008  int rc = SQLITE_OK;
32009  int reserved = 0;
32010  unixFile *pFile = (unixFile*)id;
32011  afpLockingContext *context;
32012
32013  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32014
32015  assert( pFile );
32016  context = (afpLockingContext *) pFile->lockingContext;
32017  if( context->reserved ){
32018    *pResOut = 1;
32019    return SQLITE_OK;
32020  }
32021  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
32022
32023  /* Check if a thread in this process holds such a lock */
32024  if( pFile->pInode->eFileLock>SHARED_LOCK ){
32025    reserved = 1;
32026  }
32027
32028  /* Otherwise see if some other process holds it.
32029   */
32030  if( !reserved ){
32031    /* lock the RESERVED byte */
32032    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
32033    if( SQLITE_OK==lrc ){
32034      /* if we succeeded in taking the reserved lock, unlock it to restore
32035      ** the original state */
32036      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
32037    } else {
32038      /* if we failed to get the lock then someone else must have it */
32039      reserved = 1;
32040    }
32041    if( IS_LOCK_ERROR(lrc) ){
32042      rc=lrc;
32043    }
32044  }
32045
32046  unixLeaveMutex();
32047  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
32048
32049  *pResOut = reserved;
32050  return rc;
32051}
32052
32053/*
32054** Lock the file with the lock specified by parameter eFileLock - one
32055** of the following:
32056**
32057**     (1) SHARED_LOCK
32058**     (2) RESERVED_LOCK
32059**     (3) PENDING_LOCK
32060**     (4) EXCLUSIVE_LOCK
32061**
32062** Sometimes when requesting one lock state, additional lock states
32063** are inserted in between.  The locking might fail on one of the later
32064** transitions leaving the lock state different from what it started but
32065** still short of its goal.  The following chart shows the allowed
32066** transitions and the inserted intermediate states:
32067**
32068**    UNLOCKED -> SHARED
32069**    SHARED -> RESERVED
32070**    SHARED -> (PENDING) -> EXCLUSIVE
32071**    RESERVED -> (PENDING) -> EXCLUSIVE
32072**    PENDING -> EXCLUSIVE
32073**
32074** This routine will only increase a lock.  Use the sqlite3OsUnlock()
32075** routine to lower a locking level.
32076*/
32077static int afpLock(sqlite3_file *id, int eFileLock){
32078  int rc = SQLITE_OK;
32079  unixFile *pFile = (unixFile*)id;
32080  unixInodeInfo *pInode = pFile->pInode;
32081  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
32082
32083  assert( pFile );
32084  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
32085           azFileLock(eFileLock), azFileLock(pFile->eFileLock),
32086           azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
32087
32088  /* If there is already a lock of this type or more restrictive on the
32089  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
32090  ** unixEnterMutex() hasn't been called yet.
32091  */
32092  if( pFile->eFileLock>=eFileLock ){
32093    OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
32094           azFileLock(eFileLock)));
32095    return SQLITE_OK;
32096  }
32097
32098  /* Make sure the locking sequence is correct
32099  **  (1) We never move from unlocked to anything higher than shared lock.
32100  **  (2) SQLite never explicitly requests a pendig lock.
32101  **  (3) A shared lock is always held when a reserve lock is requested.
32102  */
32103  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
32104  assert( eFileLock!=PENDING_LOCK );
32105  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
32106
32107  /* This mutex is needed because pFile->pInode is shared across threads
32108  */
32109  unixEnterMutex();
32110  pInode = pFile->pInode;
32111
32112  /* If some thread using this PID has a lock via a different unixFile*
32113  ** handle that precludes the requested lock, return BUSY.
32114  */
32115  if( (pFile->eFileLock!=pInode->eFileLock &&
32116       (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
32117     ){
32118    rc = SQLITE_BUSY;
32119    goto afp_end_lock;
32120  }
32121
32122  /* If a SHARED lock is requested, and some thread using this PID already
32123  ** has a SHARED or RESERVED lock, then increment reference counts and
32124  ** return SQLITE_OK.
32125  */
32126  if( eFileLock==SHARED_LOCK &&
32127     (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
32128    assert( eFileLock==SHARED_LOCK );
32129    assert( pFile->eFileLock==0 );
32130    assert( pInode->nShared>0 );
32131    pFile->eFileLock = SHARED_LOCK;
32132    pInode->nShared++;
32133    pInode->nLock++;
32134    goto afp_end_lock;
32135  }
32136
32137  /* A PENDING lock is needed before acquiring a SHARED lock and before
32138  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
32139  ** be released.
32140  */
32141  if( eFileLock==SHARED_LOCK
32142      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
32143  ){
32144    int failed;
32145    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
32146    if (failed) {
32147      rc = failed;
32148      goto afp_end_lock;
32149    }
32150  }
32151
32152  /* If control gets to this point, then actually go ahead and make
32153  ** operating system calls for the specified lock.
32154  */
32155  if( eFileLock==SHARED_LOCK ){
32156    int lrc1, lrc2, lrc1Errno = 0;
32157    long lk, mask;
32158
32159    assert( pInode->nShared==0 );
32160    assert( pInode->eFileLock==0 );
32161
32162    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
32163    /* Now get the read-lock SHARED_LOCK */
32164    /* note that the quality of the randomness doesn't matter that much */
32165    lk = random();
32166    pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
32167    lrc1 = afpSetLock(context->dbPath, pFile,
32168          SHARED_FIRST+pInode->sharedByte, 1, 1);
32169    if( IS_LOCK_ERROR(lrc1) ){
32170      lrc1Errno = pFile->lastErrno;
32171    }
32172    /* Drop the temporary PENDING lock */
32173    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
32174
32175    if( IS_LOCK_ERROR(lrc1) ) {
32176      storeLastErrno(pFile, lrc1Errno);
32177      rc = lrc1;
32178      goto afp_end_lock;
32179    } else if( IS_LOCK_ERROR(lrc2) ){
32180      rc = lrc2;
32181      goto afp_end_lock;
32182    } else if( lrc1 != SQLITE_OK ) {
32183      rc = lrc1;
32184    } else {
32185      pFile->eFileLock = SHARED_LOCK;
32186      pInode->nLock++;
32187      pInode->nShared = 1;
32188    }
32189  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
32190    /* We are trying for an exclusive lock but another thread in this
32191     ** same process is still holding a shared lock. */
32192    rc = SQLITE_BUSY;
32193  }else{
32194    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
32195    ** assumed that there is a SHARED or greater lock on the file
32196    ** already.
32197    */
32198    int failed = 0;
32199    assert( 0!=pFile->eFileLock );
32200    if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
32201        /* Acquire a RESERVED lock */
32202        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
32203      if( !failed ){
32204        context->reserved = 1;
32205      }
32206    }
32207    if (!failed && eFileLock == EXCLUSIVE_LOCK) {
32208      /* Acquire an EXCLUSIVE lock */
32209
32210      /* Remove the shared lock before trying the range.  we'll need to
32211      ** reestablish the shared lock if we can't get the  afpUnlock
32212      */
32213      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
32214                         pInode->sharedByte, 1, 0)) ){
32215        int failed2 = SQLITE_OK;
32216        /* now attemmpt to get the exclusive lock range */
32217        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
32218                               SHARED_SIZE, 1);
32219        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
32220                       SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
32221          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
32222          ** a critical I/O error
32223          */
32224          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
32225               SQLITE_IOERR_LOCK;
32226          goto afp_end_lock;
32227        }
32228      }else{
32229        rc = failed;
32230      }
32231    }
32232    if( failed ){
32233      rc = failed;
32234    }
32235  }
32236
32237  if( rc==SQLITE_OK ){
32238    pFile->eFileLock = eFileLock;
32239    pInode->eFileLock = eFileLock;
32240  }else if( eFileLock==EXCLUSIVE_LOCK ){
32241    pFile->eFileLock = PENDING_LOCK;
32242    pInode->eFileLock = PENDING_LOCK;
32243  }
32244
32245afp_end_lock:
32246  unixLeaveMutex();
32247  OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
32248         rc==SQLITE_OK ? "ok" : "failed"));
32249  return rc;
32250}
32251
32252/*
32253** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32254** must be either NO_LOCK or SHARED_LOCK.
32255**
32256** If the locking level of the file descriptor is already at or below
32257** the requested locking level, this routine is a no-op.
32258*/
32259static int afpUnlock(sqlite3_file *id, int eFileLock) {
32260  int rc = SQLITE_OK;
32261  unixFile *pFile = (unixFile*)id;
32262  unixInodeInfo *pInode;
32263  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
32264  int skipShared = 0;
32265#ifdef SQLITE_TEST
32266  int h = pFile->h;
32267#endif
32268
32269  assert( pFile );
32270  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
32271           pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
32272           osGetpid(0)));
32273
32274  assert( eFileLock<=SHARED_LOCK );
32275  if( pFile->eFileLock<=eFileLock ){
32276    return SQLITE_OK;
32277  }
32278  unixEnterMutex();
32279  pInode = pFile->pInode;
32280  assert( pInode->nShared!=0 );
32281  if( pFile->eFileLock>SHARED_LOCK ){
32282    assert( pInode->eFileLock==pFile->eFileLock );
32283    SimulateIOErrorBenign(1);
32284    SimulateIOError( h=(-1) )
32285    SimulateIOErrorBenign(0);
32286
32287#ifdef SQLITE_DEBUG
32288    /* When reducing a lock such that other processes can start
32289    ** reading the database file again, make sure that the
32290    ** transaction counter was updated if any part of the database
32291    ** file changed.  If the transaction counter is not updated,
32292    ** other connections to the same file might not realize that
32293    ** the file has changed and hence might not know to flush their
32294    ** cache.  The use of a stale cache can lead to database corruption.
32295    */
32296    assert( pFile->inNormalWrite==0
32297           || pFile->dbUpdate==0
32298           || pFile->transCntrChng==1 );
32299    pFile->inNormalWrite = 0;
32300#endif
32301
32302    if( pFile->eFileLock==EXCLUSIVE_LOCK ){
32303      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
32304      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
32305        /* only re-establish the shared lock if necessary */
32306        int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
32307        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
32308      } else {
32309        skipShared = 1;
32310      }
32311    }
32312    if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
32313      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
32314    }
32315    if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
32316      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
32317      if( !rc ){
32318        context->reserved = 0;
32319      }
32320    }
32321    if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
32322      pInode->eFileLock = SHARED_LOCK;
32323    }
32324  }
32325  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
32326
32327    /* Decrement the shared lock counter.  Release the lock using an
32328    ** OS call only when all threads in this same process have released
32329    ** the lock.
32330    */
32331    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
32332    pInode->nShared--;
32333    if( pInode->nShared==0 ){
32334      SimulateIOErrorBenign(1);
32335      SimulateIOError( h=(-1) )
32336      SimulateIOErrorBenign(0);
32337      if( !skipShared ){
32338        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
32339      }
32340      if( !rc ){
32341        pInode->eFileLock = NO_LOCK;
32342        pFile->eFileLock = NO_LOCK;
32343      }
32344    }
32345    if( rc==SQLITE_OK ){
32346      pInode->nLock--;
32347      assert( pInode->nLock>=0 );
32348      if( pInode->nLock==0 ){
32349        closePendingFds(pFile);
32350      }
32351    }
32352  }
32353
32354  unixLeaveMutex();
32355  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
32356  return rc;
32357}
32358
32359/*
32360** Close a file & cleanup AFP specific locking context
32361*/
32362static int afpClose(sqlite3_file *id) {
32363  int rc = SQLITE_OK;
32364  unixFile *pFile = (unixFile*)id;
32365  assert( id!=0 );
32366  afpUnlock(id, NO_LOCK);
32367  unixEnterMutex();
32368  if( pFile->pInode && pFile->pInode->nLock ){
32369    /* If there are outstanding locks, do not actually close the file just
32370    ** yet because that would clear those locks.  Instead, add the file
32371    ** descriptor to pInode->aPending.  It will be automatically closed when
32372    ** the last lock is cleared.
32373    */
32374    setPendingFd(pFile);
32375  }
32376  releaseInodeInfo(pFile);
32377  sqlite3_free(pFile->lockingContext);
32378  rc = closeUnixFile(id);
32379  unixLeaveMutex();
32380  return rc;
32381}
32382
32383#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32384/*
32385** The code above is the AFP lock implementation.  The code is specific
32386** to MacOSX and does not work on other unix platforms.  No alternative
32387** is available.  If you don't compile for a mac, then the "unix-afp"
32388** VFS is not available.
32389**
32390********************* End of the AFP lock implementation **********************
32391******************************************************************************/
32392
32393/******************************************************************************
32394*************************** Begin NFS Locking ********************************/
32395
32396#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
32397/*
32398 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32399 ** must be either NO_LOCK or SHARED_LOCK.
32400 **
32401 ** If the locking level of the file descriptor is already at or below
32402 ** the requested locking level, this routine is a no-op.
32403 */
32404static int nfsUnlock(sqlite3_file *id, int eFileLock){
32405  return posixUnlock(id, eFileLock, 1);
32406}
32407
32408#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32409/*
32410** The code above is the NFS lock implementation.  The code is specific
32411** to MacOSX and does not work on other unix platforms.  No alternative
32412** is available.
32413**
32414********************* End of the NFS lock implementation **********************
32415******************************************************************************/
32416
32417/******************************************************************************
32418**************** Non-locking sqlite3_file methods *****************************
32419**
32420** The next division contains implementations for all methods of the
32421** sqlite3_file object other than the locking methods.  The locking
32422** methods were defined in divisions above (one locking method per
32423** division).  Those methods that are common to all locking modes
32424** are gather together into this division.
32425*/
32426
32427/*
32428** Seek to the offset passed as the second argument, then read cnt
32429** bytes into pBuf. Return the number of bytes actually read.
32430**
32431** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
32432** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
32433** one system to another.  Since SQLite does not define USE_PREAD
32434** in any form by default, we will not attempt to define _XOPEN_SOURCE.
32435** See tickets #2741 and #2681.
32436**
32437** To avoid stomping the errno value on a failed read the lastErrno value
32438** is set before returning.
32439*/
32440static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
32441  int got;
32442  int prior = 0;
32443#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
32444  i64 newOffset;
32445#endif
32446  TIMER_START;
32447  assert( cnt==(cnt&0x1ffff) );
32448  assert( id->h>2 );
32449  do{
32450#if defined(USE_PREAD)
32451    got = osPread(id->h, pBuf, cnt, offset);
32452    SimulateIOError( got = -1 );
32453#elif defined(USE_PREAD64)
32454    got = osPread64(id->h, pBuf, cnt, offset);
32455    SimulateIOError( got = -1 );
32456#else
32457    newOffset = lseek(id->h, offset, SEEK_SET);
32458    SimulateIOError( newOffset = -1 );
32459    if( newOffset<0 ){
32460      storeLastErrno((unixFile*)id, errno);
32461      return -1;
32462    }
32463    got = osRead(id->h, pBuf, cnt);
32464#endif
32465    if( got==cnt ) break;
32466    if( got<0 ){
32467      if( errno==EINTR ){ got = 1; continue; }
32468      prior = 0;
32469      storeLastErrno((unixFile*)id,  errno);
32470      break;
32471    }else if( got>0 ){
32472      cnt -= got;
32473      offset += got;
32474      prior += got;
32475      pBuf = (void*)(got + (char*)pBuf);
32476    }
32477  }while( got>0 );
32478  TIMER_END;
32479  OSTRACE(("READ    %-3d %5d %7lld %llu\n",
32480            id->h, got+prior, offset-prior, TIMER_ELAPSED));
32481  return got+prior;
32482}
32483
32484/*
32485** Read data from a file into a buffer.  Return SQLITE_OK if all
32486** bytes were read successfully and SQLITE_IOERR if anything goes
32487** wrong.
32488*/
32489static int unixRead(
32490  sqlite3_file *id,
32491  void *pBuf,
32492  int amt,
32493  sqlite3_int64 offset
32494){
32495  unixFile *pFile = (unixFile *)id;
32496  int got;
32497  assert( id );
32498  assert( offset>=0 );
32499  assert( amt>0 );
32500
32501  /* If this is a database file (not a journal, master-journal or temp
32502  ** file), the bytes in the locking range should never be read or written. */
32503#if 0
32504  assert( pFile->pUnused==0
32505       || offset>=PENDING_BYTE+512
32506       || offset+amt<=PENDING_BYTE
32507  );
32508#endif
32509
32510#if SQLITE_MAX_MMAP_SIZE>0
32511  /* Deal with as much of this read request as possible by transfering
32512  ** data from the memory mapping using memcpy().  */
32513  if( offset<pFile->mmapSize ){
32514    if( offset+amt <= pFile->mmapSize ){
32515      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
32516      return SQLITE_OK;
32517    }else{
32518      int nCopy = pFile->mmapSize - offset;
32519      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
32520      pBuf = &((u8 *)pBuf)[nCopy];
32521      amt -= nCopy;
32522      offset += nCopy;
32523    }
32524  }
32525#endif
32526
32527  got = seekAndRead(pFile, offset, pBuf, amt);
32528  if( got==amt ){
32529    return SQLITE_OK;
32530  }else if( got<0 ){
32531    /* lastErrno set by seekAndRead */
32532    return SQLITE_IOERR_READ;
32533  }else{
32534    storeLastErrno(pFile, 0);   /* not a system error */
32535    /* Unread parts of the buffer must be zero-filled */
32536    memset(&((char*)pBuf)[got], 0, amt-got);
32537    return SQLITE_IOERR_SHORT_READ;
32538  }
32539}
32540
32541/*
32542** Attempt to seek the file-descriptor passed as the first argument to
32543** absolute offset iOff, then attempt to write nBuf bytes of data from
32544** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
32545** return the actual number of bytes written (which may be less than
32546** nBuf).
32547*/
32548static int seekAndWriteFd(
32549  int fd,                         /* File descriptor to write to */
32550  i64 iOff,                       /* File offset to begin writing at */
32551  const void *pBuf,               /* Copy data from this buffer to the file */
32552  int nBuf,                       /* Size of buffer pBuf in bytes */
32553  int *piErrno                    /* OUT: Error number if error occurs */
32554){
32555  int rc = 0;                     /* Value returned by system call */
32556
32557  assert( nBuf==(nBuf&0x1ffff) );
32558  assert( fd>2 );
32559  assert( piErrno!=0 );
32560  nBuf &= 0x1ffff;
32561  TIMER_START;
32562
32563#if defined(USE_PREAD)
32564  do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
32565#elif defined(USE_PREAD64)
32566  do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
32567#else
32568  do{
32569    i64 iSeek = lseek(fd, iOff, SEEK_SET);
32570    SimulateIOError( iSeek = -1 );
32571    if( iSeek<0 ){
32572      rc = -1;
32573      break;
32574    }
32575    rc = osWrite(fd, pBuf, nBuf);
32576  }while( rc<0 && errno==EINTR );
32577#endif
32578
32579  TIMER_END;
32580  OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
32581
32582  if( rc<0 ) *piErrno = errno;
32583  return rc;
32584}
32585
32586
32587/*
32588** Seek to the offset in id->offset then read cnt bytes into pBuf.
32589** Return the number of bytes actually read.  Update the offset.
32590**
32591** To avoid stomping the errno value on a failed write the lastErrno value
32592** is set before returning.
32593*/
32594static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
32595  return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
32596}
32597
32598
32599/*
32600** Write data from a buffer into a file.  Return SQLITE_OK on success
32601** or some other error code on failure.
32602*/
32603static int unixWrite(
32604  sqlite3_file *id,
32605  const void *pBuf,
32606  int amt,
32607  sqlite3_int64 offset
32608){
32609  unixFile *pFile = (unixFile*)id;
32610  int wrote = 0;
32611  assert( id );
32612  assert( amt>0 );
32613
32614  /* If this is a database file (not a journal, master-journal or temp
32615  ** file), the bytes in the locking range should never be read or written. */
32616#if 0
32617  assert( pFile->pUnused==0
32618       || offset>=PENDING_BYTE+512
32619       || offset+amt<=PENDING_BYTE
32620  );
32621#endif
32622
32623#ifdef SQLITE_DEBUG
32624  /* If we are doing a normal write to a database file (as opposed to
32625  ** doing a hot-journal rollback or a write to some file other than a
32626  ** normal database file) then record the fact that the database
32627  ** has changed.  If the transaction counter is modified, record that
32628  ** fact too.
32629  */
32630  if( pFile->inNormalWrite ){
32631    pFile->dbUpdate = 1;  /* The database has been modified */
32632    if( offset<=24 && offset+amt>=27 ){
32633      int rc;
32634      char oldCntr[4];
32635      SimulateIOErrorBenign(1);
32636      rc = seekAndRead(pFile, 24, oldCntr, 4);
32637      SimulateIOErrorBenign(0);
32638      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
32639        pFile->transCntrChng = 1;  /* The transaction counter has changed */
32640      }
32641    }
32642  }
32643#endif
32644
32645#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
32646  /* Deal with as much of this write request as possible by transfering
32647  ** data from the memory mapping using memcpy().  */
32648  if( offset<pFile->mmapSize ){
32649    if( offset+amt <= pFile->mmapSize ){
32650      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
32651      return SQLITE_OK;
32652    }else{
32653      int nCopy = pFile->mmapSize - offset;
32654      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
32655      pBuf = &((u8 *)pBuf)[nCopy];
32656      amt -= nCopy;
32657      offset += nCopy;
32658    }
32659  }
32660#endif
32661
32662  while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
32663    amt -= wrote;
32664    offset += wrote;
32665    pBuf = &((char*)pBuf)[wrote];
32666  }
32667  SimulateIOError(( wrote=(-1), amt=1 ));
32668  SimulateDiskfullError(( wrote=0, amt=1 ));
32669
32670  if( amt>wrote ){
32671    if( wrote<0 && pFile->lastErrno!=ENOSPC ){
32672      /* lastErrno set by seekAndWrite */
32673      return SQLITE_IOERR_WRITE;
32674    }else{
32675      storeLastErrno(pFile, 0); /* not a system error */
32676      return SQLITE_FULL;
32677    }
32678  }
32679
32680  return SQLITE_OK;
32681}
32682
32683#ifdef SQLITE_TEST
32684/*
32685** Count the number of fullsyncs and normal syncs.  This is used to test
32686** that syncs and fullsyncs are occurring at the right times.
32687*/
32688SQLITE_API int sqlite3_sync_count = 0;
32689SQLITE_API int sqlite3_fullsync_count = 0;
32690#endif
32691
32692/*
32693** We do not trust systems to provide a working fdatasync().  Some do.
32694** Others do no.  To be safe, we will stick with the (slightly slower)
32695** fsync(). If you know that your system does support fdatasync() correctly,
32696** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
32697*/
32698#if !defined(fdatasync) && !HAVE_FDATASYNC
32699# define fdatasync fsync
32700#endif
32701
32702/*
32703** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
32704** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
32705** only available on Mac OS X.  But that could change.
32706*/
32707#ifdef F_FULLFSYNC
32708# define HAVE_FULLFSYNC 1
32709#else
32710# define HAVE_FULLFSYNC 0
32711#endif
32712
32713
32714/*
32715** The fsync() system call does not work as advertised on many
32716** unix systems.  The following procedure is an attempt to make
32717** it work better.
32718**
32719** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
32720** for testing when we want to run through the test suite quickly.
32721** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
32722** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
32723** or power failure will likely corrupt the database file.
32724**
32725** SQLite sets the dataOnly flag if the size of the file is unchanged.
32726** The idea behind dataOnly is that it should only write the file content
32727** to disk, not the inode.  We only set dataOnly if the file size is
32728** unchanged since the file size is part of the inode.  However,
32729** Ted Ts'o tells us that fdatasync() will also write the inode if the
32730** file size has changed.  The only real difference between fdatasync()
32731** and fsync(), Ted tells us, is that fdatasync() will not flush the
32732** inode if the mtime or owner or other inode attributes have changed.
32733** We only care about the file size, not the other file attributes, so
32734** as far as SQLite is concerned, an fdatasync() is always adequate.
32735** So, we always use fdatasync() if it is available, regardless of
32736** the value of the dataOnly flag.
32737*/
32738static int full_fsync(int fd, int fullSync, int dataOnly){
32739  int rc;
32740
32741  /* The following "ifdef/elif/else/" block has the same structure as
32742  ** the one below. It is replicated here solely to avoid cluttering
32743  ** up the real code with the UNUSED_PARAMETER() macros.
32744  */
32745#ifdef SQLITE_NO_SYNC
32746  UNUSED_PARAMETER(fd);
32747  UNUSED_PARAMETER(fullSync);
32748  UNUSED_PARAMETER(dataOnly);
32749#elif HAVE_FULLFSYNC
32750  UNUSED_PARAMETER(dataOnly);
32751#else
32752  UNUSED_PARAMETER(fullSync);
32753  UNUSED_PARAMETER(dataOnly);
32754#endif
32755
32756  /* Record the number of times that we do a normal fsync() and
32757  ** FULLSYNC.  This is used during testing to verify that this procedure
32758  ** gets called with the correct arguments.
32759  */
32760#ifdef SQLITE_TEST
32761  if( fullSync ) sqlite3_fullsync_count++;
32762  sqlite3_sync_count++;
32763#endif
32764
32765  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
32766  ** no-op.  But go ahead and call fstat() to validate the file
32767  ** descriptor as we need a method to provoke a failure during
32768  ** coverate testing.
32769  */
32770#ifdef SQLITE_NO_SYNC
32771  {
32772    struct stat buf;
32773    rc = osFstat(fd, &buf);
32774  }
32775#elif HAVE_FULLFSYNC
32776  if( fullSync ){
32777    rc = osFcntl(fd, F_FULLFSYNC, 0);
32778  }else{
32779    rc = 1;
32780  }
32781  /* If the FULLFSYNC failed, fall back to attempting an fsync().
32782  ** It shouldn't be possible for fullfsync to fail on the local
32783  ** file system (on OSX), so failure indicates that FULLFSYNC
32784  ** isn't supported for this file system. So, attempt an fsync
32785  ** and (for now) ignore the overhead of a superfluous fcntl call.
32786  ** It'd be better to detect fullfsync support once and avoid
32787  ** the fcntl call every time sync is called.
32788  */
32789  if( rc ) rc = fsync(fd);
32790
32791#elif defined(__APPLE__)
32792  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
32793  ** so currently we default to the macro that redefines fdatasync to fsync
32794  */
32795  rc = fsync(fd);
32796#else
32797  rc = fdatasync(fd);
32798#if OS_VXWORKS
32799  if( rc==-1 && errno==ENOTSUP ){
32800    rc = fsync(fd);
32801  }
32802#endif /* OS_VXWORKS */
32803#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
32804
32805  if( OS_VXWORKS && rc!= -1 ){
32806    rc = 0;
32807  }
32808  return rc;
32809}
32810
32811/*
32812** Open a file descriptor to the directory containing file zFilename.
32813** If successful, *pFd is set to the opened file descriptor and
32814** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
32815** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
32816** value.
32817**
32818** The directory file descriptor is used for only one thing - to
32819** fsync() a directory to make sure file creation and deletion events
32820** are flushed to disk.  Such fsyncs are not needed on newer
32821** journaling filesystems, but are required on older filesystems.
32822**
32823** This routine can be overridden using the xSetSysCall interface.
32824** The ability to override this routine was added in support of the
32825** chromium sandbox.  Opening a directory is a security risk (we are
32826** told) so making it overrideable allows the chromium sandbox to
32827** replace this routine with a harmless no-op.  To make this routine
32828** a no-op, replace it with a stub that returns SQLITE_OK but leaves
32829** *pFd set to a negative number.
32830**
32831** If SQLITE_OK is returned, the caller is responsible for closing
32832** the file descriptor *pFd using close().
32833*/
32834static int openDirectory(const char *zFilename, int *pFd){
32835  int ii;
32836  int fd = -1;
32837  char zDirname[MAX_PATHNAME+1];
32838
32839  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
32840  for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
32841  if( ii>0 ){
32842    zDirname[ii] = '\0';
32843  }else{
32844    if( zDirname[0]!='/' ) zDirname[0] = '.';
32845    zDirname[1] = 0;
32846  }
32847  fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
32848  if( fd>=0 ){
32849    OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
32850  }
32851  *pFd = fd;
32852  if( fd>=0 ) return SQLITE_OK;
32853  return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
32854}
32855
32856/*
32857** Make sure all writes to a particular file are committed to disk.
32858**
32859** If dataOnly==0 then both the file itself and its metadata (file
32860** size, access time, etc) are synced.  If dataOnly!=0 then only the
32861** file data is synced.
32862**
32863** Under Unix, also make sure that the directory entry for the file
32864** has been created by fsync-ing the directory that contains the file.
32865** If we do not do this and we encounter a power failure, the directory
32866** entry for the journal might not exist after we reboot.  The next
32867** SQLite to access the file will not know that the journal exists (because
32868** the directory entry for the journal was never created) and the transaction
32869** will not roll back - possibly leading to database corruption.
32870*/
32871static int unixSync(sqlite3_file *id, int flags){
32872  int rc;
32873  unixFile *pFile = (unixFile*)id;
32874
32875  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
32876  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
32877
32878  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
32879  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
32880      || (flags&0x0F)==SQLITE_SYNC_FULL
32881  );
32882
32883  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
32884  ** line is to test that doing so does not cause any problems.
32885  */
32886  SimulateDiskfullError( return SQLITE_FULL );
32887
32888  assert( pFile );
32889  OSTRACE(("SYNC    %-3d\n", pFile->h));
32890  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
32891  SimulateIOError( rc=1 );
32892  if( rc ){
32893    storeLastErrno(pFile, errno);
32894    return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
32895  }
32896
32897  /* Also fsync the directory containing the file if the DIRSYNC flag
32898  ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
32899  ** are unable to fsync a directory, so ignore errors on the fsync.
32900  */
32901  if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
32902    int dirfd;
32903    OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
32904            HAVE_FULLFSYNC, isFullsync));
32905    rc = osOpenDirectory(pFile->zPath, &dirfd);
32906    if( rc==SQLITE_OK ){
32907      full_fsync(dirfd, 0, 0);
32908      robust_close(pFile, dirfd, __LINE__);
32909    }else{
32910      assert( rc==SQLITE_CANTOPEN );
32911      rc = SQLITE_OK;
32912    }
32913    pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
32914  }
32915  return rc;
32916}
32917
32918/*
32919** Truncate an open file to a specified size
32920*/
32921static int unixTruncate(sqlite3_file *id, i64 nByte){
32922  unixFile *pFile = (unixFile *)id;
32923  int rc;
32924  assert( pFile );
32925  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
32926
32927  /* If the user has configured a chunk-size for this file, truncate the
32928  ** file so that it consists of an integer number of chunks (i.e. the
32929  ** actual file size after the operation may be larger than the requested
32930  ** size).
32931  */
32932  if( pFile->szChunk>0 ){
32933    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
32934  }
32935
32936  rc = robust_ftruncate(pFile->h, nByte);
32937  if( rc ){
32938    storeLastErrno(pFile, errno);
32939    return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
32940  }else{
32941#ifdef SQLITE_DEBUG
32942    /* If we are doing a normal write to a database file (as opposed to
32943    ** doing a hot-journal rollback or a write to some file other than a
32944    ** normal database file) and we truncate the file to zero length,
32945    ** that effectively updates the change counter.  This might happen
32946    ** when restoring a database using the backup API from a zero-length
32947    ** source.
32948    */
32949    if( pFile->inNormalWrite && nByte==0 ){
32950      pFile->transCntrChng = 1;
32951    }
32952#endif
32953
32954#if SQLITE_MAX_MMAP_SIZE>0
32955    /* If the file was just truncated to a size smaller than the currently
32956    ** mapped region, reduce the effective mapping size as well. SQLite will
32957    ** use read() and write() to access data beyond this point from now on.
32958    */
32959    if( nByte<pFile->mmapSize ){
32960      pFile->mmapSize = nByte;
32961    }
32962#endif
32963
32964    return SQLITE_OK;
32965  }
32966}
32967
32968/*
32969** Determine the current size of a file in bytes
32970*/
32971static int unixFileSize(sqlite3_file *id, i64 *pSize){
32972  int rc;
32973  struct stat buf;
32974  assert( id );
32975  rc = osFstat(((unixFile*)id)->h, &buf);
32976  SimulateIOError( rc=1 );
32977  if( rc!=0 ){
32978    storeLastErrno((unixFile*)id, errno);
32979    return SQLITE_IOERR_FSTAT;
32980  }
32981  *pSize = buf.st_size;
32982
32983  /* When opening a zero-size database, the findInodeInfo() procedure
32984  ** writes a single byte into that file in order to work around a bug
32985  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
32986  ** layers, we need to report this file size as zero even though it is
32987  ** really 1.   Ticket #3260.
32988  */
32989  if( *pSize==1 ) *pSize = 0;
32990
32991
32992  return SQLITE_OK;
32993}
32994
32995#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
32996/*
32997** Handler for proxy-locking file-control verbs.  Defined below in the
32998** proxying locking division.
32999*/
33000static int proxyFileControl(sqlite3_file*,int,void*);
33001#endif
33002
33003/*
33004** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
33005** file-control operation.  Enlarge the database to nBytes in size
33006** (rounded up to the next chunk-size).  If the database is already
33007** nBytes or larger, this routine is a no-op.
33008*/
33009static int fcntlSizeHint(unixFile *pFile, i64 nByte){
33010  if( pFile->szChunk>0 ){
33011    i64 nSize;                    /* Required file size */
33012    struct stat buf;              /* Used to hold return values of fstat() */
33013
33014    if( osFstat(pFile->h, &buf) ){
33015      return SQLITE_IOERR_FSTAT;
33016    }
33017
33018    nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
33019    if( nSize>(i64)buf.st_size ){
33020
33021#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
33022      /* The code below is handling the return value of osFallocate()
33023      ** correctly. posix_fallocate() is defined to "returns zero on success,
33024      ** or an error number on  failure". See the manpage for details. */
33025      int err;
33026      do{
33027        err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
33028      }while( err==EINTR );
33029      if( err ) return SQLITE_IOERR_WRITE;
33030#else
33031      /* If the OS does not have posix_fallocate(), fake it. Write a
33032      ** single byte to the last byte in each block that falls entirely
33033      ** within the extended region. Then, if required, a single byte
33034      ** at offset (nSize-1), to set the size of the file correctly.
33035      ** This is a similar technique to that used by glibc on systems
33036      ** that do not have a real fallocate() call.
33037      */
33038      int nBlk = buf.st_blksize;  /* File-system block size */
33039      int nWrite = 0;             /* Number of bytes written by seekAndWrite */
33040      i64 iWrite;                 /* Next offset to write to */
33041
33042      iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
33043      assert( iWrite>=buf.st_size );
33044      assert( ((iWrite+1)%nBlk)==0 );
33045      for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
33046        if( iWrite>=nSize ) iWrite = nSize - 1;
33047        nWrite = seekAndWrite(pFile, iWrite, "", 1);
33048        if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
33049      }
33050#endif
33051    }
33052  }
33053
33054#if SQLITE_MAX_MMAP_SIZE>0
33055  if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
33056    int rc;
33057    if( pFile->szChunk<=0 ){
33058      if( robust_ftruncate(pFile->h, nByte) ){
33059        storeLastErrno(pFile, errno);
33060        return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
33061      }
33062    }
33063
33064    rc = unixMapfile(pFile, nByte);
33065    return rc;
33066  }
33067#endif
33068
33069  return SQLITE_OK;
33070}
33071
33072/*
33073** If *pArg is initially negative then this is a query.  Set *pArg to
33074** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
33075**
33076** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
33077*/
33078static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
33079  if( *pArg<0 ){
33080    *pArg = (pFile->ctrlFlags & mask)!=0;
33081  }else if( (*pArg)==0 ){
33082    pFile->ctrlFlags &= ~mask;
33083  }else{
33084    pFile->ctrlFlags |= mask;
33085  }
33086}
33087
33088/* Forward declaration */
33089static int unixGetTempname(int nBuf, char *zBuf);
33090
33091/*
33092** Information and control of an open file handle.
33093*/
33094static int unixFileControl(sqlite3_file *id, int op, void *pArg){
33095  unixFile *pFile = (unixFile*)id;
33096  switch( op ){
33097    case SQLITE_FCNTL_LOCKSTATE: {
33098      *(int*)pArg = pFile->eFileLock;
33099      return SQLITE_OK;
33100    }
33101    case SQLITE_FCNTL_LAST_ERRNO: {
33102      *(int*)pArg = pFile->lastErrno;
33103      return SQLITE_OK;
33104    }
33105    case SQLITE_FCNTL_CHUNK_SIZE: {
33106      pFile->szChunk = *(int *)pArg;
33107      return SQLITE_OK;
33108    }
33109    case SQLITE_FCNTL_SIZE_HINT: {
33110      int rc;
33111      SimulateIOErrorBenign(1);
33112      rc = fcntlSizeHint(pFile, *(i64 *)pArg);
33113      SimulateIOErrorBenign(0);
33114      return rc;
33115    }
33116    case SQLITE_FCNTL_PERSIST_WAL: {
33117      unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
33118      return SQLITE_OK;
33119    }
33120    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
33121      unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
33122      return SQLITE_OK;
33123    }
33124    case SQLITE_FCNTL_VFSNAME: {
33125      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
33126      return SQLITE_OK;
33127    }
33128    case SQLITE_FCNTL_TEMPFILENAME: {
33129      char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
33130      if( zTFile ){
33131        unixGetTempname(pFile->pVfs->mxPathname, zTFile);
33132        *(char**)pArg = zTFile;
33133      }
33134      return SQLITE_OK;
33135    }
33136    case SQLITE_FCNTL_HAS_MOVED: {
33137      *(int*)pArg = fileHasMoved(pFile);
33138      return SQLITE_OK;
33139    }
33140#if SQLITE_MAX_MMAP_SIZE>0
33141    case SQLITE_FCNTL_MMAP_SIZE: {
33142      i64 newLimit = *(i64*)pArg;
33143      int rc = SQLITE_OK;
33144      if( newLimit>sqlite3GlobalConfig.mxMmap ){
33145        newLimit = sqlite3GlobalConfig.mxMmap;
33146      }
33147      *(i64*)pArg = pFile->mmapSizeMax;
33148      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
33149        pFile->mmapSizeMax = newLimit;
33150        if( pFile->mmapSize>0 ){
33151          unixUnmapfile(pFile);
33152          rc = unixMapfile(pFile, -1);
33153        }
33154      }
33155      return rc;
33156    }
33157#endif
33158#ifdef SQLITE_DEBUG
33159    /* The pager calls this method to signal that it has done
33160    ** a rollback and that the database is therefore unchanged and
33161    ** it hence it is OK for the transaction change counter to be
33162    ** unchanged.
33163    */
33164    case SQLITE_FCNTL_DB_UNCHANGED: {
33165      ((unixFile*)id)->dbUpdate = 0;
33166      return SQLITE_OK;
33167    }
33168#endif
33169#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
33170    case SQLITE_FCNTL_SET_LOCKPROXYFILE:
33171    case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
33172      return proxyFileControl(id,op,pArg);
33173    }
33174#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
33175  }
33176  return SQLITE_NOTFOUND;
33177}
33178
33179/*
33180** Return the sector size in bytes of the underlying block device for
33181** the specified file. This is almost always 512 bytes, but may be
33182** larger for some devices.
33183**
33184** SQLite code assumes this function cannot fail. It also assumes that
33185** if two files are created in the same file-system directory (i.e.
33186** a database and its journal file) that the sector size will be the
33187** same for both.
33188*/
33189#ifndef __QNXNTO__
33190static int unixSectorSize(sqlite3_file *NotUsed){
33191  UNUSED_PARAMETER(NotUsed);
33192  return SQLITE_DEFAULT_SECTOR_SIZE;
33193}
33194#endif
33195
33196/*
33197** The following version of unixSectorSize() is optimized for QNX.
33198*/
33199#ifdef __QNXNTO__
33200#include <sys/dcmd_blk.h>
33201#include <sys/statvfs.h>
33202static int unixSectorSize(sqlite3_file *id){
33203  unixFile *pFile = (unixFile*)id;
33204  if( pFile->sectorSize == 0 ){
33205    struct statvfs fsInfo;
33206
33207    /* Set defaults for non-supported filesystems */
33208    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
33209    pFile->deviceCharacteristics = 0;
33210    if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
33211      return pFile->sectorSize;
33212    }
33213
33214    if( !strcmp(fsInfo.f_basetype, "tmp") ) {
33215      pFile->sectorSize = fsInfo.f_bsize;
33216      pFile->deviceCharacteristics =
33217        SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
33218        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
33219                                      ** the write succeeds */
33220        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
33221                                      ** so it is ordered */
33222        0;
33223    }else if( strstr(fsInfo.f_basetype, "etfs") ){
33224      pFile->sectorSize = fsInfo.f_bsize;
33225      pFile->deviceCharacteristics =
33226        /* etfs cluster size writes are atomic */
33227        (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
33228        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
33229                                      ** the write succeeds */
33230        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
33231                                      ** so it is ordered */
33232        0;
33233    }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
33234      pFile->sectorSize = fsInfo.f_bsize;
33235      pFile->deviceCharacteristics =
33236        SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
33237        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
33238                                      ** the write succeeds */
33239        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
33240                                      ** so it is ordered */
33241        0;
33242    }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
33243      pFile->sectorSize = fsInfo.f_bsize;
33244      pFile->deviceCharacteristics =
33245        /* full bitset of atomics from max sector size and smaller */
33246        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
33247        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
33248                                      ** so it is ordered */
33249        0;
33250    }else if( strstr(fsInfo.f_basetype, "dos") ){
33251      pFile->sectorSize = fsInfo.f_bsize;
33252      pFile->deviceCharacteristics =
33253        /* full bitset of atomics from max sector size and smaller */
33254        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
33255        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
33256                                      ** so it is ordered */
33257        0;
33258    }else{
33259      pFile->deviceCharacteristics =
33260        SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
33261        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
33262                                      ** the write succeeds */
33263        0;
33264    }
33265  }
33266  /* Last chance verification.  If the sector size isn't a multiple of 512
33267  ** then it isn't valid.*/
33268  if( pFile->sectorSize % 512 != 0 ){
33269    pFile->deviceCharacteristics = 0;
33270    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
33271  }
33272  return pFile->sectorSize;
33273}
33274#endif /* __QNXNTO__ */
33275
33276/*
33277** Return the device characteristics for the file.
33278**
33279** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
33280** However, that choice is controversial since technically the underlying
33281** file system does not always provide powersafe overwrites.  (In other
33282** words, after a power-loss event, parts of the file that were never
33283** written might end up being altered.)  However, non-PSOW behavior is very,
33284** very rare.  And asserting PSOW makes a large reduction in the amount
33285** of required I/O for journaling, since a lot of padding is eliminated.
33286**  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
33287** available to turn it off and URI query parameter available to turn it off.
33288*/
33289static int unixDeviceCharacteristics(sqlite3_file *id){
33290  unixFile *p = (unixFile*)id;
33291  int rc = 0;
33292#ifdef __QNXNTO__
33293  if( p->sectorSize==0 ) unixSectorSize(id);
33294  rc = p->deviceCharacteristics;
33295#endif
33296  if( p->ctrlFlags & UNIXFILE_PSOW ){
33297    rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
33298  }
33299  return rc;
33300}
33301
33302#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
33303
33304/*
33305** Return the system page size.
33306**
33307** This function should not be called directly by other code in this file.
33308** Instead, it should be called via macro osGetpagesize().
33309*/
33310static int unixGetpagesize(void){
33311#if OS_VXWORKS
33312  return 1024;
33313#elif defined(_BSD_SOURCE)
33314  return getpagesize();
33315#else
33316  return (int)sysconf(_SC_PAGESIZE);
33317#endif
33318}
33319
33320#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
33321
33322#ifndef SQLITE_OMIT_WAL
33323
33324/*
33325** Object used to represent an shared memory buffer.
33326**
33327** When multiple threads all reference the same wal-index, each thread
33328** has its own unixShm object, but they all point to a single instance
33329** of this unixShmNode object.  In other words, each wal-index is opened
33330** only once per process.
33331**
33332** Each unixShmNode object is connected to a single unixInodeInfo object.
33333** We could coalesce this object into unixInodeInfo, but that would mean
33334** every open file that does not use shared memory (in other words, most
33335** open files) would have to carry around this extra information.  So
33336** the unixInodeInfo object contains a pointer to this unixShmNode object
33337** and the unixShmNode object is created only when needed.
33338**
33339** unixMutexHeld() must be true when creating or destroying
33340** this object or while reading or writing the following fields:
33341**
33342**      nRef
33343**
33344** The following fields are read-only after the object is created:
33345**
33346**      fid
33347**      zFilename
33348**
33349** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
33350** unixMutexHeld() is true when reading or writing any other field
33351** in this structure.
33352*/
33353struct unixShmNode {
33354  unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
33355  sqlite3_mutex *mutex;      /* Mutex to access this object */
33356  char *zFilename;           /* Name of the mmapped file */
33357  int h;                     /* Open file descriptor */
33358  int szRegion;              /* Size of shared-memory regions */
33359  u16 nRegion;               /* Size of array apRegion */
33360  u8 isReadonly;             /* True if read-only */
33361  char **apRegion;           /* Array of mapped shared-memory regions */
33362  int nRef;                  /* Number of unixShm objects pointing to this */
33363  unixShm *pFirst;           /* All unixShm objects pointing to this */
33364#ifdef SQLITE_DEBUG
33365  u8 exclMask;               /* Mask of exclusive locks held */
33366  u8 sharedMask;             /* Mask of shared locks held */
33367  u8 nextShmId;              /* Next available unixShm.id value */
33368#endif
33369};
33370
33371/*
33372** Structure used internally by this VFS to record the state of an
33373** open shared memory connection.
33374**
33375** The following fields are initialized when this object is created and
33376** are read-only thereafter:
33377**
33378**    unixShm.pFile
33379**    unixShm.id
33380**
33381** All other fields are read/write.  The unixShm.pFile->mutex must be held
33382** while accessing any read/write fields.
33383*/
33384struct unixShm {
33385  unixShmNode *pShmNode;     /* The underlying unixShmNode object */
33386  unixShm *pNext;            /* Next unixShm with the same unixShmNode */
33387  u8 hasMutex;               /* True if holding the unixShmNode mutex */
33388  u8 id;                     /* Id of this connection within its unixShmNode */
33389  u16 sharedMask;            /* Mask of shared locks held */
33390  u16 exclMask;              /* Mask of exclusive locks held */
33391};
33392
33393/*
33394** Constants used for locking
33395*/
33396#define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
33397#define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
33398
33399/*
33400** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
33401**
33402** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
33403** otherwise.
33404*/
33405static int unixShmSystemLock(
33406  unixFile *pFile,       /* Open connection to the WAL file */
33407  int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
33408  int ofst,              /* First byte of the locking range */
33409  int n                  /* Number of bytes to lock */
33410){
33411  unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
33412  struct flock f;        /* The posix advisory locking structure */
33413  int rc = SQLITE_OK;    /* Result code form fcntl() */
33414
33415  /* Access to the unixShmNode object is serialized by the caller */
33416  pShmNode = pFile->pInode->pShmNode;
33417  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
33418
33419  /* Shared locks never span more than one byte */
33420  assert( n==1 || lockType!=F_RDLCK );
33421
33422  /* Locks are within range */
33423  assert( n>=1 && n<=SQLITE_SHM_NLOCK );
33424
33425  if( pShmNode->h>=0 ){
33426    /* Initialize the locking parameters */
33427    memset(&f, 0, sizeof(f));
33428    f.l_type = lockType;
33429    f.l_whence = SEEK_SET;
33430    f.l_start = ofst;
33431    f.l_len = n;
33432
33433    rc = osFcntl(pShmNode->h, F_SETLK, &f);
33434    rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
33435  }
33436
33437  /* Update the global lock state and do debug tracing */
33438#ifdef SQLITE_DEBUG
33439  { u16 mask;
33440  OSTRACE(("SHM-LOCK "));
33441  mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
33442  if( rc==SQLITE_OK ){
33443    if( lockType==F_UNLCK ){
33444      OSTRACE(("unlock %d ok", ofst));
33445      pShmNode->exclMask &= ~mask;
33446      pShmNode->sharedMask &= ~mask;
33447    }else if( lockType==F_RDLCK ){
33448      OSTRACE(("read-lock %d ok", ofst));
33449      pShmNode->exclMask &= ~mask;
33450      pShmNode->sharedMask |= mask;
33451    }else{
33452      assert( lockType==F_WRLCK );
33453      OSTRACE(("write-lock %d ok", ofst));
33454      pShmNode->exclMask |= mask;
33455      pShmNode->sharedMask &= ~mask;
33456    }
33457  }else{
33458    if( lockType==F_UNLCK ){
33459      OSTRACE(("unlock %d failed", ofst));
33460    }else if( lockType==F_RDLCK ){
33461      OSTRACE(("read-lock failed"));
33462    }else{
33463      assert( lockType==F_WRLCK );
33464      OSTRACE(("write-lock %d failed", ofst));
33465    }
33466  }
33467  OSTRACE((" - afterwards %03x,%03x\n",
33468           pShmNode->sharedMask, pShmNode->exclMask));
33469  }
33470#endif
33471
33472  return rc;
33473}
33474
33475/*
33476** Return the minimum number of 32KB shm regions that should be mapped at
33477** a time, assuming that each mapping must be an integer multiple of the
33478** current system page-size.
33479**
33480** Usually, this is 1. The exception seems to be systems that are configured
33481** to use 64KB pages - in this case each mapping must cover at least two
33482** shm regions.
33483*/
33484static int unixShmRegionPerMap(void){
33485  int shmsz = 32*1024;            /* SHM region size */
33486  int pgsz = osGetpagesize();   /* System page size */
33487  assert( ((pgsz-1)&pgsz)==0 );   /* Page size must be a power of 2 */
33488  if( pgsz<shmsz ) return 1;
33489  return pgsz/shmsz;
33490}
33491
33492/*
33493** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
33494**
33495** This is not a VFS shared-memory method; it is a utility function called
33496** by VFS shared-memory methods.
33497*/
33498static void unixShmPurge(unixFile *pFd){
33499  unixShmNode *p = pFd->pInode->pShmNode;
33500  assert( unixMutexHeld() );
33501  if( p && ALWAYS(p->nRef==0) ){
33502    int nShmPerMap = unixShmRegionPerMap();
33503    int i;
33504    assert( p->pInode==pFd->pInode );
33505    sqlite3_mutex_free(p->mutex);
33506    for(i=0; i<p->nRegion; i+=nShmPerMap){
33507      if( p->h>=0 ){
33508        osMunmap(p->apRegion[i], p->szRegion);
33509      }else{
33510        sqlite3_free(p->apRegion[i]);
33511      }
33512    }
33513    sqlite3_free(p->apRegion);
33514    if( p->h>=0 ){
33515      robust_close(pFd, p->h, __LINE__);
33516      p->h = -1;
33517    }
33518    p->pInode->pShmNode = 0;
33519    sqlite3_free(p);
33520  }
33521}
33522
33523/*
33524** Open a shared-memory area associated with open database file pDbFd.
33525** This particular implementation uses mmapped files.
33526**
33527** The file used to implement shared-memory is in the same directory
33528** as the open database file and has the same name as the open database
33529** file with the "-shm" suffix added.  For example, if the database file
33530** is "/home/user1/config.db" then the file that is created and mmapped
33531** for shared memory will be called "/home/user1/config.db-shm".
33532**
33533** Another approach to is to use files in /dev/shm or /dev/tmp or an
33534** some other tmpfs mount. But if a file in a different directory
33535** from the database file is used, then differing access permissions
33536** or a chroot() might cause two different processes on the same
33537** database to end up using different files for shared memory -
33538** meaning that their memory would not really be shared - resulting
33539** in database corruption.  Nevertheless, this tmpfs file usage
33540** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
33541** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
33542** option results in an incompatible build of SQLite;  builds of SQLite
33543** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
33544** same database file at the same time, database corruption will likely
33545** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
33546** "unsupported" and may go away in a future SQLite release.
33547**
33548** When opening a new shared-memory file, if no other instances of that
33549** file are currently open, in this process or in other processes, then
33550** the file must be truncated to zero length or have its header cleared.
33551**
33552** If the original database file (pDbFd) is using the "unix-excl" VFS
33553** that means that an exclusive lock is held on the database file and
33554** that no other processes are able to read or write the database.  In
33555** that case, we do not really need shared memory.  No shared memory
33556** file is created.  The shared memory will be simulated with heap memory.
33557*/
33558static int unixOpenSharedMemory(unixFile *pDbFd){
33559  struct unixShm *p = 0;          /* The connection to be opened */
33560  struct unixShmNode *pShmNode;   /* The underlying mmapped file */
33561  int rc;                         /* Result code */
33562  unixInodeInfo *pInode;          /* The inode of fd */
33563  char *zShmFilename;             /* Name of the file used for SHM */
33564  int nShmFilename;               /* Size of the SHM filename in bytes */
33565
33566  /* Allocate space for the new unixShm object. */
33567  p = sqlite3_malloc64( sizeof(*p) );
33568  if( p==0 ) return SQLITE_NOMEM_BKPT;
33569  memset(p, 0, sizeof(*p));
33570  assert( pDbFd->pShm==0 );
33571
33572  /* Check to see if a unixShmNode object already exists. Reuse an existing
33573  ** one if present. Create a new one if necessary.
33574  */
33575  unixEnterMutex();
33576  pInode = pDbFd->pInode;
33577  pShmNode = pInode->pShmNode;
33578  if( pShmNode==0 ){
33579    struct stat sStat;                 /* fstat() info for database file */
33580#ifndef SQLITE_SHM_DIRECTORY
33581    const char *zBasePath = pDbFd->zPath;
33582#endif
33583
33584    /* Call fstat() to figure out the permissions on the database file. If
33585    ** a new *-shm file is created, an attempt will be made to create it
33586    ** with the same permissions.
33587    */
33588    if( osFstat(pDbFd->h, &sStat) ){
33589      rc = SQLITE_IOERR_FSTAT;
33590      goto shm_open_err;
33591    }
33592
33593#ifdef SQLITE_SHM_DIRECTORY
33594    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
33595#else
33596    nShmFilename = 6 + (int)strlen(zBasePath);
33597#endif
33598    pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
33599    if( pShmNode==0 ){
33600      rc = SQLITE_NOMEM_BKPT;
33601      goto shm_open_err;
33602    }
33603    memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
33604    zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
33605#ifdef SQLITE_SHM_DIRECTORY
33606    sqlite3_snprintf(nShmFilename, zShmFilename,
33607                     SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
33608                     (u32)sStat.st_ino, (u32)sStat.st_dev);
33609#else
33610    sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
33611    sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
33612#endif
33613    pShmNode->h = -1;
33614    pDbFd->pInode->pShmNode = pShmNode;
33615    pShmNode->pInode = pDbFd->pInode;
33616    if( sqlite3GlobalConfig.bCoreMutex ){
33617      pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
33618      if( pShmNode->mutex==0 ){
33619        rc = SQLITE_NOMEM_BKPT;
33620        goto shm_open_err;
33621      }
33622    }
33623
33624    if( pInode->bProcessLock==0 ){
33625      int openFlags = O_RDWR | O_CREAT;
33626      if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
33627        openFlags = O_RDONLY;
33628        pShmNode->isReadonly = 1;
33629      }
33630      pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
33631      if( pShmNode->h<0 ){
33632        rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
33633        goto shm_open_err;
33634      }
33635
33636      /* If this process is running as root, make sure that the SHM file
33637      ** is owned by the same user that owns the original database.  Otherwise,
33638      ** the original owner will not be able to connect.
33639      */
33640      robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
33641
33642      /* Check to see if another process is holding the dead-man switch.
33643      ** If not, truncate the file to zero length.
33644      */
33645      rc = SQLITE_OK;
33646      if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
33647        if( robust_ftruncate(pShmNode->h, 0) ){
33648          rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
33649        }
33650      }
33651      if( rc==SQLITE_OK ){
33652        rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
33653      }
33654      if( rc ) goto shm_open_err;
33655    }
33656  }
33657
33658  /* Make the new connection a child of the unixShmNode */
33659  p->pShmNode = pShmNode;
33660#ifdef SQLITE_DEBUG
33661  p->id = pShmNode->nextShmId++;
33662#endif
33663  pShmNode->nRef++;
33664  pDbFd->pShm = p;
33665  unixLeaveMutex();
33666
33667  /* The reference count on pShmNode has already been incremented under
33668  ** the cover of the unixEnterMutex() mutex and the pointer from the
33669  ** new (struct unixShm) object to the pShmNode has been set. All that is
33670  ** left to do is to link the new object into the linked list starting
33671  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
33672  ** mutex.
33673  */
33674  sqlite3_mutex_enter(pShmNode->mutex);
33675  p->pNext = pShmNode->pFirst;
33676  pShmNode->pFirst = p;
33677  sqlite3_mutex_leave(pShmNode->mutex);
33678  return SQLITE_OK;
33679
33680  /* Jump here on any error */
33681shm_open_err:
33682  unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
33683  sqlite3_free(p);
33684  unixLeaveMutex();
33685  return rc;
33686}
33687
33688/*
33689** This function is called to obtain a pointer to region iRegion of the
33690** shared-memory associated with the database file fd. Shared-memory regions
33691** are numbered starting from zero. Each shared-memory region is szRegion
33692** bytes in size.
33693**
33694** If an error occurs, an error code is returned and *pp is set to NULL.
33695**
33696** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
33697** region has not been allocated (by any client, including one running in a
33698** separate process), then *pp is set to NULL and SQLITE_OK returned. If
33699** bExtend is non-zero and the requested shared-memory region has not yet
33700** been allocated, it is allocated by this function.
33701**
33702** If the shared-memory region has already been allocated or is allocated by
33703** this call as described above, then it is mapped into this processes
33704** address space (if it is not already), *pp is set to point to the mapped
33705** memory and SQLITE_OK returned.
33706*/
33707static int unixShmMap(
33708  sqlite3_file *fd,               /* Handle open on database file */
33709  int iRegion,                    /* Region to retrieve */
33710  int szRegion,                   /* Size of regions */
33711  int bExtend,                    /* True to extend file if necessary */
33712  void volatile **pp              /* OUT: Mapped memory */
33713){
33714  unixFile *pDbFd = (unixFile*)fd;
33715  unixShm *p;
33716  unixShmNode *pShmNode;
33717  int rc = SQLITE_OK;
33718  int nShmPerMap = unixShmRegionPerMap();
33719  int nReqRegion;
33720
33721  /* If the shared-memory file has not yet been opened, open it now. */
33722  if( pDbFd->pShm==0 ){
33723    rc = unixOpenSharedMemory(pDbFd);
33724    if( rc!=SQLITE_OK ) return rc;
33725  }
33726
33727  p = pDbFd->pShm;
33728  pShmNode = p->pShmNode;
33729  sqlite3_mutex_enter(pShmNode->mutex);
33730  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
33731  assert( pShmNode->pInode==pDbFd->pInode );
33732  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
33733  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
33734
33735  /* Minimum number of regions required to be mapped. */
33736  nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
33737
33738  if( pShmNode->nRegion<nReqRegion ){
33739    char **apNew;                      /* New apRegion[] array */
33740    int nByte = nReqRegion*szRegion;   /* Minimum required file size */
33741    struct stat sStat;                 /* Used by fstat() */
33742
33743    pShmNode->szRegion = szRegion;
33744
33745    if( pShmNode->h>=0 ){
33746      /* The requested region is not mapped into this processes address space.
33747      ** Check to see if it has been allocated (i.e. if the wal-index file is
33748      ** large enough to contain the requested region).
33749      */
33750      if( osFstat(pShmNode->h, &sStat) ){
33751        rc = SQLITE_IOERR_SHMSIZE;
33752        goto shmpage_out;
33753      }
33754
33755      if( sStat.st_size<nByte ){
33756        /* The requested memory region does not exist. If bExtend is set to
33757        ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
33758        */
33759        if( !bExtend ){
33760          goto shmpage_out;
33761        }
33762
33763        /* Alternatively, if bExtend is true, extend the file. Do this by
33764        ** writing a single byte to the end of each (OS) page being
33765        ** allocated or extended. Technically, we need only write to the
33766        ** last page in order to extend the file. But writing to all new
33767        ** pages forces the OS to allocate them immediately, which reduces
33768        ** the chances of SIGBUS while accessing the mapped region later on.
33769        */
33770        else{
33771          static const int pgsz = 4096;
33772          int iPg;
33773
33774          /* Write to the last byte of each newly allocated or extended page */
33775          assert( (nByte % pgsz)==0 );
33776          for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
33777            int x = 0;
33778            if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
33779              const char *zFile = pShmNode->zFilename;
33780              rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
33781              goto shmpage_out;
33782            }
33783          }
33784        }
33785      }
33786    }
33787
33788    /* Map the requested memory region into this processes address space. */
33789    apNew = (char **)sqlite3_realloc(
33790        pShmNode->apRegion, nReqRegion*sizeof(char *)
33791    );
33792    if( !apNew ){
33793      rc = SQLITE_IOERR_NOMEM_BKPT;
33794      goto shmpage_out;
33795    }
33796    pShmNode->apRegion = apNew;
33797    while( pShmNode->nRegion<nReqRegion ){
33798      int nMap = szRegion*nShmPerMap;
33799      int i;
33800      void *pMem;
33801      if( pShmNode->h>=0 ){
33802        pMem = osMmap(0, nMap,
33803            pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
33804            MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
33805        );
33806        if( pMem==MAP_FAILED ){
33807          rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
33808          goto shmpage_out;
33809        }
33810      }else{
33811        pMem = sqlite3_malloc64(szRegion);
33812        if( pMem==0 ){
33813          rc = SQLITE_NOMEM_BKPT;
33814          goto shmpage_out;
33815        }
33816        memset(pMem, 0, szRegion);
33817      }
33818
33819      for(i=0; i<nShmPerMap; i++){
33820        pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
33821      }
33822      pShmNode->nRegion += nShmPerMap;
33823    }
33824  }
33825
33826shmpage_out:
33827  if( pShmNode->nRegion>iRegion ){
33828    *pp = pShmNode->apRegion[iRegion];
33829  }else{
33830    *pp = 0;
33831  }
33832  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
33833  sqlite3_mutex_leave(pShmNode->mutex);
33834  return rc;
33835}
33836
33837/*
33838** Change the lock state for a shared-memory segment.
33839**
33840** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
33841** different here than in posix.  In xShmLock(), one can go from unlocked
33842** to shared and back or from unlocked to exclusive and back.  But one may
33843** not go from shared to exclusive or from exclusive to shared.
33844*/
33845static int unixShmLock(
33846  sqlite3_file *fd,          /* Database file holding the shared memory */
33847  int ofst,                  /* First lock to acquire or release */
33848  int n,                     /* Number of locks to acquire or release */
33849  int flags                  /* What to do with the lock */
33850){
33851  unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
33852  unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
33853  unixShm *pX;                          /* For looping over all siblings */
33854  unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
33855  int rc = SQLITE_OK;                   /* Result code */
33856  u16 mask;                             /* Mask of locks to take or release */
33857
33858  assert( pShmNode==pDbFd->pInode->pShmNode );
33859  assert( pShmNode->pInode==pDbFd->pInode );
33860  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
33861  assert( n>=1 );
33862  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
33863       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
33864       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
33865       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
33866  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
33867  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
33868  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
33869
33870  mask = (1<<(ofst+n)) - (1<<ofst);
33871  assert( n>1 || mask==(1<<ofst) );
33872  sqlite3_mutex_enter(pShmNode->mutex);
33873  if( flags & SQLITE_SHM_UNLOCK ){
33874    u16 allMask = 0; /* Mask of locks held by siblings */
33875
33876    /* See if any siblings hold this same lock */
33877    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33878      if( pX==p ) continue;
33879      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
33880      allMask |= pX->sharedMask;
33881    }
33882
33883    /* Unlock the system-level locks */
33884    if( (mask & allMask)==0 ){
33885      rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
33886    }else{
33887      rc = SQLITE_OK;
33888    }
33889
33890    /* Undo the local locks */
33891    if( rc==SQLITE_OK ){
33892      p->exclMask &= ~mask;
33893      p->sharedMask &= ~mask;
33894    }
33895  }else if( flags & SQLITE_SHM_SHARED ){
33896    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
33897
33898    /* Find out which shared locks are already held by sibling connections.
33899    ** If any sibling already holds an exclusive lock, go ahead and return
33900    ** SQLITE_BUSY.
33901    */
33902    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33903      if( (pX->exclMask & mask)!=0 ){
33904        rc = SQLITE_BUSY;
33905        break;
33906      }
33907      allShared |= pX->sharedMask;
33908    }
33909
33910    /* Get shared locks at the system level, if necessary */
33911    if( rc==SQLITE_OK ){
33912      if( (allShared & mask)==0 ){
33913        rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
33914      }else{
33915        rc = SQLITE_OK;
33916      }
33917    }
33918
33919    /* Get the local shared locks */
33920    if( rc==SQLITE_OK ){
33921      p->sharedMask |= mask;
33922    }
33923  }else{
33924    /* Make sure no sibling connections hold locks that will block this
33925    ** lock.  If any do, return SQLITE_BUSY right away.
33926    */
33927    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33928      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
33929        rc = SQLITE_BUSY;
33930        break;
33931      }
33932    }
33933
33934    /* Get the exclusive locks at the system level.  Then if successful
33935    ** also mark the local connection as being locked.
33936    */
33937    if( rc==SQLITE_OK ){
33938      rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
33939      if( rc==SQLITE_OK ){
33940        assert( (p->sharedMask & mask)==0 );
33941        p->exclMask |= mask;
33942      }
33943    }
33944  }
33945  sqlite3_mutex_leave(pShmNode->mutex);
33946  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
33947           p->id, osGetpid(0), p->sharedMask, p->exclMask));
33948  return rc;
33949}
33950
33951/*
33952** Implement a memory barrier or memory fence on shared memory.
33953**
33954** All loads and stores begun before the barrier must complete before
33955** any load or store begun after the barrier.
33956*/
33957static void unixShmBarrier(
33958  sqlite3_file *fd                /* Database file holding the shared memory */
33959){
33960  UNUSED_PARAMETER(fd);
33961  sqlite3MemoryBarrier();         /* compiler-defined memory barrier */
33962  unixEnterMutex();               /* Also mutex, for redundancy */
33963  unixLeaveMutex();
33964}
33965
33966/*
33967** Close a connection to shared-memory.  Delete the underlying
33968** storage if deleteFlag is true.
33969**
33970** If there is no shared memory associated with the connection then this
33971** routine is a harmless no-op.
33972*/
33973static int unixShmUnmap(
33974  sqlite3_file *fd,               /* The underlying database file */
33975  int deleteFlag                  /* Delete shared-memory if true */
33976){
33977  unixShm *p;                     /* The connection to be closed */
33978  unixShmNode *pShmNode;          /* The underlying shared-memory file */
33979  unixShm **pp;                   /* For looping over sibling connections */
33980  unixFile *pDbFd;                /* The underlying database file */
33981
33982  pDbFd = (unixFile*)fd;
33983  p = pDbFd->pShm;
33984  if( p==0 ) return SQLITE_OK;
33985  pShmNode = p->pShmNode;
33986
33987  assert( pShmNode==pDbFd->pInode->pShmNode );
33988  assert( pShmNode->pInode==pDbFd->pInode );
33989
33990  /* Remove connection p from the set of connections associated
33991  ** with pShmNode */
33992  sqlite3_mutex_enter(pShmNode->mutex);
33993  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
33994  *pp = p->pNext;
33995
33996  /* Free the connection p */
33997  sqlite3_free(p);
33998  pDbFd->pShm = 0;
33999  sqlite3_mutex_leave(pShmNode->mutex);
34000
34001  /* If pShmNode->nRef has reached 0, then close the underlying
34002  ** shared-memory file, too */
34003  unixEnterMutex();
34004  assert( pShmNode->nRef>0 );
34005  pShmNode->nRef--;
34006  if( pShmNode->nRef==0 ){
34007    if( deleteFlag && pShmNode->h>=0 ){
34008      osUnlink(pShmNode->zFilename);
34009    }
34010    unixShmPurge(pDbFd);
34011  }
34012  unixLeaveMutex();
34013
34014  return SQLITE_OK;
34015}
34016
34017
34018#else
34019# define unixShmMap     0
34020# define unixShmLock    0
34021# define unixShmBarrier 0
34022# define unixShmUnmap   0
34023#endif /* #ifndef SQLITE_OMIT_WAL */
34024
34025#if SQLITE_MAX_MMAP_SIZE>0
34026/*
34027** If it is currently memory mapped, unmap file pFd.
34028*/
34029static void unixUnmapfile(unixFile *pFd){
34030  assert( pFd->nFetchOut==0 );
34031  if( pFd->pMapRegion ){
34032    osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
34033    pFd->pMapRegion = 0;
34034    pFd->mmapSize = 0;
34035    pFd->mmapSizeActual = 0;
34036  }
34037}
34038
34039/*
34040** Attempt to set the size of the memory mapping maintained by file
34041** descriptor pFd to nNew bytes. Any existing mapping is discarded.
34042**
34043** If successful, this function sets the following variables:
34044**
34045**       unixFile.pMapRegion
34046**       unixFile.mmapSize
34047**       unixFile.mmapSizeActual
34048**
34049** If unsuccessful, an error message is logged via sqlite3_log() and
34050** the three variables above are zeroed. In this case SQLite should
34051** continue accessing the database using the xRead() and xWrite()
34052** methods.
34053*/
34054static void unixRemapfile(
34055  unixFile *pFd,                  /* File descriptor object */
34056  i64 nNew                        /* Required mapping size */
34057){
34058  const char *zErr = "mmap";
34059  int h = pFd->h;                      /* File descriptor open on db file */
34060  u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
34061  i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
34062  u8 *pNew = 0;                        /* Location of new mapping */
34063  int flags = PROT_READ;               /* Flags to pass to mmap() */
34064
34065  assert( pFd->nFetchOut==0 );
34066  assert( nNew>pFd->mmapSize );
34067  assert( nNew<=pFd->mmapSizeMax );
34068  assert( nNew>0 );
34069  assert( pFd->mmapSizeActual>=pFd->mmapSize );
34070  assert( MAP_FAILED!=0 );
34071
34072#ifdef SQLITE_MMAP_READWRITE
34073  if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
34074#endif
34075
34076  if( pOrig ){
34077#if HAVE_MREMAP
34078    i64 nReuse = pFd->mmapSize;
34079#else
34080    const int szSyspage = osGetpagesize();
34081    i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
34082#endif
34083    u8 *pReq = &pOrig[nReuse];
34084
34085    /* Unmap any pages of the existing mapping that cannot be reused. */
34086    if( nReuse!=nOrig ){
34087      osMunmap(pReq, nOrig-nReuse);
34088    }
34089
34090#if HAVE_MREMAP
34091    pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
34092    zErr = "mremap";
34093#else
34094    pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
34095    if( pNew!=MAP_FAILED ){
34096      if( pNew!=pReq ){
34097        osMunmap(pNew, nNew - nReuse);
34098        pNew = 0;
34099      }else{
34100        pNew = pOrig;
34101      }
34102    }
34103#endif
34104
34105    /* The attempt to extend the existing mapping failed. Free it. */
34106    if( pNew==MAP_FAILED || pNew==0 ){
34107      osMunmap(pOrig, nReuse);
34108    }
34109  }
34110
34111  /* If pNew is still NULL, try to create an entirely new mapping. */
34112  if( pNew==0 ){
34113    pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
34114  }
34115
34116  if( pNew==MAP_FAILED ){
34117    pNew = 0;
34118    nNew = 0;
34119    unixLogError(SQLITE_OK, zErr, pFd->zPath);
34120
34121    /* If the mmap() above failed, assume that all subsequent mmap() calls
34122    ** will probably fail too. Fall back to using xRead/xWrite exclusively
34123    ** in this case.  */
34124    pFd->mmapSizeMax = 0;
34125  }
34126  pFd->pMapRegion = (void *)pNew;
34127  pFd->mmapSize = pFd->mmapSizeActual = nNew;
34128}
34129
34130/*
34131** Memory map or remap the file opened by file-descriptor pFd (if the file
34132** is already mapped, the existing mapping is replaced by the new). Or, if
34133** there already exists a mapping for this file, and there are still
34134** outstanding xFetch() references to it, this function is a no-op.
34135**
34136** If parameter nByte is non-negative, then it is the requested size of
34137** the mapping to create. Otherwise, if nByte is less than zero, then the
34138** requested size is the size of the file on disk. The actual size of the
34139** created mapping is either the requested size or the value configured
34140** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
34141**
34142** SQLITE_OK is returned if no error occurs (even if the mapping is not
34143** recreated as a result of outstanding references) or an SQLite error
34144** code otherwise.
34145*/
34146static int unixMapfile(unixFile *pFd, i64 nMap){
34147  assert( nMap>=0 || pFd->nFetchOut==0 );
34148  assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
34149  if( pFd->nFetchOut>0 ) return SQLITE_OK;
34150
34151  if( nMap<0 ){
34152    struct stat statbuf;          /* Low-level file information */
34153    if( osFstat(pFd->h, &statbuf) ){
34154      return SQLITE_IOERR_FSTAT;
34155    }
34156    nMap = statbuf.st_size;
34157  }
34158  if( nMap>pFd->mmapSizeMax ){
34159    nMap = pFd->mmapSizeMax;
34160  }
34161
34162  assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
34163  if( nMap!=pFd->mmapSize ){
34164    unixRemapfile(pFd, nMap);
34165  }
34166
34167  return SQLITE_OK;
34168}
34169#endif /* SQLITE_MAX_MMAP_SIZE>0 */
34170
34171/*
34172** If possible, return a pointer to a mapping of file fd starting at offset
34173** iOff. The mapping must be valid for at least nAmt bytes.
34174**
34175** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
34176** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
34177** Finally, if an error does occur, return an SQLite error code. The final
34178** value of *pp is undefined in this case.
34179**
34180** If this function does return a pointer, the caller must eventually
34181** release the reference by calling unixUnfetch().
34182*/
34183static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
34184#if SQLITE_MAX_MMAP_SIZE>0
34185  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
34186#endif
34187  *pp = 0;
34188
34189#if SQLITE_MAX_MMAP_SIZE>0
34190  if( pFd->mmapSizeMax>0 ){
34191    if( pFd->pMapRegion==0 ){
34192      int rc = unixMapfile(pFd, -1);
34193      if( rc!=SQLITE_OK ) return rc;
34194    }
34195    if( pFd->mmapSize >= iOff+nAmt ){
34196      *pp = &((u8 *)pFd->pMapRegion)[iOff];
34197      pFd->nFetchOut++;
34198    }
34199  }
34200#endif
34201  return SQLITE_OK;
34202}
34203
34204/*
34205** If the third argument is non-NULL, then this function releases a
34206** reference obtained by an earlier call to unixFetch(). The second
34207** argument passed to this function must be the same as the corresponding
34208** argument that was passed to the unixFetch() invocation.
34209**
34210** Or, if the third argument is NULL, then this function is being called
34211** to inform the VFS layer that, according to POSIX, any existing mapping
34212** may now be invalid and should be unmapped.
34213*/
34214static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
34215#if SQLITE_MAX_MMAP_SIZE>0
34216  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
34217  UNUSED_PARAMETER(iOff);
34218
34219  /* If p==0 (unmap the entire file) then there must be no outstanding
34220  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
34221  ** then there must be at least one outstanding.  */
34222  assert( (p==0)==(pFd->nFetchOut==0) );
34223
34224  /* If p!=0, it must match the iOff value. */
34225  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
34226
34227  if( p ){
34228    pFd->nFetchOut--;
34229  }else{
34230    unixUnmapfile(pFd);
34231  }
34232
34233  assert( pFd->nFetchOut>=0 );
34234#else
34235  UNUSED_PARAMETER(fd);
34236  UNUSED_PARAMETER(p);
34237  UNUSED_PARAMETER(iOff);
34238#endif
34239  return SQLITE_OK;
34240}
34241
34242/*
34243** Here ends the implementation of all sqlite3_file methods.
34244**
34245********************** End sqlite3_file Methods *******************************
34246******************************************************************************/
34247
34248/*
34249** This division contains definitions of sqlite3_io_methods objects that
34250** implement various file locking strategies.  It also contains definitions
34251** of "finder" functions.  A finder-function is used to locate the appropriate
34252** sqlite3_io_methods object for a particular database file.  The pAppData
34253** field of the sqlite3_vfs VFS objects are initialized to be pointers to
34254** the correct finder-function for that VFS.
34255**
34256** Most finder functions return a pointer to a fixed sqlite3_io_methods
34257** object.  The only interesting finder-function is autolockIoFinder, which
34258** looks at the filesystem type and tries to guess the best locking
34259** strategy from that.
34260**
34261** For finder-function F, two objects are created:
34262**
34263**    (1) The real finder-function named "FImpt()".
34264**
34265**    (2) A constant pointer to this function named just "F".
34266**
34267**
34268** A pointer to the F pointer is used as the pAppData value for VFS
34269** objects.  We have to do this instead of letting pAppData point
34270** directly at the finder-function since C90 rules prevent a void*
34271** from be cast into a function pointer.
34272**
34273**
34274** Each instance of this macro generates two objects:
34275**
34276**   *  A constant sqlite3_io_methods object call METHOD that has locking
34277**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
34278**
34279**   *  An I/O method finder function called FINDER that returns a pointer
34280**      to the METHOD object in the previous bullet.
34281*/
34282#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP)     \
34283static const sqlite3_io_methods METHOD = {                                   \
34284   VERSION,                    /* iVersion */                                \
34285   CLOSE,                      /* xClose */                                  \
34286   unixRead,                   /* xRead */                                   \
34287   unixWrite,                  /* xWrite */                                  \
34288   unixTruncate,               /* xTruncate */                               \
34289   unixSync,                   /* xSync */                                   \
34290   unixFileSize,               /* xFileSize */                               \
34291   LOCK,                       /* xLock */                                   \
34292   UNLOCK,                     /* xUnlock */                                 \
34293   CKLOCK,                     /* xCheckReservedLock */                      \
34294   unixFileControl,            /* xFileControl */                            \
34295   unixSectorSize,             /* xSectorSize */                             \
34296   unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
34297   SHMMAP,                     /* xShmMap */                                 \
34298   unixShmLock,                /* xShmLock */                                \
34299   unixShmBarrier,             /* xShmBarrier */                             \
34300   unixShmUnmap,               /* xShmUnmap */                               \
34301   unixFetch,                  /* xFetch */                                  \
34302   unixUnfetch,                /* xUnfetch */                                \
34303};                                                                           \
34304static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
34305  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
34306  return &METHOD;                                                            \
34307}                                                                            \
34308static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
34309    = FINDER##Impl;
34310
34311/*
34312** Here are all of the sqlite3_io_methods objects for each of the
34313** locking strategies.  Functions that return pointers to these methods
34314** are also created.
34315*/
34316IOMETHODS(
34317  posixIoFinder,            /* Finder function name */
34318  posixIoMethods,           /* sqlite3_io_methods object name */
34319  3,                        /* shared memory and mmap are enabled */
34320  unixClose,                /* xClose method */
34321  unixLock,                 /* xLock method */
34322  unixUnlock,               /* xUnlock method */
34323  unixCheckReservedLock,    /* xCheckReservedLock method */
34324  unixShmMap                /* xShmMap method */
34325)
34326IOMETHODS(
34327  nolockIoFinder,           /* Finder function name */
34328  nolockIoMethods,          /* sqlite3_io_methods object name */
34329  3,                        /* shared memory is disabled */
34330  nolockClose,              /* xClose method */
34331  nolockLock,               /* xLock method */
34332  nolockUnlock,             /* xUnlock method */
34333  nolockCheckReservedLock,  /* xCheckReservedLock method */
34334  0                         /* xShmMap method */
34335)
34336IOMETHODS(
34337  dotlockIoFinder,          /* Finder function name */
34338  dotlockIoMethods,         /* sqlite3_io_methods object name */
34339  1,                        /* shared memory is disabled */
34340  dotlockClose,             /* xClose method */
34341  dotlockLock,              /* xLock method */
34342  dotlockUnlock,            /* xUnlock method */
34343  dotlockCheckReservedLock, /* xCheckReservedLock method */
34344  0                         /* xShmMap method */
34345)
34346
34347#if SQLITE_ENABLE_LOCKING_STYLE
34348IOMETHODS(
34349  flockIoFinder,            /* Finder function name */
34350  flockIoMethods,           /* sqlite3_io_methods object name */
34351  1,                        /* shared memory is disabled */
34352  flockClose,               /* xClose method */
34353  flockLock,                /* xLock method */
34354  flockUnlock,              /* xUnlock method */
34355  flockCheckReservedLock,   /* xCheckReservedLock method */
34356  0                         /* xShmMap method */
34357)
34358#endif
34359
34360#if OS_VXWORKS
34361IOMETHODS(
34362  semIoFinder,              /* Finder function name */
34363  semIoMethods,             /* sqlite3_io_methods object name */
34364  1,                        /* shared memory is disabled */
34365  semXClose,                /* xClose method */
34366  semXLock,                 /* xLock method */
34367  semXUnlock,               /* xUnlock method */
34368  semXCheckReservedLock,    /* xCheckReservedLock method */
34369  0                         /* xShmMap method */
34370)
34371#endif
34372
34373#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34374IOMETHODS(
34375  afpIoFinder,              /* Finder function name */
34376  afpIoMethods,             /* sqlite3_io_methods object name */
34377  1,                        /* shared memory is disabled */
34378  afpClose,                 /* xClose method */
34379  afpLock,                  /* xLock method */
34380  afpUnlock,                /* xUnlock method */
34381  afpCheckReservedLock,     /* xCheckReservedLock method */
34382  0                         /* xShmMap method */
34383)
34384#endif
34385
34386/*
34387** The proxy locking method is a "super-method" in the sense that it
34388** opens secondary file descriptors for the conch and lock files and
34389** it uses proxy, dot-file, AFP, and flock() locking methods on those
34390** secondary files.  For this reason, the division that implements
34391** proxy locking is located much further down in the file.  But we need
34392** to go ahead and define the sqlite3_io_methods and finder function
34393** for proxy locking here.  So we forward declare the I/O methods.
34394*/
34395#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34396static int proxyClose(sqlite3_file*);
34397static int proxyLock(sqlite3_file*, int);
34398static int proxyUnlock(sqlite3_file*, int);
34399static int proxyCheckReservedLock(sqlite3_file*, int*);
34400IOMETHODS(
34401  proxyIoFinder,            /* Finder function name */
34402  proxyIoMethods,           /* sqlite3_io_methods object name */
34403  1,                        /* shared memory is disabled */
34404  proxyClose,               /* xClose method */
34405  proxyLock,                /* xLock method */
34406  proxyUnlock,              /* xUnlock method */
34407  proxyCheckReservedLock,   /* xCheckReservedLock method */
34408  0                         /* xShmMap method */
34409)
34410#endif
34411
34412/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
34413#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34414IOMETHODS(
34415  nfsIoFinder,               /* Finder function name */
34416  nfsIoMethods,              /* sqlite3_io_methods object name */
34417  1,                         /* shared memory is disabled */
34418  unixClose,                 /* xClose method */
34419  unixLock,                  /* xLock method */
34420  nfsUnlock,                 /* xUnlock method */
34421  unixCheckReservedLock,     /* xCheckReservedLock method */
34422  0                          /* xShmMap method */
34423)
34424#endif
34425
34426#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34427/*
34428** This "finder" function attempts to determine the best locking strategy
34429** for the database file "filePath".  It then returns the sqlite3_io_methods
34430** object that implements that strategy.
34431**
34432** This is for MacOSX only.
34433*/
34434static const sqlite3_io_methods *autolockIoFinderImpl(
34435  const char *filePath,    /* name of the database file */
34436  unixFile *pNew           /* open file object for the database file */
34437){
34438  static const struct Mapping {
34439    const char *zFilesystem;              /* Filesystem type name */
34440    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
34441  } aMap[] = {
34442    { "hfs",    &posixIoMethods },
34443    { "ufs",    &posixIoMethods },
34444    { "afpfs",  &afpIoMethods },
34445    { "smbfs",  &afpIoMethods },
34446    { "webdav", &nolockIoMethods },
34447    { 0, 0 }
34448  };
34449  int i;
34450  struct statfs fsInfo;
34451  struct flock lockInfo;
34452
34453  if( !filePath ){
34454    /* If filePath==NULL that means we are dealing with a transient file
34455    ** that does not need to be locked. */
34456    return &nolockIoMethods;
34457  }
34458  if( statfs(filePath, &fsInfo) != -1 ){
34459    if( fsInfo.f_flags & MNT_RDONLY ){
34460      return &nolockIoMethods;
34461    }
34462    for(i=0; aMap[i].zFilesystem; i++){
34463      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
34464        return aMap[i].pMethods;
34465      }
34466    }
34467  }
34468
34469  /* Default case. Handles, amongst others, "nfs".
34470  ** Test byte-range lock using fcntl(). If the call succeeds,
34471  ** assume that the file-system supports POSIX style locks.
34472  */
34473  lockInfo.l_len = 1;
34474  lockInfo.l_start = 0;
34475  lockInfo.l_whence = SEEK_SET;
34476  lockInfo.l_type = F_RDLCK;
34477  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
34478    if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
34479      return &nfsIoMethods;
34480    } else {
34481      return &posixIoMethods;
34482    }
34483  }else{
34484    return &dotlockIoMethods;
34485  }
34486}
34487static const sqlite3_io_methods
34488  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
34489
34490#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
34491
34492#if OS_VXWORKS
34493/*
34494** This "finder" function for VxWorks checks to see if posix advisory
34495** locking works.  If it does, then that is what is used.  If it does not
34496** work, then fallback to named semaphore locking.
34497*/
34498static const sqlite3_io_methods *vxworksIoFinderImpl(
34499  const char *filePath,    /* name of the database file */
34500  unixFile *pNew           /* the open file object */
34501){
34502  struct flock lockInfo;
34503
34504  if( !filePath ){
34505    /* If filePath==NULL that means we are dealing with a transient file
34506    ** that does not need to be locked. */
34507    return &nolockIoMethods;
34508  }
34509
34510  /* Test if fcntl() is supported and use POSIX style locks.
34511  ** Otherwise fall back to the named semaphore method.
34512  */
34513  lockInfo.l_len = 1;
34514  lockInfo.l_start = 0;
34515  lockInfo.l_whence = SEEK_SET;
34516  lockInfo.l_type = F_RDLCK;
34517  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
34518    return &posixIoMethods;
34519  }else{
34520    return &semIoMethods;
34521  }
34522}
34523static const sqlite3_io_methods
34524  *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
34525
34526#endif /* OS_VXWORKS */
34527
34528/*
34529** An abstract type for a pointer to an IO method finder function:
34530*/
34531typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
34532
34533
34534/****************************************************************************
34535**************************** sqlite3_vfs methods ****************************
34536**
34537** This division contains the implementation of methods on the
34538** sqlite3_vfs object.
34539*/
34540
34541/*
34542** Initialize the contents of the unixFile structure pointed to by pId.
34543*/
34544static int fillInUnixFile(
34545  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
34546  int h,                  /* Open file descriptor of file being opened */
34547  sqlite3_file *pId,      /* Write to the unixFile structure here */
34548  const char *zFilename,  /* Name of the file being opened */
34549  int ctrlFlags           /* Zero or more UNIXFILE_* values */
34550){
34551  const sqlite3_io_methods *pLockingStyle;
34552  unixFile *pNew = (unixFile *)pId;
34553  int rc = SQLITE_OK;
34554
34555  assert( pNew->pInode==NULL );
34556
34557  /* Usually the path zFilename should not be a relative pathname. The
34558  ** exception is when opening the proxy "conch" file in builds that
34559  ** include the special Apple locking styles.
34560  */
34561#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34562  assert( zFilename==0 || zFilename[0]=='/'
34563    || pVfs->pAppData==(void*)&autolockIoFinder );
34564#else
34565  assert( zFilename==0 || zFilename[0]=='/' );
34566#endif
34567
34568  /* No locking occurs in temporary files */
34569  assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
34570
34571  OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
34572  pNew->h = h;
34573  pNew->pVfs = pVfs;
34574  pNew->zPath = zFilename;
34575  pNew->ctrlFlags = (u8)ctrlFlags;
34576#if SQLITE_MAX_MMAP_SIZE>0
34577  pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
34578#endif
34579  if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
34580                           "psow", SQLITE_POWERSAFE_OVERWRITE) ){
34581    pNew->ctrlFlags |= UNIXFILE_PSOW;
34582  }
34583  if( strcmp(pVfs->zName,"unix-excl")==0 ){
34584    pNew->ctrlFlags |= UNIXFILE_EXCL;
34585  }
34586
34587#if OS_VXWORKS
34588  pNew->pId = vxworksFindFileId(zFilename);
34589  if( pNew->pId==0 ){
34590    ctrlFlags |= UNIXFILE_NOLOCK;
34591    rc = SQLITE_NOMEM_BKPT;
34592  }
34593#endif
34594
34595  if( ctrlFlags & UNIXFILE_NOLOCK ){
34596    pLockingStyle = &nolockIoMethods;
34597  }else{
34598    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
34599#if SQLITE_ENABLE_LOCKING_STYLE
34600    /* Cache zFilename in the locking context (AFP and dotlock override) for
34601    ** proxyLock activation is possible (remote proxy is based on db name)
34602    ** zFilename remains valid until file is closed, to support */
34603    pNew->lockingContext = (void*)zFilename;
34604#endif
34605  }
34606
34607  if( pLockingStyle == &posixIoMethods
34608#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34609    || pLockingStyle == &nfsIoMethods
34610#endif
34611  ){
34612    unixEnterMutex();
34613    rc = findInodeInfo(pNew, &pNew->pInode);
34614    if( rc!=SQLITE_OK ){
34615      /* If an error occurred in findInodeInfo(), close the file descriptor
34616      ** immediately, before releasing the mutex. findInodeInfo() may fail
34617      ** in two scenarios:
34618      **
34619      **   (a) A call to fstat() failed.
34620      **   (b) A malloc failed.
34621      **
34622      ** Scenario (b) may only occur if the process is holding no other
34623      ** file descriptors open on the same file. If there were other file
34624      ** descriptors on this file, then no malloc would be required by
34625      ** findInodeInfo(). If this is the case, it is quite safe to close
34626      ** handle h - as it is guaranteed that no posix locks will be released
34627      ** by doing so.
34628      **
34629      ** If scenario (a) caused the error then things are not so safe. The
34630      ** implicit assumption here is that if fstat() fails, things are in
34631      ** such bad shape that dropping a lock or two doesn't matter much.
34632      */
34633      robust_close(pNew, h, __LINE__);
34634      h = -1;
34635    }
34636    unixLeaveMutex();
34637  }
34638
34639#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34640  else if( pLockingStyle == &afpIoMethods ){
34641    /* AFP locking uses the file path so it needs to be included in
34642    ** the afpLockingContext.
34643    */
34644    afpLockingContext *pCtx;
34645    pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
34646    if( pCtx==0 ){
34647      rc = SQLITE_NOMEM_BKPT;
34648    }else{
34649      /* NB: zFilename exists and remains valid until the file is closed
34650      ** according to requirement F11141.  So we do not need to make a
34651      ** copy of the filename. */
34652      pCtx->dbPath = zFilename;
34653      pCtx->reserved = 0;
34654      srandomdev();
34655      unixEnterMutex();
34656      rc = findInodeInfo(pNew, &pNew->pInode);
34657      if( rc!=SQLITE_OK ){
34658        sqlite3_free(pNew->lockingContext);
34659        robust_close(pNew, h, __LINE__);
34660        h = -1;
34661      }
34662      unixLeaveMutex();
34663    }
34664  }
34665#endif
34666
34667  else if( pLockingStyle == &dotlockIoMethods ){
34668    /* Dotfile locking uses the file path so it needs to be included in
34669    ** the dotlockLockingContext
34670    */
34671    char *zLockFile;
34672    int nFilename;
34673    assert( zFilename!=0 );
34674    nFilename = (int)strlen(zFilename) + 6;
34675    zLockFile = (char *)sqlite3_malloc64(nFilename);
34676    if( zLockFile==0 ){
34677      rc = SQLITE_NOMEM_BKPT;
34678    }else{
34679      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
34680    }
34681    pNew->lockingContext = zLockFile;
34682  }
34683
34684#if OS_VXWORKS
34685  else if( pLockingStyle == &semIoMethods ){
34686    /* Named semaphore locking uses the file path so it needs to be
34687    ** included in the semLockingContext
34688    */
34689    unixEnterMutex();
34690    rc = findInodeInfo(pNew, &pNew->pInode);
34691    if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
34692      char *zSemName = pNew->pInode->aSemName;
34693      int n;
34694      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
34695                       pNew->pId->zCanonicalName);
34696      for( n=1; zSemName[n]; n++ )
34697        if( zSemName[n]=='/' ) zSemName[n] = '_';
34698      pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
34699      if( pNew->pInode->pSem == SEM_FAILED ){
34700        rc = SQLITE_NOMEM_BKPT;
34701        pNew->pInode->aSemName[0] = '\0';
34702      }
34703    }
34704    unixLeaveMutex();
34705  }
34706#endif
34707
34708  storeLastErrno(pNew, 0);
34709#if OS_VXWORKS
34710  if( rc!=SQLITE_OK ){
34711    if( h>=0 ) robust_close(pNew, h, __LINE__);
34712    h = -1;
34713    osUnlink(zFilename);
34714    pNew->ctrlFlags |= UNIXFILE_DELETE;
34715  }
34716#endif
34717  if( rc!=SQLITE_OK ){
34718    if( h>=0 ) robust_close(pNew, h, __LINE__);
34719  }else{
34720    pNew->pMethod = pLockingStyle;
34721    OpenCounter(+1);
34722    verifyDbFile(pNew);
34723  }
34724  return rc;
34725}
34726
34727/*
34728** Return the name of a directory in which to put temporary files.
34729** If no suitable temporary file directory can be found, return NULL.
34730*/
34731static const char *unixTempFileDir(void){
34732  static const char *azDirs[] = {
34733     0,
34734     0,
34735     "/var/tmp",
34736     "/usr/tmp",
34737     "/tmp",
34738     "."
34739  };
34740  unsigned int i = 0;
34741  struct stat buf;
34742  const char *zDir = sqlite3_temp_directory;
34743
34744  if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
34745  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
34746  while(1){
34747    if( zDir!=0
34748     && osStat(zDir, &buf)==0
34749     && S_ISDIR(buf.st_mode)
34750     && osAccess(zDir, 03)==0
34751    ){
34752      return zDir;
34753    }
34754    if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
34755    zDir = azDirs[i++];
34756  }
34757  return 0;
34758}
34759
34760/*
34761** Create a temporary file name in zBuf.  zBuf must be allocated
34762** by the calling process and must be big enough to hold at least
34763** pVfs->mxPathname bytes.
34764*/
34765static int unixGetTempname(int nBuf, char *zBuf){
34766  const char *zDir;
34767  int iLimit = 0;
34768
34769  /* It's odd to simulate an io-error here, but really this is just
34770  ** using the io-error infrastructure to test that SQLite handles this
34771  ** function failing.
34772  */
34773  zBuf[0] = 0;
34774  SimulateIOError( return SQLITE_IOERR );
34775
34776  zDir = unixTempFileDir();
34777  if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
34778  do{
34779    u64 r;
34780    sqlite3_randomness(sizeof(r), &r);
34781    assert( nBuf>2 );
34782    zBuf[nBuf-2] = 0;
34783    sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
34784                     zDir, r, 0);
34785    if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
34786  }while( osAccess(zBuf,0)==0 );
34787  return SQLITE_OK;
34788}
34789
34790#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34791/*
34792** Routine to transform a unixFile into a proxy-locking unixFile.
34793** Implementation in the proxy-lock division, but used by unixOpen()
34794** if SQLITE_PREFER_PROXY_LOCKING is defined.
34795*/
34796static int proxyTransformUnixFile(unixFile*, const char*);
34797#endif
34798
34799/*
34800** Search for an unused file descriptor that was opened on the database
34801** file (not a journal or master-journal file) identified by pathname
34802** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
34803** argument to this function.
34804**
34805** Such a file descriptor may exist if a database connection was closed
34806** but the associated file descriptor could not be closed because some
34807** other file descriptor open on the same file is holding a file-lock.
34808** Refer to comments in the unixClose() function and the lengthy comment
34809** describing "Posix Advisory Locking" at the start of this file for
34810** further details. Also, ticket #4018.
34811**
34812** If a suitable file descriptor is found, then it is returned. If no
34813** such file descriptor is located, -1 is returned.
34814*/
34815static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
34816  UnixUnusedFd *pUnused = 0;
34817
34818  /* Do not search for an unused file descriptor on vxworks. Not because
34819  ** vxworks would not benefit from the change (it might, we're not sure),
34820  ** but because no way to test it is currently available. It is better
34821  ** not to risk breaking vxworks support for the sake of such an obscure
34822  ** feature.  */
34823#if !OS_VXWORKS
34824  struct stat sStat;                   /* Results of stat() call */
34825
34826  /* A stat() call may fail for various reasons. If this happens, it is
34827  ** almost certain that an open() call on the same path will also fail.
34828  ** For this reason, if an error occurs in the stat() call here, it is
34829  ** ignored and -1 is returned. The caller will try to open a new file
34830  ** descriptor on the same path, fail, and return an error to SQLite.
34831  **
34832  ** Even if a subsequent open() call does succeed, the consequences of
34833  ** not searching for a reusable file descriptor are not dire.  */
34834  if( 0==osStat(zPath, &sStat) ){
34835    unixInodeInfo *pInode;
34836
34837    unixEnterMutex();
34838    pInode = inodeList;
34839    while( pInode && (pInode->fileId.dev!=sStat.st_dev
34840                     || pInode->fileId.ino!=sStat.st_ino) ){
34841       pInode = pInode->pNext;
34842    }
34843    if( pInode ){
34844      UnixUnusedFd **pp;
34845      for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
34846      pUnused = *pp;
34847      if( pUnused ){
34848        *pp = pUnused->pNext;
34849      }
34850    }
34851    unixLeaveMutex();
34852  }
34853#endif    /* if !OS_VXWORKS */
34854  return pUnused;
34855}
34856
34857/*
34858** This function is called by unixOpen() to determine the unix permissions
34859** to create new files with. If no error occurs, then SQLITE_OK is returned
34860** and a value suitable for passing as the third argument to open(2) is
34861** written to *pMode. If an IO error occurs, an SQLite error code is
34862** returned and the value of *pMode is not modified.
34863**
34864** In most cases, this routine sets *pMode to 0, which will become
34865** an indication to robust_open() to create the file using
34866** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
34867** But if the file being opened is a WAL or regular journal file, then
34868** this function queries the file-system for the permissions on the
34869** corresponding database file and sets *pMode to this value. Whenever
34870** possible, WAL and journal files are created using the same permissions
34871** as the associated database file.
34872**
34873** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
34874** original filename is unavailable.  But 8_3_NAMES is only used for
34875** FAT filesystems and permissions do not matter there, so just use
34876** the default permissions.
34877*/
34878static int findCreateFileMode(
34879  const char *zPath,              /* Path of file (possibly) being created */
34880  int flags,                      /* Flags passed as 4th argument to xOpen() */
34881  mode_t *pMode,                  /* OUT: Permissions to open file with */
34882  uid_t *pUid,                    /* OUT: uid to set on the file */
34883  gid_t *pGid                     /* OUT: gid to set on the file */
34884){
34885  int rc = SQLITE_OK;             /* Return Code */
34886  *pMode = 0;
34887  *pUid = 0;
34888  *pGid = 0;
34889  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
34890    char zDb[MAX_PATHNAME+1];     /* Database file path */
34891    int nDb;                      /* Number of valid bytes in zDb */
34892    struct stat sStat;            /* Output of stat() on database file */
34893
34894    /* zPath is a path to a WAL or journal file. The following block derives
34895    ** the path to the associated database file from zPath. This block handles
34896    ** the following naming conventions:
34897    **
34898    **   "<path to db>-journal"
34899    **   "<path to db>-wal"
34900    **   "<path to db>-journalNN"
34901    **   "<path to db>-walNN"
34902    **
34903    ** where NN is a decimal number. The NN naming schemes are
34904    ** used by the test_multiplex.c module.
34905    */
34906    nDb = sqlite3Strlen30(zPath) - 1;
34907    while( zPath[nDb]!='-' ){
34908#ifndef SQLITE_ENABLE_8_3_NAMES
34909      /* In the normal case (8+3 filenames disabled) the journal filename
34910      ** is guaranteed to contain a '-' character. */
34911      assert( nDb>0 );
34912      assert( sqlite3Isalnum(zPath[nDb]) );
34913#else
34914      /* If 8+3 names are possible, then the journal file might not contain
34915      ** a '-' character.  So check for that case and return early. */
34916      if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
34917#endif
34918      nDb--;
34919    }
34920    memcpy(zDb, zPath, nDb);
34921    zDb[nDb] = '\0';
34922
34923    if( 0==osStat(zDb, &sStat) ){
34924      *pMode = sStat.st_mode & 0777;
34925      *pUid = sStat.st_uid;
34926      *pGid = sStat.st_gid;
34927    }else{
34928      rc = SQLITE_IOERR_FSTAT;
34929    }
34930  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
34931    *pMode = 0600;
34932  }
34933  return rc;
34934}
34935
34936/*
34937** Open the file zPath.
34938**
34939** Previously, the SQLite OS layer used three functions in place of this
34940** one:
34941**
34942**     sqlite3OsOpenReadWrite();
34943**     sqlite3OsOpenReadOnly();
34944**     sqlite3OsOpenExclusive();
34945**
34946** These calls correspond to the following combinations of flags:
34947**
34948**     ReadWrite() ->     (READWRITE | CREATE)
34949**     ReadOnly()  ->     (READONLY)
34950**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
34951**
34952** The old OpenExclusive() accepted a boolean argument - "delFlag". If
34953** true, the file was configured to be automatically deleted when the
34954** file handle closed. To achieve the same effect using this new
34955** interface, add the DELETEONCLOSE flag to those specified above for
34956** OpenExclusive().
34957*/
34958static int unixOpen(
34959  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
34960  const char *zPath,           /* Pathname of file to be opened */
34961  sqlite3_file *pFile,         /* The file descriptor to be filled in */
34962  int flags,                   /* Input flags to control the opening */
34963  int *pOutFlags               /* Output flags returned to SQLite core */
34964){
34965  unixFile *p = (unixFile *)pFile;
34966  int fd = -1;                   /* File descriptor returned by open() */
34967  int openFlags = 0;             /* Flags to pass to open() */
34968  int eType = flags&0xFFFFFF00;  /* Type of file to open */
34969  int noLock;                    /* True to omit locking primitives */
34970  int rc = SQLITE_OK;            /* Function Return Code */
34971  int ctrlFlags = 0;             /* UNIXFILE_* flags */
34972
34973  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
34974  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
34975  int isCreate     = (flags & SQLITE_OPEN_CREATE);
34976  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
34977  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
34978#if SQLITE_ENABLE_LOCKING_STYLE
34979  int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
34980#endif
34981#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
34982  struct statfs fsInfo;
34983#endif
34984
34985  /* If creating a master or main-file journal, this function will open
34986  ** a file-descriptor on the directory too. The first time unixSync()
34987  ** is called the directory file descriptor will be fsync()ed and close()d.
34988  */
34989  int syncDir = (isCreate && (
34990        eType==SQLITE_OPEN_MASTER_JOURNAL
34991     || eType==SQLITE_OPEN_MAIN_JOURNAL
34992     || eType==SQLITE_OPEN_WAL
34993  ));
34994
34995  /* If argument zPath is a NULL pointer, this function is required to open
34996  ** a temporary file. Use this buffer to store the file name in.
34997  */
34998  char zTmpname[MAX_PATHNAME+2];
34999  const char *zName = zPath;
35000
35001  /* Check the following statements are true:
35002  **
35003  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
35004  **   (b) if CREATE is set, then READWRITE must also be set, and
35005  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
35006  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
35007  */
35008  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
35009  assert(isCreate==0 || isReadWrite);
35010  assert(isExclusive==0 || isCreate);
35011  assert(isDelete==0 || isCreate);
35012
35013  /* The main DB, main journal, WAL file and master journal are never
35014  ** automatically deleted. Nor are they ever temporary files.  */
35015  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
35016  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
35017  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
35018  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
35019
35020  /* Assert that the upper layer has set one of the "file-type" flags. */
35021  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
35022       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
35023       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
35024       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
35025  );
35026
35027  /* Detect a pid change and reset the PRNG.  There is a race condition
35028  ** here such that two or more threads all trying to open databases at
35029  ** the same instant might all reset the PRNG.  But multiple resets
35030  ** are harmless.
35031  */
35032  if( randomnessPid!=osGetpid(0) ){
35033    randomnessPid = osGetpid(0);
35034    sqlite3_randomness(0,0);
35035  }
35036
35037  memset(p, 0, sizeof(unixFile));
35038
35039  if( eType==SQLITE_OPEN_MAIN_DB ){
35040    UnixUnusedFd *pUnused;
35041    pUnused = findReusableFd(zName, flags);
35042    if( pUnused ){
35043      fd = pUnused->fd;
35044    }else{
35045      pUnused = sqlite3_malloc64(sizeof(*pUnused));
35046      if( !pUnused ){
35047        return SQLITE_NOMEM_BKPT;
35048      }
35049    }
35050    p->pUnused = pUnused;
35051
35052    /* Database filenames are double-zero terminated if they are not
35053    ** URIs with parameters.  Hence, they can always be passed into
35054    ** sqlite3_uri_parameter(). */
35055    assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
35056
35057  }else if( !zName ){
35058    /* If zName is NULL, the upper layer is requesting a temp file. */
35059    assert(isDelete && !syncDir);
35060    rc = unixGetTempname(pVfs->mxPathname, zTmpname);
35061    if( rc!=SQLITE_OK ){
35062      return rc;
35063    }
35064    zName = zTmpname;
35065
35066    /* Generated temporary filenames are always double-zero terminated
35067    ** for use by sqlite3_uri_parameter(). */
35068    assert( zName[strlen(zName)+1]==0 );
35069  }
35070
35071  /* Determine the value of the flags parameter passed to POSIX function
35072  ** open(). These must be calculated even if open() is not called, as
35073  ** they may be stored as part of the file handle and used by the
35074  ** 'conch file' locking functions later on.  */
35075  if( isReadonly )  openFlags |= O_RDONLY;
35076  if( isReadWrite ) openFlags |= O_RDWR;
35077  if( isCreate )    openFlags |= O_CREAT;
35078  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
35079  openFlags |= (O_LARGEFILE|O_BINARY);
35080
35081  if( fd<0 ){
35082    mode_t openMode;              /* Permissions to create file with */
35083    uid_t uid;                    /* Userid for the file */
35084    gid_t gid;                    /* Groupid for the file */
35085    rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
35086    if( rc!=SQLITE_OK ){
35087      assert( !p->pUnused );
35088      assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
35089      return rc;
35090    }
35091    fd = robust_open(zName, openFlags, openMode);
35092    OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
35093    assert( !isExclusive || (openFlags & O_CREAT)!=0 );
35094    if( fd<0 && errno!=EISDIR && isReadWrite ){
35095      /* Failed to open the file for read/write access. Try read-only. */
35096      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
35097      openFlags &= ~(O_RDWR|O_CREAT);
35098      flags |= SQLITE_OPEN_READONLY;
35099      openFlags |= O_RDONLY;
35100      isReadonly = 1;
35101      fd = robust_open(zName, openFlags, openMode);
35102    }
35103    if( fd<0 ){
35104      rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
35105      goto open_finished;
35106    }
35107
35108    /* If this process is running as root and if creating a new rollback
35109    ** journal or WAL file, set the ownership of the journal or WAL to be
35110    ** the same as the original database.
35111    */
35112    if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
35113      robustFchown(fd, uid, gid);
35114    }
35115  }
35116  assert( fd>=0 );
35117  if( pOutFlags ){
35118    *pOutFlags = flags;
35119  }
35120
35121  if( p->pUnused ){
35122    p->pUnused->fd = fd;
35123    p->pUnused->flags = flags;
35124  }
35125
35126  if( isDelete ){
35127#if OS_VXWORKS
35128    zPath = zName;
35129#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
35130    zPath = sqlite3_mprintf("%s", zName);
35131    if( zPath==0 ){
35132      robust_close(p, fd, __LINE__);
35133      return SQLITE_NOMEM_BKPT;
35134    }
35135#else
35136    osUnlink(zName);
35137#endif
35138  }
35139#if SQLITE_ENABLE_LOCKING_STYLE
35140  else{
35141    p->openFlags = openFlags;
35142  }
35143#endif
35144
35145#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
35146  if( fstatfs(fd, &fsInfo) == -1 ){
35147    storeLastErrno(p, errno);
35148    robust_close(p, fd, __LINE__);
35149    return SQLITE_IOERR_ACCESS;
35150  }
35151  if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
35152    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
35153  }
35154  if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
35155    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
35156  }
35157#endif
35158
35159  /* Set up appropriate ctrlFlags */
35160  if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
35161  if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
35162  noLock = eType!=SQLITE_OPEN_MAIN_DB;
35163  if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
35164  if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
35165  if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
35166
35167#if SQLITE_ENABLE_LOCKING_STYLE
35168#if SQLITE_PREFER_PROXY_LOCKING
35169  isAutoProxy = 1;
35170#endif
35171  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
35172    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
35173    int useProxy = 0;
35174
35175    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
35176    ** never use proxy, NULL means use proxy for non-local files only.  */
35177    if( envforce!=NULL ){
35178      useProxy = atoi(envforce)>0;
35179    }else{
35180      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
35181    }
35182    if( useProxy ){
35183      rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
35184      if( rc==SQLITE_OK ){
35185        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
35186        if( rc!=SQLITE_OK ){
35187          /* Use unixClose to clean up the resources added in fillInUnixFile
35188          ** and clear all the structure's references.  Specifically,
35189          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
35190          */
35191          unixClose(pFile);
35192          return rc;
35193        }
35194      }
35195      goto open_finished;
35196    }
35197  }
35198#endif
35199
35200  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
35201
35202open_finished:
35203  if( rc!=SQLITE_OK ){
35204    sqlite3_free(p->pUnused);
35205  }
35206  return rc;
35207}
35208
35209
35210/*
35211** Delete the file at zPath. If the dirSync argument is true, fsync()
35212** the directory after deleting the file.
35213*/
35214static int unixDelete(
35215  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
35216  const char *zPath,        /* Name of file to be deleted */
35217  int dirSync               /* If true, fsync() directory after deleting file */
35218){
35219  int rc = SQLITE_OK;
35220  UNUSED_PARAMETER(NotUsed);
35221  SimulateIOError(return SQLITE_IOERR_DELETE);
35222  if( osUnlink(zPath)==(-1) ){
35223    if( errno==ENOENT
35224#if OS_VXWORKS
35225        || osAccess(zPath,0)!=0
35226#endif
35227    ){
35228      rc = SQLITE_IOERR_DELETE_NOENT;
35229    }else{
35230      rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
35231    }
35232    return rc;
35233  }
35234#ifndef SQLITE_DISABLE_DIRSYNC
35235  if( (dirSync & 1)!=0 ){
35236    int fd;
35237    rc = osOpenDirectory(zPath, &fd);
35238    if( rc==SQLITE_OK ){
35239      if( full_fsync(fd,0,0) ){
35240        rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
35241      }
35242      robust_close(0, fd, __LINE__);
35243    }else{
35244      assert( rc==SQLITE_CANTOPEN );
35245      rc = SQLITE_OK;
35246    }
35247  }
35248#endif
35249  return rc;
35250}
35251
35252/*
35253** Test the existence of or access permissions of file zPath. The
35254** test performed depends on the value of flags:
35255**
35256**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
35257**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
35258**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
35259**
35260** Otherwise return 0.
35261*/
35262static int unixAccess(
35263  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
35264  const char *zPath,      /* Path of the file to examine */
35265  int flags,              /* What do we want to learn about the zPath file? */
35266  int *pResOut            /* Write result boolean here */
35267){
35268  UNUSED_PARAMETER(NotUsed);
35269  SimulateIOError( return SQLITE_IOERR_ACCESS; );
35270  assert( pResOut!=0 );
35271
35272  /* The spec says there are three possible values for flags.  But only
35273  ** two of them are actually used */
35274  assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
35275
35276  if( flags==SQLITE_ACCESS_EXISTS ){
35277    struct stat buf;
35278    *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
35279  }else{
35280    *pResOut = osAccess(zPath, W_OK|R_OK)==0;
35281  }
35282  return SQLITE_OK;
35283}
35284
35285/*
35286**
35287*/
35288static int mkFullPathname(
35289  const char *zPath,              /* Input path */
35290  char *zOut,                     /* Output buffer */
35291  int nOut                        /* Allocated size of buffer zOut */
35292){
35293  int nPath = sqlite3Strlen30(zPath);
35294  int iOff = 0;
35295  if( zPath[0]!='/' ){
35296    if( osGetcwd(zOut, nOut-2)==0 ){
35297      return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
35298    }
35299    iOff = sqlite3Strlen30(zOut);
35300    zOut[iOff++] = '/';
35301  }
35302  if( (iOff+nPath+1)>nOut ){
35303    /* SQLite assumes that xFullPathname() nul-terminates the output buffer
35304    ** even if it returns an error.  */
35305    zOut[iOff] = '\0';
35306    return SQLITE_CANTOPEN_BKPT;
35307  }
35308  sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
35309  return SQLITE_OK;
35310}
35311
35312/*
35313** Turn a relative pathname into a full pathname. The relative path
35314** is stored as a nul-terminated string in the buffer pointed to by
35315** zPath.
35316**
35317** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
35318** (in this case, MAX_PATHNAME bytes). The full-path is written to
35319** this buffer before returning.
35320*/
35321static int unixFullPathname(
35322  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
35323  const char *zPath,            /* Possibly relative input path */
35324  int nOut,                     /* Size of output buffer in bytes */
35325  char *zOut                    /* Output buffer */
35326){
35327#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
35328  return mkFullPathname(zPath, zOut, nOut);
35329#else
35330  int rc = SQLITE_OK;
35331  int nByte;
35332  int nLink = 1;                /* Number of symbolic links followed so far */
35333  const char *zIn = zPath;      /* Input path for each iteration of loop */
35334  char *zDel = 0;
35335
35336  assert( pVfs->mxPathname==MAX_PATHNAME );
35337  UNUSED_PARAMETER(pVfs);
35338
35339  /* It's odd to simulate an io-error here, but really this is just
35340  ** using the io-error infrastructure to test that SQLite handles this
35341  ** function failing. This function could fail if, for example, the
35342  ** current working directory has been unlinked.
35343  */
35344  SimulateIOError( return SQLITE_ERROR );
35345
35346  do {
35347
35348    /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
35349    ** link, or false otherwise.  */
35350    int bLink = 0;
35351    struct stat buf;
35352    if( osLstat(zIn, &buf)!=0 ){
35353      if( errno!=ENOENT ){
35354        rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
35355      }
35356    }else{
35357      bLink = S_ISLNK(buf.st_mode);
35358    }
35359
35360    if( bLink ){
35361      if( zDel==0 ){
35362        zDel = sqlite3_malloc(nOut);
35363        if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
35364      }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
35365        rc = SQLITE_CANTOPEN_BKPT;
35366      }
35367
35368      if( rc==SQLITE_OK ){
35369        nByte = osReadlink(zIn, zDel, nOut-1);
35370        if( nByte<0 ){
35371          rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
35372        }else{
35373          if( zDel[0]!='/' ){
35374            int n;
35375            for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
35376            if( nByte+n+1>nOut ){
35377              rc = SQLITE_CANTOPEN_BKPT;
35378            }else{
35379              memmove(&zDel[n], zDel, nByte+1);
35380              memcpy(zDel, zIn, n);
35381              nByte += n;
35382            }
35383          }
35384          zDel[nByte] = '\0';
35385        }
35386      }
35387
35388      zIn = zDel;
35389    }
35390
35391    assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
35392    if( rc==SQLITE_OK && zIn!=zOut ){
35393      rc = mkFullPathname(zIn, zOut, nOut);
35394    }
35395    if( bLink==0 ) break;
35396    zIn = zOut;
35397  }while( rc==SQLITE_OK );
35398
35399  sqlite3_free(zDel);
35400  return rc;
35401#endif   /* HAVE_READLINK && HAVE_LSTAT */
35402}
35403
35404
35405#ifndef SQLITE_OMIT_LOAD_EXTENSION
35406/*
35407** Interfaces for opening a shared library, finding entry points
35408** within the shared library, and closing the shared library.
35409*/
35410#include <dlfcn.h>
35411static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
35412  UNUSED_PARAMETER(NotUsed);
35413  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
35414}
35415
35416/*
35417** SQLite calls this function immediately after a call to unixDlSym() or
35418** unixDlOpen() fails (returns a null pointer). If a more detailed error
35419** message is available, it is written to zBufOut. If no error message
35420** is available, zBufOut is left unmodified and SQLite uses a default
35421** error message.
35422*/
35423static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
35424  const char *zErr;
35425  UNUSED_PARAMETER(NotUsed);
35426  unixEnterMutex();
35427  zErr = dlerror();
35428  if( zErr ){
35429    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
35430  }
35431  unixLeaveMutex();
35432}
35433static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
35434  /*
35435  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
35436  ** cast into a pointer to a function.  And yet the library dlsym() routine
35437  ** returns a void* which is really a pointer to a function.  So how do we
35438  ** use dlsym() with -pedantic-errors?
35439  **
35440  ** Variable x below is defined to be a pointer to a function taking
35441  ** parameters void* and const char* and returning a pointer to a function.
35442  ** We initialize x by assigning it a pointer to the dlsym() function.
35443  ** (That assignment requires a cast.)  Then we call the function that
35444  ** x points to.
35445  **
35446  ** This work-around is unlikely to work correctly on any system where
35447  ** you really cannot cast a function pointer into void*.  But then, on the
35448  ** other hand, dlsym() will not work on such a system either, so we have
35449  ** not really lost anything.
35450  */
35451  void (*(*x)(void*,const char*))(void);
35452  UNUSED_PARAMETER(NotUsed);
35453  x = (void(*(*)(void*,const char*))(void))dlsym;
35454  return (*x)(p, zSym);
35455}
35456static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
35457  UNUSED_PARAMETER(NotUsed);
35458  dlclose(pHandle);
35459}
35460#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
35461  #define unixDlOpen  0
35462  #define unixDlError 0
35463  #define unixDlSym   0
35464  #define unixDlClose 0
35465#endif
35466
35467/*
35468** Write nBuf bytes of random data to the supplied buffer zBuf.
35469*/
35470static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
35471  UNUSED_PARAMETER(NotUsed);
35472  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
35473
35474  /* We have to initialize zBuf to prevent valgrind from reporting
35475  ** errors.  The reports issued by valgrind are incorrect - we would
35476  ** prefer that the randomness be increased by making use of the
35477  ** uninitialized space in zBuf - but valgrind errors tend to worry
35478  ** some users.  Rather than argue, it seems easier just to initialize
35479  ** the whole array and silence valgrind, even if that means less randomness
35480  ** in the random seed.
35481  **
35482  ** When testing, initializing zBuf[] to zero is all we do.  That means
35483  ** that we always use the same random number sequence.  This makes the
35484  ** tests repeatable.
35485  */
35486  memset(zBuf, 0, nBuf);
35487  randomnessPid = osGetpid(0);
35488#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
35489  {
35490    int fd, got;
35491    fd = robust_open("/dev/urandom", O_RDONLY, 0);
35492    if( fd<0 ){
35493      time_t t;
35494      time(&t);
35495      memcpy(zBuf, &t, sizeof(t));
35496      memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
35497      assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
35498      nBuf = sizeof(t) + sizeof(randomnessPid);
35499    }else{
35500      do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
35501      robust_close(0, fd, __LINE__);
35502    }
35503  }
35504#endif
35505  return nBuf;
35506}
35507
35508
35509/*
35510** Sleep for a little while.  Return the amount of time slept.
35511** The argument is the number of microseconds we want to sleep.
35512** The return value is the number of microseconds of sleep actually
35513** requested from the underlying operating system, a number which
35514** might be greater than or equal to the argument, but not less
35515** than the argument.
35516*/
35517static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
35518#if OS_VXWORKS
35519  struct timespec sp;
35520
35521  sp.tv_sec = microseconds / 1000000;
35522  sp.tv_nsec = (microseconds % 1000000) * 1000;
35523  nanosleep(&sp, NULL);
35524  UNUSED_PARAMETER(NotUsed);
35525  return microseconds;
35526#elif defined(HAVE_USLEEP) && HAVE_USLEEP
35527  usleep(microseconds);
35528  UNUSED_PARAMETER(NotUsed);
35529  return microseconds;
35530#else
35531  int seconds = (microseconds+999999)/1000000;
35532  sleep(seconds);
35533  UNUSED_PARAMETER(NotUsed);
35534  return seconds*1000000;
35535#endif
35536}
35537
35538/*
35539** The following variable, if set to a non-zero value, is interpreted as
35540** the number of seconds since 1970 and is used to set the result of
35541** sqlite3OsCurrentTime() during testing.
35542*/
35543#ifdef SQLITE_TEST
35544SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
35545#endif
35546
35547/*
35548** Find the current time (in Universal Coordinated Time).  Write into *piNow
35549** the current time and date as a Julian Day number times 86_400_000.  In
35550** other words, write into *piNow the number of milliseconds since the Julian
35551** epoch of noon in Greenwich on November 24, 4714 B.C according to the
35552** proleptic Gregorian calendar.
35553**
35554** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
35555** cannot be found.
35556*/
35557static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
35558  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
35559  int rc = SQLITE_OK;
35560#if defined(NO_GETTOD)
35561  time_t t;
35562  time(&t);
35563  *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
35564#elif OS_VXWORKS
35565  struct timespec sNow;
35566  clock_gettime(CLOCK_REALTIME, &sNow);
35567  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
35568#else
35569  struct timeval sNow;
35570  (void)gettimeofday(&sNow, 0);  /* Cannot fail given valid arguments */
35571  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
35572#endif
35573
35574#ifdef SQLITE_TEST
35575  if( sqlite3_current_time ){
35576    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
35577  }
35578#endif
35579  UNUSED_PARAMETER(NotUsed);
35580  return rc;
35581}
35582
35583#ifndef SQLITE_OMIT_DEPRECATED
35584/*
35585** Find the current time (in Universal Coordinated Time).  Write the
35586** current time and date as a Julian Day number into *prNow and
35587** return 0.  Return 1 if the time and date cannot be found.
35588*/
35589static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
35590  sqlite3_int64 i = 0;
35591  int rc;
35592  UNUSED_PARAMETER(NotUsed);
35593  rc = unixCurrentTimeInt64(0, &i);
35594  *prNow = i/86400000.0;
35595  return rc;
35596}
35597#else
35598# define unixCurrentTime 0
35599#endif
35600
35601/*
35602** The xGetLastError() method is designed to return a better
35603** low-level error message when operating-system problems come up
35604** during SQLite operation.  Only the integer return code is currently
35605** used.
35606*/
35607static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
35608  UNUSED_PARAMETER(NotUsed);
35609  UNUSED_PARAMETER(NotUsed2);
35610  UNUSED_PARAMETER(NotUsed3);
35611  return errno;
35612}
35613
35614
35615/*
35616************************ End of sqlite3_vfs methods ***************************
35617******************************************************************************/
35618
35619/******************************************************************************
35620************************** Begin Proxy Locking ********************************
35621**
35622** Proxy locking is a "uber-locking-method" in this sense:  It uses the
35623** other locking methods on secondary lock files.  Proxy locking is a
35624** meta-layer over top of the primitive locking implemented above.  For
35625** this reason, the division that implements of proxy locking is deferred
35626** until late in the file (here) after all of the other I/O methods have
35627** been defined - so that the primitive locking methods are available
35628** as services to help with the implementation of proxy locking.
35629**
35630****
35631**
35632** The default locking schemes in SQLite use byte-range locks on the
35633** database file to coordinate safe, concurrent access by multiple readers
35634** and writers [http://sqlite.org/lockingv3.html].  The five file locking
35635** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
35636** as POSIX read & write locks over fixed set of locations (via fsctl),
35637** on AFP and SMB only exclusive byte-range locks are available via fsctl
35638** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
35639** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
35640** address in the shared range is taken for a SHARED lock, the entire
35641** shared range is taken for an EXCLUSIVE lock):
35642**
35643**      PENDING_BYTE        0x40000000
35644**      RESERVED_BYTE       0x40000001
35645**      SHARED_RANGE        0x40000002 -> 0x40000200
35646**
35647** This works well on the local file system, but shows a nearly 100x
35648** slowdown in read performance on AFP because the AFP client disables
35649** the read cache when byte-range locks are present.  Enabling the read
35650** cache exposes a cache coherency problem that is present on all OS X
35651** supported network file systems.  NFS and AFP both observe the
35652** close-to-open semantics for ensuring cache coherency
35653** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
35654** address the requirements for concurrent database access by multiple
35655** readers and writers
35656** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
35657**
35658** To address the performance and cache coherency issues, proxy file locking
35659** changes the way database access is controlled by limiting access to a
35660** single host at a time and moving file locks off of the database file
35661** and onto a proxy file on the local file system.
35662**
35663**
35664** Using proxy locks
35665** -----------------
35666**
35667** C APIs
35668**
35669**  sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
35670**                       <proxy_path> | ":auto:");
35671**  sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
35672**                       &<proxy_path>);
35673**
35674**
35675** SQL pragmas
35676**
35677**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
35678**  PRAGMA [database.]lock_proxy_file
35679**
35680** Specifying ":auto:" means that if there is a conch file with a matching
35681** host ID in it, the proxy path in the conch file will be used, otherwise
35682** a proxy path based on the user's temp dir
35683** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
35684** actual proxy file name is generated from the name and path of the
35685** database file.  For example:
35686**
35687**       For database path "/Users/me/foo.db"
35688**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
35689**
35690** Once a lock proxy is configured for a database connection, it can not
35691** be removed, however it may be switched to a different proxy path via
35692** the above APIs (assuming the conch file is not being held by another
35693** connection or process).
35694**
35695**
35696** How proxy locking works
35697** -----------------------
35698**
35699** Proxy file locking relies primarily on two new supporting files:
35700**
35701**   *  conch file to limit access to the database file to a single host
35702**      at a time
35703**
35704**   *  proxy file to act as a proxy for the advisory locks normally
35705**      taken on the database
35706**
35707** The conch file - to use a proxy file, sqlite must first "hold the conch"
35708** by taking an sqlite-style shared lock on the conch file, reading the
35709** contents and comparing the host's unique host ID (see below) and lock
35710** proxy path against the values stored in the conch.  The conch file is
35711** stored in the same directory as the database file and the file name
35712** is patterned after the database file name as ".<databasename>-conch".
35713** If the conch file does not exist, or its contents do not match the
35714** host ID and/or proxy path, then the lock is escalated to an exclusive
35715** lock and the conch file contents is updated with the host ID and proxy
35716** path and the lock is downgraded to a shared lock again.  If the conch
35717** is held by another process (with a shared lock), the exclusive lock
35718** will fail and SQLITE_BUSY is returned.
35719**
35720** The proxy file - a single-byte file used for all advisory file locks
35721** normally taken on the database file.   This allows for safe sharing
35722** of the database file for multiple readers and writers on the same
35723** host (the conch ensures that they all use the same local lock file).
35724**
35725** Requesting the lock proxy does not immediately take the conch, it is
35726** only taken when the first request to lock database file is made.
35727** This matches the semantics of the traditional locking behavior, where
35728** opening a connection to a database file does not take a lock on it.
35729** The shared lock and an open file descriptor are maintained until
35730** the connection to the database is closed.
35731**
35732** The proxy file and the lock file are never deleted so they only need
35733** to be created the first time they are used.
35734**
35735** Configuration options
35736** ---------------------
35737**
35738**  SQLITE_PREFER_PROXY_LOCKING
35739**
35740**       Database files accessed on non-local file systems are
35741**       automatically configured for proxy locking, lock files are
35742**       named automatically using the same logic as
35743**       PRAGMA lock_proxy_file=":auto:"
35744**
35745**  SQLITE_PROXY_DEBUG
35746**
35747**       Enables the logging of error messages during host id file
35748**       retrieval and creation
35749**
35750**  LOCKPROXYDIR
35751**
35752**       Overrides the default directory used for lock proxy files that
35753**       are named automatically via the ":auto:" setting
35754**
35755**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
35756**
35757**       Permissions to use when creating a directory for storing the
35758**       lock proxy files, only used when LOCKPROXYDIR is not set.
35759**
35760**
35761** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
35762** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
35763** force proxy locking to be used for every database file opened, and 0
35764** will force automatic proxy locking to be disabled for all database
35765** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
35766** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
35767*/
35768
35769/*
35770** Proxy locking is only available on MacOSX
35771*/
35772#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35773
35774/*
35775** The proxyLockingContext has the path and file structures for the remote
35776** and local proxy files in it
35777*/
35778typedef struct proxyLockingContext proxyLockingContext;
35779struct proxyLockingContext {
35780  unixFile *conchFile;         /* Open conch file */
35781  char *conchFilePath;         /* Name of the conch file */
35782  unixFile *lockProxy;         /* Open proxy lock file */
35783  char *lockProxyPath;         /* Name of the proxy lock file */
35784  char *dbPath;                /* Name of the open file */
35785  int conchHeld;               /* 1 if the conch is held, -1 if lockless */
35786  int nFails;                  /* Number of conch taking failures */
35787  void *oldLockingContext;     /* Original lockingcontext to restore on close */
35788  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
35789};
35790
35791/*
35792** The proxy lock file path for the database at dbPath is written into lPath,
35793** which must point to valid, writable memory large enough for a maxLen length
35794** file path.
35795*/
35796static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
35797  int len;
35798  int dbLen;
35799  int i;
35800
35801#ifdef LOCKPROXYDIR
35802  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
35803#else
35804# ifdef _CS_DARWIN_USER_TEMP_DIR
35805  {
35806    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
35807      OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
35808               lPath, errno, osGetpid(0)));
35809      return SQLITE_IOERR_LOCK;
35810    }
35811    len = strlcat(lPath, "sqliteplocks", maxLen);
35812  }
35813# else
35814  len = strlcpy(lPath, "/tmp/", maxLen);
35815# endif
35816#endif
35817
35818  if( lPath[len-1]!='/' ){
35819    len = strlcat(lPath, "/", maxLen);
35820  }
35821
35822  /* transform the db path to a unique cache name */
35823  dbLen = (int)strlen(dbPath);
35824  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
35825    char c = dbPath[i];
35826    lPath[i+len] = (c=='/')?'_':c;
35827  }
35828  lPath[i+len]='\0';
35829  strlcat(lPath, ":auto:", maxLen);
35830  OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
35831  return SQLITE_OK;
35832}
35833
35834/*
35835 ** Creates the lock file and any missing directories in lockPath
35836 */
35837static int proxyCreateLockPath(const char *lockPath){
35838  int i, len;
35839  char buf[MAXPATHLEN];
35840  int start = 0;
35841
35842  assert(lockPath!=NULL);
35843  /* try to create all the intermediate directories */
35844  len = (int)strlen(lockPath);
35845  buf[0] = lockPath[0];
35846  for( i=1; i<len; i++ ){
35847    if( lockPath[i] == '/' && (i - start > 0) ){
35848      /* only mkdir if leaf dir != "." or "/" or ".." */
35849      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
35850         || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
35851        buf[i]='\0';
35852        if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
35853          int err=errno;
35854          if( err!=EEXIST ) {
35855            OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
35856                     "'%s' proxy lock path=%s pid=%d\n",
35857                     buf, strerror(err), lockPath, osGetpid(0)));
35858            return err;
35859          }
35860        }
35861      }
35862      start=i+1;
35863    }
35864    buf[i] = lockPath[i];
35865  }
35866  OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
35867  return 0;
35868}
35869
35870/*
35871** Create a new VFS file descriptor (stored in memory obtained from
35872** sqlite3_malloc) and open the file named "path" in the file descriptor.
35873**
35874** The caller is responsible not only for closing the file descriptor
35875** but also for freeing the memory associated with the file descriptor.
35876*/
35877static int proxyCreateUnixFile(
35878    const char *path,        /* path for the new unixFile */
35879    unixFile **ppFile,       /* unixFile created and returned by ref */
35880    int islockfile           /* if non zero missing dirs will be created */
35881) {
35882  int fd = -1;
35883  unixFile *pNew;
35884  int rc = SQLITE_OK;
35885  int openFlags = O_RDWR | O_CREAT;
35886  sqlite3_vfs dummyVfs;
35887  int terrno = 0;
35888  UnixUnusedFd *pUnused = NULL;
35889
35890  /* 1. first try to open/create the file
35891  ** 2. if that fails, and this is a lock file (not-conch), try creating
35892  ** the parent directories and then try again.
35893  ** 3. if that fails, try to open the file read-only
35894  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
35895  */
35896  pUnused = findReusableFd(path, openFlags);
35897  if( pUnused ){
35898    fd = pUnused->fd;
35899  }else{
35900    pUnused = sqlite3_malloc64(sizeof(*pUnused));
35901    if( !pUnused ){
35902      return SQLITE_NOMEM_BKPT;
35903    }
35904  }
35905  if( fd<0 ){
35906    fd = robust_open(path, openFlags, 0);
35907    terrno = errno;
35908    if( fd<0 && errno==ENOENT && islockfile ){
35909      if( proxyCreateLockPath(path) == SQLITE_OK ){
35910        fd = robust_open(path, openFlags, 0);
35911      }
35912    }
35913  }
35914  if( fd<0 ){
35915    openFlags = O_RDONLY;
35916    fd = robust_open(path, openFlags, 0);
35917    terrno = errno;
35918  }
35919  if( fd<0 ){
35920    if( islockfile ){
35921      return SQLITE_BUSY;
35922    }
35923    switch (terrno) {
35924      case EACCES:
35925        return SQLITE_PERM;
35926      case EIO:
35927        return SQLITE_IOERR_LOCK; /* even though it is the conch */
35928      default:
35929        return SQLITE_CANTOPEN_BKPT;
35930    }
35931  }
35932
35933  pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
35934  if( pNew==NULL ){
35935    rc = SQLITE_NOMEM_BKPT;
35936    goto end_create_proxy;
35937  }
35938  memset(pNew, 0, sizeof(unixFile));
35939  pNew->openFlags = openFlags;
35940  memset(&dummyVfs, 0, sizeof(dummyVfs));
35941  dummyVfs.pAppData = (void*)&autolockIoFinder;
35942  dummyVfs.zName = "dummy";
35943  pUnused->fd = fd;
35944  pUnused->flags = openFlags;
35945  pNew->pUnused = pUnused;
35946
35947  rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
35948  if( rc==SQLITE_OK ){
35949    *ppFile = pNew;
35950    return SQLITE_OK;
35951  }
35952end_create_proxy:
35953  robust_close(pNew, fd, __LINE__);
35954  sqlite3_free(pNew);
35955  sqlite3_free(pUnused);
35956  return rc;
35957}
35958
35959#ifdef SQLITE_TEST
35960/* simulate multiple hosts by creating unique hostid file paths */
35961SQLITE_API int sqlite3_hostid_num = 0;
35962#endif
35963
35964#define PROXY_HOSTIDLEN    16  /* conch file host id length */
35965
35966#ifdef HAVE_GETHOSTUUID
35967/* Not always defined in the headers as it ought to be */
35968extern int gethostuuid(uuid_t id, const struct timespec *wait);
35969#endif
35970
35971/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
35972** bytes of writable memory.
35973*/
35974static int proxyGetHostID(unsigned char *pHostID, int *pError){
35975  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
35976  memset(pHostID, 0, PROXY_HOSTIDLEN);
35977#ifdef HAVE_GETHOSTUUID
35978  {
35979    struct timespec timeout = {1, 0}; /* 1 sec timeout */
35980    if( gethostuuid(pHostID, &timeout) ){
35981      int err = errno;
35982      if( pError ){
35983        *pError = err;
35984      }
35985      return SQLITE_IOERR;
35986    }
35987  }
35988#else
35989  UNUSED_PARAMETER(pError);
35990#endif
35991#ifdef SQLITE_TEST
35992  /* simulate multiple hosts by creating unique hostid file paths */
35993  if( sqlite3_hostid_num != 0){
35994    pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
35995  }
35996#endif
35997
35998  return SQLITE_OK;
35999}
36000
36001/* The conch file contains the header, host id and lock file path
36002 */
36003#define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
36004#define PROXY_HEADERLEN    1   /* conch file header length */
36005#define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
36006#define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
36007
36008/*
36009** Takes an open conch file, copies the contents to a new path and then moves
36010** it back.  The newly created file's file descriptor is assigned to the
36011** conch file structure and finally the original conch file descriptor is
36012** closed.  Returns zero if successful.
36013*/
36014static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
36015  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36016  unixFile *conchFile = pCtx->conchFile;
36017  char tPath[MAXPATHLEN];
36018  char buf[PROXY_MAXCONCHLEN];
36019  char *cPath = pCtx->conchFilePath;
36020  size_t readLen = 0;
36021  size_t pathLen = 0;
36022  char errmsg[64] = "";
36023  int fd = -1;
36024  int rc = -1;
36025  UNUSED_PARAMETER(myHostID);
36026
36027  /* create a new path by replace the trailing '-conch' with '-break' */
36028  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
36029  if( pathLen>MAXPATHLEN || pathLen<6 ||
36030     (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
36031    sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
36032    goto end_breaklock;
36033  }
36034  /* read the conch content */
36035  readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
36036  if( readLen<PROXY_PATHINDEX ){
36037    sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
36038    goto end_breaklock;
36039  }
36040  /* write it out to the temporary break file */
36041  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
36042  if( fd<0 ){
36043    sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
36044    goto end_breaklock;
36045  }
36046  if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
36047    sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
36048    goto end_breaklock;
36049  }
36050  if( rename(tPath, cPath) ){
36051    sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
36052    goto end_breaklock;
36053  }
36054  rc = 0;
36055  fprintf(stderr, "broke stale lock on %s\n", cPath);
36056  robust_close(pFile, conchFile->h, __LINE__);
36057  conchFile->h = fd;
36058  conchFile->openFlags = O_RDWR | O_CREAT;
36059
36060end_breaklock:
36061  if( rc ){
36062    if( fd>=0 ){
36063      osUnlink(tPath);
36064      robust_close(pFile, fd, __LINE__);
36065    }
36066    fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
36067  }
36068  return rc;
36069}
36070
36071/* Take the requested lock on the conch file and break a stale lock if the
36072** host id matches.
36073*/
36074static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
36075  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36076  unixFile *conchFile = pCtx->conchFile;
36077  int rc = SQLITE_OK;
36078  int nTries = 0;
36079  struct timespec conchModTime;
36080
36081  memset(&conchModTime, 0, sizeof(conchModTime));
36082  do {
36083    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
36084    nTries ++;
36085    if( rc==SQLITE_BUSY ){
36086      /* If the lock failed (busy):
36087       * 1st try: get the mod time of the conch, wait 0.5s and try again.
36088       * 2nd try: fail if the mod time changed or host id is different, wait
36089       *           10 sec and try again
36090       * 3rd try: break the lock unless the mod time has changed.
36091       */
36092      struct stat buf;
36093      if( osFstat(conchFile->h, &buf) ){
36094        storeLastErrno(pFile, errno);
36095        return SQLITE_IOERR_LOCK;
36096      }
36097
36098      if( nTries==1 ){
36099        conchModTime = buf.st_mtimespec;
36100        usleep(500000); /* wait 0.5 sec and try the lock again*/
36101        continue;
36102      }
36103
36104      assert( nTries>1 );
36105      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
36106         conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
36107        return SQLITE_BUSY;
36108      }
36109
36110      if( nTries==2 ){
36111        char tBuf[PROXY_MAXCONCHLEN];
36112        int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
36113        if( len<0 ){
36114          storeLastErrno(pFile, errno);
36115          return SQLITE_IOERR_LOCK;
36116        }
36117        if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
36118          /* don't break the lock if the host id doesn't match */
36119          if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
36120            return SQLITE_BUSY;
36121          }
36122        }else{
36123          /* don't break the lock on short read or a version mismatch */
36124          return SQLITE_BUSY;
36125        }
36126        usleep(10000000); /* wait 10 sec and try the lock again */
36127        continue;
36128      }
36129
36130      assert( nTries==3 );
36131      if( 0==proxyBreakConchLock(pFile, myHostID) ){
36132        rc = SQLITE_OK;
36133        if( lockType==EXCLUSIVE_LOCK ){
36134          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
36135        }
36136        if( !rc ){
36137          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
36138        }
36139      }
36140    }
36141  } while( rc==SQLITE_BUSY && nTries<3 );
36142
36143  return rc;
36144}
36145
36146/* Takes the conch by taking a shared lock and read the contents conch, if
36147** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
36148** lockPath means that the lockPath in the conch file will be used if the
36149** host IDs match, or a new lock path will be generated automatically
36150** and written to the conch file.
36151*/
36152static int proxyTakeConch(unixFile *pFile){
36153  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36154
36155  if( pCtx->conchHeld!=0 ){
36156    return SQLITE_OK;
36157  }else{
36158    unixFile *conchFile = pCtx->conchFile;
36159    uuid_t myHostID;
36160    int pError = 0;
36161    char readBuf[PROXY_MAXCONCHLEN];
36162    char lockPath[MAXPATHLEN];
36163    char *tempLockPath = NULL;
36164    int rc = SQLITE_OK;
36165    int createConch = 0;
36166    int hostIdMatch = 0;
36167    int readLen = 0;
36168    int tryOldLockPath = 0;
36169    int forceNewLockPath = 0;
36170
36171    OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
36172             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
36173             osGetpid(0)));
36174
36175    rc = proxyGetHostID(myHostID, &pError);
36176    if( (rc&0xff)==SQLITE_IOERR ){
36177      storeLastErrno(pFile, pError);
36178      goto end_takeconch;
36179    }
36180    rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
36181    if( rc!=SQLITE_OK ){
36182      goto end_takeconch;
36183    }
36184    /* read the existing conch file */
36185    readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
36186    if( readLen<0 ){
36187      /* I/O error: lastErrno set by seekAndRead */
36188      storeLastErrno(pFile, conchFile->lastErrno);
36189      rc = SQLITE_IOERR_READ;
36190      goto end_takeconch;
36191    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
36192             readBuf[0]!=(char)PROXY_CONCHVERSION ){
36193      /* a short read or version format mismatch means we need to create a new
36194      ** conch file.
36195      */
36196      createConch = 1;
36197    }
36198    /* if the host id matches and the lock path already exists in the conch
36199    ** we'll try to use the path there, if we can't open that path, we'll
36200    ** retry with a new auto-generated path
36201    */
36202    do { /* in case we need to try again for an :auto: named lock file */
36203
36204      if( !createConch && !forceNewLockPath ){
36205        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
36206                                  PROXY_HOSTIDLEN);
36207        /* if the conch has data compare the contents */
36208        if( !pCtx->lockProxyPath ){
36209          /* for auto-named local lock file, just check the host ID and we'll
36210           ** use the local lock file path that's already in there
36211           */
36212          if( hostIdMatch ){
36213            size_t pathLen = (readLen - PROXY_PATHINDEX);
36214
36215            if( pathLen>=MAXPATHLEN ){
36216              pathLen=MAXPATHLEN-1;
36217            }
36218            memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
36219            lockPath[pathLen] = 0;
36220            tempLockPath = lockPath;
36221            tryOldLockPath = 1;
36222            /* create a copy of the lock path if the conch is taken */
36223            goto end_takeconch;
36224          }
36225        }else if( hostIdMatch
36226               && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
36227                           readLen-PROXY_PATHINDEX)
36228        ){
36229          /* conch host and lock path match */
36230          goto end_takeconch;
36231        }
36232      }
36233
36234      /* if the conch isn't writable and doesn't match, we can't take it */
36235      if( (conchFile->openFlags&O_RDWR) == 0 ){
36236        rc = SQLITE_BUSY;
36237        goto end_takeconch;
36238      }
36239
36240      /* either the conch didn't match or we need to create a new one */
36241      if( !pCtx->lockProxyPath ){
36242        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
36243        tempLockPath = lockPath;
36244        /* create a copy of the lock path _only_ if the conch is taken */
36245      }
36246
36247      /* update conch with host and path (this will fail if other process
36248      ** has a shared lock already), if the host id matches, use the big
36249      ** stick.
36250      */
36251      futimes(conchFile->h, NULL);
36252      if( hostIdMatch && !createConch ){
36253        if( conchFile->pInode && conchFile->pInode->nShared>1 ){
36254          /* We are trying for an exclusive lock but another thread in this
36255           ** same process is still holding a shared lock. */
36256          rc = SQLITE_BUSY;
36257        } else {
36258          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
36259        }
36260      }else{
36261        rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
36262      }
36263      if( rc==SQLITE_OK ){
36264        char writeBuffer[PROXY_MAXCONCHLEN];
36265        int writeSize = 0;
36266
36267        writeBuffer[0] = (char)PROXY_CONCHVERSION;
36268        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
36269        if( pCtx->lockProxyPath!=NULL ){
36270          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
36271                  MAXPATHLEN);
36272        }else{
36273          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
36274        }
36275        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
36276        robust_ftruncate(conchFile->h, writeSize);
36277        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
36278        full_fsync(conchFile->h,0,0);
36279        /* If we created a new conch file (not just updated the contents of a
36280         ** valid conch file), try to match the permissions of the database
36281         */
36282        if( rc==SQLITE_OK && createConch ){
36283          struct stat buf;
36284          int err = osFstat(pFile->h, &buf);
36285          if( err==0 ){
36286            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
36287                                        S_IROTH|S_IWOTH);
36288            /* try to match the database file R/W permissions, ignore failure */
36289#ifndef SQLITE_PROXY_DEBUG
36290            osFchmod(conchFile->h, cmode);
36291#else
36292            do{
36293              rc = osFchmod(conchFile->h, cmode);
36294            }while( rc==(-1) && errno==EINTR );
36295            if( rc!=0 ){
36296              int code = errno;
36297              fprintf(stderr, "fchmod %o FAILED with %d %s\n",
36298                      cmode, code, strerror(code));
36299            } else {
36300              fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
36301            }
36302          }else{
36303            int code = errno;
36304            fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
36305                    err, code, strerror(code));
36306#endif
36307          }
36308        }
36309      }
36310      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
36311
36312    end_takeconch:
36313      OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
36314      if( rc==SQLITE_OK && pFile->openFlags ){
36315        int fd;
36316        if( pFile->h>=0 ){
36317          robust_close(pFile, pFile->h, __LINE__);
36318        }
36319        pFile->h = -1;
36320        fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
36321        OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
36322        if( fd>=0 ){
36323          pFile->h = fd;
36324        }else{
36325          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
36326           during locking */
36327        }
36328      }
36329      if( rc==SQLITE_OK && !pCtx->lockProxy ){
36330        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
36331        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
36332        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
36333          /* we couldn't create the proxy lock file with the old lock file path
36334           ** so try again via auto-naming
36335           */
36336          forceNewLockPath = 1;
36337          tryOldLockPath = 0;
36338          continue; /* go back to the do {} while start point, try again */
36339        }
36340      }
36341      if( rc==SQLITE_OK ){
36342        /* Need to make a copy of path if we extracted the value
36343         ** from the conch file or the path was allocated on the stack
36344         */
36345        if( tempLockPath ){
36346          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
36347          if( !pCtx->lockProxyPath ){
36348            rc = SQLITE_NOMEM_BKPT;
36349          }
36350        }
36351      }
36352      if( rc==SQLITE_OK ){
36353        pCtx->conchHeld = 1;
36354
36355        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
36356          afpLockingContext *afpCtx;
36357          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
36358          afpCtx->dbPath = pCtx->lockProxyPath;
36359        }
36360      } else {
36361        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
36362      }
36363      OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
36364               rc==SQLITE_OK?"ok":"failed"));
36365      return rc;
36366    } while (1); /* in case we need to retry the :auto: lock file -
36367                 ** we should never get here except via the 'continue' call. */
36368  }
36369}
36370
36371/*
36372** If pFile holds a lock on a conch file, then release that lock.
36373*/
36374static int proxyReleaseConch(unixFile *pFile){
36375  int rc = SQLITE_OK;         /* Subroutine return code */
36376  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
36377  unixFile *conchFile;        /* Name of the conch file */
36378
36379  pCtx = (proxyLockingContext *)pFile->lockingContext;
36380  conchFile = pCtx->conchFile;
36381  OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
36382           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
36383           osGetpid(0)));
36384  if( pCtx->conchHeld>0 ){
36385    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
36386  }
36387  pCtx->conchHeld = 0;
36388  OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
36389           (rc==SQLITE_OK ? "ok" : "failed")));
36390  return rc;
36391}
36392
36393/*
36394** Given the name of a database file, compute the name of its conch file.
36395** Store the conch filename in memory obtained from sqlite3_malloc64().
36396** Make *pConchPath point to the new name.  Return SQLITE_OK on success
36397** or SQLITE_NOMEM if unable to obtain memory.
36398**
36399** The caller is responsible for ensuring that the allocated memory
36400** space is eventually freed.
36401**
36402** *pConchPath is set to NULL if a memory allocation error occurs.
36403*/
36404static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
36405  int i;                        /* Loop counter */
36406  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
36407  char *conchPath;              /* buffer in which to construct conch name */
36408
36409  /* Allocate space for the conch filename and initialize the name to
36410  ** the name of the original database file. */
36411  *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
36412  if( conchPath==0 ){
36413    return SQLITE_NOMEM_BKPT;
36414  }
36415  memcpy(conchPath, dbPath, len+1);
36416
36417  /* now insert a "." before the last / character */
36418  for( i=(len-1); i>=0; i-- ){
36419    if( conchPath[i]=='/' ){
36420      i++;
36421      break;
36422    }
36423  }
36424  conchPath[i]='.';
36425  while ( i<len ){
36426    conchPath[i+1]=dbPath[i];
36427    i++;
36428  }
36429
36430  /* append the "-conch" suffix to the file */
36431  memcpy(&conchPath[i+1], "-conch", 7);
36432  assert( (int)strlen(conchPath) == len+7 );
36433
36434  return SQLITE_OK;
36435}
36436
36437
36438/* Takes a fully configured proxy locking-style unix file and switches
36439** the local lock file path
36440*/
36441static int switchLockProxyPath(unixFile *pFile, const char *path) {
36442  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
36443  char *oldPath = pCtx->lockProxyPath;
36444  int rc = SQLITE_OK;
36445
36446  if( pFile->eFileLock!=NO_LOCK ){
36447    return SQLITE_BUSY;
36448  }
36449
36450  /* nothing to do if the path is NULL, :auto: or matches the existing path */
36451  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
36452    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
36453    return SQLITE_OK;
36454  }else{
36455    unixFile *lockProxy = pCtx->lockProxy;
36456    pCtx->lockProxy=NULL;
36457    pCtx->conchHeld = 0;
36458    if( lockProxy!=NULL ){
36459      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
36460      if( rc ) return rc;
36461      sqlite3_free(lockProxy);
36462    }
36463    sqlite3_free(oldPath);
36464    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
36465  }
36466
36467  return rc;
36468}
36469
36470/*
36471** pFile is a file that has been opened by a prior xOpen call.  dbPath
36472** is a string buffer at least MAXPATHLEN+1 characters in size.
36473**
36474** This routine find the filename associated with pFile and writes it
36475** int dbPath.
36476*/
36477static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
36478#if defined(__APPLE__)
36479  if( pFile->pMethod == &afpIoMethods ){
36480    /* afp style keeps a reference to the db path in the filePath field
36481    ** of the struct */
36482    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
36483    strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
36484            MAXPATHLEN);
36485  } else
36486#endif
36487  if( pFile->pMethod == &dotlockIoMethods ){
36488    /* dot lock style uses the locking context to store the dot lock
36489    ** file path */
36490    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
36491    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
36492  }else{
36493    /* all other styles use the locking context to store the db file path */
36494    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
36495    strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
36496  }
36497  return SQLITE_OK;
36498}
36499
36500/*
36501** Takes an already filled in unix file and alters it so all file locking
36502** will be performed on the local proxy lock file.  The following fields
36503** are preserved in the locking context so that they can be restored and
36504** the unix structure properly cleaned up at close time:
36505**  ->lockingContext
36506**  ->pMethod
36507*/
36508static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
36509  proxyLockingContext *pCtx;
36510  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
36511  char *lockPath=NULL;
36512  int rc = SQLITE_OK;
36513
36514  if( pFile->eFileLock!=NO_LOCK ){
36515    return SQLITE_BUSY;
36516  }
36517  proxyGetDbPathForUnixFile(pFile, dbPath);
36518  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
36519    lockPath=NULL;
36520  }else{
36521    lockPath=(char *)path;
36522  }
36523
36524  OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
36525           (lockPath ? lockPath : ":auto:"), osGetpid(0)));
36526
36527  pCtx = sqlite3_malloc64( sizeof(*pCtx) );
36528  if( pCtx==0 ){
36529    return SQLITE_NOMEM_BKPT;
36530  }
36531  memset(pCtx, 0, sizeof(*pCtx));
36532
36533  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
36534  if( rc==SQLITE_OK ){
36535    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
36536    if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
36537      /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
36538      ** (c) the file system is read-only, then enable no-locking access.
36539      ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
36540      ** that openFlags will have only one of O_RDONLY or O_RDWR.
36541      */
36542      struct statfs fsInfo;
36543      struct stat conchInfo;
36544      int goLockless = 0;
36545
36546      if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
36547        int err = errno;
36548        if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
36549          goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
36550        }
36551      }
36552      if( goLockless ){
36553        pCtx->conchHeld = -1; /* read only FS/ lockless */
36554        rc = SQLITE_OK;
36555      }
36556    }
36557  }
36558  if( rc==SQLITE_OK && lockPath ){
36559    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
36560  }
36561
36562  if( rc==SQLITE_OK ){
36563    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
36564    if( pCtx->dbPath==NULL ){
36565      rc = SQLITE_NOMEM_BKPT;
36566    }
36567  }
36568  if( rc==SQLITE_OK ){
36569    /* all memory is allocated, proxys are created and assigned,
36570    ** switch the locking context and pMethod then return.
36571    */
36572    pCtx->oldLockingContext = pFile->lockingContext;
36573    pFile->lockingContext = pCtx;
36574    pCtx->pOldMethod = pFile->pMethod;
36575    pFile->pMethod = &proxyIoMethods;
36576  }else{
36577    if( pCtx->conchFile ){
36578      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
36579      sqlite3_free(pCtx->conchFile);
36580    }
36581    sqlite3DbFree(0, pCtx->lockProxyPath);
36582    sqlite3_free(pCtx->conchFilePath);
36583    sqlite3_free(pCtx);
36584  }
36585  OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
36586           (rc==SQLITE_OK ? "ok" : "failed")));
36587  return rc;
36588}
36589
36590
36591/*
36592** This routine handles sqlite3_file_control() calls that are specific
36593** to proxy locking.
36594*/
36595static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
36596  switch( op ){
36597    case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
36598      unixFile *pFile = (unixFile*)id;
36599      if( pFile->pMethod == &proxyIoMethods ){
36600        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
36601        proxyTakeConch(pFile);
36602        if( pCtx->lockProxyPath ){
36603          *(const char **)pArg = pCtx->lockProxyPath;
36604        }else{
36605          *(const char **)pArg = ":auto: (not held)";
36606        }
36607      } else {
36608        *(const char **)pArg = NULL;
36609      }
36610      return SQLITE_OK;
36611    }
36612    case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
36613      unixFile *pFile = (unixFile*)id;
36614      int rc = SQLITE_OK;
36615      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
36616      if( pArg==NULL || (const char *)pArg==0 ){
36617        if( isProxyStyle ){
36618          /* turn off proxy locking - not supported.  If support is added for
36619          ** switching proxy locking mode off then it will need to fail if
36620          ** the journal mode is WAL mode.
36621          */
36622          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
36623        }else{
36624          /* turn off proxy locking - already off - NOOP */
36625          rc = SQLITE_OK;
36626        }
36627      }else{
36628        const char *proxyPath = (const char *)pArg;
36629        if( isProxyStyle ){
36630          proxyLockingContext *pCtx =
36631            (proxyLockingContext*)pFile->lockingContext;
36632          if( !strcmp(pArg, ":auto:")
36633           || (pCtx->lockProxyPath &&
36634               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
36635          ){
36636            rc = SQLITE_OK;
36637          }else{
36638            rc = switchLockProxyPath(pFile, proxyPath);
36639          }
36640        }else{
36641          /* turn on proxy file locking */
36642          rc = proxyTransformUnixFile(pFile, proxyPath);
36643        }
36644      }
36645      return rc;
36646    }
36647    default: {
36648      assert( 0 );  /* The call assures that only valid opcodes are sent */
36649    }
36650  }
36651  /*NOTREACHED*/
36652  return SQLITE_ERROR;
36653}
36654
36655/*
36656** Within this division (the proxying locking implementation) the procedures
36657** above this point are all utilities.  The lock-related methods of the
36658** proxy-locking sqlite3_io_method object follow.
36659*/
36660
36661
36662/*
36663** This routine checks if there is a RESERVED lock held on the specified
36664** file by this or any other process. If such a lock is held, set *pResOut
36665** to a non-zero value otherwise *pResOut is set to zero.  The return value
36666** is set to SQLITE_OK unless an I/O error occurs during lock checking.
36667*/
36668static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
36669  unixFile *pFile = (unixFile*)id;
36670  int rc = proxyTakeConch(pFile);
36671  if( rc==SQLITE_OK ){
36672    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36673    if( pCtx->conchHeld>0 ){
36674      unixFile *proxy = pCtx->lockProxy;
36675      return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
36676    }else{ /* conchHeld < 0 is lockless */
36677      pResOut=0;
36678    }
36679  }
36680  return rc;
36681}
36682
36683/*
36684** Lock the file with the lock specified by parameter eFileLock - one
36685** of the following:
36686**
36687**     (1) SHARED_LOCK
36688**     (2) RESERVED_LOCK
36689**     (3) PENDING_LOCK
36690**     (4) EXCLUSIVE_LOCK
36691**
36692** Sometimes when requesting one lock state, additional lock states
36693** are inserted in between.  The locking might fail on one of the later
36694** transitions leaving the lock state different from what it started but
36695** still short of its goal.  The following chart shows the allowed
36696** transitions and the inserted intermediate states:
36697**
36698**    UNLOCKED -> SHARED
36699**    SHARED -> RESERVED
36700**    SHARED -> (PENDING) -> EXCLUSIVE
36701**    RESERVED -> (PENDING) -> EXCLUSIVE
36702**    PENDING -> EXCLUSIVE
36703**
36704** This routine will only increase a lock.  Use the sqlite3OsUnlock()
36705** routine to lower a locking level.
36706*/
36707static int proxyLock(sqlite3_file *id, int eFileLock) {
36708  unixFile *pFile = (unixFile*)id;
36709  int rc = proxyTakeConch(pFile);
36710  if( rc==SQLITE_OK ){
36711    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36712    if( pCtx->conchHeld>0 ){
36713      unixFile *proxy = pCtx->lockProxy;
36714      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
36715      pFile->eFileLock = proxy->eFileLock;
36716    }else{
36717      /* conchHeld < 0 is lockless */
36718    }
36719  }
36720  return rc;
36721}
36722
36723
36724/*
36725** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
36726** must be either NO_LOCK or SHARED_LOCK.
36727**
36728** If the locking level of the file descriptor is already at or below
36729** the requested locking level, this routine is a no-op.
36730*/
36731static int proxyUnlock(sqlite3_file *id, int eFileLock) {
36732  unixFile *pFile = (unixFile*)id;
36733  int rc = proxyTakeConch(pFile);
36734  if( rc==SQLITE_OK ){
36735    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36736    if( pCtx->conchHeld>0 ){
36737      unixFile *proxy = pCtx->lockProxy;
36738      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
36739      pFile->eFileLock = proxy->eFileLock;
36740    }else{
36741      /* conchHeld < 0 is lockless */
36742    }
36743  }
36744  return rc;
36745}
36746
36747/*
36748** Close a file that uses proxy locks.
36749*/
36750static int proxyClose(sqlite3_file *id) {
36751  if( ALWAYS(id) ){
36752    unixFile *pFile = (unixFile*)id;
36753    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36754    unixFile *lockProxy = pCtx->lockProxy;
36755    unixFile *conchFile = pCtx->conchFile;
36756    int rc = SQLITE_OK;
36757
36758    if( lockProxy ){
36759      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
36760      if( rc ) return rc;
36761      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
36762      if( rc ) return rc;
36763      sqlite3_free(lockProxy);
36764      pCtx->lockProxy = 0;
36765    }
36766    if( conchFile ){
36767      if( pCtx->conchHeld ){
36768        rc = proxyReleaseConch(pFile);
36769        if( rc ) return rc;
36770      }
36771      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
36772      if( rc ) return rc;
36773      sqlite3_free(conchFile);
36774    }
36775    sqlite3DbFree(0, pCtx->lockProxyPath);
36776    sqlite3_free(pCtx->conchFilePath);
36777    sqlite3DbFree(0, pCtx->dbPath);
36778    /* restore the original locking context and pMethod then close it */
36779    pFile->lockingContext = pCtx->oldLockingContext;
36780    pFile->pMethod = pCtx->pOldMethod;
36781    sqlite3_free(pCtx);
36782    return pFile->pMethod->xClose(id);
36783  }
36784  return SQLITE_OK;
36785}
36786
36787
36788
36789#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
36790/*
36791** The proxy locking style is intended for use with AFP filesystems.
36792** And since AFP is only supported on MacOSX, the proxy locking is also
36793** restricted to MacOSX.
36794**
36795**
36796******************* End of the proxy lock implementation **********************
36797******************************************************************************/
36798
36799/*
36800** Initialize the operating system interface.
36801**
36802** This routine registers all VFS implementations for unix-like operating
36803** systems.  This routine, and the sqlite3_os_end() routine that follows,
36804** should be the only routines in this file that are visible from other
36805** files.
36806**
36807** This routine is called once during SQLite initialization and by a
36808** single thread.  The memory allocation and mutex subsystems have not
36809** necessarily been initialized when this routine is called, and so they
36810** should not be used.
36811*/
36812SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
36813  /*
36814  ** The following macro defines an initializer for an sqlite3_vfs object.
36815  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
36816  ** to the "finder" function.  (pAppData is a pointer to a pointer because
36817  ** silly C90 rules prohibit a void* from being cast to a function pointer
36818  ** and so we have to go through the intermediate pointer to avoid problems
36819  ** when compiling with -pedantic-errors on GCC.)
36820  **
36821  ** The FINDER parameter to this macro is the name of the pointer to the
36822  ** finder-function.  The finder-function returns a pointer to the
36823  ** sqlite_io_methods object that implements the desired locking
36824  ** behaviors.  See the division above that contains the IOMETHODS
36825  ** macro for addition information on finder-functions.
36826  **
36827  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
36828  ** object.  But the "autolockIoFinder" available on MacOSX does a little
36829  ** more than that; it looks at the filesystem type that hosts the
36830  ** database file and tries to choose an locking method appropriate for
36831  ** that filesystem time.
36832  */
36833  #define UNIXVFS(VFSNAME, FINDER) {                        \
36834    3,                    /* iVersion */                    \
36835    sizeof(unixFile),     /* szOsFile */                    \
36836    MAX_PATHNAME,         /* mxPathname */                  \
36837    0,                    /* pNext */                       \
36838    VFSNAME,              /* zName */                       \
36839    (void*)&FINDER,       /* pAppData */                    \
36840    unixOpen,             /* xOpen */                       \
36841    unixDelete,           /* xDelete */                     \
36842    unixAccess,           /* xAccess */                     \
36843    unixFullPathname,     /* xFullPathname */               \
36844    unixDlOpen,           /* xDlOpen */                     \
36845    unixDlError,          /* xDlError */                    \
36846    unixDlSym,            /* xDlSym */                      \
36847    unixDlClose,          /* xDlClose */                    \
36848    unixRandomness,       /* xRandomness */                 \
36849    unixSleep,            /* xSleep */                      \
36850    unixCurrentTime,      /* xCurrentTime */                \
36851    unixGetLastError,     /* xGetLastError */               \
36852    unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
36853    unixSetSystemCall,    /* xSetSystemCall */              \
36854    unixGetSystemCall,    /* xGetSystemCall */              \
36855    unixNextSystemCall,   /* xNextSystemCall */             \
36856  }
36857
36858  /*
36859  ** All default VFSes for unix are contained in the following array.
36860  **
36861  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
36862  ** by the SQLite core when the VFS is registered.  So the following
36863  ** array cannot be const.
36864  */
36865  static sqlite3_vfs aVfs[] = {
36866#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
36867    UNIXVFS("unix",          autolockIoFinder ),
36868#elif OS_VXWORKS
36869    UNIXVFS("unix",          vxworksIoFinder ),
36870#else
36871    UNIXVFS("unix",          posixIoFinder ),
36872#endif
36873    UNIXVFS("unix-none",     nolockIoFinder ),
36874    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
36875    UNIXVFS("unix-excl",     posixIoFinder ),
36876#if OS_VXWORKS
36877    UNIXVFS("unix-namedsem", semIoFinder ),
36878#endif
36879#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
36880    UNIXVFS("unix-posix",    posixIoFinder ),
36881#endif
36882#if SQLITE_ENABLE_LOCKING_STYLE
36883    UNIXVFS("unix-flock",    flockIoFinder ),
36884#endif
36885#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
36886    UNIXVFS("unix-afp",      afpIoFinder ),
36887    UNIXVFS("unix-nfs",      nfsIoFinder ),
36888    UNIXVFS("unix-proxy",    proxyIoFinder ),
36889#endif
36890  };
36891  unsigned int i;          /* Loop counter */
36892
36893  /* Double-check that the aSyscall[] array has been constructed
36894  ** correctly.  See ticket [bb3a86e890c8e96ab] */
36895  assert( ArraySize(aSyscall)==28 );
36896
36897  /* Register all VFSes defined in the aVfs[] array */
36898  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
36899    sqlite3_vfs_register(&aVfs[i], i==0);
36900  }
36901  return SQLITE_OK;
36902}
36903
36904/*
36905** Shutdown the operating system interface.
36906**
36907** Some operating systems might need to do some cleanup in this routine,
36908** to release dynamically allocated objects.  But not on unix.
36909** This routine is a no-op for unix.
36910*/
36911SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
36912  return SQLITE_OK;
36913}
36914
36915#endif /* SQLITE_OS_UNIX */
36916
36917/************** End of os_unix.c *********************************************/
36918/************** Begin file os_win.c ******************************************/
36919/*
36920** 2004 May 22
36921**
36922** The author disclaims copyright to this source code.  In place of
36923** a legal notice, here is a blessing:
36924**
36925**    May you do good and not evil.
36926**    May you find forgiveness for yourself and forgive others.
36927**    May you share freely, never taking more than you give.
36928**
36929******************************************************************************
36930**
36931** This file contains code that is specific to Windows.
36932*/
36933/* #include "sqliteInt.h" */
36934#if SQLITE_OS_WIN               /* This file is used for Windows only */
36935
36936/*
36937** Include code that is common to all os_*.c files
36938*/
36939/************** Include os_common.h in the middle of os_win.c ****************/
36940/************** Begin file os_common.h ***************************************/
36941/*
36942** 2004 May 22
36943**
36944** The author disclaims copyright to this source code.  In place of
36945** a legal notice, here is a blessing:
36946**
36947**    May you do good and not evil.
36948**    May you find forgiveness for yourself and forgive others.
36949**    May you share freely, never taking more than you give.
36950**
36951******************************************************************************
36952**
36953** This file contains macros and a little bit of code that is common to
36954** all of the platform-specific files (os_*.c) and is #included into those
36955** files.
36956**
36957** This file should be #included by the os_*.c files only.  It is not a
36958** general purpose header file.
36959*/
36960#ifndef _OS_COMMON_H_
36961#define _OS_COMMON_H_
36962
36963/*
36964** At least two bugs have slipped in because we changed the MEMORY_DEBUG
36965** macro to SQLITE_DEBUG and some older makefiles have not yet made the
36966** switch.  The following code should catch this problem at compile-time.
36967*/
36968#ifdef MEMORY_DEBUG
36969# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
36970#endif
36971
36972/*
36973** Macros for performance tracing.  Normally turned off.  Only works
36974** on i486 hardware.
36975*/
36976#ifdef SQLITE_PERFORMANCE_TRACE
36977
36978/*
36979** hwtime.h contains inline assembler code for implementing
36980** high-performance timing routines.
36981*/
36982/************** Include hwtime.h in the middle of os_common.h ****************/
36983/************** Begin file hwtime.h ******************************************/
36984/*
36985** 2008 May 27
36986**
36987** The author disclaims copyright to this source code.  In place of
36988** a legal notice, here is a blessing:
36989**
36990**    May you do good and not evil.
36991**    May you find forgiveness for yourself and forgive others.
36992**    May you share freely, never taking more than you give.
36993**
36994******************************************************************************
36995**
36996** This file contains inline asm code for retrieving "high-performance"
36997** counters for x86 class CPUs.
36998*/
36999#ifndef SQLITE_HWTIME_H
37000#define SQLITE_HWTIME_H
37001
37002/*
37003** The following routine only works on pentium-class (or newer) processors.
37004** It uses the RDTSC opcode to read the cycle count value out of the
37005** processor and returns that value.  This can be used for high-res
37006** profiling.
37007*/
37008#if (defined(__GNUC__) || defined(_MSC_VER)) && \
37009      (defined(i386) || defined(__i386__) || defined(_M_IX86))
37010
37011  #if defined(__GNUC__)
37012
37013  __inline__ sqlite_uint64 sqlite3Hwtime(void){
37014     unsigned int lo, hi;
37015     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
37016     return (sqlite_uint64)hi << 32 | lo;
37017  }
37018
37019  #elif defined(_MSC_VER)
37020
37021  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
37022     __asm {
37023        rdtsc
37024        ret       ; return value at EDX:EAX
37025     }
37026  }
37027
37028  #endif
37029
37030#elif (defined(__GNUC__) && defined(__x86_64__))
37031
37032  __inline__ sqlite_uint64 sqlite3Hwtime(void){
37033      unsigned long val;
37034      __asm__ __volatile__ ("rdtsc" : "=A" (val));
37035      return val;
37036  }
37037
37038#elif (defined(__GNUC__) && defined(__ppc__))
37039
37040  __inline__ sqlite_uint64 sqlite3Hwtime(void){
37041      unsigned long long retval;
37042      unsigned long junk;
37043      __asm__ __volatile__ ("\n\
37044          1:      mftbu   %1\n\
37045                  mftb    %L0\n\
37046                  mftbu   %0\n\
37047                  cmpw    %0,%1\n\
37048                  bne     1b"
37049                  : "=r" (retval), "=r" (junk));
37050      return retval;
37051  }
37052
37053#else
37054
37055  #error Need implementation of sqlite3Hwtime() for your platform.
37056
37057  /*
37058  ** To compile without implementing sqlite3Hwtime() for your platform,
37059  ** you can remove the above #error and use the following
37060  ** stub function.  You will lose timing support for many
37061  ** of the debugging and testing utilities, but it should at
37062  ** least compile and run.
37063  */
37064SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
37065
37066#endif
37067
37068#endif /* !defined(SQLITE_HWTIME_H) */
37069
37070/************** End of hwtime.h **********************************************/
37071/************** Continuing where we left off in os_common.h ******************/
37072
37073static sqlite_uint64 g_start;
37074static sqlite_uint64 g_elapsed;
37075#define TIMER_START       g_start=sqlite3Hwtime()
37076#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
37077#define TIMER_ELAPSED     g_elapsed
37078#else
37079#define TIMER_START
37080#define TIMER_END
37081#define TIMER_ELAPSED     ((sqlite_uint64)0)
37082#endif
37083
37084/*
37085** If we compile with the SQLITE_TEST macro set, then the following block
37086** of code will give us the ability to simulate a disk I/O error.  This
37087** is used for testing the I/O recovery logic.
37088*/
37089#if defined(SQLITE_TEST)
37090SQLITE_API extern int sqlite3_io_error_hit;
37091SQLITE_API extern int sqlite3_io_error_hardhit;
37092SQLITE_API extern int sqlite3_io_error_pending;
37093SQLITE_API extern int sqlite3_io_error_persist;
37094SQLITE_API extern int sqlite3_io_error_benign;
37095SQLITE_API extern int sqlite3_diskfull_pending;
37096SQLITE_API extern int sqlite3_diskfull;
37097#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
37098#define SimulateIOError(CODE)  \
37099  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
37100       || sqlite3_io_error_pending-- == 1 )  \
37101              { local_ioerr(); CODE; }
37102static void local_ioerr(){
37103  IOTRACE(("IOERR\n"));
37104  sqlite3_io_error_hit++;
37105  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
37106}
37107#define SimulateDiskfullError(CODE) \
37108   if( sqlite3_diskfull_pending ){ \
37109     if( sqlite3_diskfull_pending == 1 ){ \
37110       local_ioerr(); \
37111       sqlite3_diskfull = 1; \
37112       sqlite3_io_error_hit = 1; \
37113       CODE; \
37114     }else{ \
37115       sqlite3_diskfull_pending--; \
37116     } \
37117   }
37118#else
37119#define SimulateIOErrorBenign(X)
37120#define SimulateIOError(A)
37121#define SimulateDiskfullError(A)
37122#endif /* defined(SQLITE_TEST) */
37123
37124/*
37125** When testing, keep a count of the number of open files.
37126*/
37127#if defined(SQLITE_TEST)
37128SQLITE_API extern int sqlite3_open_file_count;
37129#define OpenCounter(X)  sqlite3_open_file_count+=(X)
37130#else
37131#define OpenCounter(X)
37132#endif /* defined(SQLITE_TEST) */
37133
37134#endif /* !defined(_OS_COMMON_H_) */
37135
37136/************** End of os_common.h *******************************************/
37137/************** Continuing where we left off in os_win.c *********************/
37138
37139/*
37140** Include the header file for the Windows VFS.
37141*/
37142/* #include "os_win.h" */
37143
37144/*
37145** Compiling and using WAL mode requires several APIs that are only
37146** available in Windows platforms based on the NT kernel.
37147*/
37148#if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
37149#  error "WAL mode requires support from the Windows NT kernel, compile\
37150 with SQLITE_OMIT_WAL."
37151#endif
37152
37153#if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
37154#  error "Memory mapped files require support from the Windows NT kernel,\
37155 compile with SQLITE_MAX_MMAP_SIZE=0."
37156#endif
37157
37158/*
37159** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
37160** based on the sub-platform)?
37161*/
37162#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
37163#  define SQLITE_WIN32_HAS_ANSI
37164#endif
37165
37166/*
37167** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
37168** based on the sub-platform)?
37169*/
37170#if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
37171    !defined(SQLITE_WIN32_NO_WIDE)
37172#  define SQLITE_WIN32_HAS_WIDE
37173#endif
37174
37175/*
37176** Make sure at least one set of Win32 APIs is available.
37177*/
37178#if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
37179#  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
37180 must be defined."
37181#endif
37182
37183/*
37184** Define the required Windows SDK version constants if they are not
37185** already available.
37186*/
37187#ifndef NTDDI_WIN8
37188#  define NTDDI_WIN8                        0x06020000
37189#endif
37190
37191#ifndef NTDDI_WINBLUE
37192#  define NTDDI_WINBLUE                     0x06030000
37193#endif
37194
37195#ifndef NTDDI_WINTHRESHOLD
37196#  define NTDDI_WINTHRESHOLD                0x06040000
37197#endif
37198
37199/*
37200** Check to see if the GetVersionEx[AW] functions are deprecated on the
37201** target system.  GetVersionEx was first deprecated in Win8.1.
37202*/
37203#ifndef SQLITE_WIN32_GETVERSIONEX
37204#  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
37205#    define SQLITE_WIN32_GETVERSIONEX   0   /* GetVersionEx() is deprecated */
37206#  else
37207#    define SQLITE_WIN32_GETVERSIONEX   1   /* GetVersionEx() is current */
37208#  endif
37209#endif
37210
37211/*
37212** Check to see if the CreateFileMappingA function is supported on the
37213** target system.  It is unavailable when using "mincore.lib" on Win10.
37214** When compiling for Windows 10, always assume "mincore.lib" is in use.
37215*/
37216#ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
37217#  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
37218#    define SQLITE_WIN32_CREATEFILEMAPPINGA   0
37219#  else
37220#    define SQLITE_WIN32_CREATEFILEMAPPINGA   1
37221#  endif
37222#endif
37223
37224/*
37225** This constant should already be defined (in the "WinDef.h" SDK file).
37226*/
37227#ifndef MAX_PATH
37228#  define MAX_PATH                      (260)
37229#endif
37230
37231/*
37232** Maximum pathname length (in chars) for Win32.  This should normally be
37233** MAX_PATH.
37234*/
37235#ifndef SQLITE_WIN32_MAX_PATH_CHARS
37236#  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
37237#endif
37238
37239/*
37240** This constant should already be defined (in the "WinNT.h" SDK file).
37241*/
37242#ifndef UNICODE_STRING_MAX_CHARS
37243#  define UNICODE_STRING_MAX_CHARS      (32767)
37244#endif
37245
37246/*
37247** Maximum pathname length (in chars) for WinNT.  This should normally be
37248** UNICODE_STRING_MAX_CHARS.
37249*/
37250#ifndef SQLITE_WINNT_MAX_PATH_CHARS
37251#  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
37252#endif
37253
37254/*
37255** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
37256** characters, so we allocate 4 bytes per character assuming worst-case of
37257** 4-bytes-per-character for UTF8.
37258*/
37259#ifndef SQLITE_WIN32_MAX_PATH_BYTES
37260#  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
37261#endif
37262
37263/*
37264** Maximum pathname length (in bytes) for WinNT.  This should normally be
37265** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
37266*/
37267#ifndef SQLITE_WINNT_MAX_PATH_BYTES
37268#  define SQLITE_WINNT_MAX_PATH_BYTES   \
37269                            (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
37270#endif
37271
37272/*
37273** Maximum error message length (in chars) for WinRT.
37274*/
37275#ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
37276#  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
37277#endif
37278
37279/*
37280** Returns non-zero if the character should be treated as a directory
37281** separator.
37282*/
37283#ifndef winIsDirSep
37284#  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
37285#endif
37286
37287/*
37288** This macro is used when a local variable is set to a value that is
37289** [sometimes] not used by the code (e.g. via conditional compilation).
37290*/
37291#ifndef UNUSED_VARIABLE_VALUE
37292#  define UNUSED_VARIABLE_VALUE(x)      (void)(x)
37293#endif
37294
37295/*
37296** Returns the character that should be used as the directory separator.
37297*/
37298#ifndef winGetDirSep
37299#  define winGetDirSep()                '\\'
37300#endif
37301
37302/*
37303** Do we need to manually define the Win32 file mapping APIs for use with WAL
37304** mode or memory mapped files (e.g. these APIs are available in the Windows
37305** CE SDK; however, they are not present in the header file)?
37306*/
37307#if SQLITE_WIN32_FILEMAPPING_API && \
37308        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
37309/*
37310** Two of the file mapping APIs are different under WinRT.  Figure out which
37311** set we need.
37312*/
37313#if SQLITE_OS_WINRT
37314WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
37315        LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
37316
37317WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
37318#else
37319#if defined(SQLITE_WIN32_HAS_ANSI)
37320WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
37321        DWORD, DWORD, DWORD, LPCSTR);
37322#endif /* defined(SQLITE_WIN32_HAS_ANSI) */
37323
37324#if defined(SQLITE_WIN32_HAS_WIDE)
37325WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
37326        DWORD, DWORD, DWORD, LPCWSTR);
37327#endif /* defined(SQLITE_WIN32_HAS_WIDE) */
37328
37329WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
37330#endif /* SQLITE_OS_WINRT */
37331
37332/*
37333** These file mapping APIs are common to both Win32 and WinRT.
37334*/
37335
37336WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
37337WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
37338#endif /* SQLITE_WIN32_FILEMAPPING_API */
37339
37340/*
37341** Some Microsoft compilers lack this definition.
37342*/
37343#ifndef INVALID_FILE_ATTRIBUTES
37344# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
37345#endif
37346
37347#ifndef FILE_FLAG_MASK
37348# define FILE_FLAG_MASK          (0xFF3C0000)
37349#endif
37350
37351#ifndef FILE_ATTRIBUTE_MASK
37352# define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
37353#endif
37354
37355#ifndef SQLITE_OMIT_WAL
37356/* Forward references to structures used for WAL */
37357typedef struct winShm winShm;           /* A connection to shared-memory */
37358typedef struct winShmNode winShmNode;   /* A region of shared-memory */
37359#endif
37360
37361/*
37362** WinCE lacks native support for file locking so we have to fake it
37363** with some code of our own.
37364*/
37365#if SQLITE_OS_WINCE
37366typedef struct winceLock {
37367  int nReaders;       /* Number of reader locks obtained */
37368  BOOL bPending;      /* Indicates a pending lock has been obtained */
37369  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
37370  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
37371} winceLock;
37372#endif
37373
37374/*
37375** The winFile structure is a subclass of sqlite3_file* specific to the win32
37376** portability layer.
37377*/
37378typedef struct winFile winFile;
37379struct winFile {
37380  const sqlite3_io_methods *pMethod; /*** Must be first ***/
37381  sqlite3_vfs *pVfs;      /* The VFS used to open this file */
37382  HANDLE h;               /* Handle for accessing the file */
37383  u8 locktype;            /* Type of lock currently held on this file */
37384  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
37385  u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
37386  DWORD lastErrno;        /* The Windows errno from the last I/O error */
37387#ifndef SQLITE_OMIT_WAL
37388  winShm *pShm;           /* Instance of shared memory on this file */
37389#endif
37390  const char *zPath;      /* Full pathname of this file */
37391  int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
37392#if SQLITE_OS_WINCE
37393  LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
37394  HANDLE hMutex;          /* Mutex used to control access to shared lock */
37395  HANDLE hShared;         /* Shared memory segment used for locking */
37396  winceLock local;        /* Locks obtained by this instance of winFile */
37397  winceLock *shared;      /* Global shared lock memory for the file  */
37398#endif
37399#if SQLITE_MAX_MMAP_SIZE>0
37400  int nFetchOut;                /* Number of outstanding xFetch references */
37401  HANDLE hMap;                  /* Handle for accessing memory mapping */
37402  void *pMapRegion;             /* Area memory mapped */
37403  sqlite3_int64 mmapSize;       /* Usable size of mapped region */
37404  sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
37405  sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
37406#endif
37407};
37408
37409/*
37410** The winVfsAppData structure is used for the pAppData member for all of the
37411** Win32 VFS variants.
37412*/
37413typedef struct winVfsAppData winVfsAppData;
37414struct winVfsAppData {
37415  const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
37416  void *pAppData;                    /* The extra pAppData, if any. */
37417  BOOL bNoLock;                      /* Non-zero if locking is disabled. */
37418};
37419
37420/*
37421** Allowed values for winFile.ctrlFlags
37422*/
37423#define WINFILE_RDONLY          0x02   /* Connection is read only */
37424#define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
37425#define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
37426
37427/*
37428 * The size of the buffer used by sqlite3_win32_write_debug().
37429 */
37430#ifndef SQLITE_WIN32_DBG_BUF_SIZE
37431#  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
37432#endif
37433
37434/*
37435 * The value used with sqlite3_win32_set_directory() to specify that
37436 * the data directory should be changed.
37437 */
37438#ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
37439#  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
37440#endif
37441
37442/*
37443 * The value used with sqlite3_win32_set_directory() to specify that
37444 * the temporary directory should be changed.
37445 */
37446#ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
37447#  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
37448#endif
37449
37450/*
37451 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
37452 * various Win32 API heap functions instead of our own.
37453 */
37454#ifdef SQLITE_WIN32_MALLOC
37455
37456/*
37457 * If this is non-zero, an isolated heap will be created by the native Win32
37458 * allocator subsystem; otherwise, the default process heap will be used.  This
37459 * setting has no effect when compiling for WinRT.  By default, this is enabled
37460 * and an isolated heap will be created to store all allocated data.
37461 *
37462 ******************************************************************************
37463 * WARNING: It is important to note that when this setting is non-zero and the
37464 *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
37465 *          function), all data that was allocated using the isolated heap will
37466 *          be freed immediately and any attempt to access any of that freed
37467 *          data will almost certainly result in an immediate access violation.
37468 ******************************************************************************
37469 */
37470#ifndef SQLITE_WIN32_HEAP_CREATE
37471#  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
37472#endif
37473
37474/*
37475 * This is cache size used in the calculation of the initial size of the
37476 * Win32-specific heap.  It cannot be negative.
37477 */
37478#ifndef SQLITE_WIN32_CACHE_SIZE
37479#  if SQLITE_DEFAULT_CACHE_SIZE>=0
37480#    define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
37481#  else
37482#    define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
37483#  endif
37484#endif
37485
37486/*
37487 * The initial size of the Win32-specific heap.  This value may be zero.
37488 */
37489#ifndef SQLITE_WIN32_HEAP_INIT_SIZE
37490#  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
37491                                       (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
37492#endif
37493
37494/*
37495 * The maximum size of the Win32-specific heap.  This value may be zero.
37496 */
37497#ifndef SQLITE_WIN32_HEAP_MAX_SIZE
37498#  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
37499#endif
37500
37501/*
37502 * The extra flags to use in calls to the Win32 heap APIs.  This value may be
37503 * zero for the default behavior.
37504 */
37505#ifndef SQLITE_WIN32_HEAP_FLAGS
37506#  define SQLITE_WIN32_HEAP_FLAGS     (0)
37507#endif
37508
37509
37510/*
37511** The winMemData structure stores information required by the Win32-specific
37512** sqlite3_mem_methods implementation.
37513*/
37514typedef struct winMemData winMemData;
37515struct winMemData {
37516#ifndef NDEBUG
37517  u32 magic1;   /* Magic number to detect structure corruption. */
37518#endif
37519  HANDLE hHeap; /* The handle to our heap. */
37520  BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
37521#ifndef NDEBUG
37522  u32 magic2;   /* Magic number to detect structure corruption. */
37523#endif
37524};
37525
37526#ifndef NDEBUG
37527#define WINMEM_MAGIC1     0x42b2830b
37528#define WINMEM_MAGIC2     0xbd4d7cf4
37529#endif
37530
37531static struct winMemData win_mem_data = {
37532#ifndef NDEBUG
37533  WINMEM_MAGIC1,
37534#endif
37535  NULL, FALSE
37536#ifndef NDEBUG
37537  ,WINMEM_MAGIC2
37538#endif
37539};
37540
37541#ifndef NDEBUG
37542#define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
37543#define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
37544#define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
37545#else
37546#define winMemAssertMagic()
37547#endif
37548
37549#define winMemGetDataPtr()  &win_mem_data
37550#define winMemGetHeap()     win_mem_data.hHeap
37551#define winMemGetOwned()    win_mem_data.bOwned
37552
37553static void *winMemMalloc(int nBytes);
37554static void winMemFree(void *pPrior);
37555static void *winMemRealloc(void *pPrior, int nBytes);
37556static int winMemSize(void *p);
37557static int winMemRoundup(int n);
37558static int winMemInit(void *pAppData);
37559static void winMemShutdown(void *pAppData);
37560
37561SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
37562#endif /* SQLITE_WIN32_MALLOC */
37563
37564/*
37565** The following variable is (normally) set once and never changes
37566** thereafter.  It records whether the operating system is Win9x
37567** or WinNT.
37568**
37569** 0:   Operating system unknown.
37570** 1:   Operating system is Win9x.
37571** 2:   Operating system is WinNT.
37572**
37573** In order to facilitate testing on a WinNT system, the test fixture
37574** can manually set this value to 1 to emulate Win98 behavior.
37575*/
37576#ifdef SQLITE_TEST
37577SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
37578#else
37579static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
37580#endif
37581
37582#ifndef SYSCALL
37583#  define SYSCALL sqlite3_syscall_ptr
37584#endif
37585
37586/*
37587** This function is not available on Windows CE or WinRT.
37588 */
37589
37590#if SQLITE_OS_WINCE || SQLITE_OS_WINRT
37591#  define osAreFileApisANSI()       1
37592#endif
37593
37594/*
37595** Many system calls are accessed through pointer-to-functions so that
37596** they may be overridden at runtime to facilitate fault injection during
37597** testing and sandboxing.  The following array holds the names and pointers
37598** to all overrideable system calls.
37599*/
37600static struct win_syscall {
37601  const char *zName;            /* Name of the system call */
37602  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
37603  sqlite3_syscall_ptr pDefault; /* Default value */
37604} aSyscall[] = {
37605#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
37606  { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
37607#else
37608  { "AreFileApisANSI",         (SYSCALL)0,                       0 },
37609#endif
37610
37611#ifndef osAreFileApisANSI
37612#define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
37613#endif
37614
37615#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
37616  { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
37617#else
37618  { "CharLowerW",              (SYSCALL)0,                       0 },
37619#endif
37620
37621#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
37622
37623#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
37624  { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
37625#else
37626  { "CharUpperW",              (SYSCALL)0,                       0 },
37627#endif
37628
37629#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
37630
37631  { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
37632
37633#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
37634
37635#if defined(SQLITE_WIN32_HAS_ANSI)
37636  { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
37637#else
37638  { "CreateFileA",             (SYSCALL)0,                       0 },
37639#endif
37640
37641#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
37642        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
37643
37644#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37645  { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
37646#else
37647  { "CreateFileW",             (SYSCALL)0,                       0 },
37648#endif
37649
37650#define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
37651        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
37652
37653#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
37654        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
37655        SQLITE_WIN32_CREATEFILEMAPPINGA
37656  { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
37657#else
37658  { "CreateFileMappingA",      (SYSCALL)0,                       0 },
37659#endif
37660
37661#define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
37662        DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
37663
37664#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
37665        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
37666  { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
37667#else
37668  { "CreateFileMappingW",      (SYSCALL)0,                       0 },
37669#endif
37670
37671#define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
37672        DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
37673
37674#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37675  { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
37676#else
37677  { "CreateMutexW",            (SYSCALL)0,                       0 },
37678#endif
37679
37680#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
37681        LPCWSTR))aSyscall[8].pCurrent)
37682
37683#if defined(SQLITE_WIN32_HAS_ANSI)
37684  { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
37685#else
37686  { "DeleteFileA",             (SYSCALL)0,                       0 },
37687#endif
37688
37689#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
37690
37691#if defined(SQLITE_WIN32_HAS_WIDE)
37692  { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
37693#else
37694  { "DeleteFileW",             (SYSCALL)0,                       0 },
37695#endif
37696
37697#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
37698
37699#if SQLITE_OS_WINCE
37700  { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
37701#else
37702  { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
37703#endif
37704
37705#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
37706        LPFILETIME))aSyscall[11].pCurrent)
37707
37708#if SQLITE_OS_WINCE
37709  { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
37710#else
37711  { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
37712#endif
37713
37714#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
37715        LPSYSTEMTIME))aSyscall[12].pCurrent)
37716
37717  { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
37718
37719#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
37720
37721#if defined(SQLITE_WIN32_HAS_ANSI)
37722  { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
37723#else
37724  { "FormatMessageA",          (SYSCALL)0,                       0 },
37725#endif
37726
37727#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
37728        DWORD,va_list*))aSyscall[14].pCurrent)
37729
37730#if defined(SQLITE_WIN32_HAS_WIDE)
37731  { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
37732#else
37733  { "FormatMessageW",          (SYSCALL)0,                       0 },
37734#endif
37735
37736#define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
37737        DWORD,va_list*))aSyscall[15].pCurrent)
37738
37739#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
37740  { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
37741#else
37742  { "FreeLibrary",             (SYSCALL)0,                       0 },
37743#endif
37744
37745#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
37746
37747  { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
37748
37749#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
37750
37751#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
37752  { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
37753#else
37754  { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
37755#endif
37756
37757#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
37758        LPDWORD))aSyscall[18].pCurrent)
37759
37760#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37761  { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
37762#else
37763  { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
37764#endif
37765
37766#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
37767        LPDWORD))aSyscall[19].pCurrent)
37768
37769#if defined(SQLITE_WIN32_HAS_ANSI)
37770  { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
37771#else
37772  { "GetFileAttributesA",      (SYSCALL)0,                       0 },
37773#endif
37774
37775#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
37776
37777#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37778  { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
37779#else
37780  { "GetFileAttributesW",      (SYSCALL)0,                       0 },
37781#endif
37782
37783#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
37784
37785#if defined(SQLITE_WIN32_HAS_WIDE)
37786  { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
37787#else
37788  { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
37789#endif
37790
37791#define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
37792        LPVOID))aSyscall[22].pCurrent)
37793
37794#if !SQLITE_OS_WINRT
37795  { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
37796#else
37797  { "GetFileSize",             (SYSCALL)0,                       0 },
37798#endif
37799
37800#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
37801
37802#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
37803  { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
37804#else
37805  { "GetFullPathNameA",        (SYSCALL)0,                       0 },
37806#endif
37807
37808#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
37809        LPSTR*))aSyscall[24].pCurrent)
37810
37811#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37812  { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
37813#else
37814  { "GetFullPathNameW",        (SYSCALL)0,                       0 },
37815#endif
37816
37817#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
37818        LPWSTR*))aSyscall[25].pCurrent)
37819
37820  { "GetLastError",            (SYSCALL)GetLastError,            0 },
37821
37822#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
37823
37824#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
37825#if SQLITE_OS_WINCE
37826  /* The GetProcAddressA() routine is only available on Windows CE. */
37827  { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
37828#else
37829  /* All other Windows platforms expect GetProcAddress() to take
37830  ** an ANSI string regardless of the _UNICODE setting */
37831  { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
37832#endif
37833#else
37834  { "GetProcAddressA",         (SYSCALL)0,                       0 },
37835#endif
37836
37837#define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
37838        LPCSTR))aSyscall[27].pCurrent)
37839
37840#if !SQLITE_OS_WINRT
37841  { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
37842#else
37843  { "GetSystemInfo",           (SYSCALL)0,                       0 },
37844#endif
37845
37846#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
37847
37848  { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
37849
37850#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
37851
37852#if !SQLITE_OS_WINCE
37853  { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
37854#else
37855  { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
37856#endif
37857
37858#define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
37859        LPFILETIME))aSyscall[30].pCurrent)
37860
37861#if defined(SQLITE_WIN32_HAS_ANSI)
37862  { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
37863#else
37864  { "GetTempPathA",            (SYSCALL)0,                       0 },
37865#endif
37866
37867#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
37868
37869#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37870  { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
37871#else
37872  { "GetTempPathW",            (SYSCALL)0,                       0 },
37873#endif
37874
37875#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
37876
37877#if !SQLITE_OS_WINRT
37878  { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
37879#else
37880  { "GetTickCount",            (SYSCALL)0,                       0 },
37881#endif
37882
37883#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
37884
37885#if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
37886  { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
37887#else
37888  { "GetVersionExA",           (SYSCALL)0,                       0 },
37889#endif
37890
37891#define osGetVersionExA ((BOOL(WINAPI*)( \
37892        LPOSVERSIONINFOA))aSyscall[34].pCurrent)
37893
37894#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
37895        SQLITE_WIN32_GETVERSIONEX
37896  { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
37897#else
37898  { "GetVersionExW",           (SYSCALL)0,                       0 },
37899#endif
37900
37901#define osGetVersionExW ((BOOL(WINAPI*)( \
37902        LPOSVERSIONINFOW))aSyscall[35].pCurrent)
37903
37904  { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
37905
37906#define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
37907        SIZE_T))aSyscall[36].pCurrent)
37908
37909#if !SQLITE_OS_WINRT
37910  { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
37911#else
37912  { "HeapCreate",              (SYSCALL)0,                       0 },
37913#endif
37914
37915#define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
37916        SIZE_T))aSyscall[37].pCurrent)
37917
37918#if !SQLITE_OS_WINRT
37919  { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
37920#else
37921  { "HeapDestroy",             (SYSCALL)0,                       0 },
37922#endif
37923
37924#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
37925
37926  { "HeapFree",                (SYSCALL)HeapFree,                0 },
37927
37928#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
37929
37930  { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
37931
37932#define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
37933        SIZE_T))aSyscall[40].pCurrent)
37934
37935  { "HeapSize",                (SYSCALL)HeapSize,                0 },
37936
37937#define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
37938        LPCVOID))aSyscall[41].pCurrent)
37939
37940#if !SQLITE_OS_WINRT
37941  { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
37942#else
37943  { "HeapValidate",            (SYSCALL)0,                       0 },
37944#endif
37945
37946#define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
37947        LPCVOID))aSyscall[42].pCurrent)
37948
37949#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
37950  { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
37951#else
37952  { "HeapCompact",             (SYSCALL)0,                       0 },
37953#endif
37954
37955#define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
37956
37957#if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
37958  { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
37959#else
37960  { "LoadLibraryA",            (SYSCALL)0,                       0 },
37961#endif
37962
37963#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
37964
37965#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
37966        !defined(SQLITE_OMIT_LOAD_EXTENSION)
37967  { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
37968#else
37969  { "LoadLibraryW",            (SYSCALL)0,                       0 },
37970#endif
37971
37972#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
37973
37974#if !SQLITE_OS_WINRT
37975  { "LocalFree",               (SYSCALL)LocalFree,               0 },
37976#else
37977  { "LocalFree",               (SYSCALL)0,                       0 },
37978#endif
37979
37980#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
37981
37982#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
37983  { "LockFile",                (SYSCALL)LockFile,                0 },
37984#else
37985  { "LockFile",                (SYSCALL)0,                       0 },
37986#endif
37987
37988#ifndef osLockFile
37989#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
37990        DWORD))aSyscall[47].pCurrent)
37991#endif
37992
37993#if !SQLITE_OS_WINCE
37994  { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
37995#else
37996  { "LockFileEx",              (SYSCALL)0,                       0 },
37997#endif
37998
37999#ifndef osLockFileEx
38000#define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
38001        LPOVERLAPPED))aSyscall[48].pCurrent)
38002#endif
38003
38004#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
38005        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
38006  { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
38007#else
38008  { "MapViewOfFile",           (SYSCALL)0,                       0 },
38009#endif
38010
38011#define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38012        SIZE_T))aSyscall[49].pCurrent)
38013
38014  { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
38015
38016#define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
38017        int))aSyscall[50].pCurrent)
38018
38019  { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
38020
38021#define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
38022        LARGE_INTEGER*))aSyscall[51].pCurrent)
38023
38024  { "ReadFile",                (SYSCALL)ReadFile,                0 },
38025
38026#define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
38027        LPOVERLAPPED))aSyscall[52].pCurrent)
38028
38029  { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
38030
38031#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
38032
38033#if !SQLITE_OS_WINRT
38034  { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
38035#else
38036  { "SetFilePointer",          (SYSCALL)0,                       0 },
38037#endif
38038
38039#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
38040        DWORD))aSyscall[54].pCurrent)
38041
38042#if !SQLITE_OS_WINRT
38043  { "Sleep",                   (SYSCALL)Sleep,                   0 },
38044#else
38045  { "Sleep",                   (SYSCALL)0,                       0 },
38046#endif
38047
38048#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
38049
38050  { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
38051
38052#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
38053        LPFILETIME))aSyscall[56].pCurrent)
38054
38055#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38056  { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
38057#else
38058  { "UnlockFile",              (SYSCALL)0,                       0 },
38059#endif
38060
38061#ifndef osUnlockFile
38062#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38063        DWORD))aSyscall[57].pCurrent)
38064#endif
38065
38066#if !SQLITE_OS_WINCE
38067  { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
38068#else
38069  { "UnlockFileEx",            (SYSCALL)0,                       0 },
38070#endif
38071
38072#define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38073        LPOVERLAPPED))aSyscall[58].pCurrent)
38074
38075#if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
38076  { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
38077#else
38078  { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
38079#endif
38080
38081#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
38082
38083  { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
38084
38085#define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
38086        LPCSTR,LPBOOL))aSyscall[60].pCurrent)
38087
38088  { "WriteFile",               (SYSCALL)WriteFile,               0 },
38089
38090#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
38091        LPOVERLAPPED))aSyscall[61].pCurrent)
38092
38093#if SQLITE_OS_WINRT
38094  { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
38095#else
38096  { "CreateEventExW",          (SYSCALL)0,                       0 },
38097#endif
38098
38099#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
38100        DWORD,DWORD))aSyscall[62].pCurrent)
38101
38102#if !SQLITE_OS_WINRT
38103  { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
38104#else
38105  { "WaitForSingleObject",     (SYSCALL)0,                       0 },
38106#endif
38107
38108#define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
38109        DWORD))aSyscall[63].pCurrent)
38110
38111#if !SQLITE_OS_WINCE
38112  { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
38113#else
38114  { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
38115#endif
38116
38117#define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
38118        BOOL))aSyscall[64].pCurrent)
38119
38120#if SQLITE_OS_WINRT
38121  { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
38122#else
38123  { "SetFilePointerEx",        (SYSCALL)0,                       0 },
38124#endif
38125
38126#define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
38127        PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
38128
38129#if SQLITE_OS_WINRT
38130  { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
38131#else
38132  { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
38133#endif
38134
38135#define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
38136        FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
38137
38138#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
38139  { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
38140#else
38141  { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
38142#endif
38143
38144#define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
38145        SIZE_T))aSyscall[67].pCurrent)
38146
38147#if SQLITE_OS_WINRT
38148  { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
38149#else
38150  { "CreateFile2",             (SYSCALL)0,                       0 },
38151#endif
38152
38153#define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
38154        LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
38155
38156#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
38157  { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
38158#else
38159  { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
38160#endif
38161
38162#define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
38163        DWORD))aSyscall[69].pCurrent)
38164
38165#if SQLITE_OS_WINRT
38166  { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
38167#else
38168  { "GetTickCount64",          (SYSCALL)0,                       0 },
38169#endif
38170
38171#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
38172
38173#if SQLITE_OS_WINRT
38174  { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
38175#else
38176  { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
38177#endif
38178
38179#define osGetNativeSystemInfo ((VOID(WINAPI*)( \
38180        LPSYSTEM_INFO))aSyscall[71].pCurrent)
38181
38182#if defined(SQLITE_WIN32_HAS_ANSI)
38183  { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
38184#else
38185  { "OutputDebugStringA",      (SYSCALL)0,                       0 },
38186#endif
38187
38188#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
38189
38190#if defined(SQLITE_WIN32_HAS_WIDE)
38191  { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
38192#else
38193  { "OutputDebugStringW",      (SYSCALL)0,                       0 },
38194#endif
38195
38196#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
38197
38198  { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
38199
38200#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
38201
38202#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
38203  { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
38204#else
38205  { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
38206#endif
38207
38208#define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
38209        LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
38210
38211/*
38212** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
38213**       is really just a macro that uses a compiler intrinsic (e.g. x64).
38214**       So do not try to make this is into a redefinable interface.
38215*/
38216#if defined(InterlockedCompareExchange)
38217  { "InterlockedCompareExchange", (SYSCALL)0,                    0 },
38218
38219#define osInterlockedCompareExchange InterlockedCompareExchange
38220#else
38221  { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
38222
38223#define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
38224        SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
38225#endif /* defined(InterlockedCompareExchange) */
38226
38227#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
38228  { "UuidCreate",               (SYSCALL)UuidCreate,             0 },
38229#else
38230  { "UuidCreate",               (SYSCALL)0,                      0 },
38231#endif
38232
38233#define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
38234
38235#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
38236  { "UuidCreateSequential",     (SYSCALL)UuidCreateSequential,   0 },
38237#else
38238  { "UuidCreateSequential",     (SYSCALL)0,                      0 },
38239#endif
38240
38241#define osUuidCreateSequential \
38242        ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
38243
38244#if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
38245  { "FlushViewOfFile",          (SYSCALL)FlushViewOfFile,        0 },
38246#else
38247  { "FlushViewOfFile",          (SYSCALL)0,                      0 },
38248#endif
38249
38250#define osFlushViewOfFile \
38251        ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
38252
38253}; /* End of the overrideable system calls */
38254
38255/*
38256** This is the xSetSystemCall() method of sqlite3_vfs for all of the
38257** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
38258** system call pointer, or SQLITE_NOTFOUND if there is no configurable
38259** system call named zName.
38260*/
38261static int winSetSystemCall(
38262  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
38263  const char *zName,            /* Name of system call to override */
38264  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
38265){
38266  unsigned int i;
38267  int rc = SQLITE_NOTFOUND;
38268
38269  UNUSED_PARAMETER(pNotUsed);
38270  if( zName==0 ){
38271    /* If no zName is given, restore all system calls to their default
38272    ** settings and return NULL
38273    */
38274    rc = SQLITE_OK;
38275    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38276      if( aSyscall[i].pDefault ){
38277        aSyscall[i].pCurrent = aSyscall[i].pDefault;
38278      }
38279    }
38280  }else{
38281    /* If zName is specified, operate on only the one system call
38282    ** specified.
38283    */
38284    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38285      if( strcmp(zName, aSyscall[i].zName)==0 ){
38286        if( aSyscall[i].pDefault==0 ){
38287          aSyscall[i].pDefault = aSyscall[i].pCurrent;
38288        }
38289        rc = SQLITE_OK;
38290        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
38291        aSyscall[i].pCurrent = pNewFunc;
38292        break;
38293      }
38294    }
38295  }
38296  return rc;
38297}
38298
38299/*
38300** Return the value of a system call.  Return NULL if zName is not a
38301** recognized system call name.  NULL is also returned if the system call
38302** is currently undefined.
38303*/
38304static sqlite3_syscall_ptr winGetSystemCall(
38305  sqlite3_vfs *pNotUsed,
38306  const char *zName
38307){
38308  unsigned int i;
38309
38310  UNUSED_PARAMETER(pNotUsed);
38311  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38312    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
38313  }
38314  return 0;
38315}
38316
38317/*
38318** Return the name of the first system call after zName.  If zName==NULL
38319** then return the name of the first system call.  Return NULL if zName
38320** is the last system call or if zName is not the name of a valid
38321** system call.
38322*/
38323static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
38324  int i = -1;
38325
38326  UNUSED_PARAMETER(p);
38327  if( zName ){
38328    for(i=0; i<ArraySize(aSyscall)-1; i++){
38329      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
38330    }
38331  }
38332  for(i++; i<ArraySize(aSyscall); i++){
38333    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
38334  }
38335  return 0;
38336}
38337
38338#ifdef SQLITE_WIN32_MALLOC
38339/*
38340** If a Win32 native heap has been configured, this function will attempt to
38341** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
38342** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
38343** "pnLargest" argument, if non-zero, will be used to return the size of the
38344** largest committed free block in the heap, in bytes.
38345*/
38346SQLITE_API int SQLITE_STDCALL sqlite3_win32_compact_heap(LPUINT pnLargest){
38347  int rc = SQLITE_OK;
38348  UINT nLargest = 0;
38349  HANDLE hHeap;
38350
38351  winMemAssertMagic();
38352  hHeap = winMemGetHeap();
38353  assert( hHeap!=0 );
38354  assert( hHeap!=INVALID_HANDLE_VALUE );
38355#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38356  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38357#endif
38358#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38359  if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
38360    DWORD lastErrno = osGetLastError();
38361    if( lastErrno==NO_ERROR ){
38362      sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
38363                  (void*)hHeap);
38364      rc = SQLITE_NOMEM_BKPT;
38365    }else{
38366      sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
38367                  osGetLastError(), (void*)hHeap);
38368      rc = SQLITE_ERROR;
38369    }
38370  }
38371#else
38372  sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
38373              (void*)hHeap);
38374  rc = SQLITE_NOTFOUND;
38375#endif
38376  if( pnLargest ) *pnLargest = nLargest;
38377  return rc;
38378}
38379
38380/*
38381** If a Win32 native heap has been configured, this function will attempt to
38382** destroy and recreate it.  If the Win32 native heap is not isolated and/or
38383** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
38384** be returned and no changes will be made to the Win32 native heap.
38385*/
38386SQLITE_API int SQLITE_STDCALL sqlite3_win32_reset_heap(){
38387  int rc;
38388  MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
38389  MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
38390  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
38391  MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
38392  sqlite3_mutex_enter(pMaster);
38393  sqlite3_mutex_enter(pMem);
38394  winMemAssertMagic();
38395  if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
38396    /*
38397    ** At this point, there should be no outstanding memory allocations on
38398    ** the heap.  Also, since both the master and memsys locks are currently
38399    ** being held by us, no other function (i.e. from another thread) should
38400    ** be able to even access the heap.  Attempt to destroy and recreate our
38401    ** isolated Win32 native heap now.
38402    */
38403    assert( winMemGetHeap()!=NULL );
38404    assert( winMemGetOwned() );
38405    assert( sqlite3_memory_used()==0 );
38406    winMemShutdown(winMemGetDataPtr());
38407    assert( winMemGetHeap()==NULL );
38408    assert( !winMemGetOwned() );
38409    assert( sqlite3_memory_used()==0 );
38410    rc = winMemInit(winMemGetDataPtr());
38411    assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
38412    assert( rc!=SQLITE_OK || winMemGetOwned() );
38413    assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
38414  }else{
38415    /*
38416    ** The Win32 native heap cannot be modified because it may be in use.
38417    */
38418    rc = SQLITE_BUSY;
38419  }
38420  sqlite3_mutex_leave(pMem);
38421  sqlite3_mutex_leave(pMaster);
38422  return rc;
38423}
38424#endif /* SQLITE_WIN32_MALLOC */
38425
38426/*
38427** This function outputs the specified (ANSI) string to the Win32 debugger
38428** (if available).
38429*/
38430
38431SQLITE_API void SQLITE_STDCALL sqlite3_win32_write_debug(const char *zBuf, int nBuf){
38432  char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
38433  int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
38434  if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
38435  assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
38436#ifdef SQLITE_ENABLE_API_ARMOR
38437  if( !zBuf ){
38438    (void)SQLITE_MISUSE_BKPT;
38439    return;
38440  }
38441#endif
38442#if defined(SQLITE_WIN32_HAS_ANSI)
38443  if( nMin>0 ){
38444    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
38445    memcpy(zDbgBuf, zBuf, nMin);
38446    osOutputDebugStringA(zDbgBuf);
38447  }else{
38448    osOutputDebugStringA(zBuf);
38449  }
38450#elif defined(SQLITE_WIN32_HAS_WIDE)
38451  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
38452  if ( osMultiByteToWideChar(
38453          osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
38454          nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
38455    return;
38456  }
38457  osOutputDebugStringW((LPCWSTR)zDbgBuf);
38458#else
38459  if( nMin>0 ){
38460    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
38461    memcpy(zDbgBuf, zBuf, nMin);
38462    fprintf(stderr, "%s", zDbgBuf);
38463  }else{
38464    fprintf(stderr, "%s", zBuf);
38465  }
38466#endif
38467}
38468
38469/*
38470** The following routine suspends the current thread for at least ms
38471** milliseconds.  This is equivalent to the Win32 Sleep() interface.
38472*/
38473#if SQLITE_OS_WINRT
38474static HANDLE sleepObj = NULL;
38475#endif
38476
38477SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds){
38478#if SQLITE_OS_WINRT
38479  if ( sleepObj==NULL ){
38480    sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
38481                                SYNCHRONIZE);
38482  }
38483  assert( sleepObj!=NULL );
38484  osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
38485#else
38486  osSleep(milliseconds);
38487#endif
38488}
38489
38490#if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
38491        SQLITE_THREADSAFE>0
38492SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
38493  DWORD rc;
38494  while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
38495                                       TRUE))==WAIT_IO_COMPLETION ){}
38496  return rc;
38497}
38498#endif
38499
38500/*
38501** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
38502** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
38503**
38504** Here is an interesting observation:  Win95, Win98, and WinME lack
38505** the LockFileEx() API.  But we can still statically link against that
38506** API as long as we don't call it when running Win95/98/ME.  A call to
38507** this routine is used to determine if the host is Win95/98/ME or
38508** WinNT/2K/XP so that we will know whether or not we can safely call
38509** the LockFileEx() API.
38510*/
38511
38512#if !SQLITE_WIN32_GETVERSIONEX
38513# define osIsNT()  (1)
38514#elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
38515# define osIsNT()  (1)
38516#elif !defined(SQLITE_WIN32_HAS_WIDE)
38517# define osIsNT()  (0)
38518#else
38519# define osIsNT()  ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
38520#endif
38521
38522/*
38523** This function determines if the machine is running a version of Windows
38524** based on the NT kernel.
38525*/
38526SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void){
38527#if SQLITE_OS_WINRT
38528  /*
38529  ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
38530  **       kernel.
38531  */
38532  return 1;
38533#elif SQLITE_WIN32_GETVERSIONEX
38534  if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
38535#if defined(SQLITE_WIN32_HAS_ANSI)
38536    OSVERSIONINFOA sInfo;
38537    sInfo.dwOSVersionInfoSize = sizeof(sInfo);
38538    osGetVersionExA(&sInfo);
38539    osInterlockedCompareExchange(&sqlite3_os_type,
38540        (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
38541#elif defined(SQLITE_WIN32_HAS_WIDE)
38542    OSVERSIONINFOW sInfo;
38543    sInfo.dwOSVersionInfoSize = sizeof(sInfo);
38544    osGetVersionExW(&sInfo);
38545    osInterlockedCompareExchange(&sqlite3_os_type,
38546        (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
38547#endif
38548  }
38549  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
38550#elif SQLITE_TEST
38551  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
38552#else
38553  /*
38554  ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
38555  **       deprecated are always assumed to be based on the NT kernel.
38556  */
38557  return 1;
38558#endif
38559}
38560
38561#ifdef SQLITE_WIN32_MALLOC
38562/*
38563** Allocate nBytes of memory.
38564*/
38565static void *winMemMalloc(int nBytes){
38566  HANDLE hHeap;
38567  void *p;
38568
38569  winMemAssertMagic();
38570  hHeap = winMemGetHeap();
38571  assert( hHeap!=0 );
38572  assert( hHeap!=INVALID_HANDLE_VALUE );
38573#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38574  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38575#endif
38576  assert( nBytes>=0 );
38577  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
38578  if( !p ){
38579    sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
38580                nBytes, osGetLastError(), (void*)hHeap);
38581  }
38582  return p;
38583}
38584
38585/*
38586** Free memory.
38587*/
38588static void winMemFree(void *pPrior){
38589  HANDLE hHeap;
38590
38591  winMemAssertMagic();
38592  hHeap = winMemGetHeap();
38593  assert( hHeap!=0 );
38594  assert( hHeap!=INVALID_HANDLE_VALUE );
38595#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38596  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
38597#endif
38598  if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
38599  if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
38600    sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
38601                pPrior, osGetLastError(), (void*)hHeap);
38602  }
38603}
38604
38605/*
38606** Change the size of an existing memory allocation
38607*/
38608static void *winMemRealloc(void *pPrior, int nBytes){
38609  HANDLE hHeap;
38610  void *p;
38611
38612  winMemAssertMagic();
38613  hHeap = winMemGetHeap();
38614  assert( hHeap!=0 );
38615  assert( hHeap!=INVALID_HANDLE_VALUE );
38616#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38617  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
38618#endif
38619  assert( nBytes>=0 );
38620  if( !pPrior ){
38621    p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
38622  }else{
38623    p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
38624  }
38625  if( !p ){
38626    sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
38627                pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
38628                (void*)hHeap);
38629  }
38630  return p;
38631}
38632
38633/*
38634** Return the size of an outstanding allocation, in bytes.
38635*/
38636static int winMemSize(void *p){
38637  HANDLE hHeap;
38638  SIZE_T n;
38639
38640  winMemAssertMagic();
38641  hHeap = winMemGetHeap();
38642  assert( hHeap!=0 );
38643  assert( hHeap!=INVALID_HANDLE_VALUE );
38644#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38645  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
38646#endif
38647  if( !p ) return 0;
38648  n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
38649  if( n==(SIZE_T)-1 ){
38650    sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
38651                p, osGetLastError(), (void*)hHeap);
38652    return 0;
38653  }
38654  return (int)n;
38655}
38656
38657/*
38658** Round up a request size to the next valid allocation size.
38659*/
38660static int winMemRoundup(int n){
38661  return n;
38662}
38663
38664/*
38665** Initialize this module.
38666*/
38667static int winMemInit(void *pAppData){
38668  winMemData *pWinMemData = (winMemData *)pAppData;
38669
38670  if( !pWinMemData ) return SQLITE_ERROR;
38671  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
38672  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
38673
38674#if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
38675  if( !pWinMemData->hHeap ){
38676    DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
38677    DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
38678    if( dwMaximumSize==0 ){
38679      dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
38680    }else if( dwInitialSize>dwMaximumSize ){
38681      dwInitialSize = dwMaximumSize;
38682    }
38683    pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
38684                                      dwInitialSize, dwMaximumSize);
38685    if( !pWinMemData->hHeap ){
38686      sqlite3_log(SQLITE_NOMEM,
38687          "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
38688          osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
38689          dwMaximumSize);
38690      return SQLITE_NOMEM_BKPT;
38691    }
38692    pWinMemData->bOwned = TRUE;
38693    assert( pWinMemData->bOwned );
38694  }
38695#else
38696  pWinMemData->hHeap = osGetProcessHeap();
38697  if( !pWinMemData->hHeap ){
38698    sqlite3_log(SQLITE_NOMEM,
38699        "failed to GetProcessHeap (%lu)", osGetLastError());
38700    return SQLITE_NOMEM_BKPT;
38701  }
38702  pWinMemData->bOwned = FALSE;
38703  assert( !pWinMemData->bOwned );
38704#endif
38705  assert( pWinMemData->hHeap!=0 );
38706  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
38707#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38708  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38709#endif
38710  return SQLITE_OK;
38711}
38712
38713/*
38714** Deinitialize this module.
38715*/
38716static void winMemShutdown(void *pAppData){
38717  winMemData *pWinMemData = (winMemData *)pAppData;
38718
38719  if( !pWinMemData ) return;
38720  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
38721  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
38722
38723  if( pWinMemData->hHeap ){
38724    assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
38725#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38726    assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38727#endif
38728    if( pWinMemData->bOwned ){
38729      if( !osHeapDestroy(pWinMemData->hHeap) ){
38730        sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
38731                    osGetLastError(), (void*)pWinMemData->hHeap);
38732      }
38733      pWinMemData->bOwned = FALSE;
38734    }
38735    pWinMemData->hHeap = NULL;
38736  }
38737}
38738
38739/*
38740** Populate the low-level memory allocation function pointers in
38741** sqlite3GlobalConfig.m with pointers to the routines in this file. The
38742** arguments specify the block of memory to manage.
38743**
38744** This routine is only called by sqlite3_config(), and therefore
38745** is not required to be threadsafe (it is not).
38746*/
38747SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
38748  static const sqlite3_mem_methods winMemMethods = {
38749    winMemMalloc,
38750    winMemFree,
38751    winMemRealloc,
38752    winMemSize,
38753    winMemRoundup,
38754    winMemInit,
38755    winMemShutdown,
38756    &win_mem_data
38757  };
38758  return &winMemMethods;
38759}
38760
38761SQLITE_PRIVATE void sqlite3MemSetDefault(void){
38762  sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
38763}
38764#endif /* SQLITE_WIN32_MALLOC */
38765
38766/*
38767** Convert a UTF-8 string to Microsoft Unicode.
38768**
38769** Space to hold the returned string is obtained from sqlite3_malloc().
38770*/
38771static LPWSTR winUtf8ToUnicode(const char *zText){
38772  int nChar;
38773  LPWSTR zWideText;
38774
38775  nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
38776  if( nChar==0 ){
38777    return 0;
38778  }
38779  zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
38780  if( zWideText==0 ){
38781    return 0;
38782  }
38783  nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
38784                                nChar);
38785  if( nChar==0 ){
38786    sqlite3_free(zWideText);
38787    zWideText = 0;
38788  }
38789  return zWideText;
38790}
38791
38792/*
38793** Convert a Microsoft Unicode string to UTF-8.
38794**
38795** Space to hold the returned string is obtained from sqlite3_malloc().
38796*/
38797static char *winUnicodeToUtf8(LPCWSTR zWideText){
38798  int nByte;
38799  char *zText;
38800
38801  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
38802  if( nByte == 0 ){
38803    return 0;
38804  }
38805  zText = sqlite3MallocZero( nByte );
38806  if( zText==0 ){
38807    return 0;
38808  }
38809  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
38810                                0, 0);
38811  if( nByte == 0 ){
38812    sqlite3_free(zText);
38813    zText = 0;
38814  }
38815  return zText;
38816}
38817
38818/*
38819** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
38820** code page.
38821**
38822** Space to hold the returned string is obtained from sqlite3_malloc().
38823*/
38824static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
38825  int nByte;
38826  LPWSTR zMbcsText;
38827  int codepage = useAnsi ? CP_ACP : CP_OEMCP;
38828
38829  nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
38830                                0)*sizeof(WCHAR);
38831  if( nByte==0 ){
38832    return 0;
38833  }
38834  zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
38835  if( zMbcsText==0 ){
38836    return 0;
38837  }
38838  nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
38839                                nByte);
38840  if( nByte==0 ){
38841    sqlite3_free(zMbcsText);
38842    zMbcsText = 0;
38843  }
38844  return zMbcsText;
38845}
38846
38847/*
38848** Convert a Microsoft Unicode string to a multi-byte character string,
38849** using the ANSI or OEM code page.
38850**
38851** Space to hold the returned string is obtained from sqlite3_malloc().
38852*/
38853static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
38854  int nByte;
38855  char *zText;
38856  int codepage = useAnsi ? CP_ACP : CP_OEMCP;
38857
38858  nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
38859  if( nByte == 0 ){
38860    return 0;
38861  }
38862  zText = sqlite3MallocZero( nByte );
38863  if( zText==0 ){
38864    return 0;
38865  }
38866  nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
38867                                nByte, 0, 0);
38868  if( nByte == 0 ){
38869    sqlite3_free(zText);
38870    zText = 0;
38871  }
38872  return zText;
38873}
38874
38875/*
38876** Convert a multi-byte character string to UTF-8.
38877**
38878** Space to hold the returned string is obtained from sqlite3_malloc().
38879*/
38880static char *winMbcsToUtf8(const char *zText, int useAnsi){
38881  char *zTextUtf8;
38882  LPWSTR zTmpWide;
38883
38884  zTmpWide = winMbcsToUnicode(zText, useAnsi);
38885  if( zTmpWide==0 ){
38886    return 0;
38887  }
38888  zTextUtf8 = winUnicodeToUtf8(zTmpWide);
38889  sqlite3_free(zTmpWide);
38890  return zTextUtf8;
38891}
38892
38893/*
38894** Convert a UTF-8 string to a multi-byte character string.
38895**
38896** Space to hold the returned string is obtained from sqlite3_malloc().
38897*/
38898static char *winUtf8ToMbcs(const char *zText, int useAnsi){
38899  char *zTextMbcs;
38900  LPWSTR zTmpWide;
38901
38902  zTmpWide = winUtf8ToUnicode(zText);
38903  if( zTmpWide==0 ){
38904    return 0;
38905  }
38906  zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
38907  sqlite3_free(zTmpWide);
38908  return zTextMbcs;
38909}
38910
38911/*
38912** This is a public wrapper for the winUtf8ToUnicode() function.
38913*/
38914SQLITE_API LPWSTR SQLITE_STDCALL sqlite3_win32_utf8_to_unicode(const char *zText){
38915#ifdef SQLITE_ENABLE_API_ARMOR
38916  if( !zText ){
38917    (void)SQLITE_MISUSE_BKPT;
38918    return 0;
38919  }
38920#endif
38921#ifndef SQLITE_OMIT_AUTOINIT
38922  if( sqlite3_initialize() ) return 0;
38923#endif
38924  return winUtf8ToUnicode(zText);
38925}
38926
38927/*
38928** This is a public wrapper for the winUnicodeToUtf8() function.
38929*/
38930SQLITE_API char *SQLITE_STDCALL sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
38931#ifdef SQLITE_ENABLE_API_ARMOR
38932  if( !zWideText ){
38933    (void)SQLITE_MISUSE_BKPT;
38934    return 0;
38935  }
38936#endif
38937#ifndef SQLITE_OMIT_AUTOINIT
38938  if( sqlite3_initialize() ) return 0;
38939#endif
38940  return winUnicodeToUtf8(zWideText);
38941}
38942
38943/*
38944** This is a public wrapper for the winMbcsToUtf8() function.
38945*/
38946SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8(const char *zText){
38947#ifdef SQLITE_ENABLE_API_ARMOR
38948  if( !zText ){
38949    (void)SQLITE_MISUSE_BKPT;
38950    return 0;
38951  }
38952#endif
38953#ifndef SQLITE_OMIT_AUTOINIT
38954  if( sqlite3_initialize() ) return 0;
38955#endif
38956  return winMbcsToUtf8(zText, osAreFileApisANSI());
38957}
38958
38959/*
38960** This is a public wrapper for the winMbcsToUtf8() function.
38961*/
38962SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
38963#ifdef SQLITE_ENABLE_API_ARMOR
38964  if( !zText ){
38965    (void)SQLITE_MISUSE_BKPT;
38966    return 0;
38967  }
38968#endif
38969#ifndef SQLITE_OMIT_AUTOINIT
38970  if( sqlite3_initialize() ) return 0;
38971#endif
38972  return winMbcsToUtf8(zText, useAnsi);
38973}
38974
38975/*
38976** This is a public wrapper for the winUtf8ToMbcs() function.
38977*/
38978SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs(const char *zText){
38979#ifdef SQLITE_ENABLE_API_ARMOR
38980  if( !zText ){
38981    (void)SQLITE_MISUSE_BKPT;
38982    return 0;
38983  }
38984#endif
38985#ifndef SQLITE_OMIT_AUTOINIT
38986  if( sqlite3_initialize() ) return 0;
38987#endif
38988  return winUtf8ToMbcs(zText, osAreFileApisANSI());
38989}
38990
38991/*
38992** This is a public wrapper for the winUtf8ToMbcs() function.
38993*/
38994SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
38995#ifdef SQLITE_ENABLE_API_ARMOR
38996  if( !zText ){
38997    (void)SQLITE_MISUSE_BKPT;
38998    return 0;
38999  }
39000#endif
39001#ifndef SQLITE_OMIT_AUTOINIT
39002  if( sqlite3_initialize() ) return 0;
39003#endif
39004  return winUtf8ToMbcs(zText, useAnsi);
39005}
39006
39007/*
39008** This function sets the data directory or the temporary directory based on
39009** the provided arguments.  The type argument must be 1 in order to set the
39010** data directory or 2 in order to set the temporary directory.  The zValue
39011** argument is the name of the directory to use.  The return value will be
39012** SQLITE_OK if successful.
39013*/
39014SQLITE_API int SQLITE_STDCALL sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
39015  char **ppDirectory = 0;
39016#ifndef SQLITE_OMIT_AUTOINIT
39017  int rc = sqlite3_initialize();
39018  if( rc ) return rc;
39019#endif
39020  if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
39021    ppDirectory = &sqlite3_data_directory;
39022  }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
39023    ppDirectory = &sqlite3_temp_directory;
39024  }
39025  assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
39026          || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
39027  );
39028  assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
39029  if( ppDirectory ){
39030    char *zValueUtf8 = 0;
39031    if( zValue && zValue[0] ){
39032      zValueUtf8 = winUnicodeToUtf8(zValue);
39033      if ( zValueUtf8==0 ){
39034        return SQLITE_NOMEM_BKPT;
39035      }
39036    }
39037    sqlite3_free(*ppDirectory);
39038    *ppDirectory = zValueUtf8;
39039    return SQLITE_OK;
39040  }
39041  return SQLITE_ERROR;
39042}
39043
39044/*
39045** The return value of winGetLastErrorMsg
39046** is zero if the error message fits in the buffer, or non-zero
39047** otherwise (if the message was truncated).
39048*/
39049static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
39050  /* FormatMessage returns 0 on failure.  Otherwise it
39051  ** returns the number of TCHARs written to the output
39052  ** buffer, excluding the terminating null char.
39053  */
39054  DWORD dwLen = 0;
39055  char *zOut = 0;
39056
39057  if( osIsNT() ){
39058#if SQLITE_OS_WINRT
39059    WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
39060    dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
39061                             FORMAT_MESSAGE_IGNORE_INSERTS,
39062                             NULL,
39063                             lastErrno,
39064                             0,
39065                             zTempWide,
39066                             SQLITE_WIN32_MAX_ERRMSG_CHARS,
39067                             0);
39068#else
39069    LPWSTR zTempWide = NULL;
39070    dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
39071                             FORMAT_MESSAGE_FROM_SYSTEM |
39072                             FORMAT_MESSAGE_IGNORE_INSERTS,
39073                             NULL,
39074                             lastErrno,
39075                             0,
39076                             (LPWSTR) &zTempWide,
39077                             0,
39078                             0);
39079#endif
39080    if( dwLen > 0 ){
39081      /* allocate a buffer and convert to UTF8 */
39082      sqlite3BeginBenignMalloc();
39083      zOut = winUnicodeToUtf8(zTempWide);
39084      sqlite3EndBenignMalloc();
39085#if !SQLITE_OS_WINRT
39086      /* free the system buffer allocated by FormatMessage */
39087      osLocalFree(zTempWide);
39088#endif
39089    }
39090  }
39091#ifdef SQLITE_WIN32_HAS_ANSI
39092  else{
39093    char *zTemp = NULL;
39094    dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
39095                             FORMAT_MESSAGE_FROM_SYSTEM |
39096                             FORMAT_MESSAGE_IGNORE_INSERTS,
39097                             NULL,
39098                             lastErrno,
39099                             0,
39100                             (LPSTR) &zTemp,
39101                             0,
39102                             0);
39103    if( dwLen > 0 ){
39104      /* allocate a buffer and convert to UTF8 */
39105      sqlite3BeginBenignMalloc();
39106      zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
39107      sqlite3EndBenignMalloc();
39108      /* free the system buffer allocated by FormatMessage */
39109      osLocalFree(zTemp);
39110    }
39111  }
39112#endif
39113  if( 0 == dwLen ){
39114    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
39115  }else{
39116    /* copy a maximum of nBuf chars to output buffer */
39117    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
39118    /* free the UTF8 buffer */
39119    sqlite3_free(zOut);
39120  }
39121  return 0;
39122}
39123
39124/*
39125**
39126** This function - winLogErrorAtLine() - is only ever called via the macro
39127** winLogError().
39128**
39129** This routine is invoked after an error occurs in an OS function.
39130** It logs a message using sqlite3_log() containing the current value of
39131** error code and, if possible, the human-readable equivalent from
39132** FormatMessage.
39133**
39134** The first argument passed to the macro should be the error code that
39135** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
39136** The two subsequent arguments should be the name of the OS function that
39137** failed and the associated file-system path, if any.
39138*/
39139#define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
39140static int winLogErrorAtLine(
39141  int errcode,                    /* SQLite error code */
39142  DWORD lastErrno,                /* Win32 last error */
39143  const char *zFunc,              /* Name of OS function that failed */
39144  const char *zPath,              /* File path associated with error */
39145  int iLine                       /* Source line number where error occurred */
39146){
39147  char zMsg[500];                 /* Human readable error text */
39148  int i;                          /* Loop counter */
39149
39150  zMsg[0] = 0;
39151  winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
39152  assert( errcode!=SQLITE_OK );
39153  if( zPath==0 ) zPath = "";
39154  for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
39155  zMsg[i] = 0;
39156  sqlite3_log(errcode,
39157      "os_win.c:%d: (%lu) %s(%s) - %s",
39158      iLine, lastErrno, zFunc, zPath, zMsg
39159  );
39160
39161  return errcode;
39162}
39163
39164/*
39165** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
39166** will be retried following a locking error - probably caused by
39167** antivirus software.  Also the initial delay before the first retry.
39168** The delay increases linearly with each retry.
39169*/
39170#ifndef SQLITE_WIN32_IOERR_RETRY
39171# define SQLITE_WIN32_IOERR_RETRY 10
39172#endif
39173#ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
39174# define SQLITE_WIN32_IOERR_RETRY_DELAY 25
39175#endif
39176static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
39177static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
39178
39179/*
39180** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
39181** error code obtained via GetLastError() is eligible to be retried.  It
39182** must accept the error code DWORD as its only argument and should return
39183** non-zero if the error code is transient in nature and the operation
39184** responsible for generating the original error might succeed upon being
39185** retried.  The argument to this macro should be a variable.
39186**
39187** Additionally, a macro named "winIoerrCanRetry2" may be defined.  If it
39188** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
39189** returns zero.  The "winIoerrCanRetry2" macro is completely optional and
39190** may be used to include additional error codes in the set that should
39191** result in the failing I/O operation being retried by the caller.  If
39192** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
39193** identical to those of the "winIoerrCanRetry1" macro.
39194*/
39195#if !defined(winIoerrCanRetry1)
39196#define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED)        || \
39197                              ((a)==ERROR_SHARING_VIOLATION)    || \
39198                              ((a)==ERROR_LOCK_VIOLATION)       || \
39199                              ((a)==ERROR_DEV_NOT_EXIST)        || \
39200                              ((a)==ERROR_NETNAME_DELETED)      || \
39201                              ((a)==ERROR_SEM_TIMEOUT)          || \
39202                              ((a)==ERROR_NETWORK_UNREACHABLE))
39203#endif
39204
39205/*
39206** If a ReadFile() or WriteFile() error occurs, invoke this routine
39207** to see if it should be retried.  Return TRUE to retry.  Return FALSE
39208** to give up with an error.
39209*/
39210static int winRetryIoerr(int *pnRetry, DWORD *pError){
39211  DWORD e = osGetLastError();
39212  if( *pnRetry>=winIoerrRetry ){
39213    if( pError ){
39214      *pError = e;
39215    }
39216    return 0;
39217  }
39218  if( winIoerrCanRetry1(e) ){
39219    sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
39220    ++*pnRetry;
39221    return 1;
39222  }
39223#if defined(winIoerrCanRetry2)
39224  else if( winIoerrCanRetry2(e) ){
39225    sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
39226    ++*pnRetry;
39227    return 1;
39228  }
39229#endif
39230  if( pError ){
39231    *pError = e;
39232  }
39233  return 0;
39234}
39235
39236/*
39237** Log a I/O error retry episode.
39238*/
39239static void winLogIoerr(int nRetry, int lineno){
39240  if( nRetry ){
39241    sqlite3_log(SQLITE_NOTICE,
39242      "delayed %dms for lock/sharing conflict at line %d",
39243      winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
39244    );
39245  }
39246}
39247
39248/*
39249** This #if does not rely on the SQLITE_OS_WINCE define because the
39250** corresponding section in "date.c" cannot use it.
39251*/
39252#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
39253    (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
39254/*
39255** The MSVC CRT on Windows CE may not have a localtime() function.
39256** So define a substitute.
39257*/
39258/* #  include <time.h> */
39259struct tm *__cdecl localtime(const time_t *t)
39260{
39261  static struct tm y;
39262  FILETIME uTm, lTm;
39263  SYSTEMTIME pTm;
39264  sqlite3_int64 t64;
39265  t64 = *t;
39266  t64 = (t64 + 11644473600)*10000000;
39267  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
39268  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
39269  osFileTimeToLocalFileTime(&uTm,&lTm);
39270  osFileTimeToSystemTime(&lTm,&pTm);
39271  y.tm_year = pTm.wYear - 1900;
39272  y.tm_mon = pTm.wMonth - 1;
39273  y.tm_wday = pTm.wDayOfWeek;
39274  y.tm_mday = pTm.wDay;
39275  y.tm_hour = pTm.wHour;
39276  y.tm_min = pTm.wMinute;
39277  y.tm_sec = pTm.wSecond;
39278  return &y;
39279}
39280#endif
39281
39282#if SQLITE_OS_WINCE
39283/*************************************************************************
39284** This section contains code for WinCE only.
39285*/
39286#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
39287
39288/*
39289** Acquire a lock on the handle h
39290*/
39291static void winceMutexAcquire(HANDLE h){
39292   DWORD dwErr;
39293   do {
39294     dwErr = osWaitForSingleObject(h, INFINITE);
39295   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
39296}
39297/*
39298** Release a lock acquired by winceMutexAcquire()
39299*/
39300#define winceMutexRelease(h) ReleaseMutex(h)
39301
39302/*
39303** Create the mutex and shared memory used for locking in the file
39304** descriptor pFile
39305*/
39306static int winceCreateLock(const char *zFilename, winFile *pFile){
39307  LPWSTR zTok;
39308  LPWSTR zName;
39309  DWORD lastErrno;
39310  BOOL bLogged = FALSE;
39311  BOOL bInit = TRUE;
39312
39313  zName = winUtf8ToUnicode(zFilename);
39314  if( zName==0 ){
39315    /* out of memory */
39316    return SQLITE_IOERR_NOMEM_BKPT;
39317  }
39318
39319  /* Initialize the local lockdata */
39320  memset(&pFile->local, 0, sizeof(pFile->local));
39321
39322  /* Replace the backslashes from the filename and lowercase it
39323  ** to derive a mutex name. */
39324  zTok = osCharLowerW(zName);
39325  for (;*zTok;zTok++){
39326    if (*zTok == '\\') *zTok = '_';
39327  }
39328
39329  /* Create/open the named mutex */
39330  pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
39331  if (!pFile->hMutex){
39332    pFile->lastErrno = osGetLastError();
39333    sqlite3_free(zName);
39334    return winLogError(SQLITE_IOERR, pFile->lastErrno,
39335                       "winceCreateLock1", zFilename);
39336  }
39337
39338  /* Acquire the mutex before continuing */
39339  winceMutexAcquire(pFile->hMutex);
39340
39341  /* Since the names of named mutexes, semaphores, file mappings etc are
39342  ** case-sensitive, take advantage of that by uppercasing the mutex name
39343  ** and using that as the shared filemapping name.
39344  */
39345  osCharUpperW(zName);
39346  pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
39347                                        PAGE_READWRITE, 0, sizeof(winceLock),
39348                                        zName);
39349
39350  /* Set a flag that indicates we're the first to create the memory so it
39351  ** must be zero-initialized */
39352  lastErrno = osGetLastError();
39353  if (lastErrno == ERROR_ALREADY_EXISTS){
39354    bInit = FALSE;
39355  }
39356
39357  sqlite3_free(zName);
39358
39359  /* If we succeeded in making the shared memory handle, map it. */
39360  if( pFile->hShared ){
39361    pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
39362             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
39363    /* If mapping failed, close the shared memory handle and erase it */
39364    if( !pFile->shared ){
39365      pFile->lastErrno = osGetLastError();
39366      winLogError(SQLITE_IOERR, pFile->lastErrno,
39367                  "winceCreateLock2", zFilename);
39368      bLogged = TRUE;
39369      osCloseHandle(pFile->hShared);
39370      pFile->hShared = NULL;
39371    }
39372  }
39373
39374  /* If shared memory could not be created, then close the mutex and fail */
39375  if( pFile->hShared==NULL ){
39376    if( !bLogged ){
39377      pFile->lastErrno = lastErrno;
39378      winLogError(SQLITE_IOERR, pFile->lastErrno,
39379                  "winceCreateLock3", zFilename);
39380      bLogged = TRUE;
39381    }
39382    winceMutexRelease(pFile->hMutex);
39383    osCloseHandle(pFile->hMutex);
39384    pFile->hMutex = NULL;
39385    return SQLITE_IOERR;
39386  }
39387
39388  /* Initialize the shared memory if we're supposed to */
39389  if( bInit ){
39390    memset(pFile->shared, 0, sizeof(winceLock));
39391  }
39392
39393  winceMutexRelease(pFile->hMutex);
39394  return SQLITE_OK;
39395}
39396
39397/*
39398** Destroy the part of winFile that deals with wince locks
39399*/
39400static void winceDestroyLock(winFile *pFile){
39401  if (pFile->hMutex){
39402    /* Acquire the mutex */
39403    winceMutexAcquire(pFile->hMutex);
39404
39405    /* The following blocks should probably assert in debug mode, but they
39406       are to cleanup in case any locks remained open */
39407    if (pFile->local.nReaders){
39408      pFile->shared->nReaders --;
39409    }
39410    if (pFile->local.bReserved){
39411      pFile->shared->bReserved = FALSE;
39412    }
39413    if (pFile->local.bPending){
39414      pFile->shared->bPending = FALSE;
39415    }
39416    if (pFile->local.bExclusive){
39417      pFile->shared->bExclusive = FALSE;
39418    }
39419
39420    /* De-reference and close our copy of the shared memory handle */
39421    osUnmapViewOfFile(pFile->shared);
39422    osCloseHandle(pFile->hShared);
39423
39424    /* Done with the mutex */
39425    winceMutexRelease(pFile->hMutex);
39426    osCloseHandle(pFile->hMutex);
39427    pFile->hMutex = NULL;
39428  }
39429}
39430
39431/*
39432** An implementation of the LockFile() API of Windows for CE
39433*/
39434static BOOL winceLockFile(
39435  LPHANDLE phFile,
39436  DWORD dwFileOffsetLow,
39437  DWORD dwFileOffsetHigh,
39438  DWORD nNumberOfBytesToLockLow,
39439  DWORD nNumberOfBytesToLockHigh
39440){
39441  winFile *pFile = HANDLE_TO_WINFILE(phFile);
39442  BOOL bReturn = FALSE;
39443
39444  UNUSED_PARAMETER(dwFileOffsetHigh);
39445  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
39446
39447  if (!pFile->hMutex) return TRUE;
39448  winceMutexAcquire(pFile->hMutex);
39449
39450  /* Wanting an exclusive lock? */
39451  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
39452       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
39453    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
39454       pFile->shared->bExclusive = TRUE;
39455       pFile->local.bExclusive = TRUE;
39456       bReturn = TRUE;
39457    }
39458  }
39459
39460  /* Want a read-only lock? */
39461  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
39462           nNumberOfBytesToLockLow == 1){
39463    if (pFile->shared->bExclusive == 0){
39464      pFile->local.nReaders ++;
39465      if (pFile->local.nReaders == 1){
39466        pFile->shared->nReaders ++;
39467      }
39468      bReturn = TRUE;
39469    }
39470  }
39471
39472  /* Want a pending lock? */
39473  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
39474           && nNumberOfBytesToLockLow == 1){
39475    /* If no pending lock has been acquired, then acquire it */
39476    if (pFile->shared->bPending == 0) {
39477      pFile->shared->bPending = TRUE;
39478      pFile->local.bPending = TRUE;
39479      bReturn = TRUE;
39480    }
39481  }
39482
39483  /* Want a reserved lock? */
39484  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
39485           && nNumberOfBytesToLockLow == 1){
39486    if (pFile->shared->bReserved == 0) {
39487      pFile->shared->bReserved = TRUE;
39488      pFile->local.bReserved = TRUE;
39489      bReturn = TRUE;
39490    }
39491  }
39492
39493  winceMutexRelease(pFile->hMutex);
39494  return bReturn;
39495}
39496
39497/*
39498** An implementation of the UnlockFile API of Windows for CE
39499*/
39500static BOOL winceUnlockFile(
39501  LPHANDLE phFile,
39502  DWORD dwFileOffsetLow,
39503  DWORD dwFileOffsetHigh,
39504  DWORD nNumberOfBytesToUnlockLow,
39505  DWORD nNumberOfBytesToUnlockHigh
39506){
39507  winFile *pFile = HANDLE_TO_WINFILE(phFile);
39508  BOOL bReturn = FALSE;
39509
39510  UNUSED_PARAMETER(dwFileOffsetHigh);
39511  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
39512
39513  if (!pFile->hMutex) return TRUE;
39514  winceMutexAcquire(pFile->hMutex);
39515
39516  /* Releasing a reader lock or an exclusive lock */
39517  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
39518    /* Did we have an exclusive lock? */
39519    if (pFile->local.bExclusive){
39520      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
39521      pFile->local.bExclusive = FALSE;
39522      pFile->shared->bExclusive = FALSE;
39523      bReturn = TRUE;
39524    }
39525
39526    /* Did we just have a reader lock? */
39527    else if (pFile->local.nReaders){
39528      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
39529             || nNumberOfBytesToUnlockLow == 1);
39530      pFile->local.nReaders --;
39531      if (pFile->local.nReaders == 0)
39532      {
39533        pFile->shared->nReaders --;
39534      }
39535      bReturn = TRUE;
39536    }
39537  }
39538
39539  /* Releasing a pending lock */
39540  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
39541           && nNumberOfBytesToUnlockLow == 1){
39542    if (pFile->local.bPending){
39543      pFile->local.bPending = FALSE;
39544      pFile->shared->bPending = FALSE;
39545      bReturn = TRUE;
39546    }
39547  }
39548  /* Releasing a reserved lock */
39549  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
39550           && nNumberOfBytesToUnlockLow == 1){
39551    if (pFile->local.bReserved) {
39552      pFile->local.bReserved = FALSE;
39553      pFile->shared->bReserved = FALSE;
39554      bReturn = TRUE;
39555    }
39556  }
39557
39558  winceMutexRelease(pFile->hMutex);
39559  return bReturn;
39560}
39561/*
39562** End of the special code for wince
39563*****************************************************************************/
39564#endif /* SQLITE_OS_WINCE */
39565
39566/*
39567** Lock a file region.
39568*/
39569static BOOL winLockFile(
39570  LPHANDLE phFile,
39571  DWORD flags,
39572  DWORD offsetLow,
39573  DWORD offsetHigh,
39574  DWORD numBytesLow,
39575  DWORD numBytesHigh
39576){
39577#if SQLITE_OS_WINCE
39578  /*
39579  ** NOTE: Windows CE is handled differently here due its lack of the Win32
39580  **       API LockFile.
39581  */
39582  return winceLockFile(phFile, offsetLow, offsetHigh,
39583                       numBytesLow, numBytesHigh);
39584#else
39585  if( osIsNT() ){
39586    OVERLAPPED ovlp;
39587    memset(&ovlp, 0, sizeof(OVERLAPPED));
39588    ovlp.Offset = offsetLow;
39589    ovlp.OffsetHigh = offsetHigh;
39590    return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
39591  }else{
39592    return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
39593                      numBytesHigh);
39594  }
39595#endif
39596}
39597
39598/*
39599** Unlock a file region.
39600 */
39601static BOOL winUnlockFile(
39602  LPHANDLE phFile,
39603  DWORD offsetLow,
39604  DWORD offsetHigh,
39605  DWORD numBytesLow,
39606  DWORD numBytesHigh
39607){
39608#if SQLITE_OS_WINCE
39609  /*
39610  ** NOTE: Windows CE is handled differently here due its lack of the Win32
39611  **       API UnlockFile.
39612  */
39613  return winceUnlockFile(phFile, offsetLow, offsetHigh,
39614                         numBytesLow, numBytesHigh);
39615#else
39616  if( osIsNT() ){
39617    OVERLAPPED ovlp;
39618    memset(&ovlp, 0, sizeof(OVERLAPPED));
39619    ovlp.Offset = offsetLow;
39620    ovlp.OffsetHigh = offsetHigh;
39621    return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
39622  }else{
39623    return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
39624                        numBytesHigh);
39625  }
39626#endif
39627}
39628
39629/*****************************************************************************
39630** The next group of routines implement the I/O methods specified
39631** by the sqlite3_io_methods object.
39632******************************************************************************/
39633
39634/*
39635** Some Microsoft compilers lack this definition.
39636*/
39637#ifndef INVALID_SET_FILE_POINTER
39638# define INVALID_SET_FILE_POINTER ((DWORD)-1)
39639#endif
39640
39641/*
39642** Move the current position of the file handle passed as the first
39643** argument to offset iOffset within the file. If successful, return 0.
39644** Otherwise, set pFile->lastErrno and return non-zero.
39645*/
39646static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
39647#if !SQLITE_OS_WINRT
39648  LONG upperBits;                 /* Most sig. 32 bits of new offset */
39649  LONG lowerBits;                 /* Least sig. 32 bits of new offset */
39650  DWORD dwRet;                    /* Value returned by SetFilePointer() */
39651  DWORD lastErrno;                /* Value returned by GetLastError() */
39652
39653  OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
39654
39655  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
39656  lowerBits = (LONG)(iOffset & 0xffffffff);
39657
39658  /* API oddity: If successful, SetFilePointer() returns a dword
39659  ** containing the lower 32-bits of the new file-offset. Or, if it fails,
39660  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
39661  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
39662  ** whether an error has actually occurred, it is also necessary to call
39663  ** GetLastError().
39664  */
39665  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
39666
39667  if( (dwRet==INVALID_SET_FILE_POINTER
39668      && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
39669    pFile->lastErrno = lastErrno;
39670    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
39671                "winSeekFile", pFile->zPath);
39672    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
39673    return 1;
39674  }
39675
39676  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
39677  return 0;
39678#else
39679  /*
39680  ** Same as above, except that this implementation works for WinRT.
39681  */
39682
39683  LARGE_INTEGER x;                /* The new offset */
39684  BOOL bRet;                      /* Value returned by SetFilePointerEx() */
39685
39686  x.QuadPart = iOffset;
39687  bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
39688
39689  if(!bRet){
39690    pFile->lastErrno = osGetLastError();
39691    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
39692                "winSeekFile", pFile->zPath);
39693    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
39694    return 1;
39695  }
39696
39697  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
39698  return 0;
39699#endif
39700}
39701
39702#if SQLITE_MAX_MMAP_SIZE>0
39703/* Forward references to VFS helper methods used for memory mapped files */
39704static int winMapfile(winFile*, sqlite3_int64);
39705static int winUnmapfile(winFile*);
39706#endif
39707
39708/*
39709** Close a file.
39710**
39711** It is reported that an attempt to close a handle might sometimes
39712** fail.  This is a very unreasonable result, but Windows is notorious
39713** for being unreasonable so I do not doubt that it might happen.  If
39714** the close fails, we pause for 100 milliseconds and try again.  As
39715** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
39716** giving up and returning an error.
39717*/
39718#define MX_CLOSE_ATTEMPT 3
39719static int winClose(sqlite3_file *id){
39720  int rc, cnt = 0;
39721  winFile *pFile = (winFile*)id;
39722
39723  assert( id!=0 );
39724#ifndef SQLITE_OMIT_WAL
39725  assert( pFile->pShm==0 );
39726#endif
39727  assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
39728  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
39729           osGetCurrentProcessId(), pFile, pFile->h));
39730
39731#if SQLITE_MAX_MMAP_SIZE>0
39732  winUnmapfile(pFile);
39733#endif
39734
39735  do{
39736    rc = osCloseHandle(pFile->h);
39737    /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
39738  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
39739#if SQLITE_OS_WINCE
39740#define WINCE_DELETION_ATTEMPTS 3
39741  {
39742    winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
39743    if( pAppData==NULL || !pAppData->bNoLock ){
39744      winceDestroyLock(pFile);
39745    }
39746  }
39747  if( pFile->zDeleteOnClose ){
39748    int cnt = 0;
39749    while(
39750           osDeleteFileW(pFile->zDeleteOnClose)==0
39751        && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
39752        && cnt++ < WINCE_DELETION_ATTEMPTS
39753    ){
39754       sqlite3_win32_sleep(100);  /* Wait a little before trying again */
39755    }
39756    sqlite3_free(pFile->zDeleteOnClose);
39757  }
39758#endif
39759  if( rc ){
39760    pFile->h = NULL;
39761  }
39762  OpenCounter(-1);
39763  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
39764           osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
39765  return rc ? SQLITE_OK
39766            : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
39767                          "winClose", pFile->zPath);
39768}
39769
39770/*
39771** Read data from a file into a buffer.  Return SQLITE_OK if all
39772** bytes were read successfully and SQLITE_IOERR if anything goes
39773** wrong.
39774*/
39775static int winRead(
39776  sqlite3_file *id,          /* File to read from */
39777  void *pBuf,                /* Write content into this buffer */
39778  int amt,                   /* Number of bytes to read */
39779  sqlite3_int64 offset       /* Begin reading at this offset */
39780){
39781#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
39782  OVERLAPPED overlapped;          /* The offset for ReadFile. */
39783#endif
39784  winFile *pFile = (winFile*)id;  /* file handle */
39785  DWORD nRead;                    /* Number of bytes actually read from file */
39786  int nRetry = 0;                 /* Number of retrys */
39787
39788  assert( id!=0 );
39789  assert( amt>0 );
39790  assert( offset>=0 );
39791  SimulateIOError(return SQLITE_IOERR_READ);
39792  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
39793           "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
39794           pFile->h, pBuf, amt, offset, pFile->locktype));
39795
39796#if SQLITE_MAX_MMAP_SIZE>0
39797  /* Deal with as much of this read request as possible by transfering
39798  ** data from the memory mapping using memcpy().  */
39799  if( offset<pFile->mmapSize ){
39800    if( offset+amt <= pFile->mmapSize ){
39801      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
39802      OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39803               osGetCurrentProcessId(), pFile, pFile->h));
39804      return SQLITE_OK;
39805    }else{
39806      int nCopy = (int)(pFile->mmapSize - offset);
39807      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
39808      pBuf = &((u8 *)pBuf)[nCopy];
39809      amt -= nCopy;
39810      offset += nCopy;
39811    }
39812  }
39813#endif
39814
39815#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
39816  if( winSeekFile(pFile, offset) ){
39817    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
39818             osGetCurrentProcessId(), pFile, pFile->h));
39819    return SQLITE_FULL;
39820  }
39821  while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
39822#else
39823  memset(&overlapped, 0, sizeof(OVERLAPPED));
39824  overlapped.Offset = (LONG)(offset & 0xffffffff);
39825  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
39826  while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
39827         osGetLastError()!=ERROR_HANDLE_EOF ){
39828#endif
39829    DWORD lastErrno;
39830    if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
39831    pFile->lastErrno = lastErrno;
39832    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
39833             osGetCurrentProcessId(), pFile, pFile->h));
39834    return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
39835                       "winRead", pFile->zPath);
39836  }
39837  winLogIoerr(nRetry, __LINE__);
39838  if( nRead<(DWORD)amt ){
39839    /* Unread parts of the buffer must be zero-filled */
39840    memset(&((char*)pBuf)[nRead], 0, amt-nRead);
39841    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
39842             osGetCurrentProcessId(), pFile, pFile->h));
39843    return SQLITE_IOERR_SHORT_READ;
39844  }
39845
39846  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39847           osGetCurrentProcessId(), pFile, pFile->h));
39848  return SQLITE_OK;
39849}
39850
39851/*
39852** Write data from a buffer into a file.  Return SQLITE_OK on success
39853** or some other error code on failure.
39854*/
39855static int winWrite(
39856  sqlite3_file *id,               /* File to write into */
39857  const void *pBuf,               /* The bytes to be written */
39858  int amt,                        /* Number of bytes to write */
39859  sqlite3_int64 offset            /* Offset into the file to begin writing at */
39860){
39861  int rc = 0;                     /* True if error has occurred, else false */
39862  winFile *pFile = (winFile*)id;  /* File handle */
39863  int nRetry = 0;                 /* Number of retries */
39864
39865  assert( amt>0 );
39866  assert( pFile );
39867  SimulateIOError(return SQLITE_IOERR_WRITE);
39868  SimulateDiskfullError(return SQLITE_FULL);
39869
39870  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
39871           "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
39872           pFile->h, pBuf, amt, offset, pFile->locktype));
39873
39874#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
39875  /* Deal with as much of this write request as possible by transfering
39876  ** data from the memory mapping using memcpy().  */
39877  if( offset<pFile->mmapSize ){
39878    if( offset+amt <= pFile->mmapSize ){
39879      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
39880      OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39881               osGetCurrentProcessId(), pFile, pFile->h));
39882      return SQLITE_OK;
39883    }else{
39884      int nCopy = (int)(pFile->mmapSize - offset);
39885      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
39886      pBuf = &((u8 *)pBuf)[nCopy];
39887      amt -= nCopy;
39888      offset += nCopy;
39889    }
39890  }
39891#endif
39892
39893#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
39894  rc = winSeekFile(pFile, offset);
39895  if( rc==0 ){
39896#else
39897  {
39898#endif
39899#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
39900    OVERLAPPED overlapped;        /* The offset for WriteFile. */
39901#endif
39902    u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
39903    int nRem = amt;               /* Number of bytes yet to be written */
39904    DWORD nWrite;                 /* Bytes written by each WriteFile() call */
39905    DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
39906
39907#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
39908    memset(&overlapped, 0, sizeof(OVERLAPPED));
39909    overlapped.Offset = (LONG)(offset & 0xffffffff);
39910    overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
39911#endif
39912
39913    while( nRem>0 ){
39914#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
39915      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
39916#else
39917      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
39918#endif
39919        if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
39920        break;
39921      }
39922      assert( nWrite==0 || nWrite<=(DWORD)nRem );
39923      if( nWrite==0 || nWrite>(DWORD)nRem ){
39924        lastErrno = osGetLastError();
39925        break;
39926      }
39927#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
39928      offset += nWrite;
39929      overlapped.Offset = (LONG)(offset & 0xffffffff);
39930      overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
39931#endif
39932      aRem += nWrite;
39933      nRem -= nWrite;
39934    }
39935    if( nRem>0 ){
39936      pFile->lastErrno = lastErrno;
39937      rc = 1;
39938    }
39939  }
39940
39941  if( rc ){
39942    if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
39943       || ( pFile->lastErrno==ERROR_DISK_FULL )){
39944      OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
39945               osGetCurrentProcessId(), pFile, pFile->h));
39946      return winLogError(SQLITE_FULL, pFile->lastErrno,
39947                         "winWrite1", pFile->zPath);
39948    }
39949    OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
39950             osGetCurrentProcessId(), pFile, pFile->h));
39951    return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
39952                       "winWrite2", pFile->zPath);
39953  }else{
39954    winLogIoerr(nRetry, __LINE__);
39955  }
39956  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39957           osGetCurrentProcessId(), pFile, pFile->h));
39958  return SQLITE_OK;
39959}
39960
39961/*
39962** Truncate an open file to a specified size
39963*/
39964static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
39965  winFile *pFile = (winFile*)id;  /* File handle object */
39966  int rc = SQLITE_OK;             /* Return code for this function */
39967  DWORD lastErrno;
39968
39969  assert( pFile );
39970  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
39971  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
39972           osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
39973
39974  /* If the user has configured a chunk-size for this file, truncate the
39975  ** file so that it consists of an integer number of chunks (i.e. the
39976  ** actual file size after the operation may be larger than the requested
39977  ** size).
39978  */
39979  if( pFile->szChunk>0 ){
39980    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
39981  }
39982
39983  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
39984  if( winSeekFile(pFile, nByte) ){
39985    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
39986                     "winTruncate1", pFile->zPath);
39987  }else if( 0==osSetEndOfFile(pFile->h) &&
39988            ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
39989    pFile->lastErrno = lastErrno;
39990    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
39991                     "winTruncate2", pFile->zPath);
39992  }
39993
39994#if SQLITE_MAX_MMAP_SIZE>0
39995  /* If the file was truncated to a size smaller than the currently
39996  ** mapped region, reduce the effective mapping size as well. SQLite will
39997  ** use read() and write() to access data beyond this point from now on.
39998  */
39999  if( pFile->pMapRegion && nByte<pFile->mmapSize ){
40000    pFile->mmapSize = nByte;
40001  }
40002#endif
40003
40004  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
40005           osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
40006  return rc;
40007}
40008
40009#ifdef SQLITE_TEST
40010/*
40011** Count the number of fullsyncs and normal syncs.  This is used to test
40012** that syncs and fullsyncs are occuring at the right times.
40013*/
40014SQLITE_API int sqlite3_sync_count = 0;
40015SQLITE_API int sqlite3_fullsync_count = 0;
40016#endif
40017
40018/*
40019** Make sure all writes to a particular file are committed to disk.
40020*/
40021static int winSync(sqlite3_file *id, int flags){
40022#ifndef SQLITE_NO_SYNC
40023  /*
40024  ** Used only when SQLITE_NO_SYNC is not defined.
40025   */
40026  BOOL rc;
40027#endif
40028#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
40029    defined(SQLITE_HAVE_OS_TRACE)
40030  /*
40031  ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
40032  ** OSTRACE() macros.
40033   */
40034  winFile *pFile = (winFile*)id;
40035#else
40036  UNUSED_PARAMETER(id);
40037#endif
40038
40039  assert( pFile );
40040  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
40041  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
40042      || (flags&0x0F)==SQLITE_SYNC_FULL
40043  );
40044
40045  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
40046  ** line is to test that doing so does not cause any problems.
40047  */
40048  SimulateDiskfullError( return SQLITE_FULL );
40049
40050  OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
40051           osGetCurrentProcessId(), pFile, pFile->h, flags,
40052           pFile->locktype));
40053
40054#ifndef SQLITE_TEST
40055  UNUSED_PARAMETER(flags);
40056#else
40057  if( (flags&0x0F)==SQLITE_SYNC_FULL ){
40058    sqlite3_fullsync_count++;
40059  }
40060  sqlite3_sync_count++;
40061#endif
40062
40063  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
40064  ** no-op
40065  */
40066#ifdef SQLITE_NO_SYNC
40067  OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40068           osGetCurrentProcessId(), pFile, pFile->h));
40069  return SQLITE_OK;
40070#else
40071#if SQLITE_MAX_MMAP_SIZE>0
40072  if( pFile->pMapRegion ){
40073    if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
40074      OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
40075               "rc=SQLITE_OK\n", osGetCurrentProcessId(),
40076               pFile, pFile->pMapRegion));
40077    }else{
40078      pFile->lastErrno = osGetLastError();
40079      OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
40080               "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
40081               pFile, pFile->pMapRegion));
40082      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
40083                         "winSync1", pFile->zPath);
40084    }
40085  }
40086#endif
40087  rc = osFlushFileBuffers(pFile->h);
40088  SimulateIOError( rc=FALSE );
40089  if( rc ){
40090    OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40091             osGetCurrentProcessId(), pFile, pFile->h));
40092    return SQLITE_OK;
40093  }else{
40094    pFile->lastErrno = osGetLastError();
40095    OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
40096             osGetCurrentProcessId(), pFile, pFile->h));
40097    return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
40098                       "winSync2", pFile->zPath);
40099  }
40100#endif
40101}
40102
40103/*
40104** Determine the current size of a file in bytes
40105*/
40106static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
40107  winFile *pFile = (winFile*)id;
40108  int rc = SQLITE_OK;
40109
40110  assert( id!=0 );
40111  assert( pSize!=0 );
40112  SimulateIOError(return SQLITE_IOERR_FSTAT);
40113  OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
40114
40115#if SQLITE_OS_WINRT
40116  {
40117    FILE_STANDARD_INFO info;
40118    if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
40119                                     &info, sizeof(info)) ){
40120      *pSize = info.EndOfFile.QuadPart;
40121    }else{
40122      pFile->lastErrno = osGetLastError();
40123      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
40124                       "winFileSize", pFile->zPath);
40125    }
40126  }
40127#else
40128  {
40129    DWORD upperBits;
40130    DWORD lowerBits;
40131    DWORD lastErrno;
40132
40133    lowerBits = osGetFileSize(pFile->h, &upperBits);
40134    *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
40135    if(   (lowerBits == INVALID_FILE_SIZE)
40136       && ((lastErrno = osGetLastError())!=NO_ERROR) ){
40137      pFile->lastErrno = lastErrno;
40138      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
40139                       "winFileSize", pFile->zPath);
40140    }
40141  }
40142#endif
40143  OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
40144           pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
40145  return rc;
40146}
40147
40148/*
40149** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
40150*/
40151#ifndef LOCKFILE_FAIL_IMMEDIATELY
40152# define LOCKFILE_FAIL_IMMEDIATELY 1
40153#endif
40154
40155#ifndef LOCKFILE_EXCLUSIVE_LOCK
40156# define LOCKFILE_EXCLUSIVE_LOCK 2
40157#endif
40158
40159/*
40160** Historically, SQLite has used both the LockFile and LockFileEx functions.
40161** When the LockFile function was used, it was always expected to fail
40162** immediately if the lock could not be obtained.  Also, it always expected to
40163** obtain an exclusive lock.  These flags are used with the LockFileEx function
40164** and reflect those expectations; therefore, they should not be changed.
40165*/
40166#ifndef SQLITE_LOCKFILE_FLAGS
40167# define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
40168                                  LOCKFILE_EXCLUSIVE_LOCK)
40169#endif
40170
40171/*
40172** Currently, SQLite never calls the LockFileEx function without wanting the
40173** call to fail immediately if the lock cannot be obtained.
40174*/
40175#ifndef SQLITE_LOCKFILEEX_FLAGS
40176# define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
40177#endif
40178
40179/*
40180** Acquire a reader lock.
40181** Different API routines are called depending on whether or not this
40182** is Win9x or WinNT.
40183*/
40184static int winGetReadLock(winFile *pFile){
40185  int res;
40186  OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
40187  if( osIsNT() ){
40188#if SQLITE_OS_WINCE
40189    /*
40190    ** NOTE: Windows CE is handled differently here due its lack of the Win32
40191    **       API LockFileEx.
40192    */
40193    res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
40194#else
40195    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
40196                      SHARED_SIZE, 0);
40197#endif
40198  }
40199#ifdef SQLITE_WIN32_HAS_ANSI
40200  else{
40201    int lk;
40202    sqlite3_randomness(sizeof(lk), &lk);
40203    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
40204    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
40205                      SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
40206  }
40207#endif
40208  if( res == 0 ){
40209    pFile->lastErrno = osGetLastError();
40210    /* No need to log a failure to lock */
40211  }
40212  OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
40213  return res;
40214}
40215
40216/*
40217** Undo a readlock
40218*/
40219static int winUnlockReadLock(winFile *pFile){
40220  int res;
40221  DWORD lastErrno;
40222  OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
40223  if( osIsNT() ){
40224    res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
40225  }
40226#ifdef SQLITE_WIN32_HAS_ANSI
40227  else{
40228    res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
40229  }
40230#endif
40231  if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
40232    pFile->lastErrno = lastErrno;
40233    winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
40234                "winUnlockReadLock", pFile->zPath);
40235  }
40236  OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
40237  return res;
40238}
40239
40240/*
40241** Lock the file with the lock specified by parameter locktype - one
40242** of the following:
40243**
40244**     (1) SHARED_LOCK
40245**     (2) RESERVED_LOCK
40246**     (3) PENDING_LOCK
40247**     (4) EXCLUSIVE_LOCK
40248**
40249** Sometimes when requesting one lock state, additional lock states
40250** are inserted in between.  The locking might fail on one of the later
40251** transitions leaving the lock state different from what it started but
40252** still short of its goal.  The following chart shows the allowed
40253** transitions and the inserted intermediate states:
40254**
40255**    UNLOCKED -> SHARED
40256**    SHARED -> RESERVED
40257**    SHARED -> (PENDING) -> EXCLUSIVE
40258**    RESERVED -> (PENDING) -> EXCLUSIVE
40259**    PENDING -> EXCLUSIVE
40260**
40261** This routine will only increase a lock.  The winUnlock() routine
40262** erases all locks at once and returns us immediately to locking level 0.
40263** It is not possible to lower the locking level one step at a time.  You
40264** must go straight to locking level 0.
40265*/
40266static int winLock(sqlite3_file *id, int locktype){
40267  int rc = SQLITE_OK;    /* Return code from subroutines */
40268  int res = 1;           /* Result of a Windows lock call */
40269  int newLocktype;       /* Set pFile->locktype to this value before exiting */
40270  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
40271  winFile *pFile = (winFile*)id;
40272  DWORD lastErrno = NO_ERROR;
40273
40274  assert( id!=0 );
40275  OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
40276           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
40277
40278  /* If there is already a lock of this type or more restrictive on the
40279  ** OsFile, do nothing. Don't use the end_lock: exit path, as
40280  ** sqlite3OsEnterMutex() hasn't been called yet.
40281  */
40282  if( pFile->locktype>=locktype ){
40283    OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
40284    return SQLITE_OK;
40285  }
40286
40287  /* Do not allow any kind of write-lock on a read-only database
40288  */
40289  if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
40290    return SQLITE_IOERR_LOCK;
40291  }
40292
40293  /* Make sure the locking sequence is correct
40294  */
40295  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
40296  assert( locktype!=PENDING_LOCK );
40297  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
40298
40299  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
40300  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
40301  ** the PENDING_LOCK byte is temporary.
40302  */
40303  newLocktype = pFile->locktype;
40304  if( pFile->locktype==NO_LOCK
40305   || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
40306  ){
40307    int cnt = 3;
40308    while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
40309                                         PENDING_BYTE, 0, 1, 0))==0 ){
40310      /* Try 3 times to get the pending lock.  This is needed to work
40311      ** around problems caused by indexing and/or anti-virus software on
40312      ** Windows systems.
40313      ** If you are using this code as a model for alternative VFSes, do not
40314      ** copy this retry logic.  It is a hack intended for Windows only.
40315      */
40316      lastErrno = osGetLastError();
40317      OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
40318               pFile->h, cnt, res));
40319      if( lastErrno==ERROR_INVALID_HANDLE ){
40320        pFile->lastErrno = lastErrno;
40321        rc = SQLITE_IOERR_LOCK;
40322        OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
40323                 pFile->h, cnt, sqlite3ErrName(rc)));
40324        return rc;
40325      }
40326      if( cnt ) sqlite3_win32_sleep(1);
40327    }
40328    gotPendingLock = res;
40329    if( !res ){
40330      lastErrno = osGetLastError();
40331    }
40332  }
40333
40334  /* Acquire a shared lock
40335  */
40336  if( locktype==SHARED_LOCK && res ){
40337    assert( pFile->locktype==NO_LOCK );
40338    res = winGetReadLock(pFile);
40339    if( res ){
40340      newLocktype = SHARED_LOCK;
40341    }else{
40342      lastErrno = osGetLastError();
40343    }
40344  }
40345
40346  /* Acquire a RESERVED lock
40347  */
40348  if( locktype==RESERVED_LOCK && res ){
40349    assert( pFile->locktype==SHARED_LOCK );
40350    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
40351    if( res ){
40352      newLocktype = RESERVED_LOCK;
40353    }else{
40354      lastErrno = osGetLastError();
40355    }
40356  }
40357
40358  /* Acquire a PENDING lock
40359  */
40360  if( locktype==EXCLUSIVE_LOCK && res ){
40361    newLocktype = PENDING_LOCK;
40362    gotPendingLock = 0;
40363  }
40364
40365  /* Acquire an EXCLUSIVE lock
40366  */
40367  if( locktype==EXCLUSIVE_LOCK && res ){
40368    assert( pFile->locktype>=SHARED_LOCK );
40369    res = winUnlockReadLock(pFile);
40370    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
40371                      SHARED_SIZE, 0);
40372    if( res ){
40373      newLocktype = EXCLUSIVE_LOCK;
40374    }else{
40375      lastErrno = osGetLastError();
40376      winGetReadLock(pFile);
40377    }
40378  }
40379
40380  /* If we are holding a PENDING lock that ought to be released, then
40381  ** release it now.
40382  */
40383  if( gotPendingLock && locktype==SHARED_LOCK ){
40384    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
40385  }
40386
40387  /* Update the state of the lock has held in the file descriptor then
40388  ** return the appropriate result code.
40389  */
40390  if( res ){
40391    rc = SQLITE_OK;
40392  }else{
40393    pFile->lastErrno = lastErrno;
40394    rc = SQLITE_BUSY;
40395    OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
40396             pFile->h, locktype, newLocktype));
40397  }
40398  pFile->locktype = (u8)newLocktype;
40399  OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
40400           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
40401  return rc;
40402}
40403
40404/*
40405** This routine checks if there is a RESERVED lock held on the specified
40406** file by this or any other process. If such a lock is held, return
40407** non-zero, otherwise zero.
40408*/
40409static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
40410  int res;
40411  winFile *pFile = (winFile*)id;
40412
40413  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
40414  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
40415
40416  assert( id!=0 );
40417  if( pFile->locktype>=RESERVED_LOCK ){
40418    res = 1;
40419    OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
40420  }else{
40421    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
40422    if( res ){
40423      winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
40424    }
40425    res = !res;
40426    OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
40427  }
40428  *pResOut = res;
40429  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
40430           pFile->h, pResOut, *pResOut));
40431  return SQLITE_OK;
40432}
40433
40434/*
40435** Lower the locking level on file descriptor id to locktype.  locktype
40436** must be either NO_LOCK or SHARED_LOCK.
40437**
40438** If the locking level of the file descriptor is already at or below
40439** the requested locking level, this routine is a no-op.
40440**
40441** It is not possible for this routine to fail if the second argument
40442** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
40443** might return SQLITE_IOERR;
40444*/
40445static int winUnlock(sqlite3_file *id, int locktype){
40446  int type;
40447  winFile *pFile = (winFile*)id;
40448  int rc = SQLITE_OK;
40449  assert( pFile!=0 );
40450  assert( locktype<=SHARED_LOCK );
40451  OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
40452           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
40453  type = pFile->locktype;
40454  if( type>=EXCLUSIVE_LOCK ){
40455    winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
40456    if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
40457      /* This should never happen.  We should always be able to
40458      ** reacquire the read lock */
40459      rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
40460                       "winUnlock", pFile->zPath);
40461    }
40462  }
40463  if( type>=RESERVED_LOCK ){
40464    winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
40465  }
40466  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
40467    winUnlockReadLock(pFile);
40468  }
40469  if( type>=PENDING_LOCK ){
40470    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
40471  }
40472  pFile->locktype = (u8)locktype;
40473  OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
40474           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
40475  return rc;
40476}
40477
40478/******************************************************************************
40479****************************** No-op Locking **********************************
40480**
40481** Of the various locking implementations available, this is by far the
40482** simplest:  locking is ignored.  No attempt is made to lock the database
40483** file for reading or writing.
40484**
40485** This locking mode is appropriate for use on read-only databases
40486** (ex: databases that are burned into CD-ROM, for example.)  It can
40487** also be used if the application employs some external mechanism to
40488** prevent simultaneous access of the same database by two or more
40489** database connections.  But there is a serious risk of database
40490** corruption if this locking mode is used in situations where multiple
40491** database connections are accessing the same database file at the same
40492** time and one or more of those connections are writing.
40493*/
40494
40495static int winNolockLock(sqlite3_file *id, int locktype){
40496  UNUSED_PARAMETER(id);
40497  UNUSED_PARAMETER(locktype);
40498  return SQLITE_OK;
40499}
40500
40501static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
40502  UNUSED_PARAMETER(id);
40503  UNUSED_PARAMETER(pResOut);
40504  return SQLITE_OK;
40505}
40506
40507static int winNolockUnlock(sqlite3_file *id, int locktype){
40508  UNUSED_PARAMETER(id);
40509  UNUSED_PARAMETER(locktype);
40510  return SQLITE_OK;
40511}
40512
40513/******************* End of the no-op lock implementation *********************
40514******************************************************************************/
40515
40516/*
40517** If *pArg is initially negative then this is a query.  Set *pArg to
40518** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
40519**
40520** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
40521*/
40522static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
40523  if( *pArg<0 ){
40524    *pArg = (pFile->ctrlFlags & mask)!=0;
40525  }else if( (*pArg)==0 ){
40526    pFile->ctrlFlags &= ~mask;
40527  }else{
40528    pFile->ctrlFlags |= mask;
40529  }
40530}
40531
40532/* Forward references to VFS helper methods used for temporary files */
40533static int winGetTempname(sqlite3_vfs *, char **);
40534static int winIsDir(const void *);
40535static BOOL winIsDriveLetterAndColon(const char *);
40536
40537/*
40538** Control and query of the open file handle.
40539*/
40540static int winFileControl(sqlite3_file *id, int op, void *pArg){
40541  winFile *pFile = (winFile*)id;
40542  OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
40543  switch( op ){
40544    case SQLITE_FCNTL_LOCKSTATE: {
40545      *(int*)pArg = pFile->locktype;
40546      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40547      return SQLITE_OK;
40548    }
40549    case SQLITE_FCNTL_LAST_ERRNO: {
40550      *(int*)pArg = (int)pFile->lastErrno;
40551      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40552      return SQLITE_OK;
40553    }
40554    case SQLITE_FCNTL_CHUNK_SIZE: {
40555      pFile->szChunk = *(int *)pArg;
40556      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40557      return SQLITE_OK;
40558    }
40559    case SQLITE_FCNTL_SIZE_HINT: {
40560      if( pFile->szChunk>0 ){
40561        sqlite3_int64 oldSz;
40562        int rc = winFileSize(id, &oldSz);
40563        if( rc==SQLITE_OK ){
40564          sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
40565          if( newSz>oldSz ){
40566            SimulateIOErrorBenign(1);
40567            rc = winTruncate(id, newSz);
40568            SimulateIOErrorBenign(0);
40569          }
40570        }
40571        OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
40572        return rc;
40573      }
40574      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40575      return SQLITE_OK;
40576    }
40577    case SQLITE_FCNTL_PERSIST_WAL: {
40578      winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
40579      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40580      return SQLITE_OK;
40581    }
40582    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
40583      winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
40584      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40585      return SQLITE_OK;
40586    }
40587    case SQLITE_FCNTL_VFSNAME: {
40588      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
40589      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40590      return SQLITE_OK;
40591    }
40592    case SQLITE_FCNTL_WIN32_AV_RETRY: {
40593      int *a = (int*)pArg;
40594      if( a[0]>0 ){
40595        winIoerrRetry = a[0];
40596      }else{
40597        a[0] = winIoerrRetry;
40598      }
40599      if( a[1]>0 ){
40600        winIoerrRetryDelay = a[1];
40601      }else{
40602        a[1] = winIoerrRetryDelay;
40603      }
40604      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40605      return SQLITE_OK;
40606    }
40607#ifdef SQLITE_TEST
40608    case SQLITE_FCNTL_WIN32_SET_HANDLE: {
40609      LPHANDLE phFile = (LPHANDLE)pArg;
40610      HANDLE hOldFile = pFile->h;
40611      pFile->h = *phFile;
40612      *phFile = hOldFile;
40613      OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
40614               hOldFile, pFile->h));
40615      return SQLITE_OK;
40616    }
40617#endif
40618    case SQLITE_FCNTL_TEMPFILENAME: {
40619      char *zTFile = 0;
40620      int rc = winGetTempname(pFile->pVfs, &zTFile);
40621      if( rc==SQLITE_OK ){
40622        *(char**)pArg = zTFile;
40623      }
40624      OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
40625      return rc;
40626    }
40627#if SQLITE_MAX_MMAP_SIZE>0
40628    case SQLITE_FCNTL_MMAP_SIZE: {
40629      i64 newLimit = *(i64*)pArg;
40630      int rc = SQLITE_OK;
40631      if( newLimit>sqlite3GlobalConfig.mxMmap ){
40632        newLimit = sqlite3GlobalConfig.mxMmap;
40633      }
40634      *(i64*)pArg = pFile->mmapSizeMax;
40635      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
40636        pFile->mmapSizeMax = newLimit;
40637        if( pFile->mmapSize>0 ){
40638          winUnmapfile(pFile);
40639          rc = winMapfile(pFile, -1);
40640        }
40641      }
40642      OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
40643      return rc;
40644    }
40645#endif
40646  }
40647  OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
40648  return SQLITE_NOTFOUND;
40649}
40650
40651/*
40652** Return the sector size in bytes of the underlying block device for
40653** the specified file. This is almost always 512 bytes, but may be
40654** larger for some devices.
40655**
40656** SQLite code assumes this function cannot fail. It also assumes that
40657** if two files are created in the same file-system directory (i.e.
40658** a database and its journal file) that the sector size will be the
40659** same for both.
40660*/
40661static int winSectorSize(sqlite3_file *id){
40662  (void)id;
40663  return SQLITE_DEFAULT_SECTOR_SIZE;
40664}
40665
40666/*
40667** Return a vector of device characteristics.
40668*/
40669static int winDeviceCharacteristics(sqlite3_file *id){
40670  winFile *p = (winFile*)id;
40671  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
40672         ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
40673}
40674
40675/*
40676** Windows will only let you create file view mappings
40677** on allocation size granularity boundaries.
40678** During sqlite3_os_init() we do a GetSystemInfo()
40679** to get the granularity size.
40680*/
40681static SYSTEM_INFO winSysInfo;
40682
40683#ifndef SQLITE_OMIT_WAL
40684
40685/*
40686** Helper functions to obtain and relinquish the global mutex. The
40687** global mutex is used to protect the winLockInfo objects used by
40688** this file, all of which may be shared by multiple threads.
40689**
40690** Function winShmMutexHeld() is used to assert() that the global mutex
40691** is held when required. This function is only used as part of assert()
40692** statements. e.g.
40693**
40694**   winShmEnterMutex()
40695**     assert( winShmMutexHeld() );
40696**   winShmLeaveMutex()
40697*/
40698static void winShmEnterMutex(void){
40699  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
40700}
40701static void winShmLeaveMutex(void){
40702  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
40703}
40704#ifndef NDEBUG
40705static int winShmMutexHeld(void) {
40706  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
40707}
40708#endif
40709
40710/*
40711** Object used to represent a single file opened and mmapped to provide
40712** shared memory.  When multiple threads all reference the same
40713** log-summary, each thread has its own winFile object, but they all
40714** point to a single instance of this object.  In other words, each
40715** log-summary is opened only once per process.
40716**
40717** winShmMutexHeld() must be true when creating or destroying
40718** this object or while reading or writing the following fields:
40719**
40720**      nRef
40721**      pNext
40722**
40723** The following fields are read-only after the object is created:
40724**
40725**      fid
40726**      zFilename
40727**
40728** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
40729** winShmMutexHeld() is true when reading or writing any other field
40730** in this structure.
40731**
40732*/
40733struct winShmNode {
40734  sqlite3_mutex *mutex;      /* Mutex to access this object */
40735  char *zFilename;           /* Name of the file */
40736  winFile hFile;             /* File handle from winOpen */
40737
40738  int szRegion;              /* Size of shared-memory regions */
40739  int nRegion;               /* Size of array apRegion */
40740  struct ShmRegion {
40741    HANDLE hMap;             /* File handle from CreateFileMapping */
40742    void *pMap;
40743  } *aRegion;
40744  DWORD lastErrno;           /* The Windows errno from the last I/O error */
40745
40746  int nRef;                  /* Number of winShm objects pointing to this */
40747  winShm *pFirst;            /* All winShm objects pointing to this */
40748  winShmNode *pNext;         /* Next in list of all winShmNode objects */
40749#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
40750  u8 nextShmId;              /* Next available winShm.id value */
40751#endif
40752};
40753
40754/*
40755** A global array of all winShmNode objects.
40756**
40757** The winShmMutexHeld() must be true while reading or writing this list.
40758*/
40759static winShmNode *winShmNodeList = 0;
40760
40761/*
40762** Structure used internally by this VFS to record the state of an
40763** open shared memory connection.
40764**
40765** The following fields are initialized when this object is created and
40766** are read-only thereafter:
40767**
40768**    winShm.pShmNode
40769**    winShm.id
40770**
40771** All other fields are read/write.  The winShm.pShmNode->mutex must be held
40772** while accessing any read/write fields.
40773*/
40774struct winShm {
40775  winShmNode *pShmNode;      /* The underlying winShmNode object */
40776  winShm *pNext;             /* Next winShm with the same winShmNode */
40777  u8 hasMutex;               /* True if holding the winShmNode mutex */
40778  u16 sharedMask;            /* Mask of shared locks held */
40779  u16 exclMask;              /* Mask of exclusive locks held */
40780#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
40781  u8 id;                     /* Id of this connection with its winShmNode */
40782#endif
40783};
40784
40785/*
40786** Constants used for locking
40787*/
40788#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
40789#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
40790
40791/*
40792** Apply advisory locks for all n bytes beginning at ofst.
40793*/
40794#define WINSHM_UNLCK  1
40795#define WINSHM_RDLCK  2
40796#define WINSHM_WRLCK  3
40797static int winShmSystemLock(
40798  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
40799  int lockType,         /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
40800  int ofst,             /* Offset to first byte to be locked/unlocked */
40801  int nByte             /* Number of bytes to lock or unlock */
40802){
40803  int rc = 0;           /* Result code form Lock/UnlockFileEx() */
40804
40805  /* Access to the winShmNode object is serialized by the caller */
40806  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
40807
40808  OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
40809           pFile->hFile.h, lockType, ofst, nByte));
40810
40811  /* Release/Acquire the system-level lock */
40812  if( lockType==WINSHM_UNLCK ){
40813    rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
40814  }else{
40815    /* Initialize the locking parameters */
40816    DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
40817    if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
40818    rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
40819  }
40820
40821  if( rc!= 0 ){
40822    rc = SQLITE_OK;
40823  }else{
40824    pFile->lastErrno =  osGetLastError();
40825    rc = SQLITE_BUSY;
40826  }
40827
40828  OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
40829           pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
40830           "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
40831
40832  return rc;
40833}
40834
40835/* Forward references to VFS methods */
40836static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
40837static int winDelete(sqlite3_vfs *,const char*,int);
40838
40839/*
40840** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
40841**
40842** This is not a VFS shared-memory method; it is a utility function called
40843** by VFS shared-memory methods.
40844*/
40845static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
40846  winShmNode **pp;
40847  winShmNode *p;
40848  assert( winShmMutexHeld() );
40849  OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
40850           osGetCurrentProcessId(), deleteFlag));
40851  pp = &winShmNodeList;
40852  while( (p = *pp)!=0 ){
40853    if( p->nRef==0 ){
40854      int i;
40855      if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
40856      for(i=0; i<p->nRegion; i++){
40857        BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
40858        OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
40859                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
40860        UNUSED_VARIABLE_VALUE(bRc);
40861        bRc = osCloseHandle(p->aRegion[i].hMap);
40862        OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
40863                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
40864        UNUSED_VARIABLE_VALUE(bRc);
40865      }
40866      if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
40867        SimulateIOErrorBenign(1);
40868        winClose((sqlite3_file *)&p->hFile);
40869        SimulateIOErrorBenign(0);
40870      }
40871      if( deleteFlag ){
40872        SimulateIOErrorBenign(1);
40873        sqlite3BeginBenignMalloc();
40874        winDelete(pVfs, p->zFilename, 0);
40875        sqlite3EndBenignMalloc();
40876        SimulateIOErrorBenign(0);
40877      }
40878      *pp = p->pNext;
40879      sqlite3_free(p->aRegion);
40880      sqlite3_free(p);
40881    }else{
40882      pp = &p->pNext;
40883    }
40884  }
40885}
40886
40887/*
40888** Open the shared-memory area associated with database file pDbFd.
40889**
40890** When opening a new shared-memory file, if no other instances of that
40891** file are currently open, in this process or in other processes, then
40892** the file must be truncated to zero length or have its header cleared.
40893*/
40894static int winOpenSharedMemory(winFile *pDbFd){
40895  struct winShm *p;                  /* The connection to be opened */
40896  struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
40897  int rc;                            /* Result code */
40898  struct winShmNode *pNew;           /* Newly allocated winShmNode */
40899  int nName;                         /* Size of zName in bytes */
40900
40901  assert( pDbFd->pShm==0 );    /* Not previously opened */
40902
40903  /* Allocate space for the new sqlite3_shm object.  Also speculatively
40904  ** allocate space for a new winShmNode and filename.
40905  */
40906  p = sqlite3MallocZero( sizeof(*p) );
40907  if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
40908  nName = sqlite3Strlen30(pDbFd->zPath);
40909  pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
40910  if( pNew==0 ){
40911    sqlite3_free(p);
40912    return SQLITE_IOERR_NOMEM_BKPT;
40913  }
40914  pNew->zFilename = (char*)&pNew[1];
40915  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
40916  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
40917
40918  /* Look to see if there is an existing winShmNode that can be used.
40919  ** If no matching winShmNode currently exists, create a new one.
40920  */
40921  winShmEnterMutex();
40922  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
40923    /* TBD need to come up with better match here.  Perhaps
40924    ** use FILE_ID_BOTH_DIR_INFO Structure.
40925    */
40926    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
40927  }
40928  if( pShmNode ){
40929    sqlite3_free(pNew);
40930  }else{
40931    pShmNode = pNew;
40932    pNew = 0;
40933    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
40934    pShmNode->pNext = winShmNodeList;
40935    winShmNodeList = pShmNode;
40936
40937    if( sqlite3GlobalConfig.bCoreMutex ){
40938      pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
40939      if( pShmNode->mutex==0 ){
40940        rc = SQLITE_IOERR_NOMEM_BKPT;
40941        goto shm_open_err;
40942      }
40943    }
40944
40945    rc = winOpen(pDbFd->pVfs,
40946                 pShmNode->zFilename,             /* Name of the file (UTF-8) */
40947                 (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
40948                 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
40949                 0);
40950    if( SQLITE_OK!=rc ){
40951      goto shm_open_err;
40952    }
40953
40954    /* Check to see if another process is holding the dead-man switch.
40955    ** If not, truncate the file to zero length.
40956    */
40957    if( winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
40958      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
40959      if( rc!=SQLITE_OK ){
40960        rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
40961                         "winOpenShm", pDbFd->zPath);
40962      }
40963    }
40964    if( rc==SQLITE_OK ){
40965      winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
40966      rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
40967    }
40968    if( rc ) goto shm_open_err;
40969  }
40970
40971  /* Make the new connection a child of the winShmNode */
40972  p->pShmNode = pShmNode;
40973#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
40974  p->id = pShmNode->nextShmId++;
40975#endif
40976  pShmNode->nRef++;
40977  pDbFd->pShm = p;
40978  winShmLeaveMutex();
40979
40980  /* The reference count on pShmNode has already been incremented under
40981  ** the cover of the winShmEnterMutex() mutex and the pointer from the
40982  ** new (struct winShm) object to the pShmNode has been set. All that is
40983  ** left to do is to link the new object into the linked list starting
40984  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
40985  ** mutex.
40986  */
40987  sqlite3_mutex_enter(pShmNode->mutex);
40988  p->pNext = pShmNode->pFirst;
40989  pShmNode->pFirst = p;
40990  sqlite3_mutex_leave(pShmNode->mutex);
40991  return SQLITE_OK;
40992
40993  /* Jump here on any error */
40994shm_open_err:
40995  winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
40996  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
40997  sqlite3_free(p);
40998  sqlite3_free(pNew);
40999  winShmLeaveMutex();
41000  return rc;
41001}
41002
41003/*
41004** Close a connection to shared-memory.  Delete the underlying
41005** storage if deleteFlag is true.
41006*/
41007static int winShmUnmap(
41008  sqlite3_file *fd,          /* Database holding shared memory */
41009  int deleteFlag             /* Delete after closing if true */
41010){
41011  winFile *pDbFd;       /* Database holding shared-memory */
41012  winShm *p;            /* The connection to be closed */
41013  winShmNode *pShmNode; /* The underlying shared-memory file */
41014  winShm **pp;          /* For looping over sibling connections */
41015
41016  pDbFd = (winFile*)fd;
41017  p = pDbFd->pShm;
41018  if( p==0 ) return SQLITE_OK;
41019  pShmNode = p->pShmNode;
41020
41021  /* Remove connection p from the set of connections associated
41022  ** with pShmNode */
41023  sqlite3_mutex_enter(pShmNode->mutex);
41024  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
41025  *pp = p->pNext;
41026
41027  /* Free the connection p */
41028  sqlite3_free(p);
41029  pDbFd->pShm = 0;
41030  sqlite3_mutex_leave(pShmNode->mutex);
41031
41032  /* If pShmNode->nRef has reached 0, then close the underlying
41033  ** shared-memory file, too */
41034  winShmEnterMutex();
41035  assert( pShmNode->nRef>0 );
41036  pShmNode->nRef--;
41037  if( pShmNode->nRef==0 ){
41038    winShmPurge(pDbFd->pVfs, deleteFlag);
41039  }
41040  winShmLeaveMutex();
41041
41042  return SQLITE_OK;
41043}
41044
41045/*
41046** Change the lock state for a shared-memory segment.
41047*/
41048static int winShmLock(
41049  sqlite3_file *fd,          /* Database file holding the shared memory */
41050  int ofst,                  /* First lock to acquire or release */
41051  int n,                     /* Number of locks to acquire or release */
41052  int flags                  /* What to do with the lock */
41053){
41054  winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
41055  winShm *p = pDbFd->pShm;              /* The shared memory being locked */
41056  winShm *pX;                           /* For looping over all siblings */
41057  winShmNode *pShmNode = p->pShmNode;
41058  int rc = SQLITE_OK;                   /* Result code */
41059  u16 mask;                             /* Mask of locks to take or release */
41060
41061  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
41062  assert( n>=1 );
41063  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
41064       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
41065       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
41066       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
41067  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
41068
41069  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
41070  assert( n>1 || mask==(1<<ofst) );
41071  sqlite3_mutex_enter(pShmNode->mutex);
41072  if( flags & SQLITE_SHM_UNLOCK ){
41073    u16 allMask = 0; /* Mask of locks held by siblings */
41074
41075    /* See if any siblings hold this same lock */
41076    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
41077      if( pX==p ) continue;
41078      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
41079      allMask |= pX->sharedMask;
41080    }
41081
41082    /* Unlock the system-level locks */
41083    if( (mask & allMask)==0 ){
41084      rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
41085    }else{
41086      rc = SQLITE_OK;
41087    }
41088
41089    /* Undo the local locks */
41090    if( rc==SQLITE_OK ){
41091      p->exclMask &= ~mask;
41092      p->sharedMask &= ~mask;
41093    }
41094  }else if( flags & SQLITE_SHM_SHARED ){
41095    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
41096
41097    /* Find out which shared locks are already held by sibling connections.
41098    ** If any sibling already holds an exclusive lock, go ahead and return
41099    ** SQLITE_BUSY.
41100    */
41101    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
41102      if( (pX->exclMask & mask)!=0 ){
41103        rc = SQLITE_BUSY;
41104        break;
41105      }
41106      allShared |= pX->sharedMask;
41107    }
41108
41109    /* Get shared locks at the system level, if necessary */
41110    if( rc==SQLITE_OK ){
41111      if( (allShared & mask)==0 ){
41112        rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
41113      }else{
41114        rc = SQLITE_OK;
41115      }
41116    }
41117
41118    /* Get the local shared locks */
41119    if( rc==SQLITE_OK ){
41120      p->sharedMask |= mask;
41121    }
41122  }else{
41123    /* Make sure no sibling connections hold locks that will block this
41124    ** lock.  If any do, return SQLITE_BUSY right away.
41125    */
41126    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
41127      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
41128        rc = SQLITE_BUSY;
41129        break;
41130      }
41131    }
41132
41133    /* Get the exclusive locks at the system level.  Then if successful
41134    ** also mark the local connection as being locked.
41135    */
41136    if( rc==SQLITE_OK ){
41137      rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
41138      if( rc==SQLITE_OK ){
41139        assert( (p->sharedMask & mask)==0 );
41140        p->exclMask |= mask;
41141      }
41142    }
41143  }
41144  sqlite3_mutex_leave(pShmNode->mutex);
41145  OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
41146           osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
41147           sqlite3ErrName(rc)));
41148  return rc;
41149}
41150
41151/*
41152** Implement a memory barrier or memory fence on shared memory.
41153**
41154** All loads and stores begun before the barrier must complete before
41155** any load or store begun after the barrier.
41156*/
41157static void winShmBarrier(
41158  sqlite3_file *fd          /* Database holding the shared memory */
41159){
41160  UNUSED_PARAMETER(fd);
41161  sqlite3MemoryBarrier();   /* compiler-defined memory barrier */
41162  winShmEnterMutex();       /* Also mutex, for redundancy */
41163  winShmLeaveMutex();
41164}
41165
41166/*
41167** This function is called to obtain a pointer to region iRegion of the
41168** shared-memory associated with the database file fd. Shared-memory regions
41169** are numbered starting from zero. Each shared-memory region is szRegion
41170** bytes in size.
41171**
41172** If an error occurs, an error code is returned and *pp is set to NULL.
41173**
41174** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
41175** region has not been allocated (by any client, including one running in a
41176** separate process), then *pp is set to NULL and SQLITE_OK returned. If
41177** isWrite is non-zero and the requested shared-memory region has not yet
41178** been allocated, it is allocated by this function.
41179**
41180** If the shared-memory region has already been allocated or is allocated by
41181** this call as described above, then it is mapped into this processes
41182** address space (if it is not already), *pp is set to point to the mapped
41183** memory and SQLITE_OK returned.
41184*/
41185static int winShmMap(
41186  sqlite3_file *fd,               /* Handle open on database file */
41187  int iRegion,                    /* Region to retrieve */
41188  int szRegion,                   /* Size of regions */
41189  int isWrite,                    /* True to extend file if necessary */
41190  void volatile **pp              /* OUT: Mapped memory */
41191){
41192  winFile *pDbFd = (winFile*)fd;
41193  winShm *pShm = pDbFd->pShm;
41194  winShmNode *pShmNode;
41195  int rc = SQLITE_OK;
41196
41197  if( !pShm ){
41198    rc = winOpenSharedMemory(pDbFd);
41199    if( rc!=SQLITE_OK ) return rc;
41200    pShm = pDbFd->pShm;
41201  }
41202  pShmNode = pShm->pShmNode;
41203
41204  sqlite3_mutex_enter(pShmNode->mutex);
41205  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
41206
41207  if( pShmNode->nRegion<=iRegion ){
41208    struct ShmRegion *apNew;           /* New aRegion[] array */
41209    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
41210    sqlite3_int64 sz;                  /* Current size of wal-index file */
41211
41212    pShmNode->szRegion = szRegion;
41213
41214    /* The requested region is not mapped into this processes address space.
41215    ** Check to see if it has been allocated (i.e. if the wal-index file is
41216    ** large enough to contain the requested region).
41217    */
41218    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
41219    if( rc!=SQLITE_OK ){
41220      rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
41221                       "winShmMap1", pDbFd->zPath);
41222      goto shmpage_out;
41223    }
41224
41225    if( sz<nByte ){
41226      /* The requested memory region does not exist. If isWrite is set to
41227      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
41228      **
41229      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
41230      ** the requested memory region.
41231      */
41232      if( !isWrite ) goto shmpage_out;
41233      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
41234      if( rc!=SQLITE_OK ){
41235        rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
41236                         "winShmMap2", pDbFd->zPath);
41237        goto shmpage_out;
41238      }
41239    }
41240
41241    /* Map the requested memory region into this processes address space. */
41242    apNew = (struct ShmRegion *)sqlite3_realloc64(
41243        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
41244    );
41245    if( !apNew ){
41246      rc = SQLITE_IOERR_NOMEM_BKPT;
41247      goto shmpage_out;
41248    }
41249    pShmNode->aRegion = apNew;
41250
41251    while( pShmNode->nRegion<=iRegion ){
41252      HANDLE hMap = NULL;         /* file-mapping handle */
41253      void *pMap = 0;             /* Mapped memory region */
41254
41255#if SQLITE_OS_WINRT
41256      hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
41257          NULL, PAGE_READWRITE, nByte, NULL
41258      );
41259#elif defined(SQLITE_WIN32_HAS_WIDE)
41260      hMap = osCreateFileMappingW(pShmNode->hFile.h,
41261          NULL, PAGE_READWRITE, 0, nByte, NULL
41262      );
41263#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
41264      hMap = osCreateFileMappingA(pShmNode->hFile.h,
41265          NULL, PAGE_READWRITE, 0, nByte, NULL
41266      );
41267#endif
41268      OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
41269               osGetCurrentProcessId(), pShmNode->nRegion, nByte,
41270               hMap ? "ok" : "failed"));
41271      if( hMap ){
41272        int iOffset = pShmNode->nRegion*szRegion;
41273        int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
41274#if SQLITE_OS_WINRT
41275        pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
41276            iOffset - iOffsetShift, szRegion + iOffsetShift
41277        );
41278#else
41279        pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
41280            0, iOffset - iOffsetShift, szRegion + iOffsetShift
41281        );
41282#endif
41283        OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
41284                 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
41285                 szRegion, pMap ? "ok" : "failed"));
41286      }
41287      if( !pMap ){
41288        pShmNode->lastErrno = osGetLastError();
41289        rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
41290                         "winShmMap3", pDbFd->zPath);
41291        if( hMap ) osCloseHandle(hMap);
41292        goto shmpage_out;
41293      }
41294
41295      pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
41296      pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
41297      pShmNode->nRegion++;
41298    }
41299  }
41300
41301shmpage_out:
41302  if( pShmNode->nRegion>iRegion ){
41303    int iOffset = iRegion*szRegion;
41304    int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
41305    char *p = (char *)pShmNode->aRegion[iRegion].pMap;
41306    *pp = (void *)&p[iOffsetShift];
41307  }else{
41308    *pp = 0;
41309  }
41310  sqlite3_mutex_leave(pShmNode->mutex);
41311  return rc;
41312}
41313
41314#else
41315# define winShmMap     0
41316# define winShmLock    0
41317# define winShmBarrier 0
41318# define winShmUnmap   0
41319#endif /* #ifndef SQLITE_OMIT_WAL */
41320
41321/*
41322** Cleans up the mapped region of the specified file, if any.
41323*/
41324#if SQLITE_MAX_MMAP_SIZE>0
41325static int winUnmapfile(winFile *pFile){
41326  assert( pFile!=0 );
41327  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
41328           "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
41329           osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
41330           pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
41331  if( pFile->pMapRegion ){
41332    if( !osUnmapViewOfFile(pFile->pMapRegion) ){
41333      pFile->lastErrno = osGetLastError();
41334      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
41335               "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
41336               pFile->pMapRegion));
41337      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
41338                         "winUnmapfile1", pFile->zPath);
41339    }
41340    pFile->pMapRegion = 0;
41341    pFile->mmapSize = 0;
41342    pFile->mmapSizeActual = 0;
41343  }
41344  if( pFile->hMap!=NULL ){
41345    if( !osCloseHandle(pFile->hMap) ){
41346      pFile->lastErrno = osGetLastError();
41347      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
41348               osGetCurrentProcessId(), pFile, pFile->hMap));
41349      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
41350                         "winUnmapfile2", pFile->zPath);
41351    }
41352    pFile->hMap = NULL;
41353  }
41354  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
41355           osGetCurrentProcessId(), pFile));
41356  return SQLITE_OK;
41357}
41358
41359/*
41360** Memory map or remap the file opened by file-descriptor pFd (if the file
41361** is already mapped, the existing mapping is replaced by the new). Or, if
41362** there already exists a mapping for this file, and there are still
41363** outstanding xFetch() references to it, this function is a no-op.
41364**
41365** If parameter nByte is non-negative, then it is the requested size of
41366** the mapping to create. Otherwise, if nByte is less than zero, then the
41367** requested size is the size of the file on disk. The actual size of the
41368** created mapping is either the requested size or the value configured
41369** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
41370**
41371** SQLITE_OK is returned if no error occurs (even if the mapping is not
41372** recreated as a result of outstanding references) or an SQLite error
41373** code otherwise.
41374*/
41375static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
41376  sqlite3_int64 nMap = nByte;
41377  int rc;
41378
41379  assert( nMap>=0 || pFd->nFetchOut==0 );
41380  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
41381           osGetCurrentProcessId(), pFd, nByte));
41382
41383  if( pFd->nFetchOut>0 ) return SQLITE_OK;
41384
41385  if( nMap<0 ){
41386    rc = winFileSize((sqlite3_file*)pFd, &nMap);
41387    if( rc ){
41388      OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
41389               osGetCurrentProcessId(), pFd));
41390      return SQLITE_IOERR_FSTAT;
41391    }
41392  }
41393  if( nMap>pFd->mmapSizeMax ){
41394    nMap = pFd->mmapSizeMax;
41395  }
41396  nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
41397
41398  if( nMap==0 && pFd->mmapSize>0 ){
41399    winUnmapfile(pFd);
41400  }
41401  if( nMap!=pFd->mmapSize ){
41402    void *pNew = 0;
41403    DWORD protect = PAGE_READONLY;
41404    DWORD flags = FILE_MAP_READ;
41405
41406    winUnmapfile(pFd);
41407#ifdef SQLITE_MMAP_READWRITE
41408    if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
41409      protect = PAGE_READWRITE;
41410      flags |= FILE_MAP_WRITE;
41411    }
41412#endif
41413#if SQLITE_OS_WINRT
41414    pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
41415#elif defined(SQLITE_WIN32_HAS_WIDE)
41416    pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
41417                                (DWORD)((nMap>>32) & 0xffffffff),
41418                                (DWORD)(nMap & 0xffffffff), NULL);
41419#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
41420    pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
41421                                (DWORD)((nMap>>32) & 0xffffffff),
41422                                (DWORD)(nMap & 0xffffffff), NULL);
41423#endif
41424    if( pFd->hMap==NULL ){
41425      pFd->lastErrno = osGetLastError();
41426      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
41427                       "winMapfile1", pFd->zPath);
41428      /* Log the error, but continue normal operation using xRead/xWrite */
41429      OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
41430               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
41431      return SQLITE_OK;
41432    }
41433    assert( (nMap % winSysInfo.dwPageSize)==0 );
41434    assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
41435#if SQLITE_OS_WINRT
41436    pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
41437#else
41438    pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
41439#endif
41440    if( pNew==NULL ){
41441      osCloseHandle(pFd->hMap);
41442      pFd->hMap = NULL;
41443      pFd->lastErrno = osGetLastError();
41444      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
41445                       "winMapfile2", pFd->zPath);
41446      /* Log the error, but continue normal operation using xRead/xWrite */
41447      OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
41448               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
41449      return SQLITE_OK;
41450    }
41451    pFd->pMapRegion = pNew;
41452    pFd->mmapSize = nMap;
41453    pFd->mmapSizeActual = nMap;
41454  }
41455
41456  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
41457           osGetCurrentProcessId(), pFd));
41458  return SQLITE_OK;
41459}
41460#endif /* SQLITE_MAX_MMAP_SIZE>0 */
41461
41462/*
41463** If possible, return a pointer to a mapping of file fd starting at offset
41464** iOff. The mapping must be valid for at least nAmt bytes.
41465**
41466** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
41467** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
41468** Finally, if an error does occur, return an SQLite error code. The final
41469** value of *pp is undefined in this case.
41470**
41471** If this function does return a pointer, the caller must eventually
41472** release the reference by calling winUnfetch().
41473*/
41474static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
41475#if SQLITE_MAX_MMAP_SIZE>0
41476  winFile *pFd = (winFile*)fd;   /* The underlying database file */
41477#endif
41478  *pp = 0;
41479
41480  OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
41481           osGetCurrentProcessId(), fd, iOff, nAmt, pp));
41482
41483#if SQLITE_MAX_MMAP_SIZE>0
41484  if( pFd->mmapSizeMax>0 ){
41485    if( pFd->pMapRegion==0 ){
41486      int rc = winMapfile(pFd, -1);
41487      if( rc!=SQLITE_OK ){
41488        OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
41489                 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
41490        return rc;
41491      }
41492    }
41493    if( pFd->mmapSize >= iOff+nAmt ){
41494      *pp = &((u8 *)pFd->pMapRegion)[iOff];
41495      pFd->nFetchOut++;
41496    }
41497  }
41498#endif
41499
41500  OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
41501           osGetCurrentProcessId(), fd, pp, *pp));
41502  return SQLITE_OK;
41503}
41504
41505/*
41506** If the third argument is non-NULL, then this function releases a
41507** reference obtained by an earlier call to winFetch(). The second
41508** argument passed to this function must be the same as the corresponding
41509** argument that was passed to the winFetch() invocation.
41510**
41511** Or, if the third argument is NULL, then this function is being called
41512** to inform the VFS layer that, according to POSIX, any existing mapping
41513** may now be invalid and should be unmapped.
41514*/
41515static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
41516#if SQLITE_MAX_MMAP_SIZE>0
41517  winFile *pFd = (winFile*)fd;   /* The underlying database file */
41518
41519  /* If p==0 (unmap the entire file) then there must be no outstanding
41520  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
41521  ** then there must be at least one outstanding.  */
41522  assert( (p==0)==(pFd->nFetchOut==0) );
41523
41524  /* If p!=0, it must match the iOff value. */
41525  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
41526
41527  OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
41528           osGetCurrentProcessId(), pFd, iOff, p));
41529
41530  if( p ){
41531    pFd->nFetchOut--;
41532  }else{
41533    /* FIXME:  If Windows truly always prevents truncating or deleting a
41534    ** file while a mapping is held, then the following winUnmapfile() call
41535    ** is unnecessary can be omitted - potentially improving
41536    ** performance.  */
41537    winUnmapfile(pFd);
41538  }
41539
41540  assert( pFd->nFetchOut>=0 );
41541#endif
41542
41543  OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
41544           osGetCurrentProcessId(), fd));
41545  return SQLITE_OK;
41546}
41547
41548/*
41549** Here ends the implementation of all sqlite3_file methods.
41550**
41551********************** End sqlite3_file Methods *******************************
41552******************************************************************************/
41553
41554/*
41555** This vector defines all the methods that can operate on an
41556** sqlite3_file for win32.
41557*/
41558static const sqlite3_io_methods winIoMethod = {
41559  3,                              /* iVersion */
41560  winClose,                       /* xClose */
41561  winRead,                        /* xRead */
41562  winWrite,                       /* xWrite */
41563  winTruncate,                    /* xTruncate */
41564  winSync,                        /* xSync */
41565  winFileSize,                    /* xFileSize */
41566  winLock,                        /* xLock */
41567  winUnlock,                      /* xUnlock */
41568  winCheckReservedLock,           /* xCheckReservedLock */
41569  winFileControl,                 /* xFileControl */
41570  winSectorSize,                  /* xSectorSize */
41571  winDeviceCharacteristics,       /* xDeviceCharacteristics */
41572  winShmMap,                      /* xShmMap */
41573  winShmLock,                     /* xShmLock */
41574  winShmBarrier,                  /* xShmBarrier */
41575  winShmUnmap,                    /* xShmUnmap */
41576  winFetch,                       /* xFetch */
41577  winUnfetch                      /* xUnfetch */
41578};
41579
41580/*
41581** This vector defines all the methods that can operate on an
41582** sqlite3_file for win32 without performing any locking.
41583*/
41584static const sqlite3_io_methods winIoNolockMethod = {
41585  3,                              /* iVersion */
41586  winClose,                       /* xClose */
41587  winRead,                        /* xRead */
41588  winWrite,                       /* xWrite */
41589  winTruncate,                    /* xTruncate */
41590  winSync,                        /* xSync */
41591  winFileSize,                    /* xFileSize */
41592  winNolockLock,                  /* xLock */
41593  winNolockUnlock,                /* xUnlock */
41594  winNolockCheckReservedLock,     /* xCheckReservedLock */
41595  winFileControl,                 /* xFileControl */
41596  winSectorSize,                  /* xSectorSize */
41597  winDeviceCharacteristics,       /* xDeviceCharacteristics */
41598  winShmMap,                      /* xShmMap */
41599  winShmLock,                     /* xShmLock */
41600  winShmBarrier,                  /* xShmBarrier */
41601  winShmUnmap,                    /* xShmUnmap */
41602  winFetch,                       /* xFetch */
41603  winUnfetch                      /* xUnfetch */
41604};
41605
41606static winVfsAppData winAppData = {
41607  &winIoMethod,       /* pMethod */
41608  0,                  /* pAppData */
41609  0                   /* bNoLock */
41610};
41611
41612static winVfsAppData winNolockAppData = {
41613  &winIoNolockMethod, /* pMethod */
41614  0,                  /* pAppData */
41615  1                   /* bNoLock */
41616};
41617
41618/****************************************************************************
41619**************************** sqlite3_vfs methods ****************************
41620**
41621** This division contains the implementation of methods on the
41622** sqlite3_vfs object.
41623*/
41624
41625#if defined(__CYGWIN__)
41626/*
41627** Convert a filename from whatever the underlying operating system
41628** supports for filenames into UTF-8.  Space to hold the result is
41629** obtained from malloc and must be freed by the calling function.
41630*/
41631static char *winConvertToUtf8Filename(const void *zFilename){
41632  char *zConverted = 0;
41633  if( osIsNT() ){
41634    zConverted = winUnicodeToUtf8(zFilename);
41635  }
41636#ifdef SQLITE_WIN32_HAS_ANSI
41637  else{
41638    zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
41639  }
41640#endif
41641  /* caller will handle out of memory */
41642  return zConverted;
41643}
41644#endif
41645
41646/*
41647** Convert a UTF-8 filename into whatever form the underlying
41648** operating system wants filenames in.  Space to hold the result
41649** is obtained from malloc and must be freed by the calling
41650** function.
41651*/
41652static void *winConvertFromUtf8Filename(const char *zFilename){
41653  void *zConverted = 0;
41654  if( osIsNT() ){
41655    zConverted = winUtf8ToUnicode(zFilename);
41656  }
41657#ifdef SQLITE_WIN32_HAS_ANSI
41658  else{
41659    zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
41660  }
41661#endif
41662  /* caller will handle out of memory */
41663  return zConverted;
41664}
41665
41666/*
41667** This function returns non-zero if the specified UTF-8 string buffer
41668** ends with a directory separator character or one was successfully
41669** added to it.
41670*/
41671static int winMakeEndInDirSep(int nBuf, char *zBuf){
41672  if( zBuf ){
41673    int nLen = sqlite3Strlen30(zBuf);
41674    if( nLen>0 ){
41675      if( winIsDirSep(zBuf[nLen-1]) ){
41676        return 1;
41677      }else if( nLen+1<nBuf ){
41678        zBuf[nLen] = winGetDirSep();
41679        zBuf[nLen+1] = '\0';
41680        return 1;
41681      }
41682    }
41683  }
41684  return 0;
41685}
41686
41687/*
41688** Create a temporary file name and store the resulting pointer into pzBuf.
41689** The pointer returned in pzBuf must be freed via sqlite3_free().
41690*/
41691static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
41692  static char zChars[] =
41693    "abcdefghijklmnopqrstuvwxyz"
41694    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
41695    "0123456789";
41696  size_t i, j;
41697  int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
41698  int nMax, nBuf, nDir, nLen;
41699  char *zBuf;
41700
41701  /* It's odd to simulate an io-error here, but really this is just
41702  ** using the io-error infrastructure to test that SQLite handles this
41703  ** function failing.
41704  */
41705  SimulateIOError( return SQLITE_IOERR );
41706
41707  /* Allocate a temporary buffer to store the fully qualified file
41708  ** name for the temporary file.  If this fails, we cannot continue.
41709  */
41710  nMax = pVfs->mxPathname; nBuf = nMax + 2;
41711  zBuf = sqlite3MallocZero( nBuf );
41712  if( !zBuf ){
41713    OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41714    return SQLITE_IOERR_NOMEM_BKPT;
41715  }
41716
41717  /* Figure out the effective temporary directory.  First, check if one
41718  ** has been explicitly set by the application; otherwise, use the one
41719  ** configured by the operating system.
41720  */
41721  nDir = nMax - (nPre + 15);
41722  assert( nDir>0 );
41723  if( sqlite3_temp_directory ){
41724    int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
41725    if( nDirLen>0 ){
41726      if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
41727        nDirLen++;
41728      }
41729      if( nDirLen>nDir ){
41730        sqlite3_free(zBuf);
41731        OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
41732        return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
41733      }
41734      sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
41735    }
41736  }
41737#if defined(__CYGWIN__)
41738  else{
41739    static const char *azDirs[] = {
41740       0, /* getenv("SQLITE_TMPDIR") */
41741       0, /* getenv("TMPDIR") */
41742       0, /* getenv("TMP") */
41743       0, /* getenv("TEMP") */
41744       0, /* getenv("USERPROFILE") */
41745       "/var/tmp",
41746       "/usr/tmp",
41747       "/tmp",
41748       ".",
41749       0        /* List terminator */
41750    };
41751    unsigned int i;
41752    const char *zDir = 0;
41753
41754    if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
41755    if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
41756    if( !azDirs[2] ) azDirs[2] = getenv("TMP");
41757    if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
41758    if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
41759    for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
41760      void *zConverted;
41761      if( zDir==0 ) continue;
41762      /* If the path starts with a drive letter followed by the colon
41763      ** character, assume it is already a native Win32 path; otherwise,
41764      ** it must be converted to a native Win32 path via the Cygwin API
41765      ** prior to using it.
41766      */
41767      if( winIsDriveLetterAndColon(zDir) ){
41768        zConverted = winConvertFromUtf8Filename(zDir);
41769        if( !zConverted ){
41770          sqlite3_free(zBuf);
41771          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41772          return SQLITE_IOERR_NOMEM_BKPT;
41773        }
41774        if( winIsDir(zConverted) ){
41775          sqlite3_snprintf(nMax, zBuf, "%s", zDir);
41776          sqlite3_free(zConverted);
41777          break;
41778        }
41779        sqlite3_free(zConverted);
41780      }else{
41781        zConverted = sqlite3MallocZero( nMax+1 );
41782        if( !zConverted ){
41783          sqlite3_free(zBuf);
41784          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41785          return SQLITE_IOERR_NOMEM_BKPT;
41786        }
41787        if( cygwin_conv_path(
41788                osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
41789                zConverted, nMax+1)<0 ){
41790          sqlite3_free(zConverted);
41791          sqlite3_free(zBuf);
41792          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
41793          return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
41794                             "winGetTempname2", zDir);
41795        }
41796        if( winIsDir(zConverted) ){
41797          /* At this point, we know the candidate directory exists and should
41798          ** be used.  However, we may need to convert the string containing
41799          ** its name into UTF-8 (i.e. if it is UTF-16 right now).
41800          */
41801          char *zUtf8 = winConvertToUtf8Filename(zConverted);
41802          if( !zUtf8 ){
41803            sqlite3_free(zConverted);
41804            sqlite3_free(zBuf);
41805            OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41806            return SQLITE_IOERR_NOMEM_BKPT;
41807          }
41808          sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
41809          sqlite3_free(zUtf8);
41810          sqlite3_free(zConverted);
41811          break;
41812        }
41813        sqlite3_free(zConverted);
41814      }
41815    }
41816  }
41817#elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
41818  else if( osIsNT() ){
41819    char *zMulti;
41820    LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
41821    if( !zWidePath ){
41822      sqlite3_free(zBuf);
41823      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41824      return SQLITE_IOERR_NOMEM_BKPT;
41825    }
41826    if( osGetTempPathW(nMax, zWidePath)==0 ){
41827      sqlite3_free(zWidePath);
41828      sqlite3_free(zBuf);
41829      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
41830      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
41831                         "winGetTempname2", 0);
41832    }
41833    zMulti = winUnicodeToUtf8(zWidePath);
41834    if( zMulti ){
41835      sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
41836      sqlite3_free(zMulti);
41837      sqlite3_free(zWidePath);
41838    }else{
41839      sqlite3_free(zWidePath);
41840      sqlite3_free(zBuf);
41841      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41842      return SQLITE_IOERR_NOMEM_BKPT;
41843    }
41844  }
41845#ifdef SQLITE_WIN32_HAS_ANSI
41846  else{
41847    char *zUtf8;
41848    char *zMbcsPath = sqlite3MallocZero( nMax );
41849    if( !zMbcsPath ){
41850      sqlite3_free(zBuf);
41851      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41852      return SQLITE_IOERR_NOMEM_BKPT;
41853    }
41854    if( osGetTempPathA(nMax, zMbcsPath)==0 ){
41855      sqlite3_free(zBuf);
41856      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
41857      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
41858                         "winGetTempname3", 0);
41859    }
41860    zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
41861    if( zUtf8 ){
41862      sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
41863      sqlite3_free(zUtf8);
41864    }else{
41865      sqlite3_free(zBuf);
41866      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41867      return SQLITE_IOERR_NOMEM_BKPT;
41868    }
41869  }
41870#endif /* SQLITE_WIN32_HAS_ANSI */
41871#endif /* !SQLITE_OS_WINRT */
41872
41873  /*
41874  ** Check to make sure the temporary directory ends with an appropriate
41875  ** separator.  If it does not and there is not enough space left to add
41876  ** one, fail.
41877  */
41878  if( !winMakeEndInDirSep(nDir+1, zBuf) ){
41879    sqlite3_free(zBuf);
41880    OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
41881    return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
41882  }
41883
41884  /*
41885  ** Check that the output buffer is large enough for the temporary file
41886  ** name in the following format:
41887  **
41888  **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
41889  **
41890  ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
41891  ** account for the space used by the 15 character random suffix and the
41892  ** two trailing NUL characters.  The final directory separator character
41893  ** has already added if it was not already present.
41894  */
41895  nLen = sqlite3Strlen30(zBuf);
41896  if( (nLen + nPre + 17) > nBuf ){
41897    sqlite3_free(zBuf);
41898    OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
41899    return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
41900  }
41901
41902  sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
41903
41904  j = sqlite3Strlen30(zBuf);
41905  sqlite3_randomness(15, &zBuf[j]);
41906  for(i=0; i<15; i++, j++){
41907    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
41908  }
41909  zBuf[j] = 0;
41910  zBuf[j+1] = 0;
41911  *pzBuf = zBuf;
41912
41913  OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
41914  return SQLITE_OK;
41915}
41916
41917/*
41918** Return TRUE if the named file is really a directory.  Return false if
41919** it is something other than a directory, or if there is any kind of memory
41920** allocation failure.
41921*/
41922static int winIsDir(const void *zConverted){
41923  DWORD attr;
41924  int rc = 0;
41925  DWORD lastErrno;
41926
41927  if( osIsNT() ){
41928    int cnt = 0;
41929    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
41930    memset(&sAttrData, 0, sizeof(sAttrData));
41931    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
41932                             GetFileExInfoStandard,
41933                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
41934    if( !rc ){
41935      return 0; /* Invalid name? */
41936    }
41937    attr = sAttrData.dwFileAttributes;
41938#if SQLITE_OS_WINCE==0
41939  }else{
41940    attr = osGetFileAttributesA((char*)zConverted);
41941#endif
41942  }
41943  return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
41944}
41945
41946/*
41947** Open a file.
41948*/
41949static int winOpen(
41950  sqlite3_vfs *pVfs,        /* Used to get maximum path length and AppData */
41951  const char *zName,        /* Name of the file (UTF-8) */
41952  sqlite3_file *id,         /* Write the SQLite file handle here */
41953  int flags,                /* Open mode flags */
41954  int *pOutFlags            /* Status return flags */
41955){
41956  HANDLE h;
41957  DWORD lastErrno = 0;
41958  DWORD dwDesiredAccess;
41959  DWORD dwShareMode;
41960  DWORD dwCreationDisposition;
41961  DWORD dwFlagsAndAttributes = 0;
41962#if SQLITE_OS_WINCE
41963  int isTemp = 0;
41964#endif
41965  winVfsAppData *pAppData;
41966  winFile *pFile = (winFile*)id;
41967  void *zConverted;              /* Filename in OS encoding */
41968  const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
41969  int cnt = 0;
41970
41971  /* If argument zPath is a NULL pointer, this function is required to open
41972  ** a temporary file. Use this buffer to store the file name in.
41973  */
41974  char *zTmpname = 0; /* For temporary filename, if necessary. */
41975
41976  int rc = SQLITE_OK;            /* Function Return Code */
41977#if !defined(NDEBUG) || SQLITE_OS_WINCE
41978  int eType = flags&0xFFFFFF00;  /* Type of file to open */
41979#endif
41980
41981  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
41982  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
41983  int isCreate     = (flags & SQLITE_OPEN_CREATE);
41984  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
41985  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
41986
41987#ifndef NDEBUG
41988  int isOpenJournal = (isCreate && (
41989        eType==SQLITE_OPEN_MASTER_JOURNAL
41990     || eType==SQLITE_OPEN_MAIN_JOURNAL
41991     || eType==SQLITE_OPEN_WAL
41992  ));
41993#endif
41994
41995  OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
41996           zUtf8Name, id, flags, pOutFlags));
41997
41998  /* Check the following statements are true:
41999  **
42000  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
42001  **   (b) if CREATE is set, then READWRITE must also be set, and
42002  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
42003  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
42004  */
42005  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
42006  assert(isCreate==0 || isReadWrite);
42007  assert(isExclusive==0 || isCreate);
42008  assert(isDelete==0 || isCreate);
42009
42010  /* The main DB, main journal, WAL file and master journal are never
42011  ** automatically deleted. Nor are they ever temporary files.  */
42012  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
42013  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
42014  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
42015  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
42016
42017  /* Assert that the upper layer has set one of the "file-type" flags. */
42018  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
42019       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
42020       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
42021       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
42022  );
42023
42024  assert( pFile!=0 );
42025  memset(pFile, 0, sizeof(winFile));
42026  pFile->h = INVALID_HANDLE_VALUE;
42027
42028#if SQLITE_OS_WINRT
42029  if( !zUtf8Name && !sqlite3_temp_directory ){
42030    sqlite3_log(SQLITE_ERROR,
42031        "sqlite3_temp_directory variable should be set for WinRT");
42032  }
42033#endif
42034
42035  /* If the second argument to this function is NULL, generate a
42036  ** temporary file name to use
42037  */
42038  if( !zUtf8Name ){
42039    assert( isDelete && !isOpenJournal );
42040    rc = winGetTempname(pVfs, &zTmpname);
42041    if( rc!=SQLITE_OK ){
42042      OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
42043      return rc;
42044    }
42045    zUtf8Name = zTmpname;
42046  }
42047
42048  /* Database filenames are double-zero terminated if they are not
42049  ** URIs with parameters.  Hence, they can always be passed into
42050  ** sqlite3_uri_parameter().
42051  */
42052  assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
42053       zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
42054
42055  /* Convert the filename to the system encoding. */
42056  zConverted = winConvertFromUtf8Filename(zUtf8Name);
42057  if( zConverted==0 ){
42058    sqlite3_free(zTmpname);
42059    OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
42060    return SQLITE_IOERR_NOMEM_BKPT;
42061  }
42062
42063  if( winIsDir(zConverted) ){
42064    sqlite3_free(zConverted);
42065    sqlite3_free(zTmpname);
42066    OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
42067    return SQLITE_CANTOPEN_ISDIR;
42068  }
42069
42070  if( isReadWrite ){
42071    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
42072  }else{
42073    dwDesiredAccess = GENERIC_READ;
42074  }
42075
42076  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
42077  ** created. SQLite doesn't use it to indicate "exclusive access"
42078  ** as it is usually understood.
42079  */
42080  if( isExclusive ){
42081    /* Creates a new file, only if it does not already exist. */
42082    /* If the file exists, it fails. */
42083    dwCreationDisposition = CREATE_NEW;
42084  }else if( isCreate ){
42085    /* Open existing file, or create if it doesn't exist */
42086    dwCreationDisposition = OPEN_ALWAYS;
42087  }else{
42088    /* Opens a file, only if it exists. */
42089    dwCreationDisposition = OPEN_EXISTING;
42090  }
42091
42092  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
42093
42094  if( isDelete ){
42095#if SQLITE_OS_WINCE
42096    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
42097    isTemp = 1;
42098#else
42099    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
42100                               | FILE_ATTRIBUTE_HIDDEN
42101                               | FILE_FLAG_DELETE_ON_CLOSE;
42102#endif
42103  }else{
42104    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
42105  }
42106  /* Reports from the internet are that performance is always
42107  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
42108#if SQLITE_OS_WINCE
42109  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
42110#endif
42111
42112  if( osIsNT() ){
42113#if SQLITE_OS_WINRT
42114    CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
42115    extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
42116    extendedParameters.dwFileAttributes =
42117            dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
42118    extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
42119    extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
42120    extendedParameters.lpSecurityAttributes = NULL;
42121    extendedParameters.hTemplateFile = NULL;
42122    while( (h = osCreateFile2((LPCWSTR)zConverted,
42123                              dwDesiredAccess,
42124                              dwShareMode,
42125                              dwCreationDisposition,
42126                              &extendedParameters))==INVALID_HANDLE_VALUE &&
42127                              winRetryIoerr(&cnt, &lastErrno) ){
42128               /* Noop */
42129    }
42130#else
42131    while( (h = osCreateFileW((LPCWSTR)zConverted,
42132                              dwDesiredAccess,
42133                              dwShareMode, NULL,
42134                              dwCreationDisposition,
42135                              dwFlagsAndAttributes,
42136                              NULL))==INVALID_HANDLE_VALUE &&
42137                              winRetryIoerr(&cnt, &lastErrno) ){
42138               /* Noop */
42139    }
42140#endif
42141  }
42142#ifdef SQLITE_WIN32_HAS_ANSI
42143  else{
42144    while( (h = osCreateFileA((LPCSTR)zConverted,
42145                              dwDesiredAccess,
42146                              dwShareMode, NULL,
42147                              dwCreationDisposition,
42148                              dwFlagsAndAttributes,
42149                              NULL))==INVALID_HANDLE_VALUE &&
42150                              winRetryIoerr(&cnt, &lastErrno) ){
42151               /* Noop */
42152    }
42153  }
42154#endif
42155  winLogIoerr(cnt, __LINE__);
42156
42157  OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
42158           dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
42159
42160  if( h==INVALID_HANDLE_VALUE ){
42161    pFile->lastErrno = lastErrno;
42162    winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
42163    sqlite3_free(zConverted);
42164    sqlite3_free(zTmpname);
42165    if( isReadWrite && !isExclusive ){
42166      return winOpen(pVfs, zName, id,
42167         ((flags|SQLITE_OPEN_READONLY) &
42168                     ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
42169         pOutFlags);
42170    }else{
42171      return SQLITE_CANTOPEN_BKPT;
42172    }
42173  }
42174
42175  if( pOutFlags ){
42176    if( isReadWrite ){
42177      *pOutFlags = SQLITE_OPEN_READWRITE;
42178    }else{
42179      *pOutFlags = SQLITE_OPEN_READONLY;
42180    }
42181  }
42182
42183  OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
42184           "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
42185           *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
42186
42187  pAppData = (winVfsAppData*)pVfs->pAppData;
42188
42189#if SQLITE_OS_WINCE
42190  {
42191    if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
42192         && ((pAppData==NULL) || !pAppData->bNoLock)
42193         && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
42194    ){
42195      osCloseHandle(h);
42196      sqlite3_free(zConverted);
42197      sqlite3_free(zTmpname);
42198      OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
42199      return rc;
42200    }
42201  }
42202  if( isTemp ){
42203    pFile->zDeleteOnClose = zConverted;
42204  }else
42205#endif
42206  {
42207    sqlite3_free(zConverted);
42208  }
42209
42210  sqlite3_free(zTmpname);
42211  pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
42212  pFile->pVfs = pVfs;
42213  pFile->h = h;
42214  if( isReadonly ){
42215    pFile->ctrlFlags |= WINFILE_RDONLY;
42216  }
42217  if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
42218    pFile->ctrlFlags |= WINFILE_PSOW;
42219  }
42220  pFile->lastErrno = NO_ERROR;
42221  pFile->zPath = zName;
42222#if SQLITE_MAX_MMAP_SIZE>0
42223  pFile->hMap = NULL;
42224  pFile->pMapRegion = 0;
42225  pFile->mmapSize = 0;
42226  pFile->mmapSizeActual = 0;
42227  pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
42228#endif
42229
42230  OpenCounter(+1);
42231  return rc;
42232}
42233
42234/*
42235** Delete the named file.
42236**
42237** Note that Windows does not allow a file to be deleted if some other
42238** process has it open.  Sometimes a virus scanner or indexing program
42239** will open a journal file shortly after it is created in order to do
42240** whatever it does.  While this other process is holding the
42241** file open, we will be unable to delete it.  To work around this
42242** problem, we delay 100 milliseconds and try to delete again.  Up
42243** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
42244** up and returning an error.
42245*/
42246static int winDelete(
42247  sqlite3_vfs *pVfs,          /* Not used on win32 */
42248  const char *zFilename,      /* Name of file to delete */
42249  int syncDir                 /* Not used on win32 */
42250){
42251  int cnt = 0;
42252  int rc;
42253  DWORD attr;
42254  DWORD lastErrno = 0;
42255  void *zConverted;
42256  UNUSED_PARAMETER(pVfs);
42257  UNUSED_PARAMETER(syncDir);
42258
42259  SimulateIOError(return SQLITE_IOERR_DELETE);
42260  OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
42261
42262  zConverted = winConvertFromUtf8Filename(zFilename);
42263  if( zConverted==0 ){
42264    OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
42265    return SQLITE_IOERR_NOMEM_BKPT;
42266  }
42267  if( osIsNT() ){
42268    do {
42269#if SQLITE_OS_WINRT
42270      WIN32_FILE_ATTRIBUTE_DATA sAttrData;
42271      memset(&sAttrData, 0, sizeof(sAttrData));
42272      if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
42273                                  &sAttrData) ){
42274        attr = sAttrData.dwFileAttributes;
42275      }else{
42276        lastErrno = osGetLastError();
42277        if( lastErrno==ERROR_FILE_NOT_FOUND
42278         || lastErrno==ERROR_PATH_NOT_FOUND ){
42279          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
42280        }else{
42281          rc = SQLITE_ERROR;
42282        }
42283        break;
42284      }
42285#else
42286      attr = osGetFileAttributesW(zConverted);
42287#endif
42288      if ( attr==INVALID_FILE_ATTRIBUTES ){
42289        lastErrno = osGetLastError();
42290        if( lastErrno==ERROR_FILE_NOT_FOUND
42291         || lastErrno==ERROR_PATH_NOT_FOUND ){
42292          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
42293        }else{
42294          rc = SQLITE_ERROR;
42295        }
42296        break;
42297      }
42298      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
42299        rc = SQLITE_ERROR; /* Files only. */
42300        break;
42301      }
42302      if ( osDeleteFileW(zConverted) ){
42303        rc = SQLITE_OK; /* Deleted OK. */
42304        break;
42305      }
42306      if ( !winRetryIoerr(&cnt, &lastErrno) ){
42307        rc = SQLITE_ERROR; /* No more retries. */
42308        break;
42309      }
42310    } while(1);
42311  }
42312#ifdef SQLITE_WIN32_HAS_ANSI
42313  else{
42314    do {
42315      attr = osGetFileAttributesA(zConverted);
42316      if ( attr==INVALID_FILE_ATTRIBUTES ){
42317        lastErrno = osGetLastError();
42318        if( lastErrno==ERROR_FILE_NOT_FOUND
42319         || lastErrno==ERROR_PATH_NOT_FOUND ){
42320          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
42321        }else{
42322          rc = SQLITE_ERROR;
42323        }
42324        break;
42325      }
42326      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
42327        rc = SQLITE_ERROR; /* Files only. */
42328        break;
42329      }
42330      if ( osDeleteFileA(zConverted) ){
42331        rc = SQLITE_OK; /* Deleted OK. */
42332        break;
42333      }
42334      if ( !winRetryIoerr(&cnt, &lastErrno) ){
42335        rc = SQLITE_ERROR; /* No more retries. */
42336        break;
42337      }
42338    } while(1);
42339  }
42340#endif
42341  if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
42342    rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
42343  }else{
42344    winLogIoerr(cnt, __LINE__);
42345  }
42346  sqlite3_free(zConverted);
42347  OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
42348  return rc;
42349}
42350
42351/*
42352** Check the existence and status of a file.
42353*/
42354static int winAccess(
42355  sqlite3_vfs *pVfs,         /* Not used on win32 */
42356  const char *zFilename,     /* Name of file to check */
42357  int flags,                 /* Type of test to make on this file */
42358  int *pResOut               /* OUT: Result */
42359){
42360  DWORD attr;
42361  int rc = 0;
42362  DWORD lastErrno = 0;
42363  void *zConverted;
42364  UNUSED_PARAMETER(pVfs);
42365
42366  SimulateIOError( return SQLITE_IOERR_ACCESS; );
42367  OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
42368           zFilename, flags, pResOut));
42369
42370  zConverted = winConvertFromUtf8Filename(zFilename);
42371  if( zConverted==0 ){
42372    OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
42373    return SQLITE_IOERR_NOMEM_BKPT;
42374  }
42375  if( osIsNT() ){
42376    int cnt = 0;
42377    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
42378    memset(&sAttrData, 0, sizeof(sAttrData));
42379    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
42380                             GetFileExInfoStandard,
42381                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
42382    if( rc ){
42383      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
42384      ** as if it does not exist.
42385      */
42386      if(    flags==SQLITE_ACCESS_EXISTS
42387          && sAttrData.nFileSizeHigh==0
42388          && sAttrData.nFileSizeLow==0 ){
42389        attr = INVALID_FILE_ATTRIBUTES;
42390      }else{
42391        attr = sAttrData.dwFileAttributes;
42392      }
42393    }else{
42394      winLogIoerr(cnt, __LINE__);
42395      if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
42396        sqlite3_free(zConverted);
42397        return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
42398                           zFilename);
42399      }else{
42400        attr = INVALID_FILE_ATTRIBUTES;
42401      }
42402    }
42403  }
42404#ifdef SQLITE_WIN32_HAS_ANSI
42405  else{
42406    attr = osGetFileAttributesA((char*)zConverted);
42407  }
42408#endif
42409  sqlite3_free(zConverted);
42410  switch( flags ){
42411    case SQLITE_ACCESS_READ:
42412    case SQLITE_ACCESS_EXISTS:
42413      rc = attr!=INVALID_FILE_ATTRIBUTES;
42414      break;
42415    case SQLITE_ACCESS_READWRITE:
42416      rc = attr!=INVALID_FILE_ATTRIBUTES &&
42417             (attr & FILE_ATTRIBUTE_READONLY)==0;
42418      break;
42419    default:
42420      assert(!"Invalid flags argument");
42421  }
42422  *pResOut = rc;
42423  OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
42424           zFilename, pResOut, *pResOut));
42425  return SQLITE_OK;
42426}
42427
42428/*
42429** Returns non-zero if the specified path name starts with a drive letter
42430** followed by a colon character.
42431*/
42432static BOOL winIsDriveLetterAndColon(
42433  const char *zPathname
42434){
42435  return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
42436}
42437
42438/*
42439** Returns non-zero if the specified path name should be used verbatim.  If
42440** non-zero is returned from this function, the calling function must simply
42441** use the provided path name verbatim -OR- resolve it into a full path name
42442** using the GetFullPathName Win32 API function (if available).
42443*/
42444static BOOL winIsVerbatimPathname(
42445  const char *zPathname
42446){
42447  /*
42448  ** If the path name starts with a forward slash or a backslash, it is either
42449  ** a legal UNC name, a volume relative path, or an absolute path name in the
42450  ** "Unix" format on Windows.  There is no easy way to differentiate between
42451  ** the final two cases; therefore, we return the safer return value of TRUE
42452  ** so that callers of this function will simply use it verbatim.
42453  */
42454  if ( winIsDirSep(zPathname[0]) ){
42455    return TRUE;
42456  }
42457
42458  /*
42459  ** If the path name starts with a letter and a colon it is either a volume
42460  ** relative path or an absolute path.  Callers of this function must not
42461  ** attempt to treat it as a relative path name (i.e. they should simply use
42462  ** it verbatim).
42463  */
42464  if ( winIsDriveLetterAndColon(zPathname) ){
42465    return TRUE;
42466  }
42467
42468  /*
42469  ** If we get to this point, the path name should almost certainly be a purely
42470  ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
42471  */
42472  return FALSE;
42473}
42474
42475/*
42476** Turn a relative pathname into a full pathname.  Write the full
42477** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
42478** bytes in size.
42479*/
42480static int winFullPathname(
42481  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
42482  const char *zRelative,        /* Possibly relative input path */
42483  int nFull,                    /* Size of output buffer in bytes */
42484  char *zFull                   /* Output buffer */
42485){
42486#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
42487  DWORD nByte;
42488  void *zConverted;
42489  char *zOut;
42490#endif
42491
42492  /* If this path name begins with "/X:", where "X" is any alphabetic
42493  ** character, discard the initial "/" from the pathname.
42494  */
42495  if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
42496    zRelative++;
42497  }
42498
42499#if defined(__CYGWIN__)
42500  SimulateIOError( return SQLITE_ERROR );
42501  UNUSED_PARAMETER(nFull);
42502  assert( nFull>=pVfs->mxPathname );
42503  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
42504    /*
42505    ** NOTE: We are dealing with a relative path name and the data
42506    **       directory has been set.  Therefore, use it as the basis
42507    **       for converting the relative path name to an absolute
42508    **       one by prepending the data directory and a slash.
42509    */
42510    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
42511    if( !zOut ){
42512      return SQLITE_IOERR_NOMEM_BKPT;
42513    }
42514    if( cygwin_conv_path(
42515            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
42516            CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
42517      sqlite3_free(zOut);
42518      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
42519                         "winFullPathname1", zRelative);
42520    }else{
42521      char *zUtf8 = winConvertToUtf8Filename(zOut);
42522      if( !zUtf8 ){
42523        sqlite3_free(zOut);
42524        return SQLITE_IOERR_NOMEM_BKPT;
42525      }
42526      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
42527                       sqlite3_data_directory, winGetDirSep(), zUtf8);
42528      sqlite3_free(zUtf8);
42529      sqlite3_free(zOut);
42530    }
42531  }else{
42532    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
42533    if( !zOut ){
42534      return SQLITE_IOERR_NOMEM_BKPT;
42535    }
42536    if( cygwin_conv_path(
42537            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
42538            zRelative, zOut, pVfs->mxPathname+1)<0 ){
42539      sqlite3_free(zOut);
42540      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
42541                         "winFullPathname2", zRelative);
42542    }else{
42543      char *zUtf8 = winConvertToUtf8Filename(zOut);
42544      if( !zUtf8 ){
42545        sqlite3_free(zOut);
42546        return SQLITE_IOERR_NOMEM_BKPT;
42547      }
42548      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
42549      sqlite3_free(zUtf8);
42550      sqlite3_free(zOut);
42551    }
42552  }
42553  return SQLITE_OK;
42554#endif
42555
42556#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
42557  SimulateIOError( return SQLITE_ERROR );
42558  /* WinCE has no concept of a relative pathname, or so I am told. */
42559  /* WinRT has no way to convert a relative path to an absolute one. */
42560  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
42561    /*
42562    ** NOTE: We are dealing with a relative path name and the data
42563    **       directory has been set.  Therefore, use it as the basis
42564    **       for converting the relative path name to an absolute
42565    **       one by prepending the data directory and a backslash.
42566    */
42567    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
42568                     sqlite3_data_directory, winGetDirSep(), zRelative);
42569  }else{
42570    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
42571  }
42572  return SQLITE_OK;
42573#endif
42574
42575#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
42576  /* It's odd to simulate an io-error here, but really this is just
42577  ** using the io-error infrastructure to test that SQLite handles this
42578  ** function failing. This function could fail if, for example, the
42579  ** current working directory has been unlinked.
42580  */
42581  SimulateIOError( return SQLITE_ERROR );
42582  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
42583    /*
42584    ** NOTE: We are dealing with a relative path name and the data
42585    **       directory has been set.  Therefore, use it as the basis
42586    **       for converting the relative path name to an absolute
42587    **       one by prepending the data directory and a backslash.
42588    */
42589    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
42590                     sqlite3_data_directory, winGetDirSep(), zRelative);
42591    return SQLITE_OK;
42592  }
42593  zConverted = winConvertFromUtf8Filename(zRelative);
42594  if( zConverted==0 ){
42595    return SQLITE_IOERR_NOMEM_BKPT;
42596  }
42597  if( osIsNT() ){
42598    LPWSTR zTemp;
42599    nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
42600    if( nByte==0 ){
42601      sqlite3_free(zConverted);
42602      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42603                         "winFullPathname1", zRelative);
42604    }
42605    nByte += 3;
42606    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
42607    if( zTemp==0 ){
42608      sqlite3_free(zConverted);
42609      return SQLITE_IOERR_NOMEM_BKPT;
42610    }
42611    nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
42612    if( nByte==0 ){
42613      sqlite3_free(zConverted);
42614      sqlite3_free(zTemp);
42615      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42616                         "winFullPathname2", zRelative);
42617    }
42618    sqlite3_free(zConverted);
42619    zOut = winUnicodeToUtf8(zTemp);
42620    sqlite3_free(zTemp);
42621  }
42622#ifdef SQLITE_WIN32_HAS_ANSI
42623  else{
42624    char *zTemp;
42625    nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
42626    if( nByte==0 ){
42627      sqlite3_free(zConverted);
42628      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42629                         "winFullPathname3", zRelative);
42630    }
42631    nByte += 3;
42632    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
42633    if( zTemp==0 ){
42634      sqlite3_free(zConverted);
42635      return SQLITE_IOERR_NOMEM_BKPT;
42636    }
42637    nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
42638    if( nByte==0 ){
42639      sqlite3_free(zConverted);
42640      sqlite3_free(zTemp);
42641      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42642                         "winFullPathname4", zRelative);
42643    }
42644    sqlite3_free(zConverted);
42645    zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
42646    sqlite3_free(zTemp);
42647  }
42648#endif
42649  if( zOut ){
42650    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
42651    sqlite3_free(zOut);
42652    return SQLITE_OK;
42653  }else{
42654    return SQLITE_IOERR_NOMEM_BKPT;
42655  }
42656#endif
42657}
42658
42659#ifndef SQLITE_OMIT_LOAD_EXTENSION
42660/*
42661** Interfaces for opening a shared library, finding entry points
42662** within the shared library, and closing the shared library.
42663*/
42664static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
42665  HANDLE h;
42666#if defined(__CYGWIN__)
42667  int nFull = pVfs->mxPathname+1;
42668  char *zFull = sqlite3MallocZero( nFull );
42669  void *zConverted = 0;
42670  if( zFull==0 ){
42671    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
42672    return 0;
42673  }
42674  if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
42675    sqlite3_free(zFull);
42676    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
42677    return 0;
42678  }
42679  zConverted = winConvertFromUtf8Filename(zFull);
42680  sqlite3_free(zFull);
42681#else
42682  void *zConverted = winConvertFromUtf8Filename(zFilename);
42683  UNUSED_PARAMETER(pVfs);
42684#endif
42685  if( zConverted==0 ){
42686    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
42687    return 0;
42688  }
42689  if( osIsNT() ){
42690#if SQLITE_OS_WINRT
42691    h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
42692#else
42693    h = osLoadLibraryW((LPCWSTR)zConverted);
42694#endif
42695  }
42696#ifdef SQLITE_WIN32_HAS_ANSI
42697  else{
42698    h = osLoadLibraryA((char*)zConverted);
42699  }
42700#endif
42701  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
42702  sqlite3_free(zConverted);
42703  return (void*)h;
42704}
42705static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
42706  UNUSED_PARAMETER(pVfs);
42707  winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
42708}
42709static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
42710  FARPROC proc;
42711  UNUSED_PARAMETER(pVfs);
42712  proc = osGetProcAddressA((HANDLE)pH, zSym);
42713  OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
42714           (void*)pH, zSym, (void*)proc));
42715  return (void(*)(void))proc;
42716}
42717static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
42718  UNUSED_PARAMETER(pVfs);
42719  osFreeLibrary((HANDLE)pHandle);
42720  OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
42721}
42722#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
42723  #define winDlOpen  0
42724  #define winDlError 0
42725  #define winDlSym   0
42726  #define winDlClose 0
42727#endif
42728
42729/* State information for the randomness gatherer. */
42730typedef struct EntropyGatherer EntropyGatherer;
42731struct EntropyGatherer {
42732  unsigned char *a;   /* Gather entropy into this buffer */
42733  int na;             /* Size of a[] in bytes */
42734  int i;              /* XOR next input into a[i] */
42735  int nXor;           /* Number of XOR operations done */
42736};
42737
42738#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
42739/* Mix sz bytes of entropy into p. */
42740static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
42741  int j, k;
42742  for(j=0, k=p->i; j<sz; j++){
42743    p->a[k++] ^= x[j];
42744    if( k>=p->na ) k = 0;
42745  }
42746  p->i = k;
42747  p->nXor += sz;
42748}
42749#endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
42750
42751/*
42752** Write up to nBuf bytes of randomness into zBuf.
42753*/
42754static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
42755#if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
42756  UNUSED_PARAMETER(pVfs);
42757  memset(zBuf, 0, nBuf);
42758  return nBuf;
42759#else
42760  EntropyGatherer e;
42761  UNUSED_PARAMETER(pVfs);
42762  memset(zBuf, 0, nBuf);
42763#if defined(_MSC_VER) && _MSC_VER>=1400 && !SQLITE_OS_WINCE
42764  rand_s((unsigned int*)zBuf); /* rand_s() is not available with MinGW */
42765#endif /* defined(_MSC_VER) && _MSC_VER>=1400 */
42766  e.a = (unsigned char*)zBuf;
42767  e.na = nBuf;
42768  e.nXor = 0;
42769  e.i = 0;
42770  {
42771    SYSTEMTIME x;
42772    osGetSystemTime(&x);
42773    xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
42774  }
42775  {
42776    DWORD pid = osGetCurrentProcessId();
42777    xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
42778  }
42779#if SQLITE_OS_WINRT
42780  {
42781    ULONGLONG cnt = osGetTickCount64();
42782    xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
42783  }
42784#else
42785  {
42786    DWORD cnt = osGetTickCount();
42787    xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
42788  }
42789#endif /* SQLITE_OS_WINRT */
42790  {
42791    LARGE_INTEGER i;
42792    osQueryPerformanceCounter(&i);
42793    xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
42794  }
42795#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
42796  {
42797    UUID id;
42798    memset(&id, 0, sizeof(UUID));
42799    osUuidCreate(&id);
42800    xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
42801    memset(&id, 0, sizeof(UUID));
42802    osUuidCreateSequential(&id);
42803    xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
42804  }
42805#endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
42806  return e.nXor>nBuf ? nBuf : e.nXor;
42807#endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
42808}
42809
42810
42811/*
42812** Sleep for a little while.  Return the amount of time slept.
42813*/
42814static int winSleep(sqlite3_vfs *pVfs, int microsec){
42815  sqlite3_win32_sleep((microsec+999)/1000);
42816  UNUSED_PARAMETER(pVfs);
42817  return ((microsec+999)/1000)*1000;
42818}
42819
42820/*
42821** The following variable, if set to a non-zero value, is interpreted as
42822** the number of seconds since 1970 and is used to set the result of
42823** sqlite3OsCurrentTime() during testing.
42824*/
42825#ifdef SQLITE_TEST
42826SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
42827#endif
42828
42829/*
42830** Find the current time (in Universal Coordinated Time).  Write into *piNow
42831** the current time and date as a Julian Day number times 86_400_000.  In
42832** other words, write into *piNow the number of milliseconds since the Julian
42833** epoch of noon in Greenwich on November 24, 4714 B.C according to the
42834** proleptic Gregorian calendar.
42835**
42836** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
42837** cannot be found.
42838*/
42839static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
42840  /* FILETIME structure is a 64-bit value representing the number of
42841     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
42842  */
42843  FILETIME ft;
42844  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
42845#ifdef SQLITE_TEST
42846  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
42847#endif
42848  /* 2^32 - to avoid use of LL and warnings in gcc */
42849  static const sqlite3_int64 max32BitValue =
42850      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
42851      (sqlite3_int64)294967296;
42852
42853#if SQLITE_OS_WINCE
42854  SYSTEMTIME time;
42855  osGetSystemTime(&time);
42856  /* if SystemTimeToFileTime() fails, it returns zero. */
42857  if (!osSystemTimeToFileTime(&time,&ft)){
42858    return SQLITE_ERROR;
42859  }
42860#else
42861  osGetSystemTimeAsFileTime( &ft );
42862#endif
42863
42864  *piNow = winFiletimeEpoch +
42865            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
42866               (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
42867
42868#ifdef SQLITE_TEST
42869  if( sqlite3_current_time ){
42870    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
42871  }
42872#endif
42873  UNUSED_PARAMETER(pVfs);
42874  return SQLITE_OK;
42875}
42876
42877/*
42878** Find the current time (in Universal Coordinated Time).  Write the
42879** current time and date as a Julian Day number into *prNow and
42880** return 0.  Return 1 if the time and date cannot be found.
42881*/
42882static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
42883  int rc;
42884  sqlite3_int64 i;
42885  rc = winCurrentTimeInt64(pVfs, &i);
42886  if( !rc ){
42887    *prNow = i/86400000.0;
42888  }
42889  return rc;
42890}
42891
42892/*
42893** The idea is that this function works like a combination of
42894** GetLastError() and FormatMessage() on Windows (or errno and
42895** strerror_r() on Unix). After an error is returned by an OS
42896** function, SQLite calls this function with zBuf pointing to
42897** a buffer of nBuf bytes. The OS layer should populate the
42898** buffer with a nul-terminated UTF-8 encoded error message
42899** describing the last IO error to have occurred within the calling
42900** thread.
42901**
42902** If the error message is too large for the supplied buffer,
42903** it should be truncated. The return value of xGetLastError
42904** is zero if the error message fits in the buffer, or non-zero
42905** otherwise (if the message was truncated). If non-zero is returned,
42906** then it is not necessary to include the nul-terminator character
42907** in the output buffer.
42908**
42909** Not supplying an error message will have no adverse effect
42910** on SQLite. It is fine to have an implementation that never
42911** returns an error message:
42912**
42913**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
42914**     assert(zBuf[0]=='\0');
42915**     return 0;
42916**   }
42917**
42918** However if an error message is supplied, it will be incorporated
42919** by sqlite into the error message available to the user using
42920** sqlite3_errmsg(), possibly making IO errors easier to debug.
42921*/
42922static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
42923  DWORD e = osGetLastError();
42924  UNUSED_PARAMETER(pVfs);
42925  if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
42926  return e;
42927}
42928
42929/*
42930** Initialize and deinitialize the operating system interface.
42931*/
42932SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
42933  static sqlite3_vfs winVfs = {
42934    3,                     /* iVersion */
42935    sizeof(winFile),       /* szOsFile */
42936    SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
42937    0,                     /* pNext */
42938    "win32",               /* zName */
42939    &winAppData,           /* pAppData */
42940    winOpen,               /* xOpen */
42941    winDelete,             /* xDelete */
42942    winAccess,             /* xAccess */
42943    winFullPathname,       /* xFullPathname */
42944    winDlOpen,             /* xDlOpen */
42945    winDlError,            /* xDlError */
42946    winDlSym,              /* xDlSym */
42947    winDlClose,            /* xDlClose */
42948    winRandomness,         /* xRandomness */
42949    winSleep,              /* xSleep */
42950    winCurrentTime,        /* xCurrentTime */
42951    winGetLastError,       /* xGetLastError */
42952    winCurrentTimeInt64,   /* xCurrentTimeInt64 */
42953    winSetSystemCall,      /* xSetSystemCall */
42954    winGetSystemCall,      /* xGetSystemCall */
42955    winNextSystemCall,     /* xNextSystemCall */
42956  };
42957#if defined(SQLITE_WIN32_HAS_WIDE)
42958  static sqlite3_vfs winLongPathVfs = {
42959    3,                     /* iVersion */
42960    sizeof(winFile),       /* szOsFile */
42961    SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
42962    0,                     /* pNext */
42963    "win32-longpath",      /* zName */
42964    &winAppData,           /* pAppData */
42965    winOpen,               /* xOpen */
42966    winDelete,             /* xDelete */
42967    winAccess,             /* xAccess */
42968    winFullPathname,       /* xFullPathname */
42969    winDlOpen,             /* xDlOpen */
42970    winDlError,            /* xDlError */
42971    winDlSym,              /* xDlSym */
42972    winDlClose,            /* xDlClose */
42973    winRandomness,         /* xRandomness */
42974    winSleep,              /* xSleep */
42975    winCurrentTime,        /* xCurrentTime */
42976    winGetLastError,       /* xGetLastError */
42977    winCurrentTimeInt64,   /* xCurrentTimeInt64 */
42978    winSetSystemCall,      /* xSetSystemCall */
42979    winGetSystemCall,      /* xGetSystemCall */
42980    winNextSystemCall,     /* xNextSystemCall */
42981  };
42982#endif
42983  static sqlite3_vfs winNolockVfs = {
42984    3,                     /* iVersion */
42985    sizeof(winFile),       /* szOsFile */
42986    SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
42987    0,                     /* pNext */
42988    "win32-none",          /* zName */
42989    &winNolockAppData,     /* pAppData */
42990    winOpen,               /* xOpen */
42991    winDelete,             /* xDelete */
42992    winAccess,             /* xAccess */
42993    winFullPathname,       /* xFullPathname */
42994    winDlOpen,             /* xDlOpen */
42995    winDlError,            /* xDlError */
42996    winDlSym,              /* xDlSym */
42997    winDlClose,            /* xDlClose */
42998    winRandomness,         /* xRandomness */
42999    winSleep,              /* xSleep */
43000    winCurrentTime,        /* xCurrentTime */
43001    winGetLastError,       /* xGetLastError */
43002    winCurrentTimeInt64,   /* xCurrentTimeInt64 */
43003    winSetSystemCall,      /* xSetSystemCall */
43004    winGetSystemCall,      /* xGetSystemCall */
43005    winNextSystemCall,     /* xNextSystemCall */
43006  };
43007#if defined(SQLITE_WIN32_HAS_WIDE)
43008  static sqlite3_vfs winLongPathNolockVfs = {
43009    3,                     /* iVersion */
43010    sizeof(winFile),       /* szOsFile */
43011    SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
43012    0,                     /* pNext */
43013    "win32-longpath-none", /* zName */
43014    &winNolockAppData,     /* pAppData */
43015    winOpen,               /* xOpen */
43016    winDelete,             /* xDelete */
43017    winAccess,             /* xAccess */
43018    winFullPathname,       /* xFullPathname */
43019    winDlOpen,             /* xDlOpen */
43020    winDlError,            /* xDlError */
43021    winDlSym,              /* xDlSym */
43022    winDlClose,            /* xDlClose */
43023    winRandomness,         /* xRandomness */
43024    winSleep,              /* xSleep */
43025    winCurrentTime,        /* xCurrentTime */
43026    winGetLastError,       /* xGetLastError */
43027    winCurrentTimeInt64,   /* xCurrentTimeInt64 */
43028    winSetSystemCall,      /* xSetSystemCall */
43029    winGetSystemCall,      /* xGetSystemCall */
43030    winNextSystemCall,     /* xNextSystemCall */
43031  };
43032#endif
43033
43034  /* Double-check that the aSyscall[] array has been constructed
43035  ** correctly.  See ticket [bb3a86e890c8e96ab] */
43036  assert( ArraySize(aSyscall)==80 );
43037
43038  /* get memory map allocation granularity */
43039  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
43040#if SQLITE_OS_WINRT
43041  osGetNativeSystemInfo(&winSysInfo);
43042#else
43043  osGetSystemInfo(&winSysInfo);
43044#endif
43045  assert( winSysInfo.dwAllocationGranularity>0 );
43046  assert( winSysInfo.dwPageSize>0 );
43047
43048  sqlite3_vfs_register(&winVfs, 1);
43049
43050#if defined(SQLITE_WIN32_HAS_WIDE)
43051  sqlite3_vfs_register(&winLongPathVfs, 0);
43052#endif
43053
43054  sqlite3_vfs_register(&winNolockVfs, 0);
43055
43056#if defined(SQLITE_WIN32_HAS_WIDE)
43057  sqlite3_vfs_register(&winLongPathNolockVfs, 0);
43058#endif
43059
43060  return SQLITE_OK;
43061}
43062
43063SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
43064#if SQLITE_OS_WINRT
43065  if( sleepObj!=NULL ){
43066    osCloseHandle(sleepObj);
43067    sleepObj = NULL;
43068  }
43069#endif
43070  return SQLITE_OK;
43071}
43072
43073#endif /* SQLITE_OS_WIN */
43074
43075/************** End of os_win.c **********************************************/
43076/************** Begin file bitvec.c ******************************************/
43077/*
43078** 2008 February 16
43079**
43080** The author disclaims copyright to this source code.  In place of
43081** a legal notice, here is a blessing:
43082**
43083**    May you do good and not evil.
43084**    May you find forgiveness for yourself and forgive others.
43085**    May you share freely, never taking more than you give.
43086**
43087*************************************************************************
43088** This file implements an object that represents a fixed-length
43089** bitmap.  Bits are numbered starting with 1.
43090**
43091** A bitmap is used to record which pages of a database file have been
43092** journalled during a transaction, or which pages have the "dont-write"
43093** property.  Usually only a few pages are meet either condition.
43094** So the bitmap is usually sparse and has low cardinality.
43095** But sometimes (for example when during a DROP of a large table) most
43096** or all of the pages in a database can get journalled.  In those cases,
43097** the bitmap becomes dense with high cardinality.  The algorithm needs
43098** to handle both cases well.
43099**
43100** The size of the bitmap is fixed when the object is created.
43101**
43102** All bits are clear when the bitmap is created.  Individual bits
43103** may be set or cleared one at a time.
43104**
43105** Test operations are about 100 times more common that set operations.
43106** Clear operations are exceedingly rare.  There are usually between
43107** 5 and 500 set operations per Bitvec object, though the number of sets can
43108** sometimes grow into tens of thousands or larger.  The size of the
43109** Bitvec object is the number of pages in the database file at the
43110** start of a transaction, and is thus usually less than a few thousand,
43111** but can be as large as 2 billion for a really big database.
43112*/
43113/* #include "sqliteInt.h" */
43114
43115/* Size of the Bitvec structure in bytes. */
43116#define BITVEC_SZ        512
43117
43118/* Round the union size down to the nearest pointer boundary, since that's how
43119** it will be aligned within the Bitvec struct. */
43120#define BITVEC_USIZE \
43121    (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
43122
43123/* Type of the array "element" for the bitmap representation.
43124** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
43125** Setting this to the "natural word" size of your CPU may improve
43126** performance. */
43127#define BITVEC_TELEM     u8
43128/* Size, in bits, of the bitmap element. */
43129#define BITVEC_SZELEM    8
43130/* Number of elements in a bitmap array. */
43131#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
43132/* Number of bits in the bitmap array. */
43133#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
43134
43135/* Number of u32 values in hash table. */
43136#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
43137/* Maximum number of entries in hash table before
43138** sub-dividing and re-hashing. */
43139#define BITVEC_MXHASH    (BITVEC_NINT/2)
43140/* Hashing function for the aHash representation.
43141** Empirical testing showed that the *37 multiplier
43142** (an arbitrary prime)in the hash function provided
43143** no fewer collisions than the no-op *1. */
43144#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
43145
43146#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
43147
43148
43149/*
43150** A bitmap is an instance of the following structure.
43151**
43152** This bitmap records the existence of zero or more bits
43153** with values between 1 and iSize, inclusive.
43154**
43155** There are three possible representations of the bitmap.
43156** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
43157** bitmap.  The least significant bit is bit 1.
43158**
43159** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
43160** a hash table that will hold up to BITVEC_MXHASH distinct values.
43161**
43162** Otherwise, the value i is redirected into one of BITVEC_NPTR
43163** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
43164** handles up to iDivisor separate values of i.  apSub[0] holds
43165** values between 1 and iDivisor.  apSub[1] holds values between
43166** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
43167** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
43168** to hold deal with values between 1 and iDivisor.
43169*/
43170struct Bitvec {
43171  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
43172  u32 nSet;       /* Number of bits that are set - only valid for aHash
43173                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
43174                  ** this would be 125. */
43175  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
43176                  /* Should >=0 for apSub element. */
43177                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
43178                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
43179  union {
43180    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
43181    u32 aHash[BITVEC_NINT];      /* Hash table representation */
43182    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
43183  } u;
43184};
43185
43186/*
43187** Create a new bitmap object able to handle bits between 0 and iSize,
43188** inclusive.  Return a pointer to the new object.  Return NULL if
43189** malloc fails.
43190*/
43191SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
43192  Bitvec *p;
43193  assert( sizeof(*p)==BITVEC_SZ );
43194  p = sqlite3MallocZero( sizeof(*p) );
43195  if( p ){
43196    p->iSize = iSize;
43197  }
43198  return p;
43199}
43200
43201/*
43202** Check to see if the i-th bit is set.  Return true or false.
43203** If p is NULL (if the bitmap has not been created) or if
43204** i is out of range, then return false.
43205*/
43206SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
43207  assert( p!=0 );
43208  i--;
43209  if( i>=p->iSize ) return 0;
43210  while( p->iDivisor ){
43211    u32 bin = i/p->iDivisor;
43212    i = i%p->iDivisor;
43213    p = p->u.apSub[bin];
43214    if (!p) {
43215      return 0;
43216    }
43217  }
43218  if( p->iSize<=BITVEC_NBIT ){
43219    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
43220  } else{
43221    u32 h = BITVEC_HASH(i++);
43222    while( p->u.aHash[h] ){
43223      if( p->u.aHash[h]==i ) return 1;
43224      h = (h+1) % BITVEC_NINT;
43225    }
43226    return 0;
43227  }
43228}
43229SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
43230  return p!=0 && sqlite3BitvecTestNotNull(p,i);
43231}
43232
43233/*
43234** Set the i-th bit.  Return 0 on success and an error code if
43235** anything goes wrong.
43236**
43237** This routine might cause sub-bitmaps to be allocated.  Failing
43238** to get the memory needed to hold the sub-bitmap is the only
43239** that can go wrong with an insert, assuming p and i are valid.
43240**
43241** The calling function must ensure that p is a valid Bitvec object
43242** and that the value for "i" is within range of the Bitvec object.
43243** Otherwise the behavior is undefined.
43244*/
43245SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
43246  u32 h;
43247  if( p==0 ) return SQLITE_OK;
43248  assert( i>0 );
43249  assert( i<=p->iSize );
43250  i--;
43251  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
43252    u32 bin = i/p->iDivisor;
43253    i = i%p->iDivisor;
43254    if( p->u.apSub[bin]==0 ){
43255      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
43256      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
43257    }
43258    p = p->u.apSub[bin];
43259  }
43260  if( p->iSize<=BITVEC_NBIT ){
43261    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
43262    return SQLITE_OK;
43263  }
43264  h = BITVEC_HASH(i++);
43265  /* if there wasn't a hash collision, and this doesn't */
43266  /* completely fill the hash, then just add it without */
43267  /* worring about sub-dividing and re-hashing. */
43268  if( !p->u.aHash[h] ){
43269    if (p->nSet<(BITVEC_NINT-1)) {
43270      goto bitvec_set_end;
43271    } else {
43272      goto bitvec_set_rehash;
43273    }
43274  }
43275  /* there was a collision, check to see if it's already */
43276  /* in hash, if not, try to find a spot for it */
43277  do {
43278    if( p->u.aHash[h]==i ) return SQLITE_OK;
43279    h++;
43280    if( h>=BITVEC_NINT ) h = 0;
43281  } while( p->u.aHash[h] );
43282  /* we didn't find it in the hash.  h points to the first */
43283  /* available free spot. check to see if this is going to */
43284  /* make our hash too "full".  */
43285bitvec_set_rehash:
43286  if( p->nSet>=BITVEC_MXHASH ){
43287    unsigned int j;
43288    int rc;
43289    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
43290    if( aiValues==0 ){
43291      return SQLITE_NOMEM_BKPT;
43292    }else{
43293      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
43294      memset(p->u.apSub, 0, sizeof(p->u.apSub));
43295      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
43296      rc = sqlite3BitvecSet(p, i);
43297      for(j=0; j<BITVEC_NINT; j++){
43298        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
43299      }
43300      sqlite3StackFree(0, aiValues);
43301      return rc;
43302    }
43303  }
43304bitvec_set_end:
43305  p->nSet++;
43306  p->u.aHash[h] = i;
43307  return SQLITE_OK;
43308}
43309
43310/*
43311** Clear the i-th bit.
43312**
43313** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
43314** that BitvecClear can use to rebuilt its hash table.
43315*/
43316SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
43317  if( p==0 ) return;
43318  assert( i>0 );
43319  i--;
43320  while( p->iDivisor ){
43321    u32 bin = i/p->iDivisor;
43322    i = i%p->iDivisor;
43323    p = p->u.apSub[bin];
43324    if (!p) {
43325      return;
43326    }
43327  }
43328  if( p->iSize<=BITVEC_NBIT ){
43329    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
43330  }else{
43331    unsigned int j;
43332    u32 *aiValues = pBuf;
43333    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
43334    memset(p->u.aHash, 0, sizeof(p->u.aHash));
43335    p->nSet = 0;
43336    for(j=0; j<BITVEC_NINT; j++){
43337      if( aiValues[j] && aiValues[j]!=(i+1) ){
43338        u32 h = BITVEC_HASH(aiValues[j]-1);
43339        p->nSet++;
43340        while( p->u.aHash[h] ){
43341          h++;
43342          if( h>=BITVEC_NINT ) h = 0;
43343        }
43344        p->u.aHash[h] = aiValues[j];
43345      }
43346    }
43347  }
43348}
43349
43350/*
43351** Destroy a bitmap object.  Reclaim all memory used.
43352*/
43353SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
43354  if( p==0 ) return;
43355  if( p->iDivisor ){
43356    unsigned int i;
43357    for(i=0; i<BITVEC_NPTR; i++){
43358      sqlite3BitvecDestroy(p->u.apSub[i]);
43359    }
43360  }
43361  sqlite3_free(p);
43362}
43363
43364/*
43365** Return the value of the iSize parameter specified when Bitvec *p
43366** was created.
43367*/
43368SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
43369  return p->iSize;
43370}
43371
43372#ifndef SQLITE_OMIT_BUILTIN_TEST
43373/*
43374** Let V[] be an array of unsigned characters sufficient to hold
43375** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
43376** Then the following macros can be used to set, clear, or test
43377** individual bits within V.
43378*/
43379#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
43380#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
43381#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
43382
43383/*
43384** This routine runs an extensive test of the Bitvec code.
43385**
43386** The input is an array of integers that acts as a program
43387** to test the Bitvec.  The integers are opcodes followed
43388** by 0, 1, or 3 operands, depending on the opcode.  Another
43389** opcode follows immediately after the last operand.
43390**
43391** There are 6 opcodes numbered from 0 through 5.  0 is the
43392** "halt" opcode and causes the test to end.
43393**
43394**    0          Halt and return the number of errors
43395**    1 N S X    Set N bits beginning with S and incrementing by X
43396**    2 N S X    Clear N bits beginning with S and incrementing by X
43397**    3 N        Set N randomly chosen bits
43398**    4 N        Clear N randomly chosen bits
43399**    5 N S X    Set N bits from S increment X in array only, not in bitvec
43400**
43401** The opcodes 1 through 4 perform set and clear operations are performed
43402** on both a Bitvec object and on a linear array of bits obtained from malloc.
43403** Opcode 5 works on the linear array only, not on the Bitvec.
43404** Opcode 5 is used to deliberately induce a fault in order to
43405** confirm that error detection works.
43406**
43407** At the conclusion of the test the linear array is compared
43408** against the Bitvec object.  If there are any differences,
43409** an error is returned.  If they are the same, zero is returned.
43410**
43411** If a memory allocation error occurs, return -1.
43412*/
43413SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
43414  Bitvec *pBitvec = 0;
43415  unsigned char *pV = 0;
43416  int rc = -1;
43417  int i, nx, pc, op;
43418  void *pTmpSpace;
43419
43420  /* Allocate the Bitvec to be tested and a linear array of
43421  ** bits to act as the reference */
43422  pBitvec = sqlite3BitvecCreate( sz );
43423  pV = sqlite3MallocZero( (sz+7)/8 + 1 );
43424  pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
43425  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
43426
43427  /* NULL pBitvec tests */
43428  sqlite3BitvecSet(0, 1);
43429  sqlite3BitvecClear(0, 1, pTmpSpace);
43430
43431  /* Run the program */
43432  pc = 0;
43433  while( (op = aOp[pc])!=0 ){
43434    switch( op ){
43435      case 1:
43436      case 2:
43437      case 5: {
43438        nx = 4;
43439        i = aOp[pc+2] - 1;
43440        aOp[pc+2] += aOp[pc+3];
43441        break;
43442      }
43443      case 3:
43444      case 4:
43445      default: {
43446        nx = 2;
43447        sqlite3_randomness(sizeof(i), &i);
43448        break;
43449      }
43450    }
43451    if( (--aOp[pc+1]) > 0 ) nx = 0;
43452    pc += nx;
43453    i = (i & 0x7fffffff)%sz;
43454    if( (op & 1)!=0 ){
43455      SETBIT(pV, (i+1));
43456      if( op!=5 ){
43457        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
43458      }
43459    }else{
43460      CLEARBIT(pV, (i+1));
43461      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
43462    }
43463  }
43464
43465  /* Test to make sure the linear array exactly matches the
43466  ** Bitvec object.  Start with the assumption that they do
43467  ** match (rc==0).  Change rc to non-zero if a discrepancy
43468  ** is found.
43469  */
43470  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
43471          + sqlite3BitvecTest(pBitvec, 0)
43472          + (sqlite3BitvecSize(pBitvec) - sz);
43473  for(i=1; i<=sz; i++){
43474    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
43475      rc = i;
43476      break;
43477    }
43478  }
43479
43480  /* Free allocated structure */
43481bitvec_end:
43482  sqlite3_free(pTmpSpace);
43483  sqlite3_free(pV);
43484  sqlite3BitvecDestroy(pBitvec);
43485  return rc;
43486}
43487#endif /* SQLITE_OMIT_BUILTIN_TEST */
43488
43489/************** End of bitvec.c **********************************************/
43490/************** Begin file pcache.c ******************************************/
43491/*
43492** 2008 August 05
43493**
43494** The author disclaims copyright to this source code.  In place of
43495** a legal notice, here is a blessing:
43496**
43497**    May you do good and not evil.
43498**    May you find forgiveness for yourself and forgive others.
43499**    May you share freely, never taking more than you give.
43500**
43501*************************************************************************
43502** This file implements that page cache.
43503*/
43504/* #include "sqliteInt.h" */
43505
43506/*
43507** A complete page cache is an instance of this structure.  Every
43508** entry in the cache holds a single page of the database file.  The
43509** btree layer only operates on the cached copy of the database pages.
43510**
43511** A page cache entry is "clean" if it exactly matches what is currently
43512** on disk.  A page is "dirty" if it has been modified and needs to be
43513** persisted to disk.
43514**
43515** pDirty, pDirtyTail, pSynced:
43516**   All dirty pages are linked into the doubly linked list using
43517**   PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
43518**   such that p was added to the list more recently than p->pDirtyNext.
43519**   PCache.pDirty points to the first (newest) element in the list and
43520**   pDirtyTail to the last (oldest).
43521**
43522**   The PCache.pSynced variable is used to optimize searching for a dirty
43523**   page to eject from the cache mid-transaction. It is better to eject
43524**   a page that does not require a journal sync than one that does.
43525**   Therefore, pSynced is maintained to that it *almost* always points
43526**   to either the oldest page in the pDirty/pDirtyTail list that has a
43527**   clear PGHDR_NEED_SYNC flag or to a page that is older than this one
43528**   (so that the right page to eject can be found by following pDirtyPrev
43529**   pointers).
43530*/
43531struct PCache {
43532  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
43533  PgHdr *pSynced;                     /* Last synced page in dirty page list */
43534  int nRefSum;                        /* Sum of ref counts over all pages */
43535  int szCache;                        /* Configured cache size */
43536  int szSpill;                        /* Size before spilling occurs */
43537  int szPage;                         /* Size of every page in this cache */
43538  int szExtra;                        /* Size of extra space for each page */
43539  u8 bPurgeable;                      /* True if pages are on backing store */
43540  u8 eCreate;                         /* eCreate value for for xFetch() */
43541  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
43542  void *pStress;                      /* Argument to xStress */
43543  sqlite3_pcache *pCache;             /* Pluggable cache module */
43544};
43545
43546/********************************** Test and Debug Logic **********************/
43547/*
43548** Debug tracing macros.  Enable by by changing the "0" to "1" and
43549** recompiling.
43550**
43551** When sqlite3PcacheTrace is 1, single line trace messages are issued.
43552** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
43553** is displayed for many operations, resulting in a lot of output.
43554*/
43555#if defined(SQLITE_DEBUG) && 0
43556  int sqlite3PcacheTrace = 2;       /* 0: off  1: simple  2: cache dumps */
43557  int sqlite3PcacheMxDump = 9999;   /* Max cache entries for pcacheDump() */
43558# define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
43559  void pcacheDump(PCache *pCache){
43560    int N;
43561    int i, j;
43562    sqlite3_pcache_page *pLower;
43563    PgHdr *pPg;
43564    unsigned char *a;
43565
43566    if( sqlite3PcacheTrace<2 ) return;
43567    if( pCache->pCache==0 ) return;
43568    N = sqlite3PcachePagecount(pCache);
43569    if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
43570    for(i=1; i<=N; i++){
43571       pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
43572       if( pLower==0 ) continue;
43573       pPg = (PgHdr*)pLower->pExtra;
43574       printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
43575       a = (unsigned char *)pLower->pBuf;
43576       for(j=0; j<12; j++) printf("%02x", a[j]);
43577       printf("\n");
43578       if( pPg->pPage==0 ){
43579         sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
43580       }
43581    }
43582  }
43583  #else
43584# define pcacheTrace(X)
43585# define pcacheDump(X)
43586#endif
43587
43588/*
43589** Check invariants on a PgHdr entry.  Return true if everything is OK.
43590** Return false if any invariant is violated.
43591**
43592** This routine is for use inside of assert() statements only.  For
43593** example:
43594**
43595**          assert( sqlite3PcachePageSanity(pPg) );
43596*/
43597#if SQLITE_DEBUG
43598SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
43599  PCache *pCache;
43600  assert( pPg!=0 );
43601  assert( pPg->pgno>0 );    /* Page number is 1 or more */
43602  pCache = pPg->pCache;
43603  assert( pCache!=0 );      /* Every page has an associated PCache */
43604  if( pPg->flags & PGHDR_CLEAN ){
43605    assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
43606    assert( pCache->pDirty!=pPg );          /* CLEAN pages not on dirty list */
43607    assert( pCache->pDirtyTail!=pPg );
43608  }
43609  /* WRITEABLE pages must also be DIRTY */
43610  if( pPg->flags & PGHDR_WRITEABLE ){
43611    assert( pPg->flags & PGHDR_DIRTY );     /* WRITEABLE implies DIRTY */
43612  }
43613  /* NEED_SYNC can be set independently of WRITEABLE.  This can happen,
43614  ** for example, when using the sqlite3PagerDontWrite() optimization:
43615  **    (1)  Page X is journalled, and gets WRITEABLE and NEED_SEEK.
43616  **    (2)  Page X moved to freelist, WRITEABLE is cleared
43617  **    (3)  Page X reused, WRITEABLE is set again
43618  ** If NEED_SYNC had been cleared in step 2, then it would not be reset
43619  ** in step 3, and page might be written into the database without first
43620  ** syncing the rollback journal, which might cause corruption on a power
43621  ** loss.
43622  **
43623  ** Another example is when the database page size is smaller than the
43624  ** disk sector size.  When any page of a sector is journalled, all pages
43625  ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
43626  ** in case they are later modified, since all pages in the same sector
43627  ** must be journalled and synced before any of those pages can be safely
43628  ** written.
43629  */
43630  return 1;
43631}
43632#endif /* SQLITE_DEBUG */
43633
43634
43635/********************************** Linked List Management ********************/
43636
43637/* Allowed values for second argument to pcacheManageDirtyList() */
43638#define PCACHE_DIRTYLIST_REMOVE   1    /* Remove pPage from dirty list */
43639#define PCACHE_DIRTYLIST_ADD      2    /* Add pPage to the dirty list */
43640#define PCACHE_DIRTYLIST_FRONT    3    /* Move pPage to the front of the list */
43641
43642/*
43643** Manage pPage's participation on the dirty list.  Bits of the addRemove
43644** argument determines what operation to do.  The 0x01 bit means first
43645** remove pPage from the dirty list.  The 0x02 means add pPage back to
43646** the dirty list.  Doing both moves pPage to the front of the dirty list.
43647*/
43648static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
43649  PCache *p = pPage->pCache;
43650
43651  pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
43652                addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
43653                pPage->pgno));
43654  if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
43655    assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
43656    assert( pPage->pDirtyPrev || pPage==p->pDirty );
43657
43658    /* Update the PCache1.pSynced variable if necessary. */
43659    if( p->pSynced==pPage ){
43660      p->pSynced = pPage->pDirtyPrev;
43661    }
43662
43663    if( pPage->pDirtyNext ){
43664      pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
43665    }else{
43666      assert( pPage==p->pDirtyTail );
43667      p->pDirtyTail = pPage->pDirtyPrev;
43668    }
43669    if( pPage->pDirtyPrev ){
43670      pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
43671    }else{
43672      /* If there are now no dirty pages in the cache, set eCreate to 2.
43673      ** This is an optimization that allows sqlite3PcacheFetch() to skip
43674      ** searching for a dirty page to eject from the cache when it might
43675      ** otherwise have to.  */
43676      assert( pPage==p->pDirty );
43677      p->pDirty = pPage->pDirtyNext;
43678      assert( p->bPurgeable || p->eCreate==2 );
43679      if( p->pDirty==0 ){         /*OPTIMIZATION-IF-TRUE*/
43680        assert( p->bPurgeable==0 || p->eCreate==1 );
43681        p->eCreate = 2;
43682      }
43683    }
43684    pPage->pDirtyNext = 0;
43685    pPage->pDirtyPrev = 0;
43686  }
43687  if( addRemove & PCACHE_DIRTYLIST_ADD ){
43688    assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
43689
43690    pPage->pDirtyNext = p->pDirty;
43691    if( pPage->pDirtyNext ){
43692      assert( pPage->pDirtyNext->pDirtyPrev==0 );
43693      pPage->pDirtyNext->pDirtyPrev = pPage;
43694    }else{
43695      p->pDirtyTail = pPage;
43696      if( p->bPurgeable ){
43697        assert( p->eCreate==2 );
43698        p->eCreate = 1;
43699      }
43700    }
43701    p->pDirty = pPage;
43702
43703    /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
43704    ** pSynced to point to it. Checking the NEED_SYNC flag is an
43705    ** optimization, as if pSynced points to a page with the NEED_SYNC
43706    ** flag set sqlite3PcacheFetchStress() searches through all newer
43707    ** entries of the dirty-list for a page with NEED_SYNC clear anyway.  */
43708    if( !p->pSynced
43709     && 0==(pPage->flags&PGHDR_NEED_SYNC)   /*OPTIMIZATION-IF-FALSE*/
43710    ){
43711      p->pSynced = pPage;
43712    }
43713  }
43714  pcacheDump(p);
43715}
43716
43717/*
43718** Wrapper around the pluggable caches xUnpin method. If the cache is
43719** being used for an in-memory database, this function is a no-op.
43720*/
43721static void pcacheUnpin(PgHdr *p){
43722  if( p->pCache->bPurgeable ){
43723    pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
43724    sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
43725    pcacheDump(p->pCache);
43726  }
43727}
43728
43729/*
43730** Compute the number of pages of cache requested.   p->szCache is the
43731** cache size requested by the "PRAGMA cache_size" statement.
43732*/
43733static int numberOfCachePages(PCache *p){
43734  if( p->szCache>=0 ){
43735    /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
43736    ** suggested cache size is set to N. */
43737    return p->szCache;
43738  }else{
43739    /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
43740    ** the number of cache pages is adjusted to use approximately abs(N*1024)
43741    ** bytes of memory. */
43742    return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
43743  }
43744}
43745
43746/*************************************************** General Interfaces ******
43747**
43748** Initialize and shutdown the page cache subsystem. Neither of these
43749** functions are threadsafe.
43750*/
43751SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
43752  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
43753    /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
43754    ** built-in default page cache is used instead of the application defined
43755    ** page cache. */
43756    sqlite3PCacheSetDefault();
43757  }
43758  return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
43759}
43760SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
43761  if( sqlite3GlobalConfig.pcache2.xShutdown ){
43762    /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
43763    sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
43764  }
43765}
43766
43767/*
43768** Return the size in bytes of a PCache object.
43769*/
43770SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
43771
43772/*
43773** Create a new PCache object. Storage space to hold the object
43774** has already been allocated and is passed in as the p pointer.
43775** The caller discovers how much space needs to be allocated by
43776** calling sqlite3PcacheSize().
43777*/
43778SQLITE_PRIVATE int sqlite3PcacheOpen(
43779  int szPage,                  /* Size of every page */
43780  int szExtra,                 /* Extra space associated with each page */
43781  int bPurgeable,              /* True if pages are on backing store */
43782  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
43783  void *pStress,               /* Argument to xStress */
43784  PCache *p                    /* Preallocated space for the PCache */
43785){
43786  memset(p, 0, sizeof(PCache));
43787  p->szPage = 1;
43788  p->szExtra = szExtra;
43789  p->bPurgeable = bPurgeable;
43790  p->eCreate = 2;
43791  p->xStress = xStress;
43792  p->pStress = pStress;
43793  p->szCache = 100;
43794  p->szSpill = 1;
43795  pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
43796  return sqlite3PcacheSetPageSize(p, szPage);
43797}
43798
43799/*
43800** Change the page size for PCache object. The caller must ensure that there
43801** are no outstanding page references when this function is called.
43802*/
43803SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
43804  assert( pCache->nRefSum==0 && pCache->pDirty==0 );
43805  if( pCache->szPage ){
43806    sqlite3_pcache *pNew;
43807    pNew = sqlite3GlobalConfig.pcache2.xCreate(
43808                szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
43809                pCache->bPurgeable
43810    );
43811    if( pNew==0 ) return SQLITE_NOMEM_BKPT;
43812    sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
43813    if( pCache->pCache ){
43814      sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
43815    }
43816    pCache->pCache = pNew;
43817    pCache->szPage = szPage;
43818    pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
43819  }
43820  return SQLITE_OK;
43821}
43822
43823/*
43824** Try to obtain a page from the cache.
43825**
43826** This routine returns a pointer to an sqlite3_pcache_page object if
43827** such an object is already in cache, or if a new one is created.
43828** This routine returns a NULL pointer if the object was not in cache
43829** and could not be created.
43830**
43831** The createFlags should be 0 to check for existing pages and should
43832** be 3 (not 1, but 3) to try to create a new page.
43833**
43834** If the createFlag is 0, then NULL is always returned if the page
43835** is not already in the cache.  If createFlag is 1, then a new page
43836** is created only if that can be done without spilling dirty pages
43837** and without exceeding the cache size limit.
43838**
43839** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
43840** initialize the sqlite3_pcache_page object and convert it into a
43841** PgHdr object.  The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
43842** routines are split this way for performance reasons. When separated
43843** they can both (usually) operate without having to push values to
43844** the stack on entry and pop them back off on exit, which saves a
43845** lot of pushing and popping.
43846*/
43847SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
43848  PCache *pCache,       /* Obtain the page from this cache */
43849  Pgno pgno,            /* Page number to obtain */
43850  int createFlag        /* If true, create page if it does not exist already */
43851){
43852  int eCreate;
43853  sqlite3_pcache_page *pRes;
43854
43855  assert( pCache!=0 );
43856  assert( pCache->pCache!=0 );
43857  assert( createFlag==3 || createFlag==0 );
43858  assert( pgno>0 );
43859  assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
43860
43861  /* eCreate defines what to do if the page does not exist.
43862  **    0     Do not allocate a new page.  (createFlag==0)
43863  **    1     Allocate a new page if doing so is inexpensive.
43864  **          (createFlag==1 AND bPurgeable AND pDirty)
43865  **    2     Allocate a new page even it doing so is difficult.
43866  **          (createFlag==1 AND !(bPurgeable AND pDirty)
43867  */
43868  eCreate = createFlag & pCache->eCreate;
43869  assert( eCreate==0 || eCreate==1 || eCreate==2 );
43870  assert( createFlag==0 || pCache->eCreate==eCreate );
43871  assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
43872  pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
43873  pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
43874               createFlag?" create":"",pRes));
43875  return pRes;
43876}
43877
43878/*
43879** If the sqlite3PcacheFetch() routine is unable to allocate a new
43880** page because no clean pages are available for reuse and the cache
43881** size limit has been reached, then this routine can be invoked to
43882** try harder to allocate a page.  This routine might invoke the stress
43883** callback to spill dirty pages to the journal.  It will then try to
43884** allocate the new page and will only fail to allocate a new page on
43885** an OOM error.
43886**
43887** This routine should be invoked only after sqlite3PcacheFetch() fails.
43888*/
43889SQLITE_PRIVATE int sqlite3PcacheFetchStress(
43890  PCache *pCache,                 /* Obtain the page from this cache */
43891  Pgno pgno,                      /* Page number to obtain */
43892  sqlite3_pcache_page **ppPage    /* Write result here */
43893){
43894  PgHdr *pPg;
43895  if( pCache->eCreate==2 ) return 0;
43896
43897  if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
43898    /* Find a dirty page to write-out and recycle. First try to find a
43899    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
43900    ** cleared), but if that is not possible settle for any other
43901    ** unreferenced dirty page.
43902    **
43903    ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
43904    ** flag is currently referenced, then the following may leave pSynced
43905    ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
43906    ** cleared). This is Ok, as pSynced is just an optimization.  */
43907    for(pPg=pCache->pSynced;
43908        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
43909        pPg=pPg->pDirtyPrev
43910    );
43911    pCache->pSynced = pPg;
43912    if( !pPg ){
43913      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
43914    }
43915    if( pPg ){
43916      int rc;
43917#ifdef SQLITE_LOG_CACHE_SPILL
43918      sqlite3_log(SQLITE_FULL,
43919                  "spill page %d making room for %d - cache used: %d/%d",
43920                  pPg->pgno, pgno,
43921                  sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
43922                numberOfCachePages(pCache));
43923#endif
43924      pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
43925      rc = pCache->xStress(pCache->pStress, pPg);
43926      pcacheDump(pCache);
43927      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
43928        return rc;
43929      }
43930    }
43931  }
43932  *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
43933  return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
43934}
43935
43936/*
43937** This is a helper routine for sqlite3PcacheFetchFinish()
43938**
43939** In the uncommon case where the page being fetched has not been
43940** initialized, this routine is invoked to do the initialization.
43941** This routine is broken out into a separate function since it
43942** requires extra stack manipulation that can be avoided in the common
43943** case.
43944*/
43945static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
43946  PCache *pCache,             /* Obtain the page from this cache */
43947  Pgno pgno,                  /* Page number obtained */
43948  sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
43949){
43950  PgHdr *pPgHdr;
43951  assert( pPage!=0 );
43952  pPgHdr = (PgHdr*)pPage->pExtra;
43953  assert( pPgHdr->pPage==0 );
43954  memset(pPgHdr, 0, sizeof(PgHdr));
43955  pPgHdr->pPage = pPage;
43956  pPgHdr->pData = pPage->pBuf;
43957  pPgHdr->pExtra = (void *)&pPgHdr[1];
43958  memset(pPgHdr->pExtra, 0, pCache->szExtra);
43959  pPgHdr->pCache = pCache;
43960  pPgHdr->pgno = pgno;
43961  pPgHdr->flags = PGHDR_CLEAN;
43962  return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
43963}
43964
43965/*
43966** This routine converts the sqlite3_pcache_page object returned by
43967** sqlite3PcacheFetch() into an initialized PgHdr object.  This routine
43968** must be called after sqlite3PcacheFetch() in order to get a usable
43969** result.
43970*/
43971SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
43972  PCache *pCache,             /* Obtain the page from this cache */
43973  Pgno pgno,                  /* Page number obtained */
43974  sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
43975){
43976  PgHdr *pPgHdr;
43977
43978  assert( pPage!=0 );
43979  pPgHdr = (PgHdr *)pPage->pExtra;
43980
43981  if( !pPgHdr->pPage ){
43982    return pcacheFetchFinishWithInit(pCache, pgno, pPage);
43983  }
43984  pCache->nRefSum++;
43985  pPgHdr->nRef++;
43986  assert( sqlite3PcachePageSanity(pPgHdr) );
43987  return pPgHdr;
43988}
43989
43990/*
43991** Decrement the reference count on a page. If the page is clean and the
43992** reference count drops to 0, then it is made eligible for recycling.
43993*/
43994SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
43995  assert( p->nRef>0 );
43996  p->pCache->nRefSum--;
43997  if( (--p->nRef)==0 ){
43998    if( p->flags&PGHDR_CLEAN ){
43999      pcacheUnpin(p);
44000    }else if( p->pDirtyPrev!=0 ){ /*OPTIMIZATION-IF-FALSE*/
44001      /* Move the page to the head of the dirty list. If p->pDirtyPrev==0,
44002      ** then page p is already at the head of the dirty list and the
44003      ** following call would be a no-op. Hence the OPTIMIZATION-IF-FALSE
44004      ** tag above.  */
44005      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
44006    }
44007  }
44008}
44009
44010/*
44011** Increase the reference count of a supplied page by 1.
44012*/
44013SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
44014  assert(p->nRef>0);
44015  assert( sqlite3PcachePageSanity(p) );
44016  p->nRef++;
44017  p->pCache->nRefSum++;
44018}
44019
44020/*
44021** Drop a page from the cache. There must be exactly one reference to the
44022** page. This function deletes that reference, so after it returns the
44023** page pointed to by p is invalid.
44024*/
44025SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
44026  assert( p->nRef==1 );
44027  assert( sqlite3PcachePageSanity(p) );
44028  if( p->flags&PGHDR_DIRTY ){
44029    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
44030  }
44031  p->pCache->nRefSum--;
44032  sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
44033}
44034
44035/*
44036** Make sure the page is marked as dirty. If it isn't dirty already,
44037** make it so.
44038*/
44039SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
44040  assert( p->nRef>0 );
44041  assert( sqlite3PcachePageSanity(p) );
44042  if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){    /*OPTIMIZATION-IF-FALSE*/
44043    p->flags &= ~PGHDR_DONT_WRITE;
44044    if( p->flags & PGHDR_CLEAN ){
44045      p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
44046      pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
44047      assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
44048      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
44049    }
44050    assert( sqlite3PcachePageSanity(p) );
44051  }
44052}
44053
44054/*
44055** Make sure the page is marked as clean. If it isn't clean already,
44056** make it so.
44057*/
44058SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
44059  assert( sqlite3PcachePageSanity(p) );
44060  if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){
44061    assert( (p->flags & PGHDR_CLEAN)==0 );
44062    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
44063    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
44064    p->flags |= PGHDR_CLEAN;
44065    pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
44066    assert( sqlite3PcachePageSanity(p) );
44067    if( p->nRef==0 ){
44068      pcacheUnpin(p);
44069    }
44070  }
44071}
44072
44073/*
44074** Make every page in the cache clean.
44075*/
44076SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
44077  PgHdr *p;
44078  pcacheTrace(("%p.CLEAN-ALL\n",pCache));
44079  while( (p = pCache->pDirty)!=0 ){
44080    sqlite3PcacheMakeClean(p);
44081  }
44082}
44083
44084/*
44085** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
44086*/
44087SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
44088  PgHdr *p;
44089  pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
44090  for(p=pCache->pDirty; p; p=p->pDirtyNext){
44091    p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
44092  }
44093  pCache->pSynced = pCache->pDirtyTail;
44094}
44095
44096/*
44097** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
44098*/
44099SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
44100  PgHdr *p;
44101  for(p=pCache->pDirty; p; p=p->pDirtyNext){
44102    p->flags &= ~PGHDR_NEED_SYNC;
44103  }
44104  pCache->pSynced = pCache->pDirtyTail;
44105}
44106
44107/*
44108** Change the page number of page p to newPgno.
44109*/
44110SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
44111  PCache *pCache = p->pCache;
44112  assert( p->nRef>0 );
44113  assert( newPgno>0 );
44114  assert( sqlite3PcachePageSanity(p) );
44115  pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
44116  sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
44117  p->pgno = newPgno;
44118  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
44119    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
44120  }
44121}
44122
44123/*
44124** Drop every cache entry whose page number is greater than "pgno". The
44125** caller must ensure that there are no outstanding references to any pages
44126** other than page 1 with a page number greater than pgno.
44127**
44128** If there is a reference to page 1 and the pgno parameter passed to this
44129** function is 0, then the data area associated with page 1 is zeroed, but
44130** the page object is not dropped.
44131*/
44132SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
44133  if( pCache->pCache ){
44134    PgHdr *p;
44135    PgHdr *pNext;
44136    pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
44137    for(p=pCache->pDirty; p; p=pNext){
44138      pNext = p->pDirtyNext;
44139      /* This routine never gets call with a positive pgno except right
44140      ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
44141      ** it must be that pgno==0.
44142      */
44143      assert( p->pgno>0 );
44144      if( p->pgno>pgno ){
44145        assert( p->flags&PGHDR_DIRTY );
44146        sqlite3PcacheMakeClean(p);
44147      }
44148    }
44149    if( pgno==0 && pCache->nRefSum ){
44150      sqlite3_pcache_page *pPage1;
44151      pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
44152      if( ALWAYS(pPage1) ){  /* Page 1 is always available in cache, because
44153                             ** pCache->nRefSum>0 */
44154        memset(pPage1->pBuf, 0, pCache->szPage);
44155        pgno = 1;
44156      }
44157    }
44158    sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
44159  }
44160}
44161
44162/*
44163** Close a cache.
44164*/
44165SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
44166  assert( pCache->pCache!=0 );
44167  pcacheTrace(("%p.CLOSE\n",pCache));
44168  sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
44169}
44170
44171/*
44172** Discard the contents of the cache.
44173*/
44174SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
44175  sqlite3PcacheTruncate(pCache, 0);
44176}
44177
44178/*
44179** Merge two lists of pages connected by pDirty and in pgno order.
44180** Do not bother fixing the pDirtyPrev pointers.
44181*/
44182static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
44183  PgHdr result, *pTail;
44184  pTail = &result;
44185  assert( pA!=0 && pB!=0 );
44186  for(;;){
44187    if( pA->pgno<pB->pgno ){
44188      pTail->pDirty = pA;
44189      pTail = pA;
44190      pA = pA->pDirty;
44191      if( pA==0 ){
44192        pTail->pDirty = pB;
44193        break;
44194      }
44195    }else{
44196      pTail->pDirty = pB;
44197      pTail = pB;
44198      pB = pB->pDirty;
44199      if( pB==0 ){
44200        pTail->pDirty = pA;
44201        break;
44202      }
44203    }
44204  }
44205  return result.pDirty;
44206}
44207
44208/*
44209** Sort the list of pages in accending order by pgno.  Pages are
44210** connected by pDirty pointers.  The pDirtyPrev pointers are
44211** corrupted by this sort.
44212**
44213** Since there cannot be more than 2^31 distinct pages in a database,
44214** there cannot be more than 31 buckets required by the merge sorter.
44215** One extra bucket is added to catch overflow in case something
44216** ever changes to make the previous sentence incorrect.
44217*/
44218#define N_SORT_BUCKET  32
44219static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
44220  PgHdr *a[N_SORT_BUCKET], *p;
44221  int i;
44222  memset(a, 0, sizeof(a));
44223  while( pIn ){
44224    p = pIn;
44225    pIn = p->pDirty;
44226    p->pDirty = 0;
44227    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
44228      if( a[i]==0 ){
44229        a[i] = p;
44230        break;
44231      }else{
44232        p = pcacheMergeDirtyList(a[i], p);
44233        a[i] = 0;
44234      }
44235    }
44236    if( NEVER(i==N_SORT_BUCKET-1) ){
44237      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
44238      ** the input list.  But that is impossible.
44239      */
44240      a[i] = pcacheMergeDirtyList(a[i], p);
44241    }
44242  }
44243  p = a[0];
44244  for(i=1; i<N_SORT_BUCKET; i++){
44245    if( a[i]==0 ) continue;
44246    p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
44247  }
44248  return p;
44249}
44250
44251/*
44252** Return a list of all dirty pages in the cache, sorted by page number.
44253*/
44254SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
44255  PgHdr *p;
44256  for(p=pCache->pDirty; p; p=p->pDirtyNext){
44257    p->pDirty = p->pDirtyNext;
44258  }
44259  return pcacheSortDirtyList(pCache->pDirty);
44260}
44261
44262/*
44263** Return the total number of references to all pages held by the cache.
44264**
44265** This is not the total number of pages referenced, but the sum of the
44266** reference count for all pages.
44267*/
44268SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
44269  return pCache->nRefSum;
44270}
44271
44272/*
44273** Return the number of references to the page supplied as an argument.
44274*/
44275SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
44276  return p->nRef;
44277}
44278
44279/*
44280** Return the total number of pages in the cache.
44281*/
44282SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
44283  assert( pCache->pCache!=0 );
44284  return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
44285}
44286
44287#ifdef SQLITE_TEST
44288/*
44289** Get the suggested cache-size value.
44290*/
44291SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
44292  return numberOfCachePages(pCache);
44293}
44294#endif
44295
44296/*
44297** Set the suggested cache-size value.
44298*/
44299SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
44300  assert( pCache->pCache!=0 );
44301  pCache->szCache = mxPage;
44302  sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
44303                                         numberOfCachePages(pCache));
44304}
44305
44306/*
44307** Set the suggested cache-spill value.  Make no changes if if the
44308** argument is zero.  Return the effective cache-spill size, which will
44309** be the larger of the szSpill and szCache.
44310*/
44311SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
44312  int res;
44313  assert( p->pCache!=0 );
44314  if( mxPage ){
44315    if( mxPage<0 ){
44316      mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
44317    }
44318    p->szSpill = mxPage;
44319  }
44320  res = numberOfCachePages(p);
44321  if( res<p->szSpill ) res = p->szSpill;
44322  return res;
44323}
44324
44325/*
44326** Free up as much memory as possible from the page cache.
44327*/
44328SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
44329  assert( pCache->pCache!=0 );
44330  sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
44331}
44332
44333/*
44334** Return the size of the header added by this middleware layer
44335** in the page-cache hierarchy.
44336*/
44337SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
44338
44339/*
44340** Return the number of dirty pages currently in the cache, as a percentage
44341** of the configured cache size.
44342*/
44343SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
44344  PgHdr *pDirty;
44345  int nDirty = 0;
44346  int nCache = numberOfCachePages(pCache);
44347  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
44348  return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
44349}
44350
44351#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
44352/*
44353** For all dirty pages currently in the cache, invoke the specified
44354** callback. This is only used if the SQLITE_CHECK_PAGES macro is
44355** defined.
44356*/
44357SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
44358  PgHdr *pDirty;
44359  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
44360    xIter(pDirty);
44361  }
44362}
44363#endif
44364
44365/************** End of pcache.c **********************************************/
44366/************** Begin file pcache1.c *****************************************/
44367/*
44368** 2008 November 05
44369**
44370** The author disclaims copyright to this source code.  In place of
44371** a legal notice, here is a blessing:
44372**
44373**    May you do good and not evil.
44374**    May you find forgiveness for yourself and forgive others.
44375**    May you share freely, never taking more than you give.
44376**
44377*************************************************************************
44378**
44379** This file implements the default page cache implementation (the
44380** sqlite3_pcache interface). It also contains part of the implementation
44381** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
44382** If the default page cache implementation is overridden, then neither of
44383** these two features are available.
44384**
44385** A Page cache line looks like this:
44386**
44387**  -------------------------------------------------------------
44388**  |  database page content   |  PgHdr1  |  MemPage  |  PgHdr  |
44389**  -------------------------------------------------------------
44390**
44391** The database page content is up front (so that buffer overreads tend to
44392** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions).   MemPage
44393** is the extension added by the btree.c module containing information such
44394** as the database page number and how that database page is used.  PgHdr
44395** is added by the pcache.c layer and contains information used to keep track
44396** of which pages are "dirty".  PgHdr1 is an extension added by this
44397** module (pcache1.c).  The PgHdr1 header is a subclass of sqlite3_pcache_page.
44398** PgHdr1 contains information needed to look up a page by its page number.
44399** The superclass sqlite3_pcache_page.pBuf points to the start of the
44400** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
44401**
44402** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
44403** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size).  The
44404** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
44405** size can vary according to architecture, compile-time options, and
44406** SQLite library version number.
44407**
44408** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
44409** using a separate memory allocation from the database page content.  This
44410** seeks to overcome the "clownshoe" problem (also called "internal
44411** fragmentation" in academic literature) of allocating a few bytes more
44412** than a power of two with the memory allocator rounding up to the next
44413** power of two, and leaving the rounded-up space unused.
44414**
44415** This module tracks pointers to PgHdr1 objects.  Only pcache.c communicates
44416** with this module.  Information is passed back and forth as PgHdr1 pointers.
44417**
44418** The pcache.c and pager.c modules deal pointers to PgHdr objects.
44419** The btree.c module deals with pointers to MemPage objects.
44420**
44421** SOURCE OF PAGE CACHE MEMORY:
44422**
44423** Memory for a page might come from any of three sources:
44424**
44425**    (1)  The general-purpose memory allocator - sqlite3Malloc()
44426**    (2)  Global page-cache memory provided using sqlite3_config() with
44427**         SQLITE_CONFIG_PAGECACHE.
44428**    (3)  PCache-local bulk allocation.
44429**
44430** The third case is a chunk of heap memory (defaulting to 100 pages worth)
44431** that is allocated when the page cache is created.  The size of the local
44432** bulk allocation can be adjusted using
44433**
44434**     sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
44435**
44436** If N is positive, then N pages worth of memory are allocated using a single
44437** sqlite3Malloc() call and that memory is used for the first N pages allocated.
44438** Or if N is negative, then -1024*N bytes of memory are allocated and used
44439** for as many pages as can be accomodated.
44440**
44441** Only one of (2) or (3) can be used.  Once the memory available to (2) or
44442** (3) is exhausted, subsequent allocations fail over to the general-purpose
44443** memory allocator (1).
44444**
44445** Earlier versions of SQLite used only methods (1) and (2).  But experiments
44446** show that method (3) with N==100 provides about a 5% performance boost for
44447** common workloads.
44448*/
44449/* #include "sqliteInt.h" */
44450
44451typedef struct PCache1 PCache1;
44452typedef struct PgHdr1 PgHdr1;
44453typedef struct PgFreeslot PgFreeslot;
44454typedef struct PGroup PGroup;
44455
44456/*
44457** Each cache entry is represented by an instance of the following
44458** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
44459** PgHdr1.pCache->szPage bytes is allocated directly before this structure
44460** in memory.
44461*/
44462struct PgHdr1 {
44463  sqlite3_pcache_page page;      /* Base class. Must be first. pBuf & pExtra */
44464  unsigned int iKey;             /* Key value (page number) */
44465  u8 isPinned;                   /* Page in use, not on the LRU list */
44466  u8 isBulkLocal;                /* This page from bulk local storage */
44467  u8 isAnchor;                   /* This is the PGroup.lru element */
44468  PgHdr1 *pNext;                 /* Next in hash table chain */
44469  PCache1 *pCache;               /* Cache that currently owns this page */
44470  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
44471  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
44472};
44473
44474/* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
44475** of one or more PCaches that are able to recycle each other's unpinned
44476** pages when they are under memory pressure.  A PGroup is an instance of
44477** the following object.
44478**
44479** This page cache implementation works in one of two modes:
44480**
44481**   (1)  Every PCache is the sole member of its own PGroup.  There is
44482**        one PGroup per PCache.
44483**
44484**   (2)  There is a single global PGroup that all PCaches are a member
44485**        of.
44486**
44487** Mode 1 uses more memory (since PCache instances are not able to rob
44488** unused pages from other PCaches) but it also operates without a mutex,
44489** and is therefore often faster.  Mode 2 requires a mutex in order to be
44490** threadsafe, but recycles pages more efficiently.
44491**
44492** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
44493** PGroup which is the pcache1.grp global variable and its mutex is
44494** SQLITE_MUTEX_STATIC_LRU.
44495*/
44496struct PGroup {
44497  sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
44498  unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
44499  unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
44500  unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
44501  unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
44502  PgHdr1 lru;                    /* The beginning and end of the LRU list */
44503};
44504
44505/* Each page cache is an instance of the following object.  Every
44506** open database file (including each in-memory database and each
44507** temporary or transient database) has a single page cache which
44508** is an instance of this object.
44509**
44510** Pointers to structures of this type are cast and returned as
44511** opaque sqlite3_pcache* handles.
44512*/
44513struct PCache1 {
44514  /* Cache configuration parameters. Page size (szPage) and the purgeable
44515  ** flag (bPurgeable) are set when the cache is created. nMax may be
44516  ** modified at any time by a call to the pcache1Cachesize() method.
44517  ** The PGroup mutex must be held when accessing nMax.
44518  */
44519  PGroup *pGroup;                     /* PGroup this cache belongs to */
44520  int szPage;                         /* Size of database content section */
44521  int szExtra;                        /* sizeof(MemPage)+sizeof(PgHdr) */
44522  int szAlloc;                        /* Total size of one pcache line */
44523  int bPurgeable;                     /* True if cache is purgeable */
44524  unsigned int nMin;                  /* Minimum number of pages reserved */
44525  unsigned int nMax;                  /* Configured "cache_size" value */
44526  unsigned int n90pct;                /* nMax*9/10 */
44527  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
44528
44529  /* Hash table of all pages. The following variables may only be accessed
44530  ** when the accessor is holding the PGroup mutex.
44531  */
44532  unsigned int nRecyclable;           /* Number of pages in the LRU list */
44533  unsigned int nPage;                 /* Total number of pages in apHash */
44534  unsigned int nHash;                 /* Number of slots in apHash[] */
44535  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
44536  PgHdr1 *pFree;                      /* List of unused pcache-local pages */
44537  void *pBulk;                        /* Bulk memory used by pcache-local */
44538};
44539
44540/*
44541** Free slots in the allocator used to divide up the global page cache
44542** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
44543*/
44544struct PgFreeslot {
44545  PgFreeslot *pNext;  /* Next free slot */
44546};
44547
44548/*
44549** Global data used by this cache.
44550*/
44551static SQLITE_WSD struct PCacheGlobal {
44552  PGroup grp;                    /* The global PGroup for mode (2) */
44553
44554  /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
44555  ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
44556  ** fixed at sqlite3_initialize() time and do not require mutex protection.
44557  ** The nFreeSlot and pFree values do require mutex protection.
44558  */
44559  int isInit;                    /* True if initialized */
44560  int separateCache;             /* Use a new PGroup for each PCache */
44561  int nInitPage;                 /* Initial bulk allocation size */
44562  int szSlot;                    /* Size of each free slot */
44563  int nSlot;                     /* The number of pcache slots */
44564  int nReserve;                  /* Try to keep nFreeSlot above this */
44565  void *pStart, *pEnd;           /* Bounds of global page cache memory */
44566  /* Above requires no mutex.  Use mutex below for variable that follow. */
44567  sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
44568  PgFreeslot *pFree;             /* Free page blocks */
44569  int nFreeSlot;                 /* Number of unused pcache slots */
44570  /* The following value requires a mutex to change.  We skip the mutex on
44571  ** reading because (1) most platforms read a 32-bit integer atomically and
44572  ** (2) even if an incorrect value is read, no great harm is done since this
44573  ** is really just an optimization. */
44574  int bUnderPressure;            /* True if low on PAGECACHE memory */
44575} pcache1_g;
44576
44577/*
44578** All code in this file should access the global structure above via the
44579** alias "pcache1". This ensures that the WSD emulation is used when
44580** compiling for systems that do not support real WSD.
44581*/
44582#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
44583
44584/*
44585** Macros to enter and leave the PCache LRU mutex.
44586*/
44587#if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
44588# define pcache1EnterMutex(X)  assert((X)->mutex==0)
44589# define pcache1LeaveMutex(X)  assert((X)->mutex==0)
44590# define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
44591#else
44592# define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
44593# define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
44594# define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
44595#endif
44596
44597/******************************************************************************/
44598/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
44599
44600
44601/*
44602** This function is called during initialization if a static buffer is
44603** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
44604** verb to sqlite3_config(). Parameter pBuf points to an allocation large
44605** enough to contain 'n' buffers of 'sz' bytes each.
44606**
44607** This routine is called from sqlite3_initialize() and so it is guaranteed
44608** to be serialized already.  There is no need for further mutexing.
44609*/
44610SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
44611  if( pcache1.isInit ){
44612    PgFreeslot *p;
44613    if( pBuf==0 ) sz = n = 0;
44614    sz = ROUNDDOWN8(sz);
44615    pcache1.szSlot = sz;
44616    pcache1.nSlot = pcache1.nFreeSlot = n;
44617    pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
44618    pcache1.pStart = pBuf;
44619    pcache1.pFree = 0;
44620    pcache1.bUnderPressure = 0;
44621    while( n-- ){
44622      p = (PgFreeslot*)pBuf;
44623      p->pNext = pcache1.pFree;
44624      pcache1.pFree = p;
44625      pBuf = (void*)&((char*)pBuf)[sz];
44626    }
44627    pcache1.pEnd = pBuf;
44628  }
44629}
44630
44631/*
44632** Try to initialize the pCache->pFree and pCache->pBulk fields.  Return
44633** true if pCache->pFree ends up containing one or more free pages.
44634*/
44635static int pcache1InitBulk(PCache1 *pCache){
44636  i64 szBulk;
44637  char *zBulk;
44638  if( pcache1.nInitPage==0 ) return 0;
44639  /* Do not bother with a bulk allocation if the cache size very small */
44640  if( pCache->nMax<3 ) return 0;
44641  sqlite3BeginBenignMalloc();
44642  if( pcache1.nInitPage>0 ){
44643    szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
44644  }else{
44645    szBulk = -1024 * (i64)pcache1.nInitPage;
44646  }
44647  if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
44648    szBulk = pCache->szAlloc*pCache->nMax;
44649  }
44650  zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
44651  sqlite3EndBenignMalloc();
44652  if( zBulk ){
44653    int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
44654    int i;
44655    for(i=0; i<nBulk; i++){
44656      PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
44657      pX->page.pBuf = zBulk;
44658      pX->page.pExtra = &pX[1];
44659      pX->isBulkLocal = 1;
44660      pX->isAnchor = 0;
44661      pX->pNext = pCache->pFree;
44662      pCache->pFree = pX;
44663      zBulk += pCache->szAlloc;
44664    }
44665  }
44666  return pCache->pFree!=0;
44667}
44668
44669/*
44670** Malloc function used within this file to allocate space from the buffer
44671** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
44672** such buffer exists or there is no space left in it, this function falls
44673** back to sqlite3Malloc().
44674**
44675** Multiple threads can run this routine at the same time.  Global variables
44676** in pcache1 need to be protected via mutex.
44677*/
44678static void *pcache1Alloc(int nByte){
44679  void *p = 0;
44680  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
44681  if( nByte<=pcache1.szSlot ){
44682    sqlite3_mutex_enter(pcache1.mutex);
44683    p = (PgHdr1 *)pcache1.pFree;
44684    if( p ){
44685      pcache1.pFree = pcache1.pFree->pNext;
44686      pcache1.nFreeSlot--;
44687      pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
44688      assert( pcache1.nFreeSlot>=0 );
44689      sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
44690      sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
44691    }
44692    sqlite3_mutex_leave(pcache1.mutex);
44693  }
44694  if( p==0 ){
44695    /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
44696    ** it from sqlite3Malloc instead.
44697    */
44698    p = sqlite3Malloc(nByte);
44699#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
44700    if( p ){
44701      int sz = sqlite3MallocSize(p);
44702      sqlite3_mutex_enter(pcache1.mutex);
44703      sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
44704      sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
44705      sqlite3_mutex_leave(pcache1.mutex);
44706    }
44707#endif
44708    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
44709  }
44710  return p;
44711}
44712
44713/*
44714** Free an allocated buffer obtained from pcache1Alloc().
44715*/
44716static void pcache1Free(void *p){
44717  if( p==0 ) return;
44718  if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
44719    PgFreeslot *pSlot;
44720    sqlite3_mutex_enter(pcache1.mutex);
44721    sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
44722    pSlot = (PgFreeslot*)p;
44723    pSlot->pNext = pcache1.pFree;
44724    pcache1.pFree = pSlot;
44725    pcache1.nFreeSlot++;
44726    pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
44727    assert( pcache1.nFreeSlot<=pcache1.nSlot );
44728    sqlite3_mutex_leave(pcache1.mutex);
44729  }else{
44730    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
44731    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
44732#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
44733    {
44734      int nFreed = 0;
44735      nFreed = sqlite3MallocSize(p);
44736      sqlite3_mutex_enter(pcache1.mutex);
44737      sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
44738      sqlite3_mutex_leave(pcache1.mutex);
44739    }
44740#endif
44741    sqlite3_free(p);
44742  }
44743}
44744
44745#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
44746/*
44747** Return the size of a pcache allocation
44748*/
44749static int pcache1MemSize(void *p){
44750  if( p>=pcache1.pStart && p<pcache1.pEnd ){
44751    return pcache1.szSlot;
44752  }else{
44753    int iSize;
44754    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
44755    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
44756    iSize = sqlite3MallocSize(p);
44757    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
44758    return iSize;
44759  }
44760}
44761#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
44762
44763/*
44764** Allocate a new page object initially associated with cache pCache.
44765*/
44766static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
44767  PgHdr1 *p = 0;
44768  void *pPg;
44769
44770  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
44771  if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
44772    p = pCache->pFree;
44773    pCache->pFree = p->pNext;
44774    p->pNext = 0;
44775  }else{
44776#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
44777    /* The group mutex must be released before pcache1Alloc() is called. This
44778    ** is because it might call sqlite3_release_memory(), which assumes that
44779    ** this mutex is not held. */
44780    assert( pcache1.separateCache==0 );
44781    assert( pCache->pGroup==&pcache1.grp );
44782    pcache1LeaveMutex(pCache->pGroup);
44783#endif
44784    if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
44785#ifdef SQLITE_PCACHE_SEPARATE_HEADER
44786    pPg = pcache1Alloc(pCache->szPage);
44787    p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
44788    if( !pPg || !p ){
44789      pcache1Free(pPg);
44790      sqlite3_free(p);
44791      pPg = 0;
44792    }
44793#else
44794    pPg = pcache1Alloc(pCache->szAlloc);
44795    p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
44796#endif
44797    if( benignMalloc ){ sqlite3EndBenignMalloc(); }
44798#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
44799    pcache1EnterMutex(pCache->pGroup);
44800#endif
44801    if( pPg==0 ) return 0;
44802    p->page.pBuf = pPg;
44803    p->page.pExtra = &p[1];
44804    p->isBulkLocal = 0;
44805    p->isAnchor = 0;
44806  }
44807  if( pCache->bPurgeable ){
44808    pCache->pGroup->nCurrentPage++;
44809  }
44810  return p;
44811}
44812
44813/*
44814** Free a page object allocated by pcache1AllocPage().
44815*/
44816static void pcache1FreePage(PgHdr1 *p){
44817  PCache1 *pCache;
44818  assert( p!=0 );
44819  pCache = p->pCache;
44820  assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
44821  if( p->isBulkLocal ){
44822    p->pNext = pCache->pFree;
44823    pCache->pFree = p;
44824  }else{
44825    pcache1Free(p->page.pBuf);
44826#ifdef SQLITE_PCACHE_SEPARATE_HEADER
44827    sqlite3_free(p);
44828#endif
44829  }
44830  if( pCache->bPurgeable ){
44831    pCache->pGroup->nCurrentPage--;
44832  }
44833}
44834
44835/*
44836** Malloc function used by SQLite to obtain space from the buffer configured
44837** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
44838** exists, this function falls back to sqlite3Malloc().
44839*/
44840SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
44841  return pcache1Alloc(sz);
44842}
44843
44844/*
44845** Free an allocated buffer obtained from sqlite3PageMalloc().
44846*/
44847SQLITE_PRIVATE void sqlite3PageFree(void *p){
44848  pcache1Free(p);
44849}
44850
44851
44852/*
44853** Return true if it desirable to avoid allocating a new page cache
44854** entry.
44855**
44856** If memory was allocated specifically to the page cache using
44857** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
44858** it is desirable to avoid allocating a new page cache entry because
44859** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
44860** for all page cache needs and we should not need to spill the
44861** allocation onto the heap.
44862**
44863** Or, the heap is used for all page cache memory but the heap is
44864** under memory pressure, then again it is desirable to avoid
44865** allocating a new page cache entry in order to avoid stressing
44866** the heap even further.
44867*/
44868static int pcache1UnderMemoryPressure(PCache1 *pCache){
44869  if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
44870    return pcache1.bUnderPressure;
44871  }else{
44872    return sqlite3HeapNearlyFull();
44873  }
44874}
44875
44876/******************************************************************************/
44877/******** General Implementation Functions ************************************/
44878
44879/*
44880** This function is used to resize the hash table used by the cache passed
44881** as the first argument.
44882**
44883** The PCache mutex must be held when this function is called.
44884*/
44885static void pcache1ResizeHash(PCache1 *p){
44886  PgHdr1 **apNew;
44887  unsigned int nNew;
44888  unsigned int i;
44889
44890  assert( sqlite3_mutex_held(p->pGroup->mutex) );
44891
44892  nNew = p->nHash*2;
44893  if( nNew<256 ){
44894    nNew = 256;
44895  }
44896
44897  pcache1LeaveMutex(p->pGroup);
44898  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
44899  apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
44900  if( p->nHash ){ sqlite3EndBenignMalloc(); }
44901  pcache1EnterMutex(p->pGroup);
44902  if( apNew ){
44903    for(i=0; i<p->nHash; i++){
44904      PgHdr1 *pPage;
44905      PgHdr1 *pNext = p->apHash[i];
44906      while( (pPage = pNext)!=0 ){
44907        unsigned int h = pPage->iKey % nNew;
44908        pNext = pPage->pNext;
44909        pPage->pNext = apNew[h];
44910        apNew[h] = pPage;
44911      }
44912    }
44913    sqlite3_free(p->apHash);
44914    p->apHash = apNew;
44915    p->nHash = nNew;
44916  }
44917}
44918
44919/*
44920** This function is used internally to remove the page pPage from the
44921** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
44922** LRU list, then this function is a no-op.
44923**
44924** The PGroup mutex must be held when this function is called.
44925*/
44926static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
44927  PCache1 *pCache;
44928
44929  assert( pPage!=0 );
44930  assert( pPage->isPinned==0 );
44931  pCache = pPage->pCache;
44932  assert( pPage->pLruNext );
44933  assert( pPage->pLruPrev );
44934  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
44935  pPage->pLruPrev->pLruNext = pPage->pLruNext;
44936  pPage->pLruNext->pLruPrev = pPage->pLruPrev;
44937  pPage->pLruNext = 0;
44938  pPage->pLruPrev = 0;
44939  pPage->isPinned = 1;
44940  assert( pPage->isAnchor==0 );
44941  assert( pCache->pGroup->lru.isAnchor==1 );
44942  pCache->nRecyclable--;
44943  return pPage;
44944}
44945
44946
44947/*
44948** Remove the page supplied as an argument from the hash table
44949** (PCache1.apHash structure) that it is currently stored in.
44950** Also free the page if freePage is true.
44951**
44952** The PGroup mutex must be held when this function is called.
44953*/
44954static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
44955  unsigned int h;
44956  PCache1 *pCache = pPage->pCache;
44957  PgHdr1 **pp;
44958
44959  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
44960  h = pPage->iKey % pCache->nHash;
44961  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
44962  *pp = (*pp)->pNext;
44963
44964  pCache->nPage--;
44965  if( freeFlag ) pcache1FreePage(pPage);
44966}
44967
44968/*
44969** If there are currently more than nMaxPage pages allocated, try
44970** to recycle pages to reduce the number allocated to nMaxPage.
44971*/
44972static void pcache1EnforceMaxPage(PCache1 *pCache){
44973  PGroup *pGroup = pCache->pGroup;
44974  PgHdr1 *p;
44975  assert( sqlite3_mutex_held(pGroup->mutex) );
44976  while( pGroup->nCurrentPage>pGroup->nMaxPage
44977      && (p=pGroup->lru.pLruPrev)->isAnchor==0
44978  ){
44979    assert( p->pCache->pGroup==pGroup );
44980    assert( p->isPinned==0 );
44981    pcache1PinPage(p);
44982    pcache1RemoveFromHash(p, 1);
44983  }
44984  if( pCache->nPage==0 && pCache->pBulk ){
44985    sqlite3_free(pCache->pBulk);
44986    pCache->pBulk = pCache->pFree = 0;
44987  }
44988}
44989
44990/*
44991** Discard all pages from cache pCache with a page number (key value)
44992** greater than or equal to iLimit. Any pinned pages that meet this
44993** criteria are unpinned before they are discarded.
44994**
44995** The PCache mutex must be held when this function is called.
44996*/
44997static void pcache1TruncateUnsafe(
44998  PCache1 *pCache,             /* The cache to truncate */
44999  unsigned int iLimit          /* Drop pages with this pgno or larger */
45000){
45001  TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
45002  unsigned int h;
45003  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
45004  for(h=0; h<pCache->nHash; h++){
45005    PgHdr1 **pp = &pCache->apHash[h];
45006    PgHdr1 *pPage;
45007    while( (pPage = *pp)!=0 ){
45008      if( pPage->iKey>=iLimit ){
45009        pCache->nPage--;
45010        *pp = pPage->pNext;
45011        if( !pPage->isPinned ) pcache1PinPage(pPage);
45012        pcache1FreePage(pPage);
45013      }else{
45014        pp = &pPage->pNext;
45015        TESTONLY( nPage++; )
45016      }
45017    }
45018  }
45019  assert( pCache->nPage==nPage );
45020}
45021
45022/******************************************************************************/
45023/******** sqlite3_pcache Methods **********************************************/
45024
45025/*
45026** Implementation of the sqlite3_pcache.xInit method.
45027*/
45028static int pcache1Init(void *NotUsed){
45029  UNUSED_PARAMETER(NotUsed);
45030  assert( pcache1.isInit==0 );
45031  memset(&pcache1, 0, sizeof(pcache1));
45032
45033
45034  /*
45035  ** The pcache1.separateCache variable is true if each PCache has its own
45036  ** private PGroup (mode-1).  pcache1.separateCache is false if the single
45037  ** PGroup in pcache1.grp is used for all page caches (mode-2).
45038  **
45039  **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
45040  **
45041  **   *  Use a unified cache in single-threaded applications that have
45042  **      configured a start-time buffer for use as page-cache memory using
45043  **      sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
45044  **      pBuf argument.
45045  **
45046  **   *  Otherwise use separate caches (mode-1)
45047  */
45048#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
45049  pcache1.separateCache = 0;
45050#elif SQLITE_THREADSAFE
45051  pcache1.separateCache = sqlite3GlobalConfig.pPage==0
45052                          || sqlite3GlobalConfig.bCoreMutex>0;
45053#else
45054  pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
45055#endif
45056
45057#if SQLITE_THREADSAFE
45058  if( sqlite3GlobalConfig.bCoreMutex ){
45059    pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
45060    pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
45061  }
45062#endif
45063  if( pcache1.separateCache
45064   && sqlite3GlobalConfig.nPage!=0
45065   && sqlite3GlobalConfig.pPage==0
45066  ){
45067    pcache1.nInitPage = sqlite3GlobalConfig.nPage;
45068  }else{
45069    pcache1.nInitPage = 0;
45070  }
45071  pcache1.grp.mxPinned = 10;
45072  pcache1.isInit = 1;
45073  return SQLITE_OK;
45074}
45075
45076/*
45077** Implementation of the sqlite3_pcache.xShutdown method.
45078** Note that the static mutex allocated in xInit does
45079** not need to be freed.
45080*/
45081static void pcache1Shutdown(void *NotUsed){
45082  UNUSED_PARAMETER(NotUsed);
45083  assert( pcache1.isInit!=0 );
45084  memset(&pcache1, 0, sizeof(pcache1));
45085}
45086
45087/* forward declaration */
45088static void pcache1Destroy(sqlite3_pcache *p);
45089
45090/*
45091** Implementation of the sqlite3_pcache.xCreate method.
45092**
45093** Allocate a new cache.
45094*/
45095static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
45096  PCache1 *pCache;      /* The newly created page cache */
45097  PGroup *pGroup;       /* The group the new page cache will belong to */
45098  int sz;               /* Bytes of memory required to allocate the new cache */
45099
45100  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
45101  assert( szExtra < 300 );
45102
45103  sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
45104  pCache = (PCache1 *)sqlite3MallocZero(sz);
45105  if( pCache ){
45106    if( pcache1.separateCache ){
45107      pGroup = (PGroup*)&pCache[1];
45108      pGroup->mxPinned = 10;
45109    }else{
45110      pGroup = &pcache1.grp;
45111    }
45112    if( pGroup->lru.isAnchor==0 ){
45113      pGroup->lru.isAnchor = 1;
45114      pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
45115    }
45116    pCache->pGroup = pGroup;
45117    pCache->szPage = szPage;
45118    pCache->szExtra = szExtra;
45119    pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
45120    pCache->bPurgeable = (bPurgeable ? 1 : 0);
45121    pcache1EnterMutex(pGroup);
45122    pcache1ResizeHash(pCache);
45123    if( bPurgeable ){
45124      pCache->nMin = 10;
45125      pGroup->nMinPage += pCache->nMin;
45126      pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45127    }
45128    pcache1LeaveMutex(pGroup);
45129    if( pCache->nHash==0 ){
45130      pcache1Destroy((sqlite3_pcache*)pCache);
45131      pCache = 0;
45132    }
45133  }
45134  return (sqlite3_pcache *)pCache;
45135}
45136
45137/*
45138** Implementation of the sqlite3_pcache.xCachesize method.
45139**
45140** Configure the cache_size limit for a cache.
45141*/
45142static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
45143  PCache1 *pCache = (PCache1 *)p;
45144  if( pCache->bPurgeable ){
45145    PGroup *pGroup = pCache->pGroup;
45146    pcache1EnterMutex(pGroup);
45147    pGroup->nMaxPage += (nMax - pCache->nMax);
45148    pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45149    pCache->nMax = nMax;
45150    pCache->n90pct = pCache->nMax*9/10;
45151    pcache1EnforceMaxPage(pCache);
45152    pcache1LeaveMutex(pGroup);
45153  }
45154}
45155
45156/*
45157** Implementation of the sqlite3_pcache.xShrink method.
45158**
45159** Free up as much memory as possible.
45160*/
45161static void pcache1Shrink(sqlite3_pcache *p){
45162  PCache1 *pCache = (PCache1*)p;
45163  if( pCache->bPurgeable ){
45164    PGroup *pGroup = pCache->pGroup;
45165    int savedMaxPage;
45166    pcache1EnterMutex(pGroup);
45167    savedMaxPage = pGroup->nMaxPage;
45168    pGroup->nMaxPage = 0;
45169    pcache1EnforceMaxPage(pCache);
45170    pGroup->nMaxPage = savedMaxPage;
45171    pcache1LeaveMutex(pGroup);
45172  }
45173}
45174
45175/*
45176** Implementation of the sqlite3_pcache.xPagecount method.
45177*/
45178static int pcache1Pagecount(sqlite3_pcache *p){
45179  int n;
45180  PCache1 *pCache = (PCache1*)p;
45181  pcache1EnterMutex(pCache->pGroup);
45182  n = pCache->nPage;
45183  pcache1LeaveMutex(pCache->pGroup);
45184  return n;
45185}
45186
45187
45188/*
45189** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
45190** in the header of the pcache1Fetch() procedure.
45191**
45192** This steps are broken out into a separate procedure because they are
45193** usually not needed, and by avoiding the stack initialization required
45194** for these steps, the main pcache1Fetch() procedure can run faster.
45195*/
45196static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
45197  PCache1 *pCache,
45198  unsigned int iKey,
45199  int createFlag
45200){
45201  unsigned int nPinned;
45202  PGroup *pGroup = pCache->pGroup;
45203  PgHdr1 *pPage = 0;
45204
45205  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
45206  assert( pCache->nPage >= pCache->nRecyclable );
45207  nPinned = pCache->nPage - pCache->nRecyclable;
45208  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
45209  assert( pCache->n90pct == pCache->nMax*9/10 );
45210  if( createFlag==1 && (
45211        nPinned>=pGroup->mxPinned
45212     || nPinned>=pCache->n90pct
45213     || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
45214  )){
45215    return 0;
45216  }
45217
45218  if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
45219  assert( pCache->nHash>0 && pCache->apHash );
45220
45221  /* Step 4. Try to recycle a page. */
45222  if( pCache->bPurgeable
45223   && !pGroup->lru.pLruPrev->isAnchor
45224   && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
45225  ){
45226    PCache1 *pOther;
45227    pPage = pGroup->lru.pLruPrev;
45228    assert( pPage->isPinned==0 );
45229    pcache1RemoveFromHash(pPage, 0);
45230    pcache1PinPage(pPage);
45231    pOther = pPage->pCache;
45232    if( pOther->szAlloc != pCache->szAlloc ){
45233      pcache1FreePage(pPage);
45234      pPage = 0;
45235    }else{
45236      pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
45237    }
45238  }
45239
45240  /* Step 5. If a usable page buffer has still not been found,
45241  ** attempt to allocate a new one.
45242  */
45243  if( !pPage ){
45244    pPage = pcache1AllocPage(pCache, createFlag==1);
45245  }
45246
45247  if( pPage ){
45248    unsigned int h = iKey % pCache->nHash;
45249    pCache->nPage++;
45250    pPage->iKey = iKey;
45251    pPage->pNext = pCache->apHash[h];
45252    pPage->pCache = pCache;
45253    pPage->pLruPrev = 0;
45254    pPage->pLruNext = 0;
45255    pPage->isPinned = 1;
45256    *(void **)pPage->page.pExtra = 0;
45257    pCache->apHash[h] = pPage;
45258    if( iKey>pCache->iMaxKey ){
45259      pCache->iMaxKey = iKey;
45260    }
45261  }
45262  return pPage;
45263}
45264
45265/*
45266** Implementation of the sqlite3_pcache.xFetch method.
45267**
45268** Fetch a page by key value.
45269**
45270** Whether or not a new page may be allocated by this function depends on
45271** the value of the createFlag argument.  0 means do not allocate a new
45272** page.  1 means allocate a new page if space is easily available.  2
45273** means to try really hard to allocate a new page.
45274**
45275** For a non-purgeable cache (a cache used as the storage for an in-memory
45276** database) there is really no difference between createFlag 1 and 2.  So
45277** the calling function (pcache.c) will never have a createFlag of 1 on
45278** a non-purgeable cache.
45279**
45280** There are three different approaches to obtaining space for a page,
45281** depending on the value of parameter createFlag (which may be 0, 1 or 2).
45282**
45283**   1. Regardless of the value of createFlag, the cache is searched for a
45284**      copy of the requested page. If one is found, it is returned.
45285**
45286**   2. If createFlag==0 and the page is not already in the cache, NULL is
45287**      returned.
45288**
45289**   3. If createFlag is 1, and the page is not already in the cache, then
45290**      return NULL (do not allocate a new page) if any of the following
45291**      conditions are true:
45292**
45293**       (a) the number of pages pinned by the cache is greater than
45294**           PCache1.nMax, or
45295**
45296**       (b) the number of pages pinned by the cache is greater than
45297**           the sum of nMax for all purgeable caches, less the sum of
45298**           nMin for all other purgeable caches, or
45299**
45300**   4. If none of the first three conditions apply and the cache is marked
45301**      as purgeable, and if one of the following is true:
45302**
45303**       (a) The number of pages allocated for the cache is already
45304**           PCache1.nMax, or
45305**
45306**       (b) The number of pages allocated for all purgeable caches is
45307**           already equal to or greater than the sum of nMax for all
45308**           purgeable caches,
45309**
45310**       (c) The system is under memory pressure and wants to avoid
45311**           unnecessary pages cache entry allocations
45312**
45313**      then attempt to recycle a page from the LRU list. If it is the right
45314**      size, return the recycled buffer. Otherwise, free the buffer and
45315**      proceed to step 5.
45316**
45317**   5. Otherwise, allocate and return a new page buffer.
45318**
45319** There are two versions of this routine.  pcache1FetchWithMutex() is
45320** the general case.  pcache1FetchNoMutex() is a faster implementation for
45321** the common case where pGroup->mutex is NULL.  The pcache1Fetch() wrapper
45322** invokes the appropriate routine.
45323*/
45324static PgHdr1 *pcache1FetchNoMutex(
45325  sqlite3_pcache *p,
45326  unsigned int iKey,
45327  int createFlag
45328){
45329  PCache1 *pCache = (PCache1 *)p;
45330  PgHdr1 *pPage = 0;
45331
45332  /* Step 1: Search the hash table for an existing entry. */
45333  pPage = pCache->apHash[iKey % pCache->nHash];
45334  while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
45335
45336  /* Step 2: If the page was found in the hash table, then return it.
45337  ** If the page was not in the hash table and createFlag is 0, abort.
45338  ** Otherwise (page not in hash and createFlag!=0) continue with
45339  ** subsequent steps to try to create the page. */
45340  if( pPage ){
45341    if( !pPage->isPinned ){
45342      return pcache1PinPage(pPage);
45343    }else{
45344      return pPage;
45345    }
45346  }else if( createFlag ){
45347    /* Steps 3, 4, and 5 implemented by this subroutine */
45348    return pcache1FetchStage2(pCache, iKey, createFlag);
45349  }else{
45350    return 0;
45351  }
45352}
45353#if PCACHE1_MIGHT_USE_GROUP_MUTEX
45354static PgHdr1 *pcache1FetchWithMutex(
45355  sqlite3_pcache *p,
45356  unsigned int iKey,
45357  int createFlag
45358){
45359  PCache1 *pCache = (PCache1 *)p;
45360  PgHdr1 *pPage;
45361
45362  pcache1EnterMutex(pCache->pGroup);
45363  pPage = pcache1FetchNoMutex(p, iKey, createFlag);
45364  assert( pPage==0 || pCache->iMaxKey>=iKey );
45365  pcache1LeaveMutex(pCache->pGroup);
45366  return pPage;
45367}
45368#endif
45369static sqlite3_pcache_page *pcache1Fetch(
45370  sqlite3_pcache *p,
45371  unsigned int iKey,
45372  int createFlag
45373){
45374#if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
45375  PCache1 *pCache = (PCache1 *)p;
45376#endif
45377
45378  assert( offsetof(PgHdr1,page)==0 );
45379  assert( pCache->bPurgeable || createFlag!=1 );
45380  assert( pCache->bPurgeable || pCache->nMin==0 );
45381  assert( pCache->bPurgeable==0 || pCache->nMin==10 );
45382  assert( pCache->nMin==0 || pCache->bPurgeable );
45383  assert( pCache->nHash>0 );
45384#if PCACHE1_MIGHT_USE_GROUP_MUTEX
45385  if( pCache->pGroup->mutex ){
45386    return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
45387  }else
45388#endif
45389  {
45390    return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
45391  }
45392}
45393
45394
45395/*
45396** Implementation of the sqlite3_pcache.xUnpin method.
45397**
45398** Mark a page as unpinned (eligible for asynchronous recycling).
45399*/
45400static void pcache1Unpin(
45401  sqlite3_pcache *p,
45402  sqlite3_pcache_page *pPg,
45403  int reuseUnlikely
45404){
45405  PCache1 *pCache = (PCache1 *)p;
45406  PgHdr1 *pPage = (PgHdr1 *)pPg;
45407  PGroup *pGroup = pCache->pGroup;
45408
45409  assert( pPage->pCache==pCache );
45410  pcache1EnterMutex(pGroup);
45411
45412  /* It is an error to call this function if the page is already
45413  ** part of the PGroup LRU list.
45414  */
45415  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
45416  assert( pPage->isPinned==1 );
45417
45418  if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
45419    pcache1RemoveFromHash(pPage, 1);
45420  }else{
45421    /* Add the page to the PGroup LRU list. */
45422    PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
45423    pPage->pLruPrev = &pGroup->lru;
45424    (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
45425    *ppFirst = pPage;
45426    pCache->nRecyclable++;
45427    pPage->isPinned = 0;
45428  }
45429
45430  pcache1LeaveMutex(pCache->pGroup);
45431}
45432
45433/*
45434** Implementation of the sqlite3_pcache.xRekey method.
45435*/
45436static void pcache1Rekey(
45437  sqlite3_pcache *p,
45438  sqlite3_pcache_page *pPg,
45439  unsigned int iOld,
45440  unsigned int iNew
45441){
45442  PCache1 *pCache = (PCache1 *)p;
45443  PgHdr1 *pPage = (PgHdr1 *)pPg;
45444  PgHdr1 **pp;
45445  unsigned int h;
45446  assert( pPage->iKey==iOld );
45447  assert( pPage->pCache==pCache );
45448
45449  pcache1EnterMutex(pCache->pGroup);
45450
45451  h = iOld%pCache->nHash;
45452  pp = &pCache->apHash[h];
45453  while( (*pp)!=pPage ){
45454    pp = &(*pp)->pNext;
45455  }
45456  *pp = pPage->pNext;
45457
45458  h = iNew%pCache->nHash;
45459  pPage->iKey = iNew;
45460  pPage->pNext = pCache->apHash[h];
45461  pCache->apHash[h] = pPage;
45462  if( iNew>pCache->iMaxKey ){
45463    pCache->iMaxKey = iNew;
45464  }
45465
45466  pcache1LeaveMutex(pCache->pGroup);
45467}
45468
45469/*
45470** Implementation of the sqlite3_pcache.xTruncate method.
45471**
45472** Discard all unpinned pages in the cache with a page number equal to
45473** or greater than parameter iLimit. Any pinned pages with a page number
45474** equal to or greater than iLimit are implicitly unpinned.
45475*/
45476static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
45477  PCache1 *pCache = (PCache1 *)p;
45478  pcache1EnterMutex(pCache->pGroup);
45479  if( iLimit<=pCache->iMaxKey ){
45480    pcache1TruncateUnsafe(pCache, iLimit);
45481    pCache->iMaxKey = iLimit-1;
45482  }
45483  pcache1LeaveMutex(pCache->pGroup);
45484}
45485
45486/*
45487** Implementation of the sqlite3_pcache.xDestroy method.
45488**
45489** Destroy a cache allocated using pcache1Create().
45490*/
45491static void pcache1Destroy(sqlite3_pcache *p){
45492  PCache1 *pCache = (PCache1 *)p;
45493  PGroup *pGroup = pCache->pGroup;
45494  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
45495  pcache1EnterMutex(pGroup);
45496  pcache1TruncateUnsafe(pCache, 0);
45497  assert( pGroup->nMaxPage >= pCache->nMax );
45498  pGroup->nMaxPage -= pCache->nMax;
45499  assert( pGroup->nMinPage >= pCache->nMin );
45500  pGroup->nMinPage -= pCache->nMin;
45501  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45502  pcache1EnforceMaxPage(pCache);
45503  pcache1LeaveMutex(pGroup);
45504  sqlite3_free(pCache->pBulk);
45505  sqlite3_free(pCache->apHash);
45506  sqlite3_free(pCache);
45507}
45508
45509/*
45510** This function is called during initialization (sqlite3_initialize()) to
45511** install the default pluggable cache module, assuming the user has not
45512** already provided an alternative.
45513*/
45514SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
45515  static const sqlite3_pcache_methods2 defaultMethods = {
45516    1,                       /* iVersion */
45517    0,                       /* pArg */
45518    pcache1Init,             /* xInit */
45519    pcache1Shutdown,         /* xShutdown */
45520    pcache1Create,           /* xCreate */
45521    pcache1Cachesize,        /* xCachesize */
45522    pcache1Pagecount,        /* xPagecount */
45523    pcache1Fetch,            /* xFetch */
45524    pcache1Unpin,            /* xUnpin */
45525    pcache1Rekey,            /* xRekey */
45526    pcache1Truncate,         /* xTruncate */
45527    pcache1Destroy,          /* xDestroy */
45528    pcache1Shrink            /* xShrink */
45529  };
45530  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
45531}
45532
45533/*
45534** Return the size of the header on each page of this PCACHE implementation.
45535*/
45536SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
45537
45538/*
45539** Return the global mutex used by this PCACHE implementation.  The
45540** sqlite3_status() routine needs access to this mutex.
45541*/
45542SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
45543  return pcache1.mutex;
45544}
45545
45546#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
45547/*
45548** This function is called to free superfluous dynamically allocated memory
45549** held by the pager system. Memory in use by any SQLite pager allocated
45550** by the current thread may be sqlite3_free()ed.
45551**
45552** nReq is the number of bytes of memory required. Once this much has
45553** been released, the function returns. The return value is the total number
45554** of bytes of memory released.
45555*/
45556SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
45557  int nFree = 0;
45558  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
45559  assert( sqlite3_mutex_notheld(pcache1.mutex) );
45560  if( sqlite3GlobalConfig.nPage==0 ){
45561    PgHdr1 *p;
45562    pcache1EnterMutex(&pcache1.grp);
45563    while( (nReq<0 || nFree<nReq)
45564       &&  (p=pcache1.grp.lru.pLruPrev)!=0
45565       &&  p->isAnchor==0
45566    ){
45567      nFree += pcache1MemSize(p->page.pBuf);
45568#ifdef SQLITE_PCACHE_SEPARATE_HEADER
45569      nFree += sqlite3MemSize(p);
45570#endif
45571      assert( p->isPinned==0 );
45572      pcache1PinPage(p);
45573      pcache1RemoveFromHash(p, 1);
45574    }
45575    pcache1LeaveMutex(&pcache1.grp);
45576  }
45577  return nFree;
45578}
45579#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
45580
45581#ifdef SQLITE_TEST
45582/*
45583** This function is used by test procedures to inspect the internal state
45584** of the global cache.
45585*/
45586SQLITE_PRIVATE void sqlite3PcacheStats(
45587  int *pnCurrent,      /* OUT: Total number of pages cached */
45588  int *pnMax,          /* OUT: Global maximum cache size */
45589  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
45590  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
45591){
45592  PgHdr1 *p;
45593  int nRecyclable = 0;
45594  for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
45595    assert( p->isPinned==0 );
45596    nRecyclable++;
45597  }
45598  *pnCurrent = pcache1.grp.nCurrentPage;
45599  *pnMax = (int)pcache1.grp.nMaxPage;
45600  *pnMin = (int)pcache1.grp.nMinPage;
45601  *pnRecyclable = nRecyclable;
45602}
45603#endif
45604
45605/************** End of pcache1.c *********************************************/
45606/************** Begin file rowset.c ******************************************/
45607/*
45608** 2008 December 3
45609**
45610** The author disclaims copyright to this source code.  In place of
45611** a legal notice, here is a blessing:
45612**
45613**    May you do good and not evil.
45614**    May you find forgiveness for yourself and forgive others.
45615**    May you share freely, never taking more than you give.
45616**
45617*************************************************************************
45618**
45619** This module implements an object we call a "RowSet".
45620**
45621** The RowSet object is a collection of rowids.  Rowids
45622** are inserted into the RowSet in an arbitrary order.  Inserts
45623** can be intermixed with tests to see if a given rowid has been
45624** previously inserted into the RowSet.
45625**
45626** After all inserts are finished, it is possible to extract the
45627** elements of the RowSet in sorted order.  Once this extraction
45628** process has started, no new elements may be inserted.
45629**
45630** Hence, the primitive operations for a RowSet are:
45631**
45632**    CREATE
45633**    INSERT
45634**    TEST
45635**    SMALLEST
45636**    DESTROY
45637**
45638** The CREATE and DESTROY primitives are the constructor and destructor,
45639** obviously.  The INSERT primitive adds a new element to the RowSet.
45640** TEST checks to see if an element is already in the RowSet.  SMALLEST
45641** extracts the least value from the RowSet.
45642**
45643** The INSERT primitive might allocate additional memory.  Memory is
45644** allocated in chunks so most INSERTs do no allocation.  There is an
45645** upper bound on the size of allocated memory.  No memory is freed
45646** until DESTROY.
45647**
45648** The TEST primitive includes a "batch" number.  The TEST primitive
45649** will only see elements that were inserted before the last change
45650** in the batch number.  In other words, if an INSERT occurs between
45651** two TESTs where the TESTs have the same batch nubmer, then the
45652** value added by the INSERT will not be visible to the second TEST.
45653** The initial batch number is zero, so if the very first TEST contains
45654** a non-zero batch number, it will see all prior INSERTs.
45655**
45656** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
45657** that is attempted.
45658**
45659** The cost of an INSERT is roughly constant.  (Sometimes new memory
45660** has to be allocated on an INSERT.)  The cost of a TEST with a new
45661** batch number is O(NlogN) where N is the number of elements in the RowSet.
45662** The cost of a TEST using the same batch number is O(logN).  The cost
45663** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
45664** primitives are constant time.  The cost of DESTROY is O(N).
45665**
45666** TEST and SMALLEST may not be used by the same RowSet.  This used to
45667** be possible, but the feature was not used, so it was removed in order
45668** to simplify the code.
45669*/
45670/* #include "sqliteInt.h" */
45671
45672
45673/*
45674** Target size for allocation chunks.
45675*/
45676#define ROWSET_ALLOCATION_SIZE 1024
45677
45678/*
45679** The number of rowset entries per allocation chunk.
45680*/
45681#define ROWSET_ENTRY_PER_CHUNK  \
45682                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
45683
45684/*
45685** Each entry in a RowSet is an instance of the following object.
45686**
45687** This same object is reused to store a linked list of trees of RowSetEntry
45688** objects.  In that alternative use, pRight points to the next entry
45689** in the list, pLeft points to the tree, and v is unused.  The
45690** RowSet.pForest value points to the head of this forest list.
45691*/
45692struct RowSetEntry {
45693  i64 v;                        /* ROWID value for this entry */
45694  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
45695  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
45696};
45697
45698/*
45699** RowSetEntry objects are allocated in large chunks (instances of the
45700** following structure) to reduce memory allocation overhead.  The
45701** chunks are kept on a linked list so that they can be deallocated
45702** when the RowSet is destroyed.
45703*/
45704struct RowSetChunk {
45705  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
45706  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
45707};
45708
45709/*
45710** A RowSet in an instance of the following structure.
45711**
45712** A typedef of this structure if found in sqliteInt.h.
45713*/
45714struct RowSet {
45715  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
45716  sqlite3 *db;                   /* The database connection */
45717  struct RowSetEntry *pEntry;    /* List of entries using pRight */
45718  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
45719  struct RowSetEntry *pFresh;    /* Source of new entry objects */
45720  struct RowSetEntry *pForest;   /* List of binary trees of entries */
45721  u16 nFresh;                    /* Number of objects on pFresh */
45722  u16 rsFlags;                   /* Various flags */
45723  int iBatch;                    /* Current insert batch */
45724};
45725
45726/*
45727** Allowed values for RowSet.rsFlags
45728*/
45729#define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
45730#define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
45731
45732/*
45733** Turn bulk memory into a RowSet object.  N bytes of memory
45734** are available at pSpace.  The db pointer is used as a memory context
45735** for any subsequent allocations that need to occur.
45736** Return a pointer to the new RowSet object.
45737**
45738** It must be the case that N is sufficient to make a Rowset.  If not
45739** an assertion fault occurs.
45740**
45741** If N is larger than the minimum, use the surplus as an initial
45742** allocation of entries available to be filled.
45743*/
45744SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
45745  RowSet *p;
45746  assert( N >= ROUND8(sizeof(*p)) );
45747  p = pSpace;
45748  p->pChunk = 0;
45749  p->db = db;
45750  p->pEntry = 0;
45751  p->pLast = 0;
45752  p->pForest = 0;
45753  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
45754  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
45755  p->rsFlags = ROWSET_SORTED;
45756  p->iBatch = 0;
45757  return p;
45758}
45759
45760/*
45761** Deallocate all chunks from a RowSet.  This frees all memory that
45762** the RowSet has allocated over its lifetime.  This routine is
45763** the destructor for the RowSet.
45764*/
45765SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
45766  struct RowSetChunk *pChunk, *pNextChunk;
45767  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
45768    pNextChunk = pChunk->pNextChunk;
45769    sqlite3DbFree(p->db, pChunk);
45770  }
45771  p->pChunk = 0;
45772  p->nFresh = 0;
45773  p->pEntry = 0;
45774  p->pLast = 0;
45775  p->pForest = 0;
45776  p->rsFlags = ROWSET_SORTED;
45777}
45778
45779/*
45780** Allocate a new RowSetEntry object that is associated with the
45781** given RowSet.  Return a pointer to the new and completely uninitialized
45782** objected.
45783**
45784** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
45785** routine returns NULL.
45786*/
45787static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
45788  assert( p!=0 );
45789  if( p->nFresh==0 ){  /*OPTIMIZATION-IF-FALSE*/
45790    /* We could allocate a fresh RowSetEntry each time one is needed, but it
45791    ** is more efficient to pull a preallocated entry from the pool */
45792    struct RowSetChunk *pNew;
45793    pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
45794    if( pNew==0 ){
45795      return 0;
45796    }
45797    pNew->pNextChunk = p->pChunk;
45798    p->pChunk = pNew;
45799    p->pFresh = pNew->aEntry;
45800    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
45801  }
45802  p->nFresh--;
45803  return p->pFresh++;
45804}
45805
45806/*
45807** Insert a new value into a RowSet.
45808**
45809** The mallocFailed flag of the database connection is set if a
45810** memory allocation fails.
45811*/
45812SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
45813  struct RowSetEntry *pEntry;  /* The new entry */
45814  struct RowSetEntry *pLast;   /* The last prior entry */
45815
45816  /* This routine is never called after sqlite3RowSetNext() */
45817  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
45818
45819  pEntry = rowSetEntryAlloc(p);
45820  if( pEntry==0 ) return;
45821  pEntry->v = rowid;
45822  pEntry->pRight = 0;
45823  pLast = p->pLast;
45824  if( pLast ){
45825    if( rowid<=pLast->v ){  /*OPTIMIZATION-IF-FALSE*/
45826      /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
45827      ** where possible */
45828      p->rsFlags &= ~ROWSET_SORTED;
45829    }
45830    pLast->pRight = pEntry;
45831  }else{
45832    p->pEntry = pEntry;
45833  }
45834  p->pLast = pEntry;
45835}
45836
45837/*
45838** Merge two lists of RowSetEntry objects.  Remove duplicates.
45839**
45840** The input lists are connected via pRight pointers and are
45841** assumed to each already be in sorted order.
45842*/
45843static struct RowSetEntry *rowSetEntryMerge(
45844  struct RowSetEntry *pA,    /* First sorted list to be merged */
45845  struct RowSetEntry *pB     /* Second sorted list to be merged */
45846){
45847  struct RowSetEntry head;
45848  struct RowSetEntry *pTail;
45849
45850  pTail = &head;
45851  assert( pA!=0 && pB!=0 );
45852  for(;;){
45853    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
45854    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
45855    if( pA->v<=pB->v ){
45856      if( pA->v<pB->v ) pTail = pTail->pRight = pA;
45857      pA = pA->pRight;
45858      if( pA==0 ){
45859        pTail->pRight = pB;
45860        break;
45861      }
45862    }else{
45863      pTail = pTail->pRight = pB;
45864      pB = pB->pRight;
45865      if( pB==0 ){
45866        pTail->pRight = pA;
45867        break;
45868      }
45869    }
45870  }
45871  return head.pRight;
45872}
45873
45874/*
45875** Sort all elements on the list of RowSetEntry objects into order of
45876** increasing v.
45877*/
45878static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
45879  unsigned int i;
45880  struct RowSetEntry *pNext, *aBucket[40];
45881
45882  memset(aBucket, 0, sizeof(aBucket));
45883  while( pIn ){
45884    pNext = pIn->pRight;
45885    pIn->pRight = 0;
45886    for(i=0; aBucket[i]; i++){
45887      pIn = rowSetEntryMerge(aBucket[i], pIn);
45888      aBucket[i] = 0;
45889    }
45890    aBucket[i] = pIn;
45891    pIn = pNext;
45892  }
45893  pIn = aBucket[0];
45894  for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
45895    if( aBucket[i]==0 ) continue;
45896    pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
45897  }
45898  return pIn;
45899}
45900
45901
45902/*
45903** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
45904** Convert this tree into a linked list connected by the pRight pointers
45905** and return pointers to the first and last elements of the new list.
45906*/
45907static void rowSetTreeToList(
45908  struct RowSetEntry *pIn,         /* Root of the input tree */
45909  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
45910  struct RowSetEntry **ppLast      /* Write tail of the output list here */
45911){
45912  assert( pIn!=0 );
45913  if( pIn->pLeft ){
45914    struct RowSetEntry *p;
45915    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
45916    p->pRight = pIn;
45917  }else{
45918    *ppFirst = pIn;
45919  }
45920  if( pIn->pRight ){
45921    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
45922  }else{
45923    *ppLast = pIn;
45924  }
45925  assert( (*ppLast)->pRight==0 );
45926}
45927
45928
45929/*
45930** Convert a sorted list of elements (connected by pRight) into a binary
45931** tree with depth of iDepth.  A depth of 1 means the tree contains a single
45932** node taken from the head of *ppList.  A depth of 2 means a tree with
45933** three nodes.  And so forth.
45934**
45935** Use as many entries from the input list as required and update the
45936** *ppList to point to the unused elements of the list.  If the input
45937** list contains too few elements, then construct an incomplete tree
45938** and leave *ppList set to NULL.
45939**
45940** Return a pointer to the root of the constructed binary tree.
45941*/
45942static struct RowSetEntry *rowSetNDeepTree(
45943  struct RowSetEntry **ppList,
45944  int iDepth
45945){
45946  struct RowSetEntry *p;         /* Root of the new tree */
45947  struct RowSetEntry *pLeft;     /* Left subtree */
45948  if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
45949    /* Prevent unnecessary deep recursion when we run out of entries */
45950    return 0;
45951  }
45952  if( iDepth>1 ){   /*OPTIMIZATION-IF-TRUE*/
45953    /* This branch causes a *balanced* tree to be generated.  A valid tree
45954    ** is still generated without this branch, but the tree is wildly
45955    ** unbalanced and inefficient. */
45956    pLeft = rowSetNDeepTree(ppList, iDepth-1);
45957    p = *ppList;
45958    if( p==0 ){     /*OPTIMIZATION-IF-FALSE*/
45959      /* It is safe to always return here, but the resulting tree
45960      ** would be unbalanced */
45961      return pLeft;
45962    }
45963    p->pLeft = pLeft;
45964    *ppList = p->pRight;
45965    p->pRight = rowSetNDeepTree(ppList, iDepth-1);
45966  }else{
45967    p = *ppList;
45968    *ppList = p->pRight;
45969    p->pLeft = p->pRight = 0;
45970  }
45971  return p;
45972}
45973
45974/*
45975** Convert a sorted list of elements into a binary tree. Make the tree
45976** as deep as it needs to be in order to contain the entire list.
45977*/
45978static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
45979  int iDepth;           /* Depth of the tree so far */
45980  struct RowSetEntry *p;       /* Current tree root */
45981  struct RowSetEntry *pLeft;   /* Left subtree */
45982
45983  assert( pList!=0 );
45984  p = pList;
45985  pList = p->pRight;
45986  p->pLeft = p->pRight = 0;
45987  for(iDepth=1; pList; iDepth++){
45988    pLeft = p;
45989    p = pList;
45990    pList = p->pRight;
45991    p->pLeft = pLeft;
45992    p->pRight = rowSetNDeepTree(&pList, iDepth);
45993  }
45994  return p;
45995}
45996
45997/*
45998** Extract the smallest element from the RowSet.
45999** Write the element into *pRowid.  Return 1 on success.  Return
46000** 0 if the RowSet is already empty.
46001**
46002** After this routine has been called, the sqlite3RowSetInsert()
46003** routine may not be called again.
46004**
46005** This routine may not be called after sqlite3RowSetTest() has
46006** been used.  Older versions of RowSet allowed that, but as the
46007** capability was not used by the code generator, it was removed
46008** for code economy.
46009*/
46010SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
46011  assert( p!=0 );
46012  assert( p->pForest==0 );  /* Cannot be used with sqlite3RowSetText() */
46013
46014  /* Merge the forest into a single sorted list on first call */
46015  if( (p->rsFlags & ROWSET_NEXT)==0 ){  /*OPTIMIZATION-IF-FALSE*/
46016    if( (p->rsFlags & ROWSET_SORTED)==0 ){  /*OPTIMIZATION-IF-FALSE*/
46017      p->pEntry = rowSetEntrySort(p->pEntry);
46018    }
46019    p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
46020  }
46021
46022  /* Return the next entry on the list */
46023  if( p->pEntry ){
46024    *pRowid = p->pEntry->v;
46025    p->pEntry = p->pEntry->pRight;
46026    if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
46027      /* Free memory immediately, rather than waiting on sqlite3_finalize() */
46028      sqlite3RowSetClear(p);
46029    }
46030    return 1;
46031  }else{
46032    return 0;
46033  }
46034}
46035
46036/*
46037** Check to see if element iRowid was inserted into the rowset as
46038** part of any insert batch prior to iBatch.  Return 1 or 0.
46039**
46040** If this is the first test of a new batch and if there exist entries
46041** on pRowSet->pEntry, then sort those entries into the forest at
46042** pRowSet->pForest so that they can be tested.
46043*/
46044SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
46045  struct RowSetEntry *p, *pTree;
46046
46047  /* This routine is never called after sqlite3RowSetNext() */
46048  assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
46049
46050  /* Sort entries into the forest on the first test of a new batch.
46051  ** To save unnecessary work, only do this when the batch number changes.
46052  */
46053  if( iBatch!=pRowSet->iBatch ){  /*OPTIMIZATION-IF-FALSE*/
46054    p = pRowSet->pEntry;
46055    if( p ){
46056      struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
46057      if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
46058        /* Only sort the current set of entiries if they need it */
46059        p = rowSetEntrySort(p);
46060      }
46061      for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
46062        ppPrevTree = &pTree->pRight;
46063        if( pTree->pLeft==0 ){
46064          pTree->pLeft = rowSetListToTree(p);
46065          break;
46066        }else{
46067          struct RowSetEntry *pAux, *pTail;
46068          rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
46069          pTree->pLeft = 0;
46070          p = rowSetEntryMerge(pAux, p);
46071        }
46072      }
46073      if( pTree==0 ){
46074        *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
46075        if( pTree ){
46076          pTree->v = 0;
46077          pTree->pRight = 0;
46078          pTree->pLeft = rowSetListToTree(p);
46079        }
46080      }
46081      pRowSet->pEntry = 0;
46082      pRowSet->pLast = 0;
46083      pRowSet->rsFlags |= ROWSET_SORTED;
46084    }
46085    pRowSet->iBatch = iBatch;
46086  }
46087
46088  /* Test to see if the iRowid value appears anywhere in the forest.
46089  ** Return 1 if it does and 0 if not.
46090  */
46091  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
46092    p = pTree->pLeft;
46093    while( p ){
46094      if( p->v<iRowid ){
46095        p = p->pRight;
46096      }else if( p->v>iRowid ){
46097        p = p->pLeft;
46098      }else{
46099        return 1;
46100      }
46101    }
46102  }
46103  return 0;
46104}
46105
46106/************** End of rowset.c **********************************************/
46107/************** Begin file pager.c *******************************************/
46108/*
46109** 2001 September 15
46110**
46111** The author disclaims copyright to this source code.  In place of
46112** a legal notice, here is a blessing:
46113**
46114**    May you do good and not evil.
46115**    May you find forgiveness for yourself and forgive others.
46116**    May you share freely, never taking more than you give.
46117**
46118*************************************************************************
46119** This is the implementation of the page cache subsystem or "pager".
46120**
46121** The pager is used to access a database disk file.  It implements
46122** atomic commit and rollback through the use of a journal file that
46123** is separate from the database file.  The pager also implements file
46124** locking to prevent two processes from writing the same database
46125** file simultaneously, or one process from reading the database while
46126** another is writing.
46127*/
46128#ifndef SQLITE_OMIT_DISKIO
46129/* #include "sqliteInt.h" */
46130/************** Include wal.h in the middle of pager.c ***********************/
46131/************** Begin file wal.h *********************************************/
46132/*
46133** 2010 February 1
46134**
46135** The author disclaims copyright to this source code.  In place of
46136** a legal notice, here is a blessing:
46137**
46138**    May you do good and not evil.
46139**    May you find forgiveness for yourself and forgive others.
46140**    May you share freely, never taking more than you give.
46141**
46142*************************************************************************
46143** This header file defines the interface to the write-ahead logging
46144** system. Refer to the comments below and the header comment attached to
46145** the implementation of each function in log.c for further details.
46146*/
46147
46148#ifndef SQLITE_WAL_H
46149#define SQLITE_WAL_H
46150
46151/* #include "sqliteInt.h" */
46152
46153/* Additional values that can be added to the sync_flags argument of
46154** sqlite3WalFrames():
46155*/
46156#define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
46157#define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
46158
46159#ifdef SQLITE_OMIT_WAL
46160# define sqlite3WalOpen(x,y,z)                   0
46161# define sqlite3WalLimit(x,y)
46162# define sqlite3WalClose(w,x,y,z)                0
46163# define sqlite3WalBeginReadTransaction(y,z)     0
46164# define sqlite3WalEndReadTransaction(z)
46165# define sqlite3WalDbsize(y)                     0
46166# define sqlite3WalBeginWriteTransaction(y)      0
46167# define sqlite3WalEndWriteTransaction(x)        0
46168# define sqlite3WalUndo(x,y,z)                   0
46169# define sqlite3WalSavepoint(y,z)
46170# define sqlite3WalSavepointUndo(y,z)            0
46171# define sqlite3WalFrames(u,v,w,x,y,z)           0
46172# define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
46173# define sqlite3WalCallback(z)                   0
46174# define sqlite3WalExclusiveMode(y,z)            0
46175# define sqlite3WalHeapMemory(z)                 0
46176# define sqlite3WalFramesize(z)                  0
46177# define sqlite3WalFindFrame(x,y,z)              0
46178# define sqlite3WalFile(x)                       0
46179#else
46180
46181#define WAL_SAVEPOINT_NDATA 4
46182
46183/* Connection to a write-ahead log (WAL) file.
46184** There is one object of this type for each pager.
46185*/
46186typedef struct Wal Wal;
46187
46188/* Open and close a connection to a write-ahead log. */
46189SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
46190SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
46191
46192/* Set the limiting size of a WAL file. */
46193SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
46194
46195/* Used by readers to open (lock) and close (unlock) a snapshot.  A
46196** snapshot is like a read-transaction.  It is the state of the database
46197** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
46198** preserves the current state even if the other threads or processes
46199** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
46200** transaction and releases the lock.
46201*/
46202SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
46203SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
46204
46205/* Read a page from the write-ahead log, if it is present. */
46206SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
46207SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
46208
46209/* If the WAL is not empty, return the size of the database. */
46210SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
46211
46212/* Obtain or release the WRITER lock. */
46213SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
46214SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
46215
46216/* Undo any frames written (but not committed) to the log */
46217SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
46218
46219/* Return an integer that records the current (uncommitted) write
46220** position in the WAL */
46221SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
46222
46223/* Move the write position of the WAL back to iFrame.  Called in
46224** response to a ROLLBACK TO command. */
46225SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
46226
46227/* Write a frame or frames to the log. */
46228SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
46229
46230/* Copy pages from the log to the database file */
46231SQLITE_PRIVATE int sqlite3WalCheckpoint(
46232  Wal *pWal,                      /* Write-ahead log connection */
46233  int eMode,                      /* One of PASSIVE, FULL and RESTART */
46234  int (*xBusy)(void*),            /* Function to call when busy */
46235  void *pBusyArg,                 /* Context argument for xBusyHandler */
46236  int sync_flags,                 /* Flags to sync db file with (or 0) */
46237  int nBuf,                       /* Size of buffer nBuf */
46238  u8 *zBuf,                       /* Temporary buffer to use */
46239  int *pnLog,                     /* OUT: Number of frames in WAL */
46240  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
46241);
46242
46243/* Return the value to pass to a sqlite3_wal_hook callback, the
46244** number of frames in the WAL at the point of the last commit since
46245** sqlite3WalCallback() was called.  If no commits have occurred since
46246** the last call, then return 0.
46247*/
46248SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
46249
46250/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
46251** by the pager layer on the database file.
46252*/
46253SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
46254
46255/* Return true if the argument is non-NULL and the WAL module is using
46256** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
46257** WAL module is using shared-memory, return false.
46258*/
46259SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
46260
46261#ifdef SQLITE_ENABLE_SNAPSHOT
46262SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
46263SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
46264#endif
46265
46266#ifdef SQLITE_ENABLE_ZIPVFS
46267/* If the WAL file is not empty, return the number of bytes of content
46268** stored in each frame (i.e. the db page-size when the WAL was created).
46269*/
46270SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
46271#endif
46272
46273/* Return the sqlite3_file object for the WAL file */
46274SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
46275
46276#endif /* ifndef SQLITE_OMIT_WAL */
46277#endif /* SQLITE_WAL_H */
46278
46279/************** End of wal.h *************************************************/
46280/************** Continuing where we left off in pager.c **********************/
46281
46282
46283/******************* NOTES ON THE DESIGN OF THE PAGER ************************
46284**
46285** This comment block describes invariants that hold when using a rollback
46286** journal.  These invariants do not apply for journal_mode=WAL,
46287** journal_mode=MEMORY, or journal_mode=OFF.
46288**
46289** Within this comment block, a page is deemed to have been synced
46290** automatically as soon as it is written when PRAGMA synchronous=OFF.
46291** Otherwise, the page is not synced until the xSync method of the VFS
46292** is called successfully on the file containing the page.
46293**
46294** Definition:  A page of the database file is said to be "overwriteable" if
46295** one or more of the following are true about the page:
46296**
46297**     (a)  The original content of the page as it was at the beginning of
46298**          the transaction has been written into the rollback journal and
46299**          synced.
46300**
46301**     (b)  The page was a freelist leaf page at the start of the transaction.
46302**
46303**     (c)  The page number is greater than the largest page that existed in
46304**          the database file at the start of the transaction.
46305**
46306** (1) A page of the database file is never overwritten unless one of the
46307**     following are true:
46308**
46309**     (a) The page and all other pages on the same sector are overwriteable.
46310**
46311**     (b) The atomic page write optimization is enabled, and the entire
46312**         transaction other than the update of the transaction sequence
46313**         number consists of a single page change.
46314**
46315** (2) The content of a page written into the rollback journal exactly matches
46316**     both the content in the database when the rollback journal was written
46317**     and the content in the database at the beginning of the current
46318**     transaction.
46319**
46320** (3) Writes to the database file are an integer multiple of the page size
46321**     in length and are aligned on a page boundary.
46322**
46323** (4) Reads from the database file are either aligned on a page boundary and
46324**     an integer multiple of the page size in length or are taken from the
46325**     first 100 bytes of the database file.
46326**
46327** (5) All writes to the database file are synced prior to the rollback journal
46328**     being deleted, truncated, or zeroed.
46329**
46330** (6) If a master journal file is used, then all writes to the database file
46331**     are synced prior to the master journal being deleted.
46332**
46333** Definition: Two databases (or the same database at two points it time)
46334** are said to be "logically equivalent" if they give the same answer to
46335** all queries.  Note in particular the content of freelist leaf
46336** pages can be changed arbitrarily without affecting the logical equivalence
46337** of the database.
46338**
46339** (7) At any time, if any subset, including the empty set and the total set,
46340**     of the unsynced changes to a rollback journal are removed and the
46341**     journal is rolled back, the resulting database file will be logically
46342**     equivalent to the database file at the beginning of the transaction.
46343**
46344** (8) When a transaction is rolled back, the xTruncate method of the VFS
46345**     is called to restore the database file to the same size it was at
46346**     the beginning of the transaction.  (In some VFSes, the xTruncate
46347**     method is a no-op, but that does not change the fact the SQLite will
46348**     invoke it.)
46349**
46350** (9) Whenever the database file is modified, at least one bit in the range
46351**     of bytes from 24 through 39 inclusive will be changed prior to releasing
46352**     the EXCLUSIVE lock, thus signaling other connections on the same
46353**     database to flush their caches.
46354**
46355** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
46356**      than one billion transactions.
46357**
46358** (11) A database file is well-formed at the beginning and at the conclusion
46359**      of every transaction.
46360**
46361** (12) An EXCLUSIVE lock is held on the database file when writing to
46362**      the database file.
46363**
46364** (13) A SHARED lock is held on the database file while reading any
46365**      content out of the database file.
46366**
46367******************************************************************************/
46368
46369/*
46370** Macros for troubleshooting.  Normally turned off
46371*/
46372#if 0
46373int sqlite3PagerTrace=1;  /* True to enable tracing */
46374#define sqlite3DebugPrintf printf
46375#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
46376#else
46377#define PAGERTRACE(X)
46378#endif
46379
46380/*
46381** The following two macros are used within the PAGERTRACE() macros above
46382** to print out file-descriptors.
46383**
46384** PAGERID() takes a pointer to a Pager struct as its argument. The
46385** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
46386** struct as its argument.
46387*/
46388#define PAGERID(p) ((int)(p->fd))
46389#define FILEHANDLEID(fd) ((int)fd)
46390
46391/*
46392** The Pager.eState variable stores the current 'state' of a pager. A
46393** pager may be in any one of the seven states shown in the following
46394** state diagram.
46395**
46396**                            OPEN <------+------+
46397**                              |         |      |
46398**                              V         |      |
46399**               +---------> READER-------+      |
46400**               |              |                |
46401**               |              V                |
46402**               |<-------WRITER_LOCKED------> ERROR
46403**               |              |                ^
46404**               |              V                |
46405**               |<------WRITER_CACHEMOD-------->|
46406**               |              |                |
46407**               |              V                |
46408**               |<-------WRITER_DBMOD---------->|
46409**               |              |                |
46410**               |              V                |
46411**               +<------WRITER_FINISHED-------->+
46412**
46413**
46414** List of state transitions and the C [function] that performs each:
46415**
46416**   OPEN              -> READER              [sqlite3PagerSharedLock]
46417**   READER            -> OPEN                [pager_unlock]
46418**
46419**   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
46420**   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
46421**   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
46422**   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
46423**   WRITER_***        -> READER              [pager_end_transaction]
46424**
46425**   WRITER_***        -> ERROR               [pager_error]
46426**   ERROR             -> OPEN                [pager_unlock]
46427**
46428**
46429**  OPEN:
46430**
46431**    The pager starts up in this state. Nothing is guaranteed in this
46432**    state - the file may or may not be locked and the database size is
46433**    unknown. The database may not be read or written.
46434**
46435**    * No read or write transaction is active.
46436**    * Any lock, or no lock at all, may be held on the database file.
46437**    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
46438**
46439**  READER:
46440**
46441**    In this state all the requirements for reading the database in
46442**    rollback (non-WAL) mode are met. Unless the pager is (or recently
46443**    was) in exclusive-locking mode, a user-level read transaction is
46444**    open. The database size is known in this state.
46445**
46446**    A connection running with locking_mode=normal enters this state when
46447**    it opens a read-transaction on the database and returns to state
46448**    OPEN after the read-transaction is completed. However a connection
46449**    running in locking_mode=exclusive (including temp databases) remains in
46450**    this state even after the read-transaction is closed. The only way
46451**    a locking_mode=exclusive connection can transition from READER to OPEN
46452**    is via the ERROR state (see below).
46453**
46454**    * A read transaction may be active (but a write-transaction cannot).
46455**    * A SHARED or greater lock is held on the database file.
46456**    * The dbSize variable may be trusted (even if a user-level read
46457**      transaction is not active). The dbOrigSize and dbFileSize variables
46458**      may not be trusted at this point.
46459**    * If the database is a WAL database, then the WAL connection is open.
46460**    * Even if a read-transaction is not open, it is guaranteed that
46461**      there is no hot-journal in the file-system.
46462**
46463**  WRITER_LOCKED:
46464**
46465**    The pager moves to this state from READER when a write-transaction
46466**    is first opened on the database. In WRITER_LOCKED state, all locks
46467**    required to start a write-transaction are held, but no actual
46468**    modifications to the cache or database have taken place.
46469**
46470**    In rollback mode, a RESERVED or (if the transaction was opened with
46471**    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
46472**    moving to this state, but the journal file is not written to or opened
46473**    to in this state. If the transaction is committed or rolled back while
46474**    in WRITER_LOCKED state, all that is required is to unlock the database
46475**    file.
46476**
46477**    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
46478**    If the connection is running with locking_mode=exclusive, an attempt
46479**    is made to obtain an EXCLUSIVE lock on the database file.
46480**
46481**    * A write transaction is active.
46482**    * If the connection is open in rollback-mode, a RESERVED or greater
46483**      lock is held on the database file.
46484**    * If the connection is open in WAL-mode, a WAL write transaction
46485**      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
46486**      called).
46487**    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
46488**    * The contents of the pager cache have not been modified.
46489**    * The journal file may or may not be open.
46490**    * Nothing (not even the first header) has been written to the journal.
46491**
46492**  WRITER_CACHEMOD:
46493**
46494**    A pager moves from WRITER_LOCKED state to this state when a page is
46495**    first modified by the upper layer. In rollback mode the journal file
46496**    is opened (if it is not already open) and a header written to the
46497**    start of it. The database file on disk has not been modified.
46498**
46499**    * A write transaction is active.
46500**    * A RESERVED or greater lock is held on the database file.
46501**    * The journal file is open and the first header has been written
46502**      to it, but the header has not been synced to disk.
46503**    * The contents of the page cache have been modified.
46504**
46505**  WRITER_DBMOD:
46506**
46507**    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
46508**    when it modifies the contents of the database file. WAL connections
46509**    never enter this state (since they do not modify the database file,
46510**    just the log file).
46511**
46512**    * A write transaction is active.
46513**    * An EXCLUSIVE or greater lock is held on the database file.
46514**    * The journal file is open and the first header has been written
46515**      and synced to disk.
46516**    * The contents of the page cache have been modified (and possibly
46517**      written to disk).
46518**
46519**  WRITER_FINISHED:
46520**
46521**    It is not possible for a WAL connection to enter this state.
46522**
46523**    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
46524**    state after the entire transaction has been successfully written into the
46525**    database file. In this state the transaction may be committed simply
46526**    by finalizing the journal file. Once in WRITER_FINISHED state, it is
46527**    not possible to modify the database further. At this point, the upper
46528**    layer must either commit or rollback the transaction.
46529**
46530**    * A write transaction is active.
46531**    * An EXCLUSIVE or greater lock is held on the database file.
46532**    * All writing and syncing of journal and database data has finished.
46533**      If no error occurred, all that remains is to finalize the journal to
46534**      commit the transaction. If an error did occur, the caller will need
46535**      to rollback the transaction.
46536**
46537**  ERROR:
46538**
46539**    The ERROR state is entered when an IO or disk-full error (including
46540**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
46541**    difficult to be sure that the in-memory pager state (cache contents,
46542**    db size etc.) are consistent with the contents of the file-system.
46543**
46544**    Temporary pager files may enter the ERROR state, but in-memory pagers
46545**    cannot.
46546**
46547**    For example, if an IO error occurs while performing a rollback,
46548**    the contents of the page-cache may be left in an inconsistent state.
46549**    At this point it would be dangerous to change back to READER state
46550**    (as usually happens after a rollback). Any subsequent readers might
46551**    report database corruption (due to the inconsistent cache), and if
46552**    they upgrade to writers, they may inadvertently corrupt the database
46553**    file. To avoid this hazard, the pager switches into the ERROR state
46554**    instead of READER following such an error.
46555**
46556**    Once it has entered the ERROR state, any attempt to use the pager
46557**    to read or write data returns an error. Eventually, once all
46558**    outstanding transactions have been abandoned, the pager is able to
46559**    transition back to OPEN state, discarding the contents of the
46560**    page-cache and any other in-memory state at the same time. Everything
46561**    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
46562**    when a read-transaction is next opened on the pager (transitioning
46563**    the pager into READER state). At that point the system has recovered
46564**    from the error.
46565**
46566**    Specifically, the pager jumps into the ERROR state if:
46567**
46568**      1. An error occurs while attempting a rollback. This happens in
46569**         function sqlite3PagerRollback().
46570**
46571**      2. An error occurs while attempting to finalize a journal file
46572**         following a commit in function sqlite3PagerCommitPhaseTwo().
46573**
46574**      3. An error occurs while attempting to write to the journal or
46575**         database file in function pagerStress() in order to free up
46576**         memory.
46577**
46578**    In other cases, the error is returned to the b-tree layer. The b-tree
46579**    layer then attempts a rollback operation. If the error condition
46580**    persists, the pager enters the ERROR state via condition (1) above.
46581**
46582**    Condition (3) is necessary because it can be triggered by a read-only
46583**    statement executed within a transaction. In this case, if the error
46584**    code were simply returned to the user, the b-tree layer would not
46585**    automatically attempt a rollback, as it assumes that an error in a
46586**    read-only statement cannot leave the pager in an internally inconsistent
46587**    state.
46588**
46589**    * The Pager.errCode variable is set to something other than SQLITE_OK.
46590**    * There are one or more outstanding references to pages (after the
46591**      last reference is dropped the pager should move back to OPEN state).
46592**    * The pager is not an in-memory pager.
46593**
46594**
46595** Notes:
46596**
46597**   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
46598**     connection is open in WAL mode. A WAL connection is always in one
46599**     of the first four states.
46600**
46601**   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
46602**     state. There are two exceptions: immediately after exclusive-mode has
46603**     been turned on (and before any read or write transactions are
46604**     executed), and when the pager is leaving the "error state".
46605**
46606**   * See also: assert_pager_state().
46607*/
46608#define PAGER_OPEN                  0
46609#define PAGER_READER                1
46610#define PAGER_WRITER_LOCKED         2
46611#define PAGER_WRITER_CACHEMOD       3
46612#define PAGER_WRITER_DBMOD          4
46613#define PAGER_WRITER_FINISHED       5
46614#define PAGER_ERROR                 6
46615
46616/*
46617** The Pager.eLock variable is almost always set to one of the
46618** following locking-states, according to the lock currently held on
46619** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
46620** This variable is kept up to date as locks are taken and released by
46621** the pagerLockDb() and pagerUnlockDb() wrappers.
46622**
46623** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
46624** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
46625** the operation was successful. In these circumstances pagerLockDb() and
46626** pagerUnlockDb() take a conservative approach - eLock is always updated
46627** when unlocking the file, and only updated when locking the file if the
46628** VFS call is successful. This way, the Pager.eLock variable may be set
46629** to a less exclusive (lower) value than the lock that is actually held
46630** at the system level, but it is never set to a more exclusive value.
46631**
46632** This is usually safe. If an xUnlock fails or appears to fail, there may
46633** be a few redundant xLock() calls or a lock may be held for longer than
46634** required, but nothing really goes wrong.
46635**
46636** The exception is when the database file is unlocked as the pager moves
46637** from ERROR to OPEN state. At this point there may be a hot-journal file
46638** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
46639** transition, by the same pager or any other). If the call to xUnlock()
46640** fails at this point and the pager is left holding an EXCLUSIVE lock, this
46641** can confuse the call to xCheckReservedLock() call made later as part
46642** of hot-journal detection.
46643**
46644** xCheckReservedLock() is defined as returning true "if there is a RESERVED
46645** lock held by this process or any others". So xCheckReservedLock may
46646** return true because the caller itself is holding an EXCLUSIVE lock (but
46647** doesn't know it because of a previous error in xUnlock). If this happens
46648** a hot-journal may be mistaken for a journal being created by an active
46649** transaction in another process, causing SQLite to read from the database
46650** without rolling it back.
46651**
46652** To work around this, if a call to xUnlock() fails when unlocking the
46653** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
46654** is only changed back to a real locking state after a successful call
46655** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
46656** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
46657** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
46658** lock on the database file before attempting to roll it back. See function
46659** PagerSharedLock() for more detail.
46660**
46661** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
46662** PAGER_OPEN state.
46663*/
46664#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
46665
46666/*
46667** A macro used for invoking the codec if there is one
46668*/
46669#ifdef SQLITE_HAS_CODEC
46670# define CODEC1(P,D,N,X,E) \
46671    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
46672# define CODEC2(P,D,N,X,E,O) \
46673    if( P->xCodec==0 ){ O=(char*)D; }else \
46674    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
46675#else
46676# define CODEC1(P,D,N,X,E)   /* NO-OP */
46677# define CODEC2(P,D,N,X,E,O) O=(char*)D
46678#endif
46679
46680/*
46681** The maximum allowed sector size. 64KiB. If the xSectorsize() method
46682** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
46683** This could conceivably cause corruption following a power failure on
46684** such a system. This is currently an undocumented limit.
46685*/
46686#define MAX_SECTOR_SIZE 0x10000
46687
46688
46689/*
46690** An instance of the following structure is allocated for each active
46691** savepoint and statement transaction in the system. All such structures
46692** are stored in the Pager.aSavepoint[] array, which is allocated and
46693** resized using sqlite3Realloc().
46694**
46695** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
46696** set to 0. If a journal-header is written into the main journal while
46697** the savepoint is active, then iHdrOffset is set to the byte offset
46698** immediately following the last journal record written into the main
46699** journal before the journal-header. This is required during savepoint
46700** rollback (see pagerPlaybackSavepoint()).
46701*/
46702typedef struct PagerSavepoint PagerSavepoint;
46703struct PagerSavepoint {
46704  i64 iOffset;                 /* Starting offset in main journal */
46705  i64 iHdrOffset;              /* See above */
46706  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
46707  Pgno nOrig;                  /* Original number of pages in file */
46708  Pgno iSubRec;                /* Index of first record in sub-journal */
46709#ifndef SQLITE_OMIT_WAL
46710  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
46711#endif
46712};
46713
46714/*
46715** Bits of the Pager.doNotSpill flag.  See further description below.
46716*/
46717#define SPILLFLAG_OFF         0x01 /* Never spill cache.  Set via pragma */
46718#define SPILLFLAG_ROLLBACK    0x02 /* Current rolling back, so do not spill */
46719#define SPILLFLAG_NOSYNC      0x04 /* Spill is ok, but do not sync */
46720
46721/*
46722** An open page cache is an instance of struct Pager. A description of
46723** some of the more important member variables follows:
46724**
46725** eState
46726**
46727**   The current 'state' of the pager object. See the comment and state
46728**   diagram above for a description of the pager state.
46729**
46730** eLock
46731**
46732**   For a real on-disk database, the current lock held on the database file -
46733**   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
46734**
46735**   For a temporary or in-memory database (neither of which require any
46736**   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
46737**   databases always have Pager.exclusiveMode==1, this tricks the pager
46738**   logic into thinking that it already has all the locks it will ever
46739**   need (and no reason to release them).
46740**
46741**   In some (obscure) circumstances, this variable may also be set to
46742**   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
46743**   details.
46744**
46745** changeCountDone
46746**
46747**   This boolean variable is used to make sure that the change-counter
46748**   (the 4-byte header field at byte offset 24 of the database file) is
46749**   not updated more often than necessary.
46750**
46751**   It is set to true when the change-counter field is updated, which
46752**   can only happen if an exclusive lock is held on the database file.
46753**   It is cleared (set to false) whenever an exclusive lock is
46754**   relinquished on the database file. Each time a transaction is committed,
46755**   The changeCountDone flag is inspected. If it is true, the work of
46756**   updating the change-counter is omitted for the current transaction.
46757**
46758**   This mechanism means that when running in exclusive mode, a connection
46759**   need only update the change-counter once, for the first transaction
46760**   committed.
46761**
46762** setMaster
46763**
46764**   When PagerCommitPhaseOne() is called to commit a transaction, it may
46765**   (or may not) specify a master-journal name to be written into the
46766**   journal file before it is synced to disk.
46767**
46768**   Whether or not a journal file contains a master-journal pointer affects
46769**   the way in which the journal file is finalized after the transaction is
46770**   committed or rolled back when running in "journal_mode=PERSIST" mode.
46771**   If a journal file does not contain a master-journal pointer, it is
46772**   finalized by overwriting the first journal header with zeroes. If
46773**   it does contain a master-journal pointer the journal file is finalized
46774**   by truncating it to zero bytes, just as if the connection were
46775**   running in "journal_mode=truncate" mode.
46776**
46777**   Journal files that contain master journal pointers cannot be finalized
46778**   simply by overwriting the first journal-header with zeroes, as the
46779**   master journal pointer could interfere with hot-journal rollback of any
46780**   subsequently interrupted transaction that reuses the journal file.
46781**
46782**   The flag is cleared as soon as the journal file is finalized (either
46783**   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
46784**   journal file from being successfully finalized, the setMaster flag
46785**   is cleared anyway (and the pager will move to ERROR state).
46786**
46787** doNotSpill
46788**
46789**   This variables control the behavior of cache-spills  (calls made by
46790**   the pcache module to the pagerStress() routine to write cached data
46791**   to the file-system in order to free up memory).
46792**
46793**   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
46794**   writing to the database from pagerStress() is disabled altogether.
46795**   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
46796**   comes up during savepoint rollback that requires the pcache module
46797**   to allocate a new page to prevent the journal file from being written
46798**   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
46799**   case is a user preference.
46800**
46801**   If the SPILLFLAG_NOSYNC bit is set, writing to the database from
46802**   pagerStress() is permitted, but syncing the journal file is not.
46803**   This flag is set by sqlite3PagerWrite() when the file-system sector-size
46804**   is larger than the database page-size in order to prevent a journal sync
46805**   from happening in between the journalling of two pages on the same sector.
46806**
46807** subjInMemory
46808**
46809**   This is a boolean variable. If true, then any required sub-journal
46810**   is opened as an in-memory journal file. If false, then in-memory
46811**   sub-journals are only used for in-memory pager files.
46812**
46813**   This variable is updated by the upper layer each time a new
46814**   write-transaction is opened.
46815**
46816** dbSize, dbOrigSize, dbFileSize
46817**
46818**   Variable dbSize is set to the number of pages in the database file.
46819**   It is valid in PAGER_READER and higher states (all states except for
46820**   OPEN and ERROR).
46821**
46822**   dbSize is set based on the size of the database file, which may be
46823**   larger than the size of the database (the value stored at offset
46824**   28 of the database header by the btree). If the size of the file
46825**   is not an integer multiple of the page-size, the value stored in
46826**   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
46827**   Except, any file that is greater than 0 bytes in size is considered
46828**   to have at least one page. (i.e. a 1KB file with 2K page-size leads
46829**   to dbSize==1).
46830**
46831**   During a write-transaction, if pages with page-numbers greater than
46832**   dbSize are modified in the cache, dbSize is updated accordingly.
46833**   Similarly, if the database is truncated using PagerTruncateImage(),
46834**   dbSize is updated.
46835**
46836**   Variables dbOrigSize and dbFileSize are valid in states
46837**   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
46838**   variable at the start of the transaction. It is used during rollback,
46839**   and to determine whether or not pages need to be journalled before
46840**   being modified.
46841**
46842**   Throughout a write-transaction, dbFileSize contains the size of
46843**   the file on disk in pages. It is set to a copy of dbSize when the
46844**   write-transaction is first opened, and updated when VFS calls are made
46845**   to write or truncate the database file on disk.
46846**
46847**   The only reason the dbFileSize variable is required is to suppress
46848**   unnecessary calls to xTruncate() after committing a transaction. If,
46849**   when a transaction is committed, the dbFileSize variable indicates
46850**   that the database file is larger than the database image (Pager.dbSize),
46851**   pager_truncate() is called. The pager_truncate() call uses xFilesize()
46852**   to measure the database file on disk, and then truncates it if required.
46853**   dbFileSize is not used when rolling back a transaction. In this case
46854**   pager_truncate() is called unconditionally (which means there may be
46855**   a call to xFilesize() that is not strictly required). In either case,
46856**   pager_truncate() may cause the file to become smaller or larger.
46857**
46858** dbHintSize
46859**
46860**   The dbHintSize variable is used to limit the number of calls made to
46861**   the VFS xFileControl(FCNTL_SIZE_HINT) method.
46862**
46863**   dbHintSize is set to a copy of the dbSize variable when a
46864**   write-transaction is opened (at the same time as dbFileSize and
46865**   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
46866**   dbHintSize is increased to the number of pages that correspond to the
46867**   size-hint passed to the method call. See pager_write_pagelist() for
46868**   details.
46869**
46870** errCode
46871**
46872**   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
46873**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
46874**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
46875**   sub-codes.
46876*/
46877struct Pager {
46878  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
46879  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
46880  u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
46881  u8 useJournal;              /* Use a rollback journal on this file */
46882  u8 noSync;                  /* Do not sync the journal if true */
46883  u8 fullSync;                /* Do extra syncs of the journal for robustness */
46884  u8 extraSync;               /* sync directory after journal delete */
46885  u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
46886  u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
46887  u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
46888  u8 tempFile;                /* zFilename is a temporary or immutable file */
46889  u8 noLock;                  /* Do not lock (except in WAL mode) */
46890  u8 readOnly;                /* True for a read-only database */
46891  u8 memDb;                   /* True to inhibit all file I/O */
46892
46893  /**************************************************************************
46894  ** The following block contains those class members that change during
46895  ** routine operation.  Class members not in this block are either fixed
46896  ** when the pager is first created or else only change when there is a
46897  ** significant mode change (such as changing the page_size, locking_mode,
46898  ** or the journal_mode).  From another view, these class members describe
46899  ** the "state" of the pager, while other class members describe the
46900  ** "configuration" of the pager.
46901  */
46902  u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
46903  u8 eLock;                   /* Current lock held on database file */
46904  u8 changeCountDone;         /* Set after incrementing the change-counter */
46905  u8 setMaster;               /* True if a m-j name has been written to jrnl */
46906  u8 doNotSpill;              /* Do not spill the cache when non-zero */
46907  u8 subjInMemory;            /* True to use in-memory sub-journals */
46908  u8 bUseFetch;               /* True to use xFetch() */
46909  u8 hasHeldSharedLock;       /* True if a shared lock has ever been held */
46910  Pgno dbSize;                /* Number of pages in the database */
46911  Pgno dbOrigSize;            /* dbSize before the current transaction */
46912  Pgno dbFileSize;            /* Number of pages in the database file */
46913  Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
46914  int errCode;                /* One of several kinds of errors */
46915  int nRec;                   /* Pages journalled since last j-header written */
46916  u32 cksumInit;              /* Quasi-random value added to every checksum */
46917  u32 nSubRec;                /* Number of records written to sub-journal */
46918  Bitvec *pInJournal;         /* One bit for each page in the database file */
46919  sqlite3_file *fd;           /* File descriptor for database */
46920  sqlite3_file *jfd;          /* File descriptor for main journal */
46921  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
46922  i64 journalOff;             /* Current write offset in the journal file */
46923  i64 journalHdr;             /* Byte offset to previous journal header */
46924  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
46925  PagerSavepoint *aSavepoint; /* Array of active savepoints */
46926  int nSavepoint;             /* Number of elements in aSavepoint[] */
46927  u32 iDataVersion;           /* Changes whenever database content changes */
46928  char dbFileVers[16];        /* Changes whenever database file changes */
46929
46930  int nMmapOut;               /* Number of mmap pages currently outstanding */
46931  sqlite3_int64 szMmap;       /* Desired maximum mmap size */
46932  PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
46933  /*
46934  ** End of the routinely-changing class members
46935  ***************************************************************************/
46936
46937  u16 nExtra;                 /* Add this many bytes to each in-memory page */
46938  i16 nReserve;               /* Number of unused bytes at end of each page */
46939  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
46940  u32 sectorSize;             /* Assumed sector size during rollback */
46941  int pageSize;               /* Number of bytes in a page */
46942  Pgno mxPgno;                /* Maximum allowed size of the database */
46943  i64 journalSizeLimit;       /* Size limit for persistent journal files */
46944  char *zFilename;            /* Name of the database file */
46945  char *zJournal;             /* Name of the journal file */
46946  int (*xBusyHandler)(void*); /* Function to call when busy */
46947  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
46948  int aStat[3];               /* Total cache hits, misses and writes */
46949#ifdef SQLITE_TEST
46950  int nRead;                  /* Database pages read */
46951#endif
46952  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
46953#ifdef SQLITE_HAS_CODEC
46954  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
46955  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
46956  void (*xCodecFree)(void*);             /* Destructor for the codec */
46957  void *pCodec;               /* First argument to xCodec... methods */
46958#endif
46959  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
46960  PCache *pPCache;            /* Pointer to page cache object */
46961#ifndef SQLITE_OMIT_WAL
46962  Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
46963  char *zWal;                 /* File name for write-ahead log */
46964#endif
46965};
46966
46967/*
46968** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
46969** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
46970** or CACHE_WRITE to sqlite3_db_status().
46971*/
46972#define PAGER_STAT_HIT   0
46973#define PAGER_STAT_MISS  1
46974#define PAGER_STAT_WRITE 2
46975
46976/*
46977** The following global variables hold counters used for
46978** testing purposes only.  These variables do not exist in
46979** a non-testing build.  These variables are not thread-safe.
46980*/
46981#ifdef SQLITE_TEST
46982SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
46983SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
46984SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
46985# define PAGER_INCR(v)  v++
46986#else
46987# define PAGER_INCR(v)
46988#endif
46989
46990
46991
46992/*
46993** Journal files begin with the following magic string.  The data
46994** was obtained from /dev/random.  It is used only as a sanity check.
46995**
46996** Since version 2.8.0, the journal format contains additional sanity
46997** checking information.  If the power fails while the journal is being
46998** written, semi-random garbage data might appear in the journal
46999** file after power is restored.  If an attempt is then made
47000** to roll the journal back, the database could be corrupted.  The additional
47001** sanity checking data is an attempt to discover the garbage in the
47002** journal and ignore it.
47003**
47004** The sanity checking information for the new journal format consists
47005** of a 32-bit checksum on each page of data.  The checksum covers both
47006** the page number and the pPager->pageSize bytes of data for the page.
47007** This cksum is initialized to a 32-bit random value that appears in the
47008** journal file right after the header.  The random initializer is important,
47009** because garbage data that appears at the end of a journal is likely
47010** data that was once in other files that have now been deleted.  If the
47011** garbage data came from an obsolete journal file, the checksums might
47012** be correct.  But by initializing the checksum to random value which
47013** is different for every journal, we minimize that risk.
47014*/
47015static const unsigned char aJournalMagic[] = {
47016  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
47017};
47018
47019/*
47020** The size of the of each page record in the journal is given by
47021** the following macro.
47022*/
47023#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
47024
47025/*
47026** The journal header size for this pager. This is usually the same
47027** size as a single disk sector. See also setSectorSize().
47028*/
47029#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
47030
47031/*
47032** The macro MEMDB is true if we are dealing with an in-memory database.
47033** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
47034** the value of MEMDB will be a constant and the compiler will optimize
47035** out code that would never execute.
47036*/
47037#ifdef SQLITE_OMIT_MEMORYDB
47038# define MEMDB 0
47039#else
47040# define MEMDB pPager->memDb
47041#endif
47042
47043/*
47044** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
47045** interfaces to access the database using memory-mapped I/O.
47046*/
47047#if SQLITE_MAX_MMAP_SIZE>0
47048# define USEFETCH(x) ((x)->bUseFetch)
47049#else
47050# define USEFETCH(x) 0
47051#endif
47052
47053/*
47054** The maximum legal page number is (2^31 - 1).
47055*/
47056#define PAGER_MAX_PGNO 2147483647
47057
47058/*
47059** The argument to this macro is a file descriptor (type sqlite3_file*).
47060** Return 0 if it is not open, or non-zero (but not 1) if it is.
47061**
47062** This is so that expressions can be written as:
47063**
47064**   if( isOpen(pPager->jfd) ){ ...
47065**
47066** instead of
47067**
47068**   if( pPager->jfd->pMethods ){ ...
47069*/
47070#define isOpen(pFd) ((pFd)->pMethods!=0)
47071
47072/*
47073** Return true if this pager uses a write-ahead log instead of the usual
47074** rollback journal. Otherwise false.
47075*/
47076#ifndef SQLITE_OMIT_WAL
47077static int pagerUseWal(Pager *pPager){
47078  return (pPager->pWal!=0);
47079}
47080#else
47081# define pagerUseWal(x) 0
47082# define pagerRollbackWal(x) 0
47083# define pagerWalFrames(v,w,x,y) 0
47084# define pagerOpenWalIfPresent(z) SQLITE_OK
47085# define pagerBeginReadTransaction(z) SQLITE_OK
47086#endif
47087
47088#ifndef NDEBUG
47089/*
47090** Usage:
47091**
47092**   assert( assert_pager_state(pPager) );
47093**
47094** This function runs many asserts to try to find inconsistencies in
47095** the internal state of the Pager object.
47096*/
47097static int assert_pager_state(Pager *p){
47098  Pager *pPager = p;
47099
47100  /* State must be valid. */
47101  assert( p->eState==PAGER_OPEN
47102       || p->eState==PAGER_READER
47103       || p->eState==PAGER_WRITER_LOCKED
47104       || p->eState==PAGER_WRITER_CACHEMOD
47105       || p->eState==PAGER_WRITER_DBMOD
47106       || p->eState==PAGER_WRITER_FINISHED
47107       || p->eState==PAGER_ERROR
47108  );
47109
47110  /* Regardless of the current state, a temp-file connection always behaves
47111  ** as if it has an exclusive lock on the database file. It never updates
47112  ** the change-counter field, so the changeCountDone flag is always set.
47113  */
47114  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
47115  assert( p->tempFile==0 || pPager->changeCountDone );
47116
47117  /* If the useJournal flag is clear, the journal-mode must be "OFF".
47118  ** And if the journal-mode is "OFF", the journal file must not be open.
47119  */
47120  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
47121  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
47122
47123  /* Check that MEMDB implies noSync. And an in-memory journal. Since
47124  ** this means an in-memory pager performs no IO at all, it cannot encounter
47125  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
47126  ** a journal file. (although the in-memory journal implementation may
47127  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
47128  ** is therefore not possible for an in-memory pager to enter the ERROR
47129  ** state.
47130  */
47131  if( MEMDB ){
47132    assert( !isOpen(p->fd) );
47133    assert( p->noSync );
47134    assert( p->journalMode==PAGER_JOURNALMODE_OFF
47135         || p->journalMode==PAGER_JOURNALMODE_MEMORY
47136    );
47137    assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
47138    assert( pagerUseWal(p)==0 );
47139  }
47140
47141  /* If changeCountDone is set, a RESERVED lock or greater must be held
47142  ** on the file.
47143  */
47144  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
47145  assert( p->eLock!=PENDING_LOCK );
47146
47147  switch( p->eState ){
47148    case PAGER_OPEN:
47149      assert( !MEMDB );
47150      assert( pPager->errCode==SQLITE_OK );
47151      assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
47152      break;
47153
47154    case PAGER_READER:
47155      assert( pPager->errCode==SQLITE_OK );
47156      assert( p->eLock!=UNKNOWN_LOCK );
47157      assert( p->eLock>=SHARED_LOCK );
47158      break;
47159
47160    case PAGER_WRITER_LOCKED:
47161      assert( p->eLock!=UNKNOWN_LOCK );
47162      assert( pPager->errCode==SQLITE_OK );
47163      if( !pagerUseWal(pPager) ){
47164        assert( p->eLock>=RESERVED_LOCK );
47165      }
47166      assert( pPager->dbSize==pPager->dbOrigSize );
47167      assert( pPager->dbOrigSize==pPager->dbFileSize );
47168      assert( pPager->dbOrigSize==pPager->dbHintSize );
47169      assert( pPager->setMaster==0 );
47170      break;
47171
47172    case PAGER_WRITER_CACHEMOD:
47173      assert( p->eLock!=UNKNOWN_LOCK );
47174      assert( pPager->errCode==SQLITE_OK );
47175      if( !pagerUseWal(pPager) ){
47176        /* It is possible that if journal_mode=wal here that neither the
47177        ** journal file nor the WAL file are open. This happens during
47178        ** a rollback transaction that switches from journal_mode=off
47179        ** to journal_mode=wal.
47180        */
47181        assert( p->eLock>=RESERVED_LOCK );
47182        assert( isOpen(p->jfd)
47183             || p->journalMode==PAGER_JOURNALMODE_OFF
47184             || p->journalMode==PAGER_JOURNALMODE_WAL
47185        );
47186      }
47187      assert( pPager->dbOrigSize==pPager->dbFileSize );
47188      assert( pPager->dbOrigSize==pPager->dbHintSize );
47189      break;
47190
47191    case PAGER_WRITER_DBMOD:
47192      assert( p->eLock==EXCLUSIVE_LOCK );
47193      assert( pPager->errCode==SQLITE_OK );
47194      assert( !pagerUseWal(pPager) );
47195      assert( p->eLock>=EXCLUSIVE_LOCK );
47196      assert( isOpen(p->jfd)
47197           || p->journalMode==PAGER_JOURNALMODE_OFF
47198           || p->journalMode==PAGER_JOURNALMODE_WAL
47199      );
47200      assert( pPager->dbOrigSize<=pPager->dbHintSize );
47201      break;
47202
47203    case PAGER_WRITER_FINISHED:
47204      assert( p->eLock==EXCLUSIVE_LOCK );
47205      assert( pPager->errCode==SQLITE_OK );
47206      assert( !pagerUseWal(pPager) );
47207      assert( isOpen(p->jfd)
47208           || p->journalMode==PAGER_JOURNALMODE_OFF
47209           || p->journalMode==PAGER_JOURNALMODE_WAL
47210      );
47211      break;
47212
47213    case PAGER_ERROR:
47214      /* There must be at least one outstanding reference to the pager if
47215      ** in ERROR state. Otherwise the pager should have already dropped
47216      ** back to OPEN state.
47217      */
47218      assert( pPager->errCode!=SQLITE_OK );
47219      assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
47220      break;
47221  }
47222
47223  return 1;
47224}
47225#endif /* ifndef NDEBUG */
47226
47227#ifdef SQLITE_DEBUG
47228/*
47229** Return a pointer to a human readable string in a static buffer
47230** containing the state of the Pager object passed as an argument. This
47231** is intended to be used within debuggers. For example, as an alternative
47232** to "print *pPager" in gdb:
47233**
47234** (gdb) printf "%s", print_pager_state(pPager)
47235*/
47236static char *print_pager_state(Pager *p){
47237  static char zRet[1024];
47238
47239  sqlite3_snprintf(1024, zRet,
47240      "Filename:      %s\n"
47241      "State:         %s errCode=%d\n"
47242      "Lock:          %s\n"
47243      "Locking mode:  locking_mode=%s\n"
47244      "Journal mode:  journal_mode=%s\n"
47245      "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
47246      "Journal:       journalOff=%lld journalHdr=%lld\n"
47247      "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
47248      , p->zFilename
47249      , p->eState==PAGER_OPEN            ? "OPEN" :
47250        p->eState==PAGER_READER          ? "READER" :
47251        p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
47252        p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
47253        p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
47254        p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
47255        p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
47256      , (int)p->errCode
47257      , p->eLock==NO_LOCK         ? "NO_LOCK" :
47258        p->eLock==RESERVED_LOCK   ? "RESERVED" :
47259        p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
47260        p->eLock==SHARED_LOCK     ? "SHARED" :
47261        p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
47262      , p->exclusiveMode ? "exclusive" : "normal"
47263      , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
47264        p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
47265        p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
47266        p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
47267        p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
47268        p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
47269      , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
47270      , p->journalOff, p->journalHdr
47271      , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
47272  );
47273
47274  return zRet;
47275}
47276#endif
47277
47278/*
47279** Return true if it is necessary to write page *pPg into the sub-journal.
47280** A page needs to be written into the sub-journal if there exists one
47281** or more open savepoints for which:
47282**
47283**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
47284**   * The bit corresponding to the page-number is not set in
47285**     PagerSavepoint.pInSavepoint.
47286*/
47287static int subjRequiresPage(PgHdr *pPg){
47288  Pager *pPager = pPg->pPager;
47289  PagerSavepoint *p;
47290  Pgno pgno = pPg->pgno;
47291  int i;
47292  for(i=0; i<pPager->nSavepoint; i++){
47293    p = &pPager->aSavepoint[i];
47294    if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
47295      return 1;
47296    }
47297  }
47298  return 0;
47299}
47300
47301#ifdef SQLITE_DEBUG
47302/*
47303** Return true if the page is already in the journal file.
47304*/
47305static int pageInJournal(Pager *pPager, PgHdr *pPg){
47306  return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
47307}
47308#endif
47309
47310/*
47311** Read a 32-bit integer from the given file descriptor.  Store the integer
47312** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
47313** error code is something goes wrong.
47314**
47315** All values are stored on disk as big-endian.
47316*/
47317static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
47318  unsigned char ac[4];
47319  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
47320  if( rc==SQLITE_OK ){
47321    *pRes = sqlite3Get4byte(ac);
47322  }
47323  return rc;
47324}
47325
47326/*
47327** Write a 32-bit integer into a string buffer in big-endian byte order.
47328*/
47329#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
47330
47331
47332/*
47333** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
47334** on success or an error code is something goes wrong.
47335*/
47336static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
47337  char ac[4];
47338  put32bits(ac, val);
47339  return sqlite3OsWrite(fd, ac, 4, offset);
47340}
47341
47342/*
47343** Unlock the database file to level eLock, which must be either NO_LOCK
47344** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
47345** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
47346**
47347** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
47348** called, do not modify it. See the comment above the #define of
47349** UNKNOWN_LOCK for an explanation of this.
47350*/
47351static int pagerUnlockDb(Pager *pPager, int eLock){
47352  int rc = SQLITE_OK;
47353
47354  assert( !pPager->exclusiveMode || pPager->eLock==eLock );
47355  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
47356  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
47357  if( isOpen(pPager->fd) ){
47358    assert( pPager->eLock>=eLock );
47359    rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
47360    if( pPager->eLock!=UNKNOWN_LOCK ){
47361      pPager->eLock = (u8)eLock;
47362    }
47363    IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
47364  }
47365  return rc;
47366}
47367
47368/*
47369** Lock the database file to level eLock, which must be either SHARED_LOCK,
47370** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
47371** Pager.eLock variable to the new locking state.
47372**
47373** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
47374** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
47375** See the comment above the #define of UNKNOWN_LOCK for an explanation
47376** of this.
47377*/
47378static int pagerLockDb(Pager *pPager, int eLock){
47379  int rc = SQLITE_OK;
47380
47381  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
47382  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
47383    rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
47384    if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
47385      pPager->eLock = (u8)eLock;
47386      IOTRACE(("LOCK %p %d\n", pPager, eLock))
47387    }
47388  }
47389  return rc;
47390}
47391
47392/*
47393** This function determines whether or not the atomic-write optimization
47394** can be used with this pager. The optimization can be used if:
47395**
47396**  (a) the value returned by OsDeviceCharacteristics() indicates that
47397**      a database page may be written atomically, and
47398**  (b) the value returned by OsSectorSize() is less than or equal
47399**      to the page size.
47400**
47401** The optimization is also always enabled for temporary files. It is
47402** an error to call this function if pPager is opened on an in-memory
47403** database.
47404**
47405** If the optimization cannot be used, 0 is returned. If it can be used,
47406** then the value returned is the size of the journal file when it
47407** contains rollback data for exactly one page.
47408*/
47409#ifdef SQLITE_ENABLE_ATOMIC_WRITE
47410static int jrnlBufferSize(Pager *pPager){
47411  assert( !MEMDB );
47412  if( !pPager->tempFile ){
47413    int dc;                           /* Device characteristics */
47414    int nSector;                      /* Sector size */
47415    int szPage;                       /* Page size */
47416
47417    assert( isOpen(pPager->fd) );
47418    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
47419    nSector = pPager->sectorSize;
47420    szPage = pPager->pageSize;
47421
47422    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
47423    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
47424    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
47425      return 0;
47426    }
47427  }
47428
47429  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
47430}
47431#else
47432# define jrnlBufferSize(x) 0
47433#endif
47434
47435/*
47436** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
47437** on the cache using a hash function.  This is used for testing
47438** and debugging only.
47439*/
47440#ifdef SQLITE_CHECK_PAGES
47441/*
47442** Return a 32-bit hash of the page data for pPage.
47443*/
47444static u32 pager_datahash(int nByte, unsigned char *pData){
47445  u32 hash = 0;
47446  int i;
47447  for(i=0; i<nByte; i++){
47448    hash = (hash*1039) + pData[i];
47449  }
47450  return hash;
47451}
47452static u32 pager_pagehash(PgHdr *pPage){
47453  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
47454}
47455static void pager_set_pagehash(PgHdr *pPage){
47456  pPage->pageHash = pager_pagehash(pPage);
47457}
47458
47459/*
47460** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
47461** is defined, and NDEBUG is not defined, an assert() statement checks
47462** that the page is either dirty or still matches the calculated page-hash.
47463*/
47464#define CHECK_PAGE(x) checkPage(x)
47465static void checkPage(PgHdr *pPg){
47466  Pager *pPager = pPg->pPager;
47467  assert( pPager->eState!=PAGER_ERROR );
47468  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
47469}
47470
47471#else
47472#define pager_datahash(X,Y)  0
47473#define pager_pagehash(X)  0
47474#define pager_set_pagehash(X)
47475#define CHECK_PAGE(x)
47476#endif  /* SQLITE_CHECK_PAGES */
47477
47478/*
47479** When this is called the journal file for pager pPager must be open.
47480** This function attempts to read a master journal file name from the
47481** end of the file and, if successful, copies it into memory supplied
47482** by the caller. See comments above writeMasterJournal() for the format
47483** used to store a master journal file name at the end of a journal file.
47484**
47485** zMaster must point to a buffer of at least nMaster bytes allocated by
47486** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
47487** enough space to write the master journal name). If the master journal
47488** name in the journal is longer than nMaster bytes (including a
47489** nul-terminator), then this is handled as if no master journal name
47490** were present in the journal.
47491**
47492** If a master journal file name is present at the end of the journal
47493** file, then it is copied into the buffer pointed to by zMaster. A
47494** nul-terminator byte is appended to the buffer following the master
47495** journal file name.
47496**
47497** If it is determined that no master journal file name is present
47498** zMaster[0] is set to 0 and SQLITE_OK returned.
47499**
47500** If an error occurs while reading from the journal file, an SQLite
47501** error code is returned.
47502*/
47503static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
47504  int rc;                    /* Return code */
47505  u32 len;                   /* Length in bytes of master journal name */
47506  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
47507  u32 cksum;                 /* MJ checksum value read from journal */
47508  u32 u;                     /* Unsigned loop counter */
47509  unsigned char aMagic[8];   /* A buffer to hold the magic header */
47510  zMaster[0] = '\0';
47511
47512  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
47513   || szJ<16
47514   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
47515   || len>=nMaster
47516   || len==0
47517   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
47518   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
47519   || memcmp(aMagic, aJournalMagic, 8)
47520   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
47521  ){
47522    return rc;
47523  }
47524
47525  /* See if the checksum matches the master journal name */
47526  for(u=0; u<len; u++){
47527    cksum -= zMaster[u];
47528  }
47529  if( cksum ){
47530    /* If the checksum doesn't add up, then one or more of the disk sectors
47531    ** containing the master journal filename is corrupted. This means
47532    ** definitely roll back, so just return SQLITE_OK and report a (nul)
47533    ** master-journal filename.
47534    */
47535    len = 0;
47536  }
47537  zMaster[len] = '\0';
47538
47539  return SQLITE_OK;
47540}
47541
47542/*
47543** Return the offset of the sector boundary at or immediately
47544** following the value in pPager->journalOff, assuming a sector
47545** size of pPager->sectorSize bytes.
47546**
47547** i.e for a sector size of 512:
47548**
47549**   Pager.journalOff          Return value
47550**   ---------------------------------------
47551**   0                         0
47552**   512                       512
47553**   100                       512
47554**   2000                      2048
47555**
47556*/
47557static i64 journalHdrOffset(Pager *pPager){
47558  i64 offset = 0;
47559  i64 c = pPager->journalOff;
47560  if( c ){
47561    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
47562  }
47563  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
47564  assert( offset>=c );
47565  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
47566  return offset;
47567}
47568
47569/*
47570** The journal file must be open when this function is called.
47571**
47572** This function is a no-op if the journal file has not been written to
47573** within the current transaction (i.e. if Pager.journalOff==0).
47574**
47575** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
47576** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
47577** zero the 28-byte header at the start of the journal file. In either case,
47578** if the pager is not in no-sync mode, sync the journal file immediately
47579** after writing or truncating it.
47580**
47581** If Pager.journalSizeLimit is set to a positive, non-zero value, and
47582** following the truncation or zeroing described above the size of the
47583** journal file in bytes is larger than this value, then truncate the
47584** journal file to Pager.journalSizeLimit bytes. The journal file does
47585** not need to be synced following this operation.
47586**
47587** If an IO error occurs, abandon processing and return the IO error code.
47588** Otherwise, return SQLITE_OK.
47589*/
47590static int zeroJournalHdr(Pager *pPager, int doTruncate){
47591  int rc = SQLITE_OK;                               /* Return code */
47592  assert( isOpen(pPager->jfd) );
47593  assert( !sqlite3JournalIsInMemory(pPager->jfd) );
47594  if( pPager->journalOff ){
47595    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
47596
47597    IOTRACE(("JZEROHDR %p\n", pPager))
47598    if( doTruncate || iLimit==0 ){
47599      rc = sqlite3OsTruncate(pPager->jfd, 0);
47600    }else{
47601      static const char zeroHdr[28] = {0};
47602      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
47603    }
47604    if( rc==SQLITE_OK && !pPager->noSync ){
47605      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
47606    }
47607
47608    /* At this point the transaction is committed but the write lock
47609    ** is still held on the file. If there is a size limit configured for
47610    ** the persistent journal and the journal file currently consumes more
47611    ** space than that limit allows for, truncate it now. There is no need
47612    ** to sync the file following this operation.
47613    */
47614    if( rc==SQLITE_OK && iLimit>0 ){
47615      i64 sz;
47616      rc = sqlite3OsFileSize(pPager->jfd, &sz);
47617      if( rc==SQLITE_OK && sz>iLimit ){
47618        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
47619      }
47620    }
47621  }
47622  return rc;
47623}
47624
47625/*
47626** The journal file must be open when this routine is called. A journal
47627** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
47628** current location.
47629**
47630** The format for the journal header is as follows:
47631** - 8 bytes: Magic identifying journal format.
47632** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
47633** - 4 bytes: Random number used for page hash.
47634** - 4 bytes: Initial database page count.
47635** - 4 bytes: Sector size used by the process that wrote this journal.
47636** - 4 bytes: Database page size.
47637**
47638** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
47639*/
47640static int writeJournalHdr(Pager *pPager){
47641  int rc = SQLITE_OK;                 /* Return code */
47642  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
47643  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
47644  u32 nWrite;                         /* Bytes of header sector written */
47645  int ii;                             /* Loop counter */
47646
47647  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
47648
47649  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
47650    nHeader = JOURNAL_HDR_SZ(pPager);
47651  }
47652
47653  /* If there are active savepoints and any of them were created
47654  ** since the most recent journal header was written, update the
47655  ** PagerSavepoint.iHdrOffset fields now.
47656  */
47657  for(ii=0; ii<pPager->nSavepoint; ii++){
47658    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
47659      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
47660    }
47661  }
47662
47663  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
47664
47665  /*
47666  ** Write the nRec Field - the number of page records that follow this
47667  ** journal header. Normally, zero is written to this value at this time.
47668  ** After the records are added to the journal (and the journal synced,
47669  ** if in full-sync mode), the zero is overwritten with the true number
47670  ** of records (see syncJournal()).
47671  **
47672  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
47673  ** reading the journal this value tells SQLite to assume that the
47674  ** rest of the journal file contains valid page records. This assumption
47675  ** is dangerous, as if a failure occurred whilst writing to the journal
47676  ** file it may contain some garbage data. There are two scenarios
47677  ** where this risk can be ignored:
47678  **
47679  **   * When the pager is in no-sync mode. Corruption can follow a
47680  **     power failure in this case anyway.
47681  **
47682  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
47683  **     that garbage data is never appended to the journal file.
47684  */
47685  assert( isOpen(pPager->fd) || pPager->noSync );
47686  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
47687   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
47688  ){
47689    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
47690    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
47691  }else{
47692    memset(zHeader, 0, sizeof(aJournalMagic)+4);
47693  }
47694
47695  /* The random check-hash initializer */
47696  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
47697  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
47698  /* The initial database size */
47699  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
47700  /* The assumed sector size for this process */
47701  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
47702
47703  /* The page size */
47704  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
47705
47706  /* Initializing the tail of the buffer is not necessary.  Everything
47707  ** works find if the following memset() is omitted.  But initializing
47708  ** the memory prevents valgrind from complaining, so we are willing to
47709  ** take the performance hit.
47710  */
47711  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
47712         nHeader-(sizeof(aJournalMagic)+20));
47713
47714  /* In theory, it is only necessary to write the 28 bytes that the
47715  ** journal header consumes to the journal file here. Then increment the
47716  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
47717  ** record is written to the following sector (leaving a gap in the file
47718  ** that will be implicitly filled in by the OS).
47719  **
47720  ** However it has been discovered that on some systems this pattern can
47721  ** be significantly slower than contiguously writing data to the file,
47722  ** even if that means explicitly writing data to the block of
47723  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
47724  ** is done.
47725  **
47726  ** The loop is required here in case the sector-size is larger than the
47727  ** database page size. Since the zHeader buffer is only Pager.pageSize
47728  ** bytes in size, more than one call to sqlite3OsWrite() may be required
47729  ** to populate the entire journal header sector.
47730  */
47731  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
47732    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
47733    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
47734    assert( pPager->journalHdr <= pPager->journalOff );
47735    pPager->journalOff += nHeader;
47736  }
47737
47738  return rc;
47739}
47740
47741/*
47742** The journal file must be open when this is called. A journal header file
47743** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
47744** file. The current location in the journal file is given by
47745** pPager->journalOff. See comments above function writeJournalHdr() for
47746** a description of the journal header format.
47747**
47748** If the header is read successfully, *pNRec is set to the number of
47749** page records following this header and *pDbSize is set to the size of the
47750** database before the transaction began, in pages. Also, pPager->cksumInit
47751** is set to the value read from the journal header. SQLITE_OK is returned
47752** in this case.
47753**
47754** If the journal header file appears to be corrupted, SQLITE_DONE is
47755** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
47756** cannot be read from the journal file an error code is returned.
47757*/
47758static int readJournalHdr(
47759  Pager *pPager,               /* Pager object */
47760  int isHot,
47761  i64 journalSize,             /* Size of the open journal file in bytes */
47762  u32 *pNRec,                  /* OUT: Value read from the nRec field */
47763  u32 *pDbSize                 /* OUT: Value of original database size field */
47764){
47765  int rc;                      /* Return code */
47766  unsigned char aMagic[8];     /* A buffer to hold the magic header */
47767  i64 iHdrOff;                 /* Offset of journal header being read */
47768
47769  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
47770
47771  /* Advance Pager.journalOff to the start of the next sector. If the
47772  ** journal file is too small for there to be a header stored at this
47773  ** point, return SQLITE_DONE.
47774  */
47775  pPager->journalOff = journalHdrOffset(pPager);
47776  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
47777    return SQLITE_DONE;
47778  }
47779  iHdrOff = pPager->journalOff;
47780
47781  /* Read in the first 8 bytes of the journal header. If they do not match
47782  ** the  magic string found at the start of each journal header, return
47783  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
47784  ** proceed.
47785  */
47786  if( isHot || iHdrOff!=pPager->journalHdr ){
47787    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
47788    if( rc ){
47789      return rc;
47790    }
47791    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
47792      return SQLITE_DONE;
47793    }
47794  }
47795
47796  /* Read the first three 32-bit fields of the journal header: The nRec
47797  ** field, the checksum-initializer and the database size at the start
47798  ** of the transaction. Return an error code if anything goes wrong.
47799  */
47800  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
47801   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
47802   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
47803  ){
47804    return rc;
47805  }
47806
47807  if( pPager->journalOff==0 ){
47808    u32 iPageSize;               /* Page-size field of journal header */
47809    u32 iSectorSize;             /* Sector-size field of journal header */
47810
47811    /* Read the page-size and sector-size journal header fields. */
47812    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
47813     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
47814    ){
47815      return rc;
47816    }
47817
47818    /* Versions of SQLite prior to 3.5.8 set the page-size field of the
47819    ** journal header to zero. In this case, assume that the Pager.pageSize
47820    ** variable is already set to the correct page size.
47821    */
47822    if( iPageSize==0 ){
47823      iPageSize = pPager->pageSize;
47824    }
47825
47826    /* Check that the values read from the page-size and sector-size fields
47827    ** are within range. To be 'in range', both values need to be a power
47828    ** of two greater than or equal to 512 or 32, and not greater than their
47829    ** respective compile time maximum limits.
47830    */
47831    if( iPageSize<512                  || iSectorSize<32
47832     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
47833     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
47834    ){
47835      /* If the either the page-size or sector-size in the journal-header is
47836      ** invalid, then the process that wrote the journal-header must have
47837      ** crashed before the header was synced. In this case stop reading
47838      ** the journal file here.
47839      */
47840      return SQLITE_DONE;
47841    }
47842
47843    /* Update the page-size to match the value read from the journal.
47844    ** Use a testcase() macro to make sure that malloc failure within
47845    ** PagerSetPagesize() is tested.
47846    */
47847    rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
47848    testcase( rc!=SQLITE_OK );
47849
47850    /* Update the assumed sector-size to match the value used by
47851    ** the process that created this journal. If this journal was
47852    ** created by a process other than this one, then this routine
47853    ** is being called from within pager_playback(). The local value
47854    ** of Pager.sectorSize is restored at the end of that routine.
47855    */
47856    pPager->sectorSize = iSectorSize;
47857  }
47858
47859  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
47860  return rc;
47861}
47862
47863
47864/*
47865** Write the supplied master journal name into the journal file for pager
47866** pPager at the current location. The master journal name must be the last
47867** thing written to a journal file. If the pager is in full-sync mode, the
47868** journal file descriptor is advanced to the next sector boundary before
47869** anything is written. The format is:
47870**
47871**   + 4 bytes: PAGER_MJ_PGNO.
47872**   + N bytes: Master journal filename in utf-8.
47873**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
47874**   + 4 bytes: Master journal name checksum.
47875**   + 8 bytes: aJournalMagic[].
47876**
47877** The master journal page checksum is the sum of the bytes in the master
47878** journal name, where each byte is interpreted as a signed 8-bit integer.
47879**
47880** If zMaster is a NULL pointer (occurs for a single database transaction),
47881** this call is a no-op.
47882*/
47883static int writeMasterJournal(Pager *pPager, const char *zMaster){
47884  int rc;                          /* Return code */
47885  int nMaster;                     /* Length of string zMaster */
47886  i64 iHdrOff;                     /* Offset of header in journal file */
47887  i64 jrnlSize;                    /* Size of journal file on disk */
47888  u32 cksum = 0;                   /* Checksum of string zMaster */
47889
47890  assert( pPager->setMaster==0 );
47891  assert( !pagerUseWal(pPager) );
47892
47893  if( !zMaster
47894   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
47895   || !isOpen(pPager->jfd)
47896  ){
47897    return SQLITE_OK;
47898  }
47899  pPager->setMaster = 1;
47900  assert( pPager->journalHdr <= pPager->journalOff );
47901
47902  /* Calculate the length in bytes and the checksum of zMaster */
47903  for(nMaster=0; zMaster[nMaster]; nMaster++){
47904    cksum += zMaster[nMaster];
47905  }
47906
47907  /* If in full-sync mode, advance to the next disk sector before writing
47908  ** the master journal name. This is in case the previous page written to
47909  ** the journal has already been synced.
47910  */
47911  if( pPager->fullSync ){
47912    pPager->journalOff = journalHdrOffset(pPager);
47913  }
47914  iHdrOff = pPager->journalOff;
47915
47916  /* Write the master journal data to the end of the journal file. If
47917  ** an error occurs, return the error code to the caller.
47918  */
47919  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
47920   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
47921   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
47922   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
47923   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
47924                                 iHdrOff+4+nMaster+8)))
47925  ){
47926    return rc;
47927  }
47928  pPager->journalOff += (nMaster+20);
47929
47930  /* If the pager is in peristent-journal mode, then the physical
47931  ** journal-file may extend past the end of the master-journal name
47932  ** and 8 bytes of magic data just written to the file. This is
47933  ** dangerous because the code to rollback a hot-journal file
47934  ** will not be able to find the master-journal name to determine
47935  ** whether or not the journal is hot.
47936  **
47937  ** Easiest thing to do in this scenario is to truncate the journal
47938  ** file to the required size.
47939  */
47940  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
47941   && jrnlSize>pPager->journalOff
47942  ){
47943    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
47944  }
47945  return rc;
47946}
47947
47948/*
47949** Discard the entire contents of the in-memory page-cache.
47950*/
47951static void pager_reset(Pager *pPager){
47952  pPager->iDataVersion++;
47953  sqlite3BackupRestart(pPager->pBackup);
47954  sqlite3PcacheClear(pPager->pPCache);
47955}
47956
47957/*
47958** Return the pPager->iDataVersion value
47959*/
47960SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
47961  assert( pPager->eState>PAGER_OPEN );
47962  return pPager->iDataVersion;
47963}
47964
47965/*
47966** Free all structures in the Pager.aSavepoint[] array and set both
47967** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
47968** if it is open and the pager is not in exclusive mode.
47969*/
47970static void releaseAllSavepoints(Pager *pPager){
47971  int ii;               /* Iterator for looping through Pager.aSavepoint */
47972  for(ii=0; ii<pPager->nSavepoint; ii++){
47973    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
47974  }
47975  if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
47976    sqlite3OsClose(pPager->sjfd);
47977  }
47978  sqlite3_free(pPager->aSavepoint);
47979  pPager->aSavepoint = 0;
47980  pPager->nSavepoint = 0;
47981  pPager->nSubRec = 0;
47982}
47983
47984/*
47985** Set the bit number pgno in the PagerSavepoint.pInSavepoint
47986** bitvecs of all open savepoints. Return SQLITE_OK if successful
47987** or SQLITE_NOMEM if a malloc failure occurs.
47988*/
47989static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
47990  int ii;                   /* Loop counter */
47991  int rc = SQLITE_OK;       /* Result code */
47992
47993  for(ii=0; ii<pPager->nSavepoint; ii++){
47994    PagerSavepoint *p = &pPager->aSavepoint[ii];
47995    if( pgno<=p->nOrig ){
47996      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
47997      testcase( rc==SQLITE_NOMEM );
47998      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
47999    }
48000  }
48001  return rc;
48002}
48003
48004/*
48005** This function is a no-op if the pager is in exclusive mode and not
48006** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
48007** state.
48008**
48009** If the pager is not in exclusive-access mode, the database file is
48010** completely unlocked. If the file is unlocked and the file-system does
48011** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
48012** closed (if it is open).
48013**
48014** If the pager is in ERROR state when this function is called, the
48015** contents of the pager cache are discarded before switching back to
48016** the OPEN state. Regardless of whether the pager is in exclusive-mode
48017** or not, any journal file left in the file-system will be treated
48018** as a hot-journal and rolled back the next time a read-transaction
48019** is opened (by this or by any other connection).
48020*/
48021static void pager_unlock(Pager *pPager){
48022
48023  assert( pPager->eState==PAGER_READER
48024       || pPager->eState==PAGER_OPEN
48025       || pPager->eState==PAGER_ERROR
48026  );
48027
48028  sqlite3BitvecDestroy(pPager->pInJournal);
48029  pPager->pInJournal = 0;
48030  releaseAllSavepoints(pPager);
48031
48032  if( pagerUseWal(pPager) ){
48033    assert( !isOpen(pPager->jfd) );
48034    sqlite3WalEndReadTransaction(pPager->pWal);
48035    pPager->eState = PAGER_OPEN;
48036  }else if( !pPager->exclusiveMode ){
48037    int rc;                       /* Error code returned by pagerUnlockDb() */
48038    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
48039
48040    /* If the operating system support deletion of open files, then
48041    ** close the journal file when dropping the database lock.  Otherwise
48042    ** another connection with journal_mode=delete might delete the file
48043    ** out from under us.
48044    */
48045    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
48046    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
48047    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
48048    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
48049    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
48050    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
48051    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
48052     || 1!=(pPager->journalMode & 5)
48053    ){
48054      sqlite3OsClose(pPager->jfd);
48055    }
48056
48057    /* If the pager is in the ERROR state and the call to unlock the database
48058    ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
48059    ** above the #define for UNKNOWN_LOCK for an explanation of why this
48060    ** is necessary.
48061    */
48062    rc = pagerUnlockDb(pPager, NO_LOCK);
48063    if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
48064      pPager->eLock = UNKNOWN_LOCK;
48065    }
48066
48067    /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
48068    ** without clearing the error code. This is intentional - the error
48069    ** code is cleared and the cache reset in the block below.
48070    */
48071    assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
48072    pPager->changeCountDone = 0;
48073    pPager->eState = PAGER_OPEN;
48074  }
48075
48076  /* If Pager.errCode is set, the contents of the pager cache cannot be
48077  ** trusted. Now that there are no outstanding references to the pager,
48078  ** it can safely move back to PAGER_OPEN state. This happens in both
48079  ** normal and exclusive-locking mode.
48080  */
48081  assert( pPager->errCode==SQLITE_OK || !MEMDB );
48082  if( pPager->errCode ){
48083    if( pPager->tempFile==0 ){
48084      pager_reset(pPager);
48085      pPager->changeCountDone = 0;
48086      pPager->eState = PAGER_OPEN;
48087    }else{
48088      pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
48089    }
48090    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
48091    pPager->errCode = SQLITE_OK;
48092  }
48093
48094  pPager->journalOff = 0;
48095  pPager->journalHdr = 0;
48096  pPager->setMaster = 0;
48097}
48098
48099/*
48100** This function is called whenever an IOERR or FULL error that requires
48101** the pager to transition into the ERROR state may ahve occurred.
48102** The first argument is a pointer to the pager structure, the second
48103** the error-code about to be returned by a pager API function. The
48104** value returned is a copy of the second argument to this function.
48105**
48106** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
48107** IOERR sub-codes, the pager enters the ERROR state and the error code
48108** is stored in Pager.errCode. While the pager remains in the ERROR state,
48109** all major API calls on the Pager will immediately return Pager.errCode.
48110**
48111** The ERROR state indicates that the contents of the pager-cache
48112** cannot be trusted. This state can be cleared by completely discarding
48113** the contents of the pager-cache. If a transaction was active when
48114** the persistent error occurred, then the rollback journal may need
48115** to be replayed to restore the contents of the database file (as if
48116** it were a hot-journal).
48117*/
48118static int pager_error(Pager *pPager, int rc){
48119  int rc2 = rc & 0xff;
48120  assert( rc==SQLITE_OK || !MEMDB );
48121  assert(
48122       pPager->errCode==SQLITE_FULL ||
48123       pPager->errCode==SQLITE_OK ||
48124       (pPager->errCode & 0xff)==SQLITE_IOERR
48125  );
48126  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
48127    pPager->errCode = rc;
48128    pPager->eState = PAGER_ERROR;
48129  }
48130  return rc;
48131}
48132
48133static int pager_truncate(Pager *pPager, Pgno nPage);
48134
48135/*
48136** The write transaction open on pPager is being committed (bCommit==1)
48137** or rolled back (bCommit==0).
48138**
48139** Return TRUE if and only if all dirty pages should be flushed to disk.
48140**
48141** Rules:
48142**
48143**   *  For non-TEMP databases, always sync to disk.  This is necessary
48144**      for transactions to be durable.
48145**
48146**   *  Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
48147**      file has been created already (via a spill on pagerStress()) and
48148**      when the number of dirty pages in memory exceeds 25% of the total
48149**      cache size.
48150*/
48151static int pagerFlushOnCommit(Pager *pPager, int bCommit){
48152  if( pPager->tempFile==0 ) return 1;
48153  if( !bCommit ) return 0;
48154  if( !isOpen(pPager->fd) ) return 0;
48155  return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
48156}
48157
48158/*
48159** This routine ends a transaction. A transaction is usually ended by
48160** either a COMMIT or a ROLLBACK operation. This routine may be called
48161** after rollback of a hot-journal, or if an error occurs while opening
48162** the journal file or writing the very first journal-header of a
48163** database transaction.
48164**
48165** This routine is never called in PAGER_ERROR state. If it is called
48166** in PAGER_NONE or PAGER_SHARED state and the lock held is less
48167** exclusive than a RESERVED lock, it is a no-op.
48168**
48169** Otherwise, any active savepoints are released.
48170**
48171** If the journal file is open, then it is "finalized". Once a journal
48172** file has been finalized it is not possible to use it to roll back a
48173** transaction. Nor will it be considered to be a hot-journal by this
48174** or any other database connection. Exactly how a journal is finalized
48175** depends on whether or not the pager is running in exclusive mode and
48176** the current journal-mode (Pager.journalMode value), as follows:
48177**
48178**   journalMode==MEMORY
48179**     Journal file descriptor is simply closed. This destroys an
48180**     in-memory journal.
48181**
48182**   journalMode==TRUNCATE
48183**     Journal file is truncated to zero bytes in size.
48184**
48185**   journalMode==PERSIST
48186**     The first 28 bytes of the journal file are zeroed. This invalidates
48187**     the first journal header in the file, and hence the entire journal
48188**     file. An invalid journal file cannot be rolled back.
48189**
48190**   journalMode==DELETE
48191**     The journal file is closed and deleted using sqlite3OsDelete().
48192**
48193**     If the pager is running in exclusive mode, this method of finalizing
48194**     the journal file is never used. Instead, if the journalMode is
48195**     DELETE and the pager is in exclusive mode, the method described under
48196**     journalMode==PERSIST is used instead.
48197**
48198** After the journal is finalized, the pager moves to PAGER_READER state.
48199** If running in non-exclusive rollback mode, the lock on the file is
48200** downgraded to a SHARED_LOCK.
48201**
48202** SQLITE_OK is returned if no error occurs. If an error occurs during
48203** any of the IO operations to finalize the journal file or unlock the
48204** database then the IO error code is returned to the user. If the
48205** operation to finalize the journal file fails, then the code still
48206** tries to unlock the database file if not in exclusive mode. If the
48207** unlock operation fails as well, then the first error code related
48208** to the first error encountered (the journal finalization one) is
48209** returned.
48210*/
48211static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
48212  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
48213  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
48214
48215  /* Do nothing if the pager does not have an open write transaction
48216  ** or at least a RESERVED lock. This function may be called when there
48217  ** is no write-transaction active but a RESERVED or greater lock is
48218  ** held under two circumstances:
48219  **
48220  **   1. After a successful hot-journal rollback, it is called with
48221  **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
48222  **
48223  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
48224  **      lock switches back to locking_mode=normal and then executes a
48225  **      read-transaction, this function is called with eState==PAGER_READER
48226  **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
48227  */
48228  assert( assert_pager_state(pPager) );
48229  assert( pPager->eState!=PAGER_ERROR );
48230  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
48231    return SQLITE_OK;
48232  }
48233
48234  releaseAllSavepoints(pPager);
48235  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
48236  if( isOpen(pPager->jfd) ){
48237    assert( !pagerUseWal(pPager) );
48238
48239    /* Finalize the journal file. */
48240    if( sqlite3JournalIsInMemory(pPager->jfd) ){
48241      /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
48242      sqlite3OsClose(pPager->jfd);
48243    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
48244      if( pPager->journalOff==0 ){
48245        rc = SQLITE_OK;
48246      }else{
48247        rc = sqlite3OsTruncate(pPager->jfd, 0);
48248        if( rc==SQLITE_OK && pPager->fullSync ){
48249          /* Make sure the new file size is written into the inode right away.
48250          ** Otherwise the journal might resurrect following a power loss and
48251          ** cause the last transaction to roll back.  See
48252          ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
48253          */
48254          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
48255        }
48256      }
48257      pPager->journalOff = 0;
48258    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
48259      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
48260    ){
48261      rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
48262      pPager->journalOff = 0;
48263    }else{
48264      /* This branch may be executed with Pager.journalMode==MEMORY if
48265      ** a hot-journal was just rolled back. In this case the journal
48266      ** file should be closed and deleted. If this connection writes to
48267      ** the database file, it will do so using an in-memory journal.
48268      */
48269      int bDelete = !pPager->tempFile;
48270      assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
48271      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
48272           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
48273           || pPager->journalMode==PAGER_JOURNALMODE_WAL
48274      );
48275      sqlite3OsClose(pPager->jfd);
48276      if( bDelete ){
48277        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
48278      }
48279    }
48280  }
48281
48282#ifdef SQLITE_CHECK_PAGES
48283  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
48284  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
48285    PgHdr *p = sqlite3PagerLookup(pPager, 1);
48286    if( p ){
48287      p->pageHash = 0;
48288      sqlite3PagerUnrefNotNull(p);
48289    }
48290  }
48291#endif
48292
48293  sqlite3BitvecDestroy(pPager->pInJournal);
48294  pPager->pInJournal = 0;
48295  pPager->nRec = 0;
48296  if( rc==SQLITE_OK ){
48297    if( pagerFlushOnCommit(pPager, bCommit) ){
48298      sqlite3PcacheCleanAll(pPager->pPCache);
48299    }else{
48300      sqlite3PcacheClearWritable(pPager->pPCache);
48301    }
48302    sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
48303  }
48304
48305  if( pagerUseWal(pPager) ){
48306    /* Drop the WAL write-lock, if any. Also, if the connection was in
48307    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
48308    ** lock held on the database file.
48309    */
48310    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
48311    assert( rc2==SQLITE_OK );
48312  }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
48313    /* This branch is taken when committing a transaction in rollback-journal
48314    ** mode if the database file on disk is larger than the database image.
48315    ** At this point the journal has been finalized and the transaction
48316    ** successfully committed, but the EXCLUSIVE lock is still held on the
48317    ** file. So it is safe to truncate the database file to its minimum
48318    ** required size.  */
48319    assert( pPager->eLock==EXCLUSIVE_LOCK );
48320    rc = pager_truncate(pPager, pPager->dbSize);
48321  }
48322
48323  if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
48324    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
48325    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
48326  }
48327
48328  if( !pPager->exclusiveMode
48329   && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
48330  ){
48331    rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
48332    pPager->changeCountDone = 0;
48333  }
48334  pPager->eState = PAGER_READER;
48335  pPager->setMaster = 0;
48336
48337  return (rc==SQLITE_OK?rc2:rc);
48338}
48339
48340/*
48341** Execute a rollback if a transaction is active and unlock the
48342** database file.
48343**
48344** If the pager has already entered the ERROR state, do not attempt
48345** the rollback at this time. Instead, pager_unlock() is called. The
48346** call to pager_unlock() will discard all in-memory pages, unlock
48347** the database file and move the pager back to OPEN state. If this
48348** means that there is a hot-journal left in the file-system, the next
48349** connection to obtain a shared lock on the pager (which may be this one)
48350** will roll it back.
48351**
48352** If the pager has not already entered the ERROR state, but an IO or
48353** malloc error occurs during a rollback, then this will itself cause
48354** the pager to enter the ERROR state. Which will be cleared by the
48355** call to pager_unlock(), as described above.
48356*/
48357static void pagerUnlockAndRollback(Pager *pPager){
48358  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
48359    assert( assert_pager_state(pPager) );
48360    if( pPager->eState>=PAGER_WRITER_LOCKED ){
48361      sqlite3BeginBenignMalloc();
48362      sqlite3PagerRollback(pPager);
48363      sqlite3EndBenignMalloc();
48364    }else if( !pPager->exclusiveMode ){
48365      assert( pPager->eState==PAGER_READER );
48366      pager_end_transaction(pPager, 0, 0);
48367    }
48368  }
48369  pager_unlock(pPager);
48370}
48371
48372/*
48373** Parameter aData must point to a buffer of pPager->pageSize bytes
48374** of data. Compute and return a checksum based ont the contents of the
48375** page of data and the current value of pPager->cksumInit.
48376**
48377** This is not a real checksum. It is really just the sum of the
48378** random initial value (pPager->cksumInit) and every 200th byte
48379** of the page data, starting with byte offset (pPager->pageSize%200).
48380** Each byte is interpreted as an 8-bit unsigned integer.
48381**
48382** Changing the formula used to compute this checksum results in an
48383** incompatible journal file format.
48384**
48385** If journal corruption occurs due to a power failure, the most likely
48386** scenario is that one end or the other of the record will be changed.
48387** It is much less likely that the two ends of the journal record will be
48388** correct and the middle be corrupt.  Thus, this "checksum" scheme,
48389** though fast and simple, catches the mostly likely kind of corruption.
48390*/
48391static u32 pager_cksum(Pager *pPager, const u8 *aData){
48392  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
48393  int i = pPager->pageSize-200;          /* Loop counter */
48394  while( i>0 ){
48395    cksum += aData[i];
48396    i -= 200;
48397  }
48398  return cksum;
48399}
48400
48401/*
48402** Report the current page size and number of reserved bytes back
48403** to the codec.
48404*/
48405#ifdef SQLITE_HAS_CODEC
48406static void pagerReportSize(Pager *pPager){
48407  if( pPager->xCodecSizeChng ){
48408    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
48409                           (int)pPager->nReserve);
48410  }
48411}
48412#else
48413# define pagerReportSize(X)     /* No-op if we do not support a codec */
48414#endif
48415
48416#ifdef SQLITE_HAS_CODEC
48417/*
48418** Make sure the number of reserved bits is the same in the destination
48419** pager as it is in the source.  This comes up when a VACUUM changes the
48420** number of reserved bits to the "optimal" amount.
48421*/
48422SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
48423  if( pDest->nReserve!=pSrc->nReserve ){
48424    pDest->nReserve = pSrc->nReserve;
48425    pagerReportSize(pDest);
48426  }
48427}
48428#endif
48429
48430/*
48431** Read a single page from either the journal file (if isMainJrnl==1) or
48432** from the sub-journal (if isMainJrnl==0) and playback that page.
48433** The page begins at offset *pOffset into the file. The *pOffset
48434** value is increased to the start of the next page in the journal.
48435**
48436** The main rollback journal uses checksums - the statement journal does
48437** not.
48438**
48439** If the page number of the page record read from the (sub-)journal file
48440** is greater than the current value of Pager.dbSize, then playback is
48441** skipped and SQLITE_OK is returned.
48442**
48443** If pDone is not NULL, then it is a record of pages that have already
48444** been played back.  If the page at *pOffset has already been played back
48445** (if the corresponding pDone bit is set) then skip the playback.
48446** Make sure the pDone bit corresponding to the *pOffset page is set
48447** prior to returning.
48448**
48449** If the page record is successfully read from the (sub-)journal file
48450** and played back, then SQLITE_OK is returned. If an IO error occurs
48451** while reading the record from the (sub-)journal file or while writing
48452** to the database file, then the IO error code is returned. If data
48453** is successfully read from the (sub-)journal file but appears to be
48454** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
48455** two circumstances:
48456**
48457**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
48458**   * If the record is being rolled back from the main journal file
48459**     and the checksum field does not match the record content.
48460**
48461** Neither of these two scenarios are possible during a savepoint rollback.
48462**
48463** If this is a savepoint rollback, then memory may have to be dynamically
48464** allocated by this function. If this is the case and an allocation fails,
48465** SQLITE_NOMEM is returned.
48466*/
48467static int pager_playback_one_page(
48468  Pager *pPager,                /* The pager being played back */
48469  i64 *pOffset,                 /* Offset of record to playback */
48470  Bitvec *pDone,                /* Bitvec of pages already played back */
48471  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
48472  int isSavepnt                 /* True for a savepoint rollback */
48473){
48474  int rc;
48475  PgHdr *pPg;                   /* An existing page in the cache */
48476  Pgno pgno;                    /* The page number of a page in journal */
48477  u32 cksum;                    /* Checksum used for sanity checking */
48478  char *aData;                  /* Temporary storage for the page */
48479  sqlite3_file *jfd;            /* The file descriptor for the journal file */
48480  int isSynced;                 /* True if journal page is synced */
48481
48482  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
48483  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
48484  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
48485  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
48486
48487  aData = pPager->pTmpSpace;
48488  assert( aData );         /* Temp storage must have already been allocated */
48489  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
48490
48491  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
48492  ** or savepoint rollback done at the request of the caller) or this is
48493  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
48494  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
48495  ** only reads from the main journal, not the sub-journal.
48496  */
48497  assert( pPager->eState>=PAGER_WRITER_CACHEMOD
48498       || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
48499  );
48500  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
48501
48502  /* Read the page number and page data from the journal or sub-journal
48503  ** file. Return an error code to the caller if an IO error occurs.
48504  */
48505  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
48506  rc = read32bits(jfd, *pOffset, &pgno);
48507  if( rc!=SQLITE_OK ) return rc;
48508  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
48509  if( rc!=SQLITE_OK ) return rc;
48510  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
48511
48512  /* Sanity checking on the page.  This is more important that I originally
48513  ** thought.  If a power failure occurs while the journal is being written,
48514  ** it could cause invalid data to be written into the journal.  We need to
48515  ** detect this invalid data (with high probability) and ignore it.
48516  */
48517  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
48518    assert( !isSavepnt );
48519    return SQLITE_DONE;
48520  }
48521  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
48522    return SQLITE_OK;
48523  }
48524  if( isMainJrnl ){
48525    rc = read32bits(jfd, (*pOffset)-4, &cksum);
48526    if( rc ) return rc;
48527    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
48528      return SQLITE_DONE;
48529    }
48530  }
48531
48532  /* If this page has already been played back before during the current
48533  ** rollback, then don't bother to play it back again.
48534  */
48535  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
48536    return rc;
48537  }
48538
48539  /* When playing back page 1, restore the nReserve setting
48540  */
48541  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
48542    pPager->nReserve = ((u8*)aData)[20];
48543    pagerReportSize(pPager);
48544  }
48545
48546  /* If the pager is in CACHEMOD state, then there must be a copy of this
48547  ** page in the pager cache. In this case just update the pager cache,
48548  ** not the database file. The page is left marked dirty in this case.
48549  **
48550  ** An exception to the above rule: If the database is in no-sync mode
48551  ** and a page is moved during an incremental vacuum then the page may
48552  ** not be in the pager cache. Later: if a malloc() or IO error occurs
48553  ** during a Movepage() call, then the page may not be in the cache
48554  ** either. So the condition described in the above paragraph is not
48555  ** assert()able.
48556  **
48557  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
48558  ** pager cache if it exists and the main file. The page is then marked
48559  ** not dirty. Since this code is only executed in PAGER_OPEN state for
48560  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
48561  ** if the pager is in OPEN state.
48562  **
48563  ** Ticket #1171:  The statement journal might contain page content that is
48564  ** different from the page content at the start of the transaction.
48565  ** This occurs when a page is changed prior to the start of a statement
48566  ** then changed again within the statement.  When rolling back such a
48567  ** statement we must not write to the original database unless we know
48568  ** for certain that original page contents are synced into the main rollback
48569  ** journal.  Otherwise, a power loss might leave modified data in the
48570  ** database file without an entry in the rollback journal that can
48571  ** restore the database to its original form.  Two conditions must be
48572  ** met before writing to the database files. (1) the database must be
48573  ** locked.  (2) we know that the original page content is fully synced
48574  ** in the main journal either because the page is not in cache or else
48575  ** the page is marked as needSync==0.
48576  **
48577  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
48578  ** is possible to fail a statement on a database that does not yet exist.
48579  ** Do not attempt to write if database file has never been opened.
48580  */
48581  if( pagerUseWal(pPager) ){
48582    pPg = 0;
48583  }else{
48584    pPg = sqlite3PagerLookup(pPager, pgno);
48585  }
48586  assert( pPg || !MEMDB );
48587  assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
48588  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
48589           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
48590           (isMainJrnl?"main-journal":"sub-journal")
48591  ));
48592  if( isMainJrnl ){
48593    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
48594  }else{
48595    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
48596  }
48597  if( isOpen(pPager->fd)
48598   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
48599   && isSynced
48600  ){
48601    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
48602    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
48603    assert( !pagerUseWal(pPager) );
48604    rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
48605    if( pgno>pPager->dbFileSize ){
48606      pPager->dbFileSize = pgno;
48607    }
48608    if( pPager->pBackup ){
48609      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
48610      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
48611      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
48612    }
48613  }else if( !isMainJrnl && pPg==0 ){
48614    /* If this is a rollback of a savepoint and data was not written to
48615    ** the database and the page is not in-memory, there is a potential
48616    ** problem. When the page is next fetched by the b-tree layer, it
48617    ** will be read from the database file, which may or may not be
48618    ** current.
48619    **
48620    ** There are a couple of different ways this can happen. All are quite
48621    ** obscure. When running in synchronous mode, this can only happen
48622    ** if the page is on the free-list at the start of the transaction, then
48623    ** populated, then moved using sqlite3PagerMovepage().
48624    **
48625    ** The solution is to add an in-memory page to the cache containing
48626    ** the data just read from the sub-journal. Mark the page as dirty
48627    ** and if the pager requires a journal-sync, then mark the page as
48628    ** requiring a journal-sync before it is written.
48629    */
48630    assert( isSavepnt );
48631    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
48632    pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
48633    rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
48634    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
48635    pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
48636    if( rc!=SQLITE_OK ) return rc;
48637    sqlite3PcacheMakeDirty(pPg);
48638  }
48639  if( pPg ){
48640    /* No page should ever be explicitly rolled back that is in use, except
48641    ** for page 1 which is held in use in order to keep the lock on the
48642    ** database active. However such a page may be rolled back as a result
48643    ** of an internal error resulting in an automatic call to
48644    ** sqlite3PagerRollback().
48645    */
48646    void *pData;
48647    pData = pPg->pData;
48648    memcpy(pData, (u8*)aData, pPager->pageSize);
48649    pPager->xReiniter(pPg);
48650    /* It used to be that sqlite3PcacheMakeClean(pPg) was called here.  But
48651    ** that call was dangerous and had no detectable benefit since the cache
48652    ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
48653    ** has been removed. */
48654    pager_set_pagehash(pPg);
48655
48656    /* If this was page 1, then restore the value of Pager.dbFileVers.
48657    ** Do this before any decoding. */
48658    if( pgno==1 ){
48659      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
48660    }
48661
48662    /* Decode the page just read from disk */
48663    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT);
48664    sqlite3PcacheRelease(pPg);
48665  }
48666  return rc;
48667}
48668
48669/*
48670** Parameter zMaster is the name of a master journal file. A single journal
48671** file that referred to the master journal file has just been rolled back.
48672** This routine checks if it is possible to delete the master journal file,
48673** and does so if it is.
48674**
48675** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
48676** available for use within this function.
48677**
48678** When a master journal file is created, it is populated with the names
48679** of all of its child journals, one after another, formatted as utf-8
48680** encoded text. The end of each child journal file is marked with a
48681** nul-terminator byte (0x00). i.e. the entire contents of a master journal
48682** file for a transaction involving two databases might be:
48683**
48684**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
48685**
48686** A master journal file may only be deleted once all of its child
48687** journals have been rolled back.
48688**
48689** This function reads the contents of the master-journal file into
48690** memory and loops through each of the child journal names. For
48691** each child journal, it checks if:
48692**
48693**   * if the child journal exists, and if so
48694**   * if the child journal contains a reference to master journal
48695**     file zMaster
48696**
48697** If a child journal can be found that matches both of the criteria
48698** above, this function returns without doing anything. Otherwise, if
48699** no such child journal can be found, file zMaster is deleted from
48700** the file-system using sqlite3OsDelete().
48701**
48702** If an IO error within this function, an error code is returned. This
48703** function allocates memory by calling sqlite3Malloc(). If an allocation
48704** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
48705** occur, SQLITE_OK is returned.
48706**
48707** TODO: This function allocates a single block of memory to load
48708** the entire contents of the master journal file. This could be
48709** a couple of kilobytes or so - potentially larger than the page
48710** size.
48711*/
48712static int pager_delmaster(Pager *pPager, const char *zMaster){
48713  sqlite3_vfs *pVfs = pPager->pVfs;
48714  int rc;                   /* Return code */
48715  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
48716  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
48717  char *zMasterJournal = 0; /* Contents of master journal file */
48718  i64 nMasterJournal;       /* Size of master journal file */
48719  char *zJournal;           /* Pointer to one journal within MJ file */
48720  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
48721  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
48722
48723  /* Allocate space for both the pJournal and pMaster file descriptors.
48724  ** If successful, open the master journal file for reading.
48725  */
48726  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
48727  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
48728  if( !pMaster ){
48729    rc = SQLITE_NOMEM_BKPT;
48730  }else{
48731    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
48732    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
48733  }
48734  if( rc!=SQLITE_OK ) goto delmaster_out;
48735
48736  /* Load the entire master journal file into space obtained from
48737  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
48738  ** sufficient space (in zMasterPtr) to hold the names of master
48739  ** journal files extracted from regular rollback-journals.
48740  */
48741  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
48742  if( rc!=SQLITE_OK ) goto delmaster_out;
48743  nMasterPtr = pVfs->mxPathname+1;
48744  zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
48745  if( !zMasterJournal ){
48746    rc = SQLITE_NOMEM_BKPT;
48747    goto delmaster_out;
48748  }
48749  zMasterPtr = &zMasterJournal[nMasterJournal+1];
48750  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
48751  if( rc!=SQLITE_OK ) goto delmaster_out;
48752  zMasterJournal[nMasterJournal] = 0;
48753
48754  zJournal = zMasterJournal;
48755  while( (zJournal-zMasterJournal)<nMasterJournal ){
48756    int exists;
48757    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
48758    if( rc!=SQLITE_OK ){
48759      goto delmaster_out;
48760    }
48761    if( exists ){
48762      /* One of the journals pointed to by the master journal exists.
48763      ** Open it and check if it points at the master journal. If
48764      ** so, return without deleting the master journal file.
48765      */
48766      int c;
48767      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
48768      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
48769      if( rc!=SQLITE_OK ){
48770        goto delmaster_out;
48771      }
48772
48773      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
48774      sqlite3OsClose(pJournal);
48775      if( rc!=SQLITE_OK ){
48776        goto delmaster_out;
48777      }
48778
48779      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
48780      if( c ){
48781        /* We have a match. Do not delete the master journal file. */
48782        goto delmaster_out;
48783      }
48784    }
48785    zJournal += (sqlite3Strlen30(zJournal)+1);
48786  }
48787
48788  sqlite3OsClose(pMaster);
48789  rc = sqlite3OsDelete(pVfs, zMaster, 0);
48790
48791delmaster_out:
48792  sqlite3_free(zMasterJournal);
48793  if( pMaster ){
48794    sqlite3OsClose(pMaster);
48795    assert( !isOpen(pJournal) );
48796    sqlite3_free(pMaster);
48797  }
48798  return rc;
48799}
48800
48801
48802/*
48803** This function is used to change the actual size of the database
48804** file in the file-system. This only happens when committing a transaction,
48805** or rolling back a transaction (including rolling back a hot-journal).
48806**
48807** If the main database file is not open, or the pager is not in either
48808** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
48809** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
48810** If the file on disk is currently larger than nPage pages, then use the VFS
48811** xTruncate() method to truncate it.
48812**
48813** Or, it might be the case that the file on disk is smaller than
48814** nPage pages. Some operating system implementations can get confused if
48815** you try to truncate a file to some size that is larger than it
48816** currently is, so detect this case and write a single zero byte to
48817** the end of the new file instead.
48818**
48819** If successful, return SQLITE_OK. If an IO error occurs while modifying
48820** the database file, return the error code to the caller.
48821*/
48822static int pager_truncate(Pager *pPager, Pgno nPage){
48823  int rc = SQLITE_OK;
48824  assert( pPager->eState!=PAGER_ERROR );
48825  assert( pPager->eState!=PAGER_READER );
48826
48827  if( isOpen(pPager->fd)
48828   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
48829  ){
48830    i64 currentSize, newSize;
48831    int szPage = pPager->pageSize;
48832    assert( pPager->eLock==EXCLUSIVE_LOCK );
48833    /* TODO: Is it safe to use Pager.dbFileSize here? */
48834    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
48835    newSize = szPage*(i64)nPage;
48836    if( rc==SQLITE_OK && currentSize!=newSize ){
48837      if( currentSize>newSize ){
48838        rc = sqlite3OsTruncate(pPager->fd, newSize);
48839      }else if( (currentSize+szPage)<=newSize ){
48840        char *pTmp = pPager->pTmpSpace;
48841        memset(pTmp, 0, szPage);
48842        testcase( (newSize-szPage) == currentSize );
48843        testcase( (newSize-szPage) >  currentSize );
48844        rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
48845      }
48846      if( rc==SQLITE_OK ){
48847        pPager->dbFileSize = nPage;
48848      }
48849    }
48850  }
48851  return rc;
48852}
48853
48854/*
48855** Return a sanitized version of the sector-size of OS file pFile. The
48856** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
48857*/
48858SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
48859  int iRet = sqlite3OsSectorSize(pFile);
48860  if( iRet<32 ){
48861    iRet = 512;
48862  }else if( iRet>MAX_SECTOR_SIZE ){
48863    assert( MAX_SECTOR_SIZE>=512 );
48864    iRet = MAX_SECTOR_SIZE;
48865  }
48866  return iRet;
48867}
48868
48869/*
48870** Set the value of the Pager.sectorSize variable for the given
48871** pager based on the value returned by the xSectorSize method
48872** of the open database file. The sector size will be used
48873** to determine the size and alignment of journal header and
48874** master journal pointers within created journal files.
48875**
48876** For temporary files the effective sector size is always 512 bytes.
48877**
48878** Otherwise, for non-temporary files, the effective sector size is
48879** the value returned by the xSectorSize() method rounded up to 32 if
48880** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
48881** is greater than MAX_SECTOR_SIZE.
48882**
48883** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
48884** the effective sector size to its minimum value (512).  The purpose of
48885** pPager->sectorSize is to define the "blast radius" of bytes that
48886** might change if a crash occurs while writing to a single byte in
48887** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
48888** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
48889** size.  For backwards compatibility of the rollback journal file format,
48890** we cannot reduce the effective sector size below 512.
48891*/
48892static void setSectorSize(Pager *pPager){
48893  assert( isOpen(pPager->fd) || pPager->tempFile );
48894
48895  if( pPager->tempFile
48896   || (sqlite3OsDeviceCharacteristics(pPager->fd) &
48897              SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
48898  ){
48899    /* Sector size doesn't matter for temporary files. Also, the file
48900    ** may not have been opened yet, in which case the OsSectorSize()
48901    ** call will segfault. */
48902    pPager->sectorSize = 512;
48903  }else{
48904    pPager->sectorSize = sqlite3SectorSize(pPager->fd);
48905  }
48906}
48907
48908/*
48909** Playback the journal and thus restore the database file to
48910** the state it was in before we started making changes.
48911**
48912** The journal file format is as follows:
48913**
48914**  (1)  8 byte prefix.  A copy of aJournalMagic[].
48915**  (2)  4 byte big-endian integer which is the number of valid page records
48916**       in the journal.  If this value is 0xffffffff, then compute the
48917**       number of page records from the journal size.
48918**  (3)  4 byte big-endian integer which is the initial value for the
48919**       sanity checksum.
48920**  (4)  4 byte integer which is the number of pages to truncate the
48921**       database to during a rollback.
48922**  (5)  4 byte big-endian integer which is the sector size.  The header
48923**       is this many bytes in size.
48924**  (6)  4 byte big-endian integer which is the page size.
48925**  (7)  zero padding out to the next sector size.
48926**  (8)  Zero or more pages instances, each as follows:
48927**        +  4 byte page number.
48928**        +  pPager->pageSize bytes of data.
48929**        +  4 byte checksum
48930**
48931** When we speak of the journal header, we mean the first 7 items above.
48932** Each entry in the journal is an instance of the 8th item.
48933**
48934** Call the value from the second bullet "nRec".  nRec is the number of
48935** valid page entries in the journal.  In most cases, you can compute the
48936** value of nRec from the size of the journal file.  But if a power
48937** failure occurred while the journal was being written, it could be the
48938** case that the size of the journal file had already been increased but
48939** the extra entries had not yet made it safely to disk.  In such a case,
48940** the value of nRec computed from the file size would be too large.  For
48941** that reason, we always use the nRec value in the header.
48942**
48943** If the nRec value is 0xffffffff it means that nRec should be computed
48944** from the file size.  This value is used when the user selects the
48945** no-sync option for the journal.  A power failure could lead to corruption
48946** in this case.  But for things like temporary table (which will be
48947** deleted when the power is restored) we don't care.
48948**
48949** If the file opened as the journal file is not a well-formed
48950** journal file then all pages up to the first corrupted page are rolled
48951** back (or no pages if the journal header is corrupted). The journal file
48952** is then deleted and SQLITE_OK returned, just as if no corruption had
48953** been encountered.
48954**
48955** If an I/O or malloc() error occurs, the journal-file is not deleted
48956** and an error code is returned.
48957**
48958** The isHot parameter indicates that we are trying to rollback a journal
48959** that might be a hot journal.  Or, it could be that the journal is
48960** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
48961** If the journal really is hot, reset the pager cache prior rolling
48962** back any content.  If the journal is merely persistent, no reset is
48963** needed.
48964*/
48965static int pager_playback(Pager *pPager, int isHot){
48966  sqlite3_vfs *pVfs = pPager->pVfs;
48967  i64 szJ;                 /* Size of the journal file in bytes */
48968  u32 nRec;                /* Number of Records in the journal */
48969  u32 u;                   /* Unsigned loop counter */
48970  Pgno mxPg = 0;           /* Size of the original file in pages */
48971  int rc;                  /* Result code of a subroutine */
48972  int res = 1;             /* Value returned by sqlite3OsAccess() */
48973  char *zMaster = 0;       /* Name of master journal file if any */
48974  int needPagerReset;      /* True to reset page prior to first page rollback */
48975  int nPlayback = 0;       /* Total number of pages restored from journal */
48976
48977  /* Figure out how many records are in the journal.  Abort early if
48978  ** the journal is empty.
48979  */
48980  assert( isOpen(pPager->jfd) );
48981  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
48982  if( rc!=SQLITE_OK ){
48983    goto end_playback;
48984  }
48985
48986  /* Read the master journal name from the journal, if it is present.
48987  ** If a master journal file name is specified, but the file is not
48988  ** present on disk, then the journal is not hot and does not need to be
48989  ** played back.
48990  **
48991  ** TODO: Technically the following is an error because it assumes that
48992  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
48993  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
48994  ** mxPathname is 512, which is the same as the minimum allowable value
48995  ** for pageSize.
48996  */
48997  zMaster = pPager->pTmpSpace;
48998  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
48999  if( rc==SQLITE_OK && zMaster[0] ){
49000    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
49001  }
49002  zMaster = 0;
49003  if( rc!=SQLITE_OK || !res ){
49004    goto end_playback;
49005  }
49006  pPager->journalOff = 0;
49007  needPagerReset = isHot;
49008
49009  /* This loop terminates either when a readJournalHdr() or
49010  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
49011  ** occurs.
49012  */
49013  while( 1 ){
49014    /* Read the next journal header from the journal file.  If there are
49015    ** not enough bytes left in the journal file for a complete header, or
49016    ** it is corrupted, then a process must have failed while writing it.
49017    ** This indicates nothing more needs to be rolled back.
49018    */
49019    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
49020    if( rc!=SQLITE_OK ){
49021      if( rc==SQLITE_DONE ){
49022        rc = SQLITE_OK;
49023      }
49024      goto end_playback;
49025    }
49026
49027    /* If nRec is 0xffffffff, then this journal was created by a process
49028    ** working in no-sync mode. This means that the rest of the journal
49029    ** file consists of pages, there are no more journal headers. Compute
49030    ** the value of nRec based on this assumption.
49031    */
49032    if( nRec==0xffffffff ){
49033      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
49034      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
49035    }
49036
49037    /* If nRec is 0 and this rollback is of a transaction created by this
49038    ** process and if this is the final header in the journal, then it means
49039    ** that this part of the journal was being filled but has not yet been
49040    ** synced to disk.  Compute the number of pages based on the remaining
49041    ** size of the file.
49042    **
49043    ** The third term of the test was added to fix ticket #2565.
49044    ** When rolling back a hot journal, nRec==0 always means that the next
49045    ** chunk of the journal contains zero pages to be rolled back.  But
49046    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
49047    ** the journal, it means that the journal might contain additional
49048    ** pages that need to be rolled back and that the number of pages
49049    ** should be computed based on the journal file size.
49050    */
49051    if( nRec==0 && !isHot &&
49052        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
49053      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
49054    }
49055
49056    /* If this is the first header read from the journal, truncate the
49057    ** database file back to its original size.
49058    */
49059    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
49060      rc = pager_truncate(pPager, mxPg);
49061      if( rc!=SQLITE_OK ){
49062        goto end_playback;
49063      }
49064      pPager->dbSize = mxPg;
49065    }
49066
49067    /* Copy original pages out of the journal and back into the
49068    ** database file and/or page cache.
49069    */
49070    for(u=0; u<nRec; u++){
49071      if( needPagerReset ){
49072        pager_reset(pPager);
49073        needPagerReset = 0;
49074      }
49075      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
49076      if( rc==SQLITE_OK ){
49077        nPlayback++;
49078      }else{
49079        if( rc==SQLITE_DONE ){
49080          pPager->journalOff = szJ;
49081          break;
49082        }else if( rc==SQLITE_IOERR_SHORT_READ ){
49083          /* If the journal has been truncated, simply stop reading and
49084          ** processing the journal. This might happen if the journal was
49085          ** not completely written and synced prior to a crash.  In that
49086          ** case, the database should have never been written in the
49087          ** first place so it is OK to simply abandon the rollback. */
49088          rc = SQLITE_OK;
49089          goto end_playback;
49090        }else{
49091          /* If we are unable to rollback, quit and return the error
49092          ** code.  This will cause the pager to enter the error state
49093          ** so that no further harm will be done.  Perhaps the next
49094          ** process to come along will be able to rollback the database.
49095          */
49096          goto end_playback;
49097        }
49098      }
49099    }
49100  }
49101  /*NOTREACHED*/
49102  assert( 0 );
49103
49104end_playback:
49105  /* Following a rollback, the database file should be back in its original
49106  ** state prior to the start of the transaction, so invoke the
49107  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
49108  ** assertion that the transaction counter was modified.
49109  */
49110#ifdef SQLITE_DEBUG
49111  if( pPager->fd->pMethods ){
49112    sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
49113  }
49114#endif
49115
49116  /* If this playback is happening automatically as a result of an IO or
49117  ** malloc error that occurred after the change-counter was updated but
49118  ** before the transaction was committed, then the change-counter
49119  ** modification may just have been reverted. If this happens in exclusive
49120  ** mode, then subsequent transactions performed by the connection will not
49121  ** update the change-counter at all. This may lead to cache inconsistency
49122  ** problems for other processes at some point in the future. So, just
49123  ** in case this has happened, clear the changeCountDone flag now.
49124  */
49125  pPager->changeCountDone = pPager->tempFile;
49126
49127  if( rc==SQLITE_OK ){
49128    zMaster = pPager->pTmpSpace;
49129    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
49130    testcase( rc!=SQLITE_OK );
49131  }
49132  if( rc==SQLITE_OK
49133   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
49134  ){
49135    rc = sqlite3PagerSync(pPager, 0);
49136  }
49137  if( rc==SQLITE_OK ){
49138    rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
49139    testcase( rc!=SQLITE_OK );
49140  }
49141  if( rc==SQLITE_OK && zMaster[0] && res ){
49142    /* If there was a master journal and this routine will return success,
49143    ** see if it is possible to delete the master journal.
49144    */
49145    rc = pager_delmaster(pPager, zMaster);
49146    testcase( rc!=SQLITE_OK );
49147  }
49148  if( isHot && nPlayback ){
49149    sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
49150                nPlayback, pPager->zJournal);
49151  }
49152
49153  /* The Pager.sectorSize variable may have been updated while rolling
49154  ** back a journal created by a process with a different sector size
49155  ** value. Reset it to the correct value for this process.
49156  */
49157  setSectorSize(pPager);
49158  return rc;
49159}
49160
49161
49162/*
49163** Read the content for page pPg out of the database file and into
49164** pPg->pData. A shared lock or greater must be held on the database
49165** file before this function is called.
49166**
49167** If page 1 is read, then the value of Pager.dbFileVers[] is set to
49168** the value read from the database file.
49169**
49170** If an IO error occurs, then the IO error is returned to the caller.
49171** Otherwise, SQLITE_OK is returned.
49172*/
49173static int readDbPage(PgHdr *pPg, u32 iFrame){
49174  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
49175  Pgno pgno = pPg->pgno;       /* Page number to read */
49176  int rc = SQLITE_OK;          /* Return code */
49177  int pgsz = pPager->pageSize; /* Number of bytes to read */
49178
49179  assert( pPager->eState>=PAGER_READER && !MEMDB );
49180  assert( isOpen(pPager->fd) );
49181
49182#ifndef SQLITE_OMIT_WAL
49183  if( iFrame ){
49184    /* Try to pull the page from the write-ahead log. */
49185    rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
49186  }else
49187#endif
49188  {
49189    i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
49190    rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
49191    if( rc==SQLITE_IOERR_SHORT_READ ){
49192      rc = SQLITE_OK;
49193    }
49194  }
49195
49196  if( pgno==1 ){
49197    if( rc ){
49198      /* If the read is unsuccessful, set the dbFileVers[] to something
49199      ** that will never be a valid file version.  dbFileVers[] is a copy
49200      ** of bytes 24..39 of the database.  Bytes 28..31 should always be
49201      ** zero or the size of the database in page. Bytes 32..35 and 35..39
49202      ** should be page numbers which are never 0xffffffff.  So filling
49203      ** pPager->dbFileVers[] with all 0xff bytes should suffice.
49204      **
49205      ** For an encrypted database, the situation is more complex:  bytes
49206      ** 24..39 of the database are white noise.  But the probability of
49207      ** white noise equaling 16 bytes of 0xff is vanishingly small so
49208      ** we should still be ok.
49209      */
49210      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
49211    }else{
49212      u8 *dbFileVers = &((u8*)pPg->pData)[24];
49213      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
49214    }
49215  }
49216  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM_BKPT);
49217
49218  PAGER_INCR(sqlite3_pager_readdb_count);
49219  PAGER_INCR(pPager->nRead);
49220  IOTRACE(("PGIN %p %d\n", pPager, pgno));
49221  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
49222               PAGERID(pPager), pgno, pager_pagehash(pPg)));
49223
49224  return rc;
49225}
49226
49227/*
49228** Update the value of the change-counter at offsets 24 and 92 in
49229** the header and the sqlite version number at offset 96.
49230**
49231** This is an unconditional update.  See also the pager_incr_changecounter()
49232** routine which only updates the change-counter if the update is actually
49233** needed, as determined by the pPager->changeCountDone state variable.
49234*/
49235static void pager_write_changecounter(PgHdr *pPg){
49236  u32 change_counter;
49237
49238  /* Increment the value just read and write it back to byte 24. */
49239  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
49240  put32bits(((char*)pPg->pData)+24, change_counter);
49241
49242  /* Also store the SQLite version number in bytes 96..99 and in
49243  ** bytes 92..95 store the change counter for which the version number
49244  ** is valid. */
49245  put32bits(((char*)pPg->pData)+92, change_counter);
49246  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
49247}
49248
49249#ifndef SQLITE_OMIT_WAL
49250/*
49251** This function is invoked once for each page that has already been
49252** written into the log file when a WAL transaction is rolled back.
49253** Parameter iPg is the page number of said page. The pCtx argument
49254** is actually a pointer to the Pager structure.
49255**
49256** If page iPg is present in the cache, and has no outstanding references,
49257** it is discarded. Otherwise, if there are one or more outstanding
49258** references, the page content is reloaded from the database. If the
49259** attempt to reload content from the database is required and fails,
49260** return an SQLite error code. Otherwise, SQLITE_OK.
49261*/
49262static int pagerUndoCallback(void *pCtx, Pgno iPg){
49263  int rc = SQLITE_OK;
49264  Pager *pPager = (Pager *)pCtx;
49265  PgHdr *pPg;
49266
49267  assert( pagerUseWal(pPager) );
49268  pPg = sqlite3PagerLookup(pPager, iPg);
49269  if( pPg ){
49270    if( sqlite3PcachePageRefcount(pPg)==1 ){
49271      sqlite3PcacheDrop(pPg);
49272    }else{
49273      u32 iFrame = 0;
49274      rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
49275      if( rc==SQLITE_OK ){
49276        rc = readDbPage(pPg, iFrame);
49277      }
49278      if( rc==SQLITE_OK ){
49279        pPager->xReiniter(pPg);
49280      }
49281      sqlite3PagerUnrefNotNull(pPg);
49282    }
49283  }
49284
49285  /* Normally, if a transaction is rolled back, any backup processes are
49286  ** updated as data is copied out of the rollback journal and into the
49287  ** database. This is not generally possible with a WAL database, as
49288  ** rollback involves simply truncating the log file. Therefore, if one
49289  ** or more frames have already been written to the log (and therefore
49290  ** also copied into the backup databases) as part of this transaction,
49291  ** the backups must be restarted.
49292  */
49293  sqlite3BackupRestart(pPager->pBackup);
49294
49295  return rc;
49296}
49297
49298/*
49299** This function is called to rollback a transaction on a WAL database.
49300*/
49301static int pagerRollbackWal(Pager *pPager){
49302  int rc;                         /* Return Code */
49303  PgHdr *pList;                   /* List of dirty pages to revert */
49304
49305  /* For all pages in the cache that are currently dirty or have already
49306  ** been written (but not committed) to the log file, do one of the
49307  ** following:
49308  **
49309  **   + Discard the cached page (if refcount==0), or
49310  **   + Reload page content from the database (if refcount>0).
49311  */
49312  pPager->dbSize = pPager->dbOrigSize;
49313  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
49314  pList = sqlite3PcacheDirtyList(pPager->pPCache);
49315  while( pList && rc==SQLITE_OK ){
49316    PgHdr *pNext = pList->pDirty;
49317    rc = pagerUndoCallback((void *)pPager, pList->pgno);
49318    pList = pNext;
49319  }
49320
49321  return rc;
49322}
49323
49324/*
49325** This function is a wrapper around sqlite3WalFrames(). As well as logging
49326** the contents of the list of pages headed by pList (connected by pDirty),
49327** this function notifies any active backup processes that the pages have
49328** changed.
49329**
49330** The list of pages passed into this routine is always sorted by page number.
49331** Hence, if page 1 appears anywhere on the list, it will be the first page.
49332*/
49333static int pagerWalFrames(
49334  Pager *pPager,                  /* Pager object */
49335  PgHdr *pList,                   /* List of frames to log */
49336  Pgno nTruncate,                 /* Database size after this commit */
49337  int isCommit                    /* True if this is a commit */
49338){
49339  int rc;                         /* Return code */
49340  int nList;                      /* Number of pages in pList */
49341  PgHdr *p;                       /* For looping over pages */
49342
49343  assert( pPager->pWal );
49344  assert( pList );
49345#ifdef SQLITE_DEBUG
49346  /* Verify that the page list is in accending order */
49347  for(p=pList; p && p->pDirty; p=p->pDirty){
49348    assert( p->pgno < p->pDirty->pgno );
49349  }
49350#endif
49351
49352  assert( pList->pDirty==0 || isCommit );
49353  if( isCommit ){
49354    /* If a WAL transaction is being committed, there is no point in writing
49355    ** any pages with page numbers greater than nTruncate into the WAL file.
49356    ** They will never be read by any client. So remove them from the pDirty
49357    ** list here. */
49358    PgHdr **ppNext = &pList;
49359    nList = 0;
49360    for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
49361      if( p->pgno<=nTruncate ){
49362        ppNext = &p->pDirty;
49363        nList++;
49364      }
49365    }
49366    assert( pList );
49367  }else{
49368    nList = 1;
49369  }
49370  pPager->aStat[PAGER_STAT_WRITE] += nList;
49371
49372  if( pList->pgno==1 ) pager_write_changecounter(pList);
49373  rc = sqlite3WalFrames(pPager->pWal,
49374      pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
49375  );
49376  if( rc==SQLITE_OK && pPager->pBackup ){
49377    for(p=pList; p; p=p->pDirty){
49378      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
49379    }
49380  }
49381
49382#ifdef SQLITE_CHECK_PAGES
49383  pList = sqlite3PcacheDirtyList(pPager->pPCache);
49384  for(p=pList; p; p=p->pDirty){
49385    pager_set_pagehash(p);
49386  }
49387#endif
49388
49389  return rc;
49390}
49391
49392/*
49393** Begin a read transaction on the WAL.
49394**
49395** This routine used to be called "pagerOpenSnapshot()" because it essentially
49396** makes a snapshot of the database at the current point in time and preserves
49397** that snapshot for use by the reader in spite of concurrently changes by
49398** other writers or checkpointers.
49399*/
49400static int pagerBeginReadTransaction(Pager *pPager){
49401  int rc;                         /* Return code */
49402  int changed = 0;                /* True if cache must be reset */
49403
49404  assert( pagerUseWal(pPager) );
49405  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
49406
49407  /* sqlite3WalEndReadTransaction() was not called for the previous
49408  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
49409  ** are in locking_mode=NORMAL and EndRead() was previously called,
49410  ** the duplicate call is harmless.
49411  */
49412  sqlite3WalEndReadTransaction(pPager->pWal);
49413
49414  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
49415  if( rc!=SQLITE_OK || changed ){
49416    pager_reset(pPager);
49417    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
49418  }
49419
49420  return rc;
49421}
49422#endif
49423
49424/*
49425** This function is called as part of the transition from PAGER_OPEN
49426** to PAGER_READER state to determine the size of the database file
49427** in pages (assuming the page size currently stored in Pager.pageSize).
49428**
49429** If no error occurs, SQLITE_OK is returned and the size of the database
49430** in pages is stored in *pnPage. Otherwise, an error code (perhaps
49431** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
49432*/
49433static int pagerPagecount(Pager *pPager, Pgno *pnPage){
49434  Pgno nPage;                     /* Value to return via *pnPage */
49435
49436  /* Query the WAL sub-system for the database size. The WalDbsize()
49437  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
49438  ** if the database size is not available. The database size is not
49439  ** available from the WAL sub-system if the log file is empty or
49440  ** contains no valid committed transactions.
49441  */
49442  assert( pPager->eState==PAGER_OPEN );
49443  assert( pPager->eLock>=SHARED_LOCK );
49444  assert( isOpen(pPager->fd) );
49445  assert( pPager->tempFile==0 );
49446  nPage = sqlite3WalDbsize(pPager->pWal);
49447
49448  /* If the number of pages in the database is not available from the
49449  ** WAL sub-system, determine the page counte based on the size of
49450  ** the database file.  If the size of the database file is not an
49451  ** integer multiple of the page-size, round up the result.
49452  */
49453  if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
49454    i64 n = 0;                    /* Size of db file in bytes */
49455    int rc = sqlite3OsFileSize(pPager->fd, &n);
49456    if( rc!=SQLITE_OK ){
49457      return rc;
49458    }
49459    nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
49460  }
49461
49462  /* If the current number of pages in the file is greater than the
49463  ** configured maximum pager number, increase the allowed limit so
49464  ** that the file can be read.
49465  */
49466  if( nPage>pPager->mxPgno ){
49467    pPager->mxPgno = (Pgno)nPage;
49468  }
49469
49470  *pnPage = nPage;
49471  return SQLITE_OK;
49472}
49473
49474#ifndef SQLITE_OMIT_WAL
49475/*
49476** Check if the *-wal file that corresponds to the database opened by pPager
49477** exists if the database is not empy, or verify that the *-wal file does
49478** not exist (by deleting it) if the database file is empty.
49479**
49480** If the database is not empty and the *-wal file exists, open the pager
49481** in WAL mode.  If the database is empty or if no *-wal file exists and
49482** if no error occurs, make sure Pager.journalMode is not set to
49483** PAGER_JOURNALMODE_WAL.
49484**
49485** Return SQLITE_OK or an error code.
49486**
49487** The caller must hold a SHARED lock on the database file to call this
49488** function. Because an EXCLUSIVE lock on the db file is required to delete
49489** a WAL on a none-empty database, this ensures there is no race condition
49490** between the xAccess() below and an xDelete() being executed by some
49491** other connection.
49492*/
49493static int pagerOpenWalIfPresent(Pager *pPager){
49494  int rc = SQLITE_OK;
49495  assert( pPager->eState==PAGER_OPEN );
49496  assert( pPager->eLock>=SHARED_LOCK );
49497
49498  if( !pPager->tempFile ){
49499    int isWal;                    /* True if WAL file exists */
49500    Pgno nPage;                   /* Size of the database file */
49501
49502    rc = pagerPagecount(pPager, &nPage);
49503    if( rc ) return rc;
49504    if( nPage==0 ){
49505      rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
49506      if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
49507      isWal = 0;
49508    }else{
49509      rc = sqlite3OsAccess(
49510          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
49511      );
49512    }
49513    if( rc==SQLITE_OK ){
49514      if( isWal ){
49515        testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
49516        rc = sqlite3PagerOpenWal(pPager, 0);
49517      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
49518        pPager->journalMode = PAGER_JOURNALMODE_DELETE;
49519      }
49520    }
49521  }
49522  return rc;
49523}
49524#endif
49525
49526/*
49527** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
49528** the entire master journal file. The case pSavepoint==NULL occurs when
49529** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
49530** savepoint.
49531**
49532** When pSavepoint is not NULL (meaning a non-transaction savepoint is
49533** being rolled back), then the rollback consists of up to three stages,
49534** performed in the order specified:
49535**
49536**   * Pages are played back from the main journal starting at byte
49537**     offset PagerSavepoint.iOffset and continuing to
49538**     PagerSavepoint.iHdrOffset, or to the end of the main journal
49539**     file if PagerSavepoint.iHdrOffset is zero.
49540**
49541**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
49542**     back starting from the journal header immediately following
49543**     PagerSavepoint.iHdrOffset to the end of the main journal file.
49544**
49545**   * Pages are then played back from the sub-journal file, starting
49546**     with the PagerSavepoint.iSubRec and continuing to the end of
49547**     the journal file.
49548**
49549** Throughout the rollback process, each time a page is rolled back, the
49550** corresponding bit is set in a bitvec structure (variable pDone in the
49551** implementation below). This is used to ensure that a page is only
49552** rolled back the first time it is encountered in either journal.
49553**
49554** If pSavepoint is NULL, then pages are only played back from the main
49555** journal file. There is no need for a bitvec in this case.
49556**
49557** In either case, before playback commences the Pager.dbSize variable
49558** is reset to the value that it held at the start of the savepoint
49559** (or transaction). No page with a page-number greater than this value
49560** is played back. If one is encountered it is simply skipped.
49561*/
49562static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
49563  i64 szJ;                 /* Effective size of the main journal */
49564  i64 iHdrOff;             /* End of first segment of main-journal records */
49565  int rc = SQLITE_OK;      /* Return code */
49566  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
49567
49568  assert( pPager->eState!=PAGER_ERROR );
49569  assert( pPager->eState>=PAGER_WRITER_LOCKED );
49570
49571  /* Allocate a bitvec to use to store the set of pages rolled back */
49572  if( pSavepoint ){
49573    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
49574    if( !pDone ){
49575      return SQLITE_NOMEM_BKPT;
49576    }
49577  }
49578
49579  /* Set the database size back to the value it was before the savepoint
49580  ** being reverted was opened.
49581  */
49582  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
49583  pPager->changeCountDone = pPager->tempFile;
49584
49585  if( !pSavepoint && pagerUseWal(pPager) ){
49586    return pagerRollbackWal(pPager);
49587  }
49588
49589  /* Use pPager->journalOff as the effective size of the main rollback
49590  ** journal.  The actual file might be larger than this in
49591  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
49592  ** past pPager->journalOff is off-limits to us.
49593  */
49594  szJ = pPager->journalOff;
49595  assert( pagerUseWal(pPager)==0 || szJ==0 );
49596
49597  /* Begin by rolling back records from the main journal starting at
49598  ** PagerSavepoint.iOffset and continuing to the next journal header.
49599  ** There might be records in the main journal that have a page number
49600  ** greater than the current database size (pPager->dbSize) but those
49601  ** will be skipped automatically.  Pages are added to pDone as they
49602  ** are played back.
49603  */
49604  if( pSavepoint && !pagerUseWal(pPager) ){
49605    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
49606    pPager->journalOff = pSavepoint->iOffset;
49607    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
49608      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
49609    }
49610    assert( rc!=SQLITE_DONE );
49611  }else{
49612    pPager->journalOff = 0;
49613  }
49614
49615  /* Continue rolling back records out of the main journal starting at
49616  ** the first journal header seen and continuing until the effective end
49617  ** of the main journal file.  Continue to skip out-of-range pages and
49618  ** continue adding pages rolled back to pDone.
49619  */
49620  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
49621    u32 ii;            /* Loop counter */
49622    u32 nJRec = 0;     /* Number of Journal Records */
49623    u32 dummy;
49624    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
49625    assert( rc!=SQLITE_DONE );
49626
49627    /*
49628    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
49629    ** test is related to ticket #2565.  See the discussion in the
49630    ** pager_playback() function for additional information.
49631    */
49632    if( nJRec==0
49633     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
49634    ){
49635      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
49636    }
49637    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
49638      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
49639    }
49640    assert( rc!=SQLITE_DONE );
49641  }
49642  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
49643
49644  /* Finally,  rollback pages from the sub-journal.  Page that were
49645  ** previously rolled back out of the main journal (and are hence in pDone)
49646  ** will be skipped.  Out-of-range pages are also skipped.
49647  */
49648  if( pSavepoint ){
49649    u32 ii;            /* Loop counter */
49650    i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
49651
49652    if( pagerUseWal(pPager) ){
49653      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
49654    }
49655    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
49656      assert( offset==(i64)ii*(4+pPager->pageSize) );
49657      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
49658    }
49659    assert( rc!=SQLITE_DONE );
49660  }
49661
49662  sqlite3BitvecDestroy(pDone);
49663  if( rc==SQLITE_OK ){
49664    pPager->journalOff = szJ;
49665  }
49666
49667  return rc;
49668}
49669
49670/*
49671** Change the maximum number of in-memory pages that are allowed
49672** before attempting to recycle clean and unused pages.
49673*/
49674SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
49675  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
49676}
49677
49678/*
49679** Change the maximum number of in-memory pages that are allowed
49680** before attempting to spill pages to journal.
49681*/
49682SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
49683  return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
49684}
49685
49686/*
49687** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
49688*/
49689static void pagerFixMaplimit(Pager *pPager){
49690#if SQLITE_MAX_MMAP_SIZE>0
49691  sqlite3_file *fd = pPager->fd;
49692  if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
49693    sqlite3_int64 sz;
49694    sz = pPager->szMmap;
49695    pPager->bUseFetch = (sz>0);
49696    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
49697  }
49698#endif
49699}
49700
49701/*
49702** Change the maximum size of any memory mapping made of the database file.
49703*/
49704SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
49705  pPager->szMmap = szMmap;
49706  pagerFixMaplimit(pPager);
49707}
49708
49709/*
49710** Free as much memory as possible from the pager.
49711*/
49712SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
49713  sqlite3PcacheShrink(pPager->pPCache);
49714}
49715
49716/*
49717** Adjust settings of the pager to those specified in the pgFlags parameter.
49718**
49719** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
49720** of the database to damage due to OS crashes or power failures by
49721** changing the number of syncs()s when writing the journals.
49722** There are four levels:
49723**
49724**    OFF       sqlite3OsSync() is never called.  This is the default
49725**              for temporary and transient files.
49726**
49727**    NORMAL    The journal is synced once before writes begin on the
49728**              database.  This is normally adequate protection, but
49729**              it is theoretically possible, though very unlikely,
49730**              that an inopertune power failure could leave the journal
49731**              in a state which would cause damage to the database
49732**              when it is rolled back.
49733**
49734**    FULL      The journal is synced twice before writes begin on the
49735**              database (with some additional information - the nRec field
49736**              of the journal header - being written in between the two
49737**              syncs).  If we assume that writing a
49738**              single disk sector is atomic, then this mode provides
49739**              assurance that the journal will not be corrupted to the
49740**              point of causing damage to the database during rollback.
49741**
49742**    EXTRA     This is like FULL except that is also syncs the directory
49743**              that contains the rollback journal after the rollback
49744**              journal is unlinked.
49745**
49746** The above is for a rollback-journal mode.  For WAL mode, OFF continues
49747** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
49748** prior to the start of checkpoint and that the database file is synced
49749** at the conclusion of the checkpoint if the entire content of the WAL
49750** was written back into the database.  But no sync operations occur for
49751** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
49752** file is synced following each commit operation, in addition to the
49753** syncs associated with NORMAL.  There is no difference between FULL
49754** and EXTRA for WAL mode.
49755**
49756** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
49757** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
49758** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
49759** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
49760** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
49761** synchronous=FULL versus synchronous=NORMAL setting determines when
49762** the xSync primitive is called and is relevant to all platforms.
49763**
49764** Numeric values associated with these states are OFF==1, NORMAL=2,
49765** and FULL=3.
49766*/
49767#ifndef SQLITE_OMIT_PAGER_PRAGMAS
49768SQLITE_PRIVATE void sqlite3PagerSetFlags(
49769  Pager *pPager,        /* The pager to set safety level for */
49770  unsigned pgFlags      /* Various flags */
49771){
49772  unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
49773  if( pPager->tempFile ){
49774    pPager->noSync = 1;
49775    pPager->fullSync = 0;
49776    pPager->extraSync = 0;
49777  }else{
49778    pPager->noSync =  level==PAGER_SYNCHRONOUS_OFF ?1:0;
49779    pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
49780    pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
49781  }
49782  if( pPager->noSync ){
49783    pPager->syncFlags = 0;
49784    pPager->ckptSyncFlags = 0;
49785  }else if( pgFlags & PAGER_FULLFSYNC ){
49786    pPager->syncFlags = SQLITE_SYNC_FULL;
49787    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
49788  }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
49789    pPager->syncFlags = SQLITE_SYNC_NORMAL;
49790    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
49791  }else{
49792    pPager->syncFlags = SQLITE_SYNC_NORMAL;
49793    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
49794  }
49795  pPager->walSyncFlags = pPager->syncFlags;
49796  if( pPager->fullSync ){
49797    pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
49798  }
49799  if( pgFlags & PAGER_CACHESPILL ){
49800    pPager->doNotSpill &= ~SPILLFLAG_OFF;
49801  }else{
49802    pPager->doNotSpill |= SPILLFLAG_OFF;
49803  }
49804}
49805#endif
49806
49807/*
49808** The following global variable is incremented whenever the library
49809** attempts to open a temporary file.  This information is used for
49810** testing and analysis only.
49811*/
49812#ifdef SQLITE_TEST
49813SQLITE_API int sqlite3_opentemp_count = 0;
49814#endif
49815
49816/*
49817** Open a temporary file.
49818**
49819** Write the file descriptor into *pFile. Return SQLITE_OK on success
49820** or some other error code if we fail. The OS will automatically
49821** delete the temporary file when it is closed.
49822**
49823** The flags passed to the VFS layer xOpen() call are those specified
49824** by parameter vfsFlags ORed with the following:
49825**
49826**     SQLITE_OPEN_READWRITE
49827**     SQLITE_OPEN_CREATE
49828**     SQLITE_OPEN_EXCLUSIVE
49829**     SQLITE_OPEN_DELETEONCLOSE
49830*/
49831static int pagerOpentemp(
49832  Pager *pPager,        /* The pager object */
49833  sqlite3_file *pFile,  /* Write the file descriptor here */
49834  int vfsFlags          /* Flags passed through to the VFS */
49835){
49836  int rc;               /* Return code */
49837
49838#ifdef SQLITE_TEST
49839  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
49840#endif
49841
49842  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
49843            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
49844  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
49845  assert( rc!=SQLITE_OK || isOpen(pFile) );
49846  return rc;
49847}
49848
49849/*
49850** Set the busy handler function.
49851**
49852** The pager invokes the busy-handler if sqlite3OsLock() returns
49853** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
49854** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
49855** lock. It does *not* invoke the busy handler when upgrading from
49856** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
49857** (which occurs during hot-journal rollback). Summary:
49858**
49859**   Transition                        | Invokes xBusyHandler
49860**   --------------------------------------------------------
49861**   NO_LOCK       -> SHARED_LOCK      | Yes
49862**   SHARED_LOCK   -> RESERVED_LOCK    | No
49863**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
49864**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
49865**
49866** If the busy-handler callback returns non-zero, the lock is
49867** retried. If it returns zero, then the SQLITE_BUSY error is
49868** returned to the caller of the pager API function.
49869*/
49870SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
49871  Pager *pPager,                       /* Pager object */
49872  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
49873  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
49874){
49875  pPager->xBusyHandler = xBusyHandler;
49876  pPager->pBusyHandlerArg = pBusyHandlerArg;
49877
49878  if( isOpen(pPager->fd) ){
49879    void **ap = (void **)&pPager->xBusyHandler;
49880    assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
49881    assert( ap[1]==pBusyHandlerArg );
49882    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
49883  }
49884}
49885
49886/*
49887** Change the page size used by the Pager object. The new page size
49888** is passed in *pPageSize.
49889**
49890** If the pager is in the error state when this function is called, it
49891** is a no-op. The value returned is the error state error code (i.e.
49892** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
49893**
49894** Otherwise, if all of the following are true:
49895**
49896**   * the new page size (value of *pPageSize) is valid (a power
49897**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
49898**
49899**   * there are no outstanding page references, and
49900**
49901**   * the database is either not an in-memory database or it is
49902**     an in-memory database that currently consists of zero pages.
49903**
49904** then the pager object page size is set to *pPageSize.
49905**
49906** If the page size is changed, then this function uses sqlite3PagerMalloc()
49907** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
49908** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
49909** In all other cases, SQLITE_OK is returned.
49910**
49911** If the page size is not changed, either because one of the enumerated
49912** conditions above is not true, the pager was in error state when this
49913** function was called, or because the memory allocation attempt failed,
49914** then *pPageSize is set to the old, retained page size before returning.
49915*/
49916SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
49917  int rc = SQLITE_OK;
49918
49919  /* It is not possible to do a full assert_pager_state() here, as this
49920  ** function may be called from within PagerOpen(), before the state
49921  ** of the Pager object is internally consistent.
49922  **
49923  ** At one point this function returned an error if the pager was in
49924  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
49925  ** there is at least one outstanding page reference, this function
49926  ** is a no-op for that case anyhow.
49927  */
49928
49929  u32 pageSize = *pPageSize;
49930  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
49931  if( (pPager->memDb==0 || pPager->dbSize==0)
49932   && sqlite3PcacheRefCount(pPager->pPCache)==0
49933   && pageSize && pageSize!=(u32)pPager->pageSize
49934  ){
49935    char *pNew = NULL;             /* New temp space */
49936    i64 nByte = 0;
49937
49938    if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
49939      rc = sqlite3OsFileSize(pPager->fd, &nByte);
49940    }
49941    if( rc==SQLITE_OK ){
49942      pNew = (char *)sqlite3PageMalloc(pageSize);
49943      if( !pNew ) rc = SQLITE_NOMEM_BKPT;
49944    }
49945
49946    if( rc==SQLITE_OK ){
49947      pager_reset(pPager);
49948      rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
49949    }
49950    if( rc==SQLITE_OK ){
49951      sqlite3PageFree(pPager->pTmpSpace);
49952      pPager->pTmpSpace = pNew;
49953      pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
49954      pPager->pageSize = pageSize;
49955    }else{
49956      sqlite3PageFree(pNew);
49957    }
49958  }
49959
49960  *pPageSize = pPager->pageSize;
49961  if( rc==SQLITE_OK ){
49962    if( nReserve<0 ) nReserve = pPager->nReserve;
49963    assert( nReserve>=0 && nReserve<1000 );
49964    pPager->nReserve = (i16)nReserve;
49965    pagerReportSize(pPager);
49966    pagerFixMaplimit(pPager);
49967  }
49968  return rc;
49969}
49970
49971/*
49972** Return a pointer to the "temporary page" buffer held internally
49973** by the pager.  This is a buffer that is big enough to hold the
49974** entire content of a database page.  This buffer is used internally
49975** during rollback and will be overwritten whenever a rollback
49976** occurs.  But other modules are free to use it too, as long as
49977** no rollbacks are happening.
49978*/
49979SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
49980  return pPager->pTmpSpace;
49981}
49982
49983/*
49984** Attempt to set the maximum database page count if mxPage is positive.
49985** Make no changes if mxPage is zero or negative.  And never reduce the
49986** maximum page count below the current size of the database.
49987**
49988** Regardless of mxPage, return the current maximum page count.
49989*/
49990SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
49991  if( mxPage>0 ){
49992    pPager->mxPgno = mxPage;
49993  }
49994  assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
49995  assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
49996  return pPager->mxPgno;
49997}
49998
49999/*
50000** The following set of routines are used to disable the simulated
50001** I/O error mechanism.  These routines are used to avoid simulated
50002** errors in places where we do not care about errors.
50003**
50004** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
50005** and generate no code.
50006*/
50007#ifdef SQLITE_TEST
50008SQLITE_API extern int sqlite3_io_error_pending;
50009SQLITE_API extern int sqlite3_io_error_hit;
50010static int saved_cnt;
50011void disable_simulated_io_errors(void){
50012  saved_cnt = sqlite3_io_error_pending;
50013  sqlite3_io_error_pending = -1;
50014}
50015void enable_simulated_io_errors(void){
50016  sqlite3_io_error_pending = saved_cnt;
50017}
50018#else
50019# define disable_simulated_io_errors()
50020# define enable_simulated_io_errors()
50021#endif
50022
50023/*
50024** Read the first N bytes from the beginning of the file into memory
50025** that pDest points to.
50026**
50027** If the pager was opened on a transient file (zFilename==""), or
50028** opened on a file less than N bytes in size, the output buffer is
50029** zeroed and SQLITE_OK returned. The rationale for this is that this
50030** function is used to read database headers, and a new transient or
50031** zero sized database has a header than consists entirely of zeroes.
50032**
50033** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
50034** the error code is returned to the caller and the contents of the
50035** output buffer undefined.
50036*/
50037SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
50038  int rc = SQLITE_OK;
50039  memset(pDest, 0, N);
50040  assert( isOpen(pPager->fd) || pPager->tempFile );
50041
50042  /* This routine is only called by btree immediately after creating
50043  ** the Pager object.  There has not been an opportunity to transition
50044  ** to WAL mode yet.
50045  */
50046  assert( !pagerUseWal(pPager) );
50047
50048  if( isOpen(pPager->fd) ){
50049    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
50050    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
50051    if( rc==SQLITE_IOERR_SHORT_READ ){
50052      rc = SQLITE_OK;
50053    }
50054  }
50055  return rc;
50056}
50057
50058/*
50059** This function may only be called when a read-transaction is open on
50060** the pager. It returns the total number of pages in the database.
50061**
50062** However, if the file is between 1 and <page-size> bytes in size, then
50063** this is considered a 1 page file.
50064*/
50065SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
50066  assert( pPager->eState>=PAGER_READER );
50067  assert( pPager->eState!=PAGER_WRITER_FINISHED );
50068  *pnPage = (int)pPager->dbSize;
50069}
50070
50071
50072/*
50073** Try to obtain a lock of type locktype on the database file. If
50074** a similar or greater lock is already held, this function is a no-op
50075** (returning SQLITE_OK immediately).
50076**
50077** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
50078** the busy callback if the lock is currently not available. Repeat
50079** until the busy callback returns false or until the attempt to
50080** obtain the lock succeeds.
50081**
50082** Return SQLITE_OK on success and an error code if we cannot obtain
50083** the lock. If the lock is obtained successfully, set the Pager.state
50084** variable to locktype before returning.
50085*/
50086static int pager_wait_on_lock(Pager *pPager, int locktype){
50087  int rc;                              /* Return code */
50088
50089  /* Check that this is either a no-op (because the requested lock is
50090  ** already held), or one of the transitions that the busy-handler
50091  ** may be invoked during, according to the comment above
50092  ** sqlite3PagerSetBusyhandler().
50093  */
50094  assert( (pPager->eLock>=locktype)
50095       || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
50096       || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
50097  );
50098
50099  do {
50100    rc = pagerLockDb(pPager, locktype);
50101  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
50102  return rc;
50103}
50104
50105/*
50106** Function assertTruncateConstraint(pPager) checks that one of the
50107** following is true for all dirty pages currently in the page-cache:
50108**
50109**   a) The page number is less than or equal to the size of the
50110**      current database image, in pages, OR
50111**
50112**   b) if the page content were written at this time, it would not
50113**      be necessary to write the current content out to the sub-journal
50114**      (as determined by function subjRequiresPage()).
50115**
50116** If the condition asserted by this function were not true, and the
50117** dirty page were to be discarded from the cache via the pagerStress()
50118** routine, pagerStress() would not write the current page content to
50119** the database file. If a savepoint transaction were rolled back after
50120** this happened, the correct behavior would be to restore the current
50121** content of the page. However, since this content is not present in either
50122** the database file or the portion of the rollback journal and
50123** sub-journal rolled back the content could not be restored and the
50124** database image would become corrupt. It is therefore fortunate that
50125** this circumstance cannot arise.
50126*/
50127#if defined(SQLITE_DEBUG)
50128static void assertTruncateConstraintCb(PgHdr *pPg){
50129  assert( pPg->flags&PGHDR_DIRTY );
50130  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
50131}
50132static void assertTruncateConstraint(Pager *pPager){
50133  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
50134}
50135#else
50136# define assertTruncateConstraint(pPager)
50137#endif
50138
50139/*
50140** Truncate the in-memory database file image to nPage pages. This
50141** function does not actually modify the database file on disk. It
50142** just sets the internal state of the pager object so that the
50143** truncation will be done when the current transaction is committed.
50144**
50145** This function is only called right before committing a transaction.
50146** Once this function has been called, the transaction must either be
50147** rolled back or committed. It is not safe to call this function and
50148** then continue writing to the database.
50149*/
50150SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
50151  assert( pPager->dbSize>=nPage );
50152  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
50153  pPager->dbSize = nPage;
50154
50155  /* At one point the code here called assertTruncateConstraint() to
50156  ** ensure that all pages being truncated away by this operation are,
50157  ** if one or more savepoints are open, present in the savepoint
50158  ** journal so that they can be restored if the savepoint is rolled
50159  ** back. This is no longer necessary as this function is now only
50160  ** called right before committing a transaction. So although the
50161  ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
50162  ** they cannot be rolled back. So the assertTruncateConstraint() call
50163  ** is no longer correct. */
50164}
50165
50166
50167/*
50168** This function is called before attempting a hot-journal rollback. It
50169** syncs the journal file to disk, then sets pPager->journalHdr to the
50170** size of the journal file so that the pager_playback() routine knows
50171** that the entire journal file has been synced.
50172**
50173** Syncing a hot-journal to disk before attempting to roll it back ensures
50174** that if a power-failure occurs during the rollback, the process that
50175** attempts rollback following system recovery sees the same journal
50176** content as this process.
50177**
50178** If everything goes as planned, SQLITE_OK is returned. Otherwise,
50179** an SQLite error code.
50180*/
50181static int pagerSyncHotJournal(Pager *pPager){
50182  int rc = SQLITE_OK;
50183  if( !pPager->noSync ){
50184    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
50185  }
50186  if( rc==SQLITE_OK ){
50187    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
50188  }
50189  return rc;
50190}
50191
50192/*
50193** Obtain a reference to a memory mapped page object for page number pgno.
50194** The new object will use the pointer pData, obtained from xFetch().
50195** If successful, set *ppPage to point to the new page reference
50196** and return SQLITE_OK. Otherwise, return an SQLite error code and set
50197** *ppPage to zero.
50198**
50199** Page references obtained by calling this function should be released
50200** by calling pagerReleaseMapPage().
50201*/
50202static int pagerAcquireMapPage(
50203  Pager *pPager,                  /* Pager object */
50204  Pgno pgno,                      /* Page number */
50205  void *pData,                    /* xFetch()'d data for this page */
50206  PgHdr **ppPage                  /* OUT: Acquired page object */
50207){
50208  PgHdr *p;                       /* Memory mapped page to return */
50209
50210  if( pPager->pMmapFreelist ){
50211    *ppPage = p = pPager->pMmapFreelist;
50212    pPager->pMmapFreelist = p->pDirty;
50213    p->pDirty = 0;
50214    memset(p->pExtra, 0, pPager->nExtra);
50215  }else{
50216    *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
50217    if( p==0 ){
50218      sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
50219      return SQLITE_NOMEM_BKPT;
50220    }
50221    p->pExtra = (void *)&p[1];
50222    p->flags = PGHDR_MMAP;
50223    p->nRef = 1;
50224    p->pPager = pPager;
50225  }
50226
50227  assert( p->pExtra==(void *)&p[1] );
50228  assert( p->pPage==0 );
50229  assert( p->flags==PGHDR_MMAP );
50230  assert( p->pPager==pPager );
50231  assert( p->nRef==1 );
50232
50233  p->pgno = pgno;
50234  p->pData = pData;
50235  pPager->nMmapOut++;
50236
50237  return SQLITE_OK;
50238}
50239
50240/*
50241** Release a reference to page pPg. pPg must have been returned by an
50242** earlier call to pagerAcquireMapPage().
50243*/
50244static void pagerReleaseMapPage(PgHdr *pPg){
50245  Pager *pPager = pPg->pPager;
50246  pPager->nMmapOut--;
50247  pPg->pDirty = pPager->pMmapFreelist;
50248  pPager->pMmapFreelist = pPg;
50249
50250  assert( pPager->fd->pMethods->iVersion>=3 );
50251  sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
50252}
50253
50254/*
50255** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
50256*/
50257static void pagerFreeMapHdrs(Pager *pPager){
50258  PgHdr *p;
50259  PgHdr *pNext;
50260  for(p=pPager->pMmapFreelist; p; p=pNext){
50261    pNext = p->pDirty;
50262    sqlite3_free(p);
50263  }
50264}
50265
50266
50267/*
50268** Shutdown the page cache.  Free all memory and close all files.
50269**
50270** If a transaction was in progress when this routine is called, that
50271** transaction is rolled back.  All outstanding pages are invalidated
50272** and their memory is freed.  Any attempt to use a page associated
50273** with this page cache after this function returns will likely
50274** result in a coredump.
50275**
50276** This function always succeeds. If a transaction is active an attempt
50277** is made to roll it back. If an error occurs during the rollback
50278** a hot journal may be left in the filesystem but no error is returned
50279** to the caller.
50280*/
50281SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
50282  u8 *pTmp = (u8 *)pPager->pTmpSpace;
50283
50284  assert( assert_pager_state(pPager) );
50285  disable_simulated_io_errors();
50286  sqlite3BeginBenignMalloc();
50287  pagerFreeMapHdrs(pPager);
50288  /* pPager->errCode = 0; */
50289  pPager->exclusiveMode = 0;
50290#ifndef SQLITE_OMIT_WAL
50291  sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
50292  pPager->pWal = 0;
50293#endif
50294  pager_reset(pPager);
50295  if( MEMDB ){
50296    pager_unlock(pPager);
50297  }else{
50298    /* If it is open, sync the journal file before calling UnlockAndRollback.
50299    ** If this is not done, then an unsynced portion of the open journal
50300    ** file may be played back into the database. If a power failure occurs
50301    ** while this is happening, the database could become corrupt.
50302    **
50303    ** If an error occurs while trying to sync the journal, shift the pager
50304    ** into the ERROR state. This causes UnlockAndRollback to unlock the
50305    ** database and close the journal file without attempting to roll it
50306    ** back or finalize it. The next database user will have to do hot-journal
50307    ** rollback before accessing the database file.
50308    */
50309    if( isOpen(pPager->jfd) ){
50310      pager_error(pPager, pagerSyncHotJournal(pPager));
50311    }
50312    pagerUnlockAndRollback(pPager);
50313  }
50314  sqlite3EndBenignMalloc();
50315  enable_simulated_io_errors();
50316  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
50317  IOTRACE(("CLOSE %p\n", pPager))
50318  sqlite3OsClose(pPager->jfd);
50319  sqlite3OsClose(pPager->fd);
50320  sqlite3PageFree(pTmp);
50321  sqlite3PcacheClose(pPager->pPCache);
50322
50323#ifdef SQLITE_HAS_CODEC
50324  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
50325#endif
50326
50327  assert( !pPager->aSavepoint && !pPager->pInJournal );
50328  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
50329
50330  sqlite3_free(pPager);
50331  return SQLITE_OK;
50332}
50333
50334#if !defined(NDEBUG) || defined(SQLITE_TEST)
50335/*
50336** Return the page number for page pPg.
50337*/
50338SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
50339  return pPg->pgno;
50340}
50341#endif
50342
50343/*
50344** Increment the reference count for page pPg.
50345*/
50346SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
50347  sqlite3PcacheRef(pPg);
50348}
50349
50350/*
50351** Sync the journal. In other words, make sure all the pages that have
50352** been written to the journal have actually reached the surface of the
50353** disk and can be restored in the event of a hot-journal rollback.
50354**
50355** If the Pager.noSync flag is set, then this function is a no-op.
50356** Otherwise, the actions required depend on the journal-mode and the
50357** device characteristics of the file-system, as follows:
50358**
50359**   * If the journal file is an in-memory journal file, no action need
50360**     be taken.
50361**
50362**   * Otherwise, if the device does not support the SAFE_APPEND property,
50363**     then the nRec field of the most recently written journal header
50364**     is updated to contain the number of journal records that have
50365**     been written following it. If the pager is operating in full-sync
50366**     mode, then the journal file is synced before this field is updated.
50367**
50368**   * If the device does not support the SEQUENTIAL property, then
50369**     journal file is synced.
50370**
50371** Or, in pseudo-code:
50372**
50373**   if( NOT <in-memory journal> ){
50374**     if( NOT SAFE_APPEND ){
50375**       if( <full-sync mode> ) xSync(<journal file>);
50376**       <update nRec field>
50377**     }
50378**     if( NOT SEQUENTIAL ) xSync(<journal file>);
50379**   }
50380**
50381** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
50382** page currently held in memory before returning SQLITE_OK. If an IO
50383** error is encountered, then the IO error code is returned to the caller.
50384*/
50385static int syncJournal(Pager *pPager, int newHdr){
50386  int rc;                         /* Return code */
50387
50388  assert( pPager->eState==PAGER_WRITER_CACHEMOD
50389       || pPager->eState==PAGER_WRITER_DBMOD
50390  );
50391  assert( assert_pager_state(pPager) );
50392  assert( !pagerUseWal(pPager) );
50393
50394  rc = sqlite3PagerExclusiveLock(pPager);
50395  if( rc!=SQLITE_OK ) return rc;
50396
50397  if( !pPager->noSync ){
50398    assert( !pPager->tempFile );
50399    if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
50400      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
50401      assert( isOpen(pPager->jfd) );
50402
50403      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
50404        /* This block deals with an obscure problem. If the last connection
50405        ** that wrote to this database was operating in persistent-journal
50406        ** mode, then the journal file may at this point actually be larger
50407        ** than Pager.journalOff bytes. If the next thing in the journal
50408        ** file happens to be a journal-header (written as part of the
50409        ** previous connection's transaction), and a crash or power-failure
50410        ** occurs after nRec is updated but before this connection writes
50411        ** anything else to the journal file (or commits/rolls back its
50412        ** transaction), then SQLite may become confused when doing the
50413        ** hot-journal rollback following recovery. It may roll back all
50414        ** of this connections data, then proceed to rolling back the old,
50415        ** out-of-date data that follows it. Database corruption.
50416        **
50417        ** To work around this, if the journal file does appear to contain
50418        ** a valid header following Pager.journalOff, then write a 0x00
50419        ** byte to the start of it to prevent it from being recognized.
50420        **
50421        ** Variable iNextHdrOffset is set to the offset at which this
50422        ** problematic header will occur, if it exists. aMagic is used
50423        ** as a temporary buffer to inspect the first couple of bytes of
50424        ** the potential journal header.
50425        */
50426        i64 iNextHdrOffset;
50427        u8 aMagic[8];
50428        u8 zHeader[sizeof(aJournalMagic)+4];
50429
50430        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
50431        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
50432
50433        iNextHdrOffset = journalHdrOffset(pPager);
50434        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
50435        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
50436          static const u8 zerobyte = 0;
50437          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
50438        }
50439        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
50440          return rc;
50441        }
50442
50443        /* Write the nRec value into the journal file header. If in
50444        ** full-synchronous mode, sync the journal first. This ensures that
50445        ** all data has really hit the disk before nRec is updated to mark
50446        ** it as a candidate for rollback.
50447        **
50448        ** This is not required if the persistent media supports the
50449        ** SAFE_APPEND property. Because in this case it is not possible
50450        ** for garbage data to be appended to the file, the nRec field
50451        ** is populated with 0xFFFFFFFF when the journal header is written
50452        ** and never needs to be updated.
50453        */
50454        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
50455          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
50456          IOTRACE(("JSYNC %p\n", pPager))
50457          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
50458          if( rc!=SQLITE_OK ) return rc;
50459        }
50460        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
50461        rc = sqlite3OsWrite(
50462            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
50463        );
50464        if( rc!=SQLITE_OK ) return rc;
50465      }
50466      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
50467        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
50468        IOTRACE(("JSYNC %p\n", pPager))
50469        rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
50470          (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
50471        );
50472        if( rc!=SQLITE_OK ) return rc;
50473      }
50474
50475      pPager->journalHdr = pPager->journalOff;
50476      if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
50477        pPager->nRec = 0;
50478        rc = writeJournalHdr(pPager);
50479        if( rc!=SQLITE_OK ) return rc;
50480      }
50481    }else{
50482      pPager->journalHdr = pPager->journalOff;
50483    }
50484  }
50485
50486  /* Unless the pager is in noSync mode, the journal file was just
50487  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
50488  ** all pages.
50489  */
50490  sqlite3PcacheClearSyncFlags(pPager->pPCache);
50491  pPager->eState = PAGER_WRITER_DBMOD;
50492  assert( assert_pager_state(pPager) );
50493  return SQLITE_OK;
50494}
50495
50496/*
50497** The argument is the first in a linked list of dirty pages connected
50498** by the PgHdr.pDirty pointer. This function writes each one of the
50499** in-memory pages in the list to the database file. The argument may
50500** be NULL, representing an empty list. In this case this function is
50501** a no-op.
50502**
50503** The pager must hold at least a RESERVED lock when this function
50504** is called. Before writing anything to the database file, this lock
50505** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
50506** SQLITE_BUSY is returned and no data is written to the database file.
50507**
50508** If the pager is a temp-file pager and the actual file-system file
50509** is not yet open, it is created and opened before any data is
50510** written out.
50511**
50512** Once the lock has been upgraded and, if necessary, the file opened,
50513** the pages are written out to the database file in list order. Writing
50514** a page is skipped if it meets either of the following criteria:
50515**
50516**   * The page number is greater than Pager.dbSize, or
50517**   * The PGHDR_DONT_WRITE flag is set on the page.
50518**
50519** If writing out a page causes the database file to grow, Pager.dbFileSize
50520** is updated accordingly. If page 1 is written out, then the value cached
50521** in Pager.dbFileVers[] is updated to match the new value stored in
50522** the database file.
50523**
50524** If everything is successful, SQLITE_OK is returned. If an IO error
50525** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
50526** be obtained, SQLITE_BUSY is returned.
50527*/
50528static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
50529  int rc = SQLITE_OK;                  /* Return code */
50530
50531  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
50532  assert( !pagerUseWal(pPager) );
50533  assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
50534  assert( pPager->eLock==EXCLUSIVE_LOCK );
50535  assert( isOpen(pPager->fd) || pList->pDirty==0 );
50536
50537  /* If the file is a temp-file has not yet been opened, open it now. It
50538  ** is not possible for rc to be other than SQLITE_OK if this branch
50539  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
50540  */
50541  if( !isOpen(pPager->fd) ){
50542    assert( pPager->tempFile && rc==SQLITE_OK );
50543    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
50544  }
50545
50546  /* Before the first write, give the VFS a hint of what the final
50547  ** file size will be.
50548  */
50549  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
50550  if( rc==SQLITE_OK
50551   && pPager->dbHintSize<pPager->dbSize
50552   && (pList->pDirty || pList->pgno>pPager->dbHintSize)
50553  ){
50554    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
50555    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
50556    pPager->dbHintSize = pPager->dbSize;
50557  }
50558
50559  while( rc==SQLITE_OK && pList ){
50560    Pgno pgno = pList->pgno;
50561
50562    /* If there are dirty pages in the page cache with page numbers greater
50563    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
50564    ** make the file smaller (presumably by auto-vacuum code). Do not write
50565    ** any such pages to the file.
50566    **
50567    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
50568    ** set (set by sqlite3PagerDontWrite()).
50569    */
50570    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
50571      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
50572      char *pData;                                   /* Data to write */
50573
50574      assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
50575      if( pList->pgno==1 ) pager_write_changecounter(pList);
50576
50577      /* Encode the database */
50578      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
50579
50580      /* Write out the page data. */
50581      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
50582
50583      /* If page 1 was just written, update Pager.dbFileVers to match
50584      ** the value now stored in the database file. If writing this
50585      ** page caused the database file to grow, update dbFileSize.
50586      */
50587      if( pgno==1 ){
50588        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
50589      }
50590      if( pgno>pPager->dbFileSize ){
50591        pPager->dbFileSize = pgno;
50592      }
50593      pPager->aStat[PAGER_STAT_WRITE]++;
50594
50595      /* Update any backup objects copying the contents of this pager. */
50596      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
50597
50598      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
50599                   PAGERID(pPager), pgno, pager_pagehash(pList)));
50600      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
50601      PAGER_INCR(sqlite3_pager_writedb_count);
50602    }else{
50603      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
50604    }
50605    pager_set_pagehash(pList);
50606    pList = pList->pDirty;
50607  }
50608
50609  return rc;
50610}
50611
50612/*
50613** Ensure that the sub-journal file is open. If it is already open, this
50614** function is a no-op.
50615**
50616** SQLITE_OK is returned if everything goes according to plan. An
50617** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
50618** fails.
50619*/
50620static int openSubJournal(Pager *pPager){
50621  int rc = SQLITE_OK;
50622  if( !isOpen(pPager->sjfd) ){
50623    const int flags =  SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
50624      | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
50625      | SQLITE_OPEN_DELETEONCLOSE;
50626    int nStmtSpill = sqlite3Config.nStmtSpill;
50627    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
50628      nStmtSpill = -1;
50629    }
50630    rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
50631  }
50632  return rc;
50633}
50634
50635/*
50636** Append a record of the current state of page pPg to the sub-journal.
50637**
50638** If successful, set the bit corresponding to pPg->pgno in the bitvecs
50639** for all open savepoints before returning.
50640**
50641** This function returns SQLITE_OK if everything is successful, an IO
50642** error code if the attempt to write to the sub-journal fails, or
50643** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
50644** bitvec.
50645*/
50646static int subjournalPage(PgHdr *pPg){
50647  int rc = SQLITE_OK;
50648  Pager *pPager = pPg->pPager;
50649  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
50650
50651    /* Open the sub-journal, if it has not already been opened */
50652    assert( pPager->useJournal );
50653    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
50654    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
50655    assert( pagerUseWal(pPager)
50656         || pageInJournal(pPager, pPg)
50657         || pPg->pgno>pPager->dbOrigSize
50658    );
50659    rc = openSubJournal(pPager);
50660
50661    /* If the sub-journal was opened successfully (or was already open),
50662    ** write the journal record into the file.  */
50663    if( rc==SQLITE_OK ){
50664      void *pData = pPg->pData;
50665      i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
50666      char *pData2;
50667
50668      CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
50669      PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
50670      rc = write32bits(pPager->sjfd, offset, pPg->pgno);
50671      if( rc==SQLITE_OK ){
50672        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
50673      }
50674    }
50675  }
50676  if( rc==SQLITE_OK ){
50677    pPager->nSubRec++;
50678    assert( pPager->nSavepoint>0 );
50679    rc = addToSavepointBitvecs(pPager, pPg->pgno);
50680  }
50681  return rc;
50682}
50683static int subjournalPageIfRequired(PgHdr *pPg){
50684  if( subjRequiresPage(pPg) ){
50685    return subjournalPage(pPg);
50686  }else{
50687    return SQLITE_OK;
50688  }
50689}
50690
50691/*
50692** This function is called by the pcache layer when it has reached some
50693** soft memory limit. The first argument is a pointer to a Pager object
50694** (cast as a void*). The pager is always 'purgeable' (not an in-memory
50695** database). The second argument is a reference to a page that is
50696** currently dirty but has no outstanding references. The page
50697** is always associated with the Pager object passed as the first
50698** argument.
50699**
50700** The job of this function is to make pPg clean by writing its contents
50701** out to the database file, if possible. This may involve syncing the
50702** journal file.
50703**
50704** If successful, sqlite3PcacheMakeClean() is called on the page and
50705** SQLITE_OK returned. If an IO error occurs while trying to make the
50706** page clean, the IO error code is returned. If the page cannot be
50707** made clean for some other reason, but no error occurs, then SQLITE_OK
50708** is returned by sqlite3PcacheMakeClean() is not called.
50709*/
50710static int pagerStress(void *p, PgHdr *pPg){
50711  Pager *pPager = (Pager *)p;
50712  int rc = SQLITE_OK;
50713
50714  assert( pPg->pPager==pPager );
50715  assert( pPg->flags&PGHDR_DIRTY );
50716
50717  /* The doNotSpill NOSYNC bit is set during times when doing a sync of
50718  ** journal (and adding a new header) is not allowed.  This occurs
50719  ** during calls to sqlite3PagerWrite() while trying to journal multiple
50720  ** pages belonging to the same sector.
50721  **
50722  ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
50723  ** regardless of whether or not a sync is required.  This is set during
50724  ** a rollback or by user request, respectively.
50725  **
50726  ** Spilling is also prohibited when in an error state since that could
50727  ** lead to database corruption.   In the current implementation it
50728  ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
50729  ** while in the error state, hence it is impossible for this routine to
50730  ** be called in the error state.  Nevertheless, we include a NEVER()
50731  ** test for the error state as a safeguard against future changes.
50732  */
50733  if( NEVER(pPager->errCode) ) return SQLITE_OK;
50734  testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
50735  testcase( pPager->doNotSpill & SPILLFLAG_OFF );
50736  testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
50737  if( pPager->doNotSpill
50738   && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
50739      || (pPg->flags & PGHDR_NEED_SYNC)!=0)
50740  ){
50741    return SQLITE_OK;
50742  }
50743
50744  pPg->pDirty = 0;
50745  if( pagerUseWal(pPager) ){
50746    /* Write a single frame for this page to the log. */
50747    rc = subjournalPageIfRequired(pPg);
50748    if( rc==SQLITE_OK ){
50749      rc = pagerWalFrames(pPager, pPg, 0, 0);
50750    }
50751  }else{
50752
50753    /* Sync the journal file if required. */
50754    if( pPg->flags&PGHDR_NEED_SYNC
50755     || pPager->eState==PAGER_WRITER_CACHEMOD
50756    ){
50757      rc = syncJournal(pPager, 1);
50758    }
50759
50760    /* Write the contents of the page out to the database file. */
50761    if( rc==SQLITE_OK ){
50762      assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
50763      rc = pager_write_pagelist(pPager, pPg);
50764    }
50765  }
50766
50767  /* Mark the page as clean. */
50768  if( rc==SQLITE_OK ){
50769    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
50770    sqlite3PcacheMakeClean(pPg);
50771  }
50772
50773  return pager_error(pPager, rc);
50774}
50775
50776/*
50777** Flush all unreferenced dirty pages to disk.
50778*/
50779SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
50780  int rc = pPager->errCode;
50781  if( !MEMDB ){
50782    PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
50783    assert( assert_pager_state(pPager) );
50784    while( rc==SQLITE_OK && pList ){
50785      PgHdr *pNext = pList->pDirty;
50786      if( pList->nRef==0 ){
50787        rc = pagerStress((void*)pPager, pList);
50788      }
50789      pList = pNext;
50790    }
50791  }
50792
50793  return rc;
50794}
50795
50796/*
50797** Allocate and initialize a new Pager object and put a pointer to it
50798** in *ppPager. The pager should eventually be freed by passing it
50799** to sqlite3PagerClose().
50800**
50801** The zFilename argument is the path to the database file to open.
50802** If zFilename is NULL then a randomly-named temporary file is created
50803** and used as the file to be cached. Temporary files are be deleted
50804** automatically when they are closed. If zFilename is ":memory:" then
50805** all information is held in cache. It is never written to disk.
50806** This can be used to implement an in-memory database.
50807**
50808** The nExtra parameter specifies the number of bytes of space allocated
50809** along with each page reference. This space is available to the user
50810** via the sqlite3PagerGetExtra() API.
50811**
50812** The flags argument is used to specify properties that affect the
50813** operation of the pager. It should be passed some bitwise combination
50814** of the PAGER_* flags.
50815**
50816** The vfsFlags parameter is a bitmask to pass to the flags parameter
50817** of the xOpen() method of the supplied VFS when opening files.
50818**
50819** If the pager object is allocated and the specified file opened
50820** successfully, SQLITE_OK is returned and *ppPager set to point to
50821** the new pager object. If an error occurs, *ppPager is set to NULL
50822** and error code returned. This function may return SQLITE_NOMEM
50823** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
50824** various SQLITE_IO_XXX errors.
50825*/
50826SQLITE_PRIVATE int sqlite3PagerOpen(
50827  sqlite3_vfs *pVfs,       /* The virtual file system to use */
50828  Pager **ppPager,         /* OUT: Return the Pager structure here */
50829  const char *zFilename,   /* Name of the database file to open */
50830  int nExtra,              /* Extra bytes append to each in-memory page */
50831  int flags,               /* flags controlling this file */
50832  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
50833  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
50834){
50835  u8 *pPtr;
50836  Pager *pPager = 0;       /* Pager object to allocate and return */
50837  int rc = SQLITE_OK;      /* Return code */
50838  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
50839  int memDb = 0;           /* True if this is an in-memory file */
50840  int readOnly = 0;        /* True if this is a read-only file */
50841  int journalFileSize;     /* Bytes to allocate for each journal fd */
50842  char *zPathname = 0;     /* Full path to database file */
50843  int nPathname = 0;       /* Number of bytes in zPathname */
50844  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
50845  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
50846  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
50847  const char *zUri = 0;    /* URI args to copy */
50848  int nUri = 0;            /* Number of bytes of URI args at *zUri */
50849
50850  /* Figure out how much space is required for each journal file-handle
50851  ** (there are two of them, the main journal and the sub-journal).  */
50852  journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
50853
50854  /* Set the output variable to NULL in case an error occurs. */
50855  *ppPager = 0;
50856
50857#ifndef SQLITE_OMIT_MEMORYDB
50858  if( flags & PAGER_MEMORY ){
50859    memDb = 1;
50860    if( zFilename && zFilename[0] ){
50861      zPathname = sqlite3DbStrDup(0, zFilename);
50862      if( zPathname==0  ) return SQLITE_NOMEM_BKPT;
50863      nPathname = sqlite3Strlen30(zPathname);
50864      zFilename = 0;
50865    }
50866  }
50867#endif
50868
50869  /* Compute and store the full pathname in an allocated buffer pointed
50870  ** to by zPathname, length nPathname. Or, if this is a temporary file,
50871  ** leave both nPathname and zPathname set to 0.
50872  */
50873  if( zFilename && zFilename[0] ){
50874    const char *z;
50875    nPathname = pVfs->mxPathname+1;
50876    zPathname = sqlite3DbMallocRaw(0, nPathname*2);
50877    if( zPathname==0 ){
50878      return SQLITE_NOMEM_BKPT;
50879    }
50880    zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
50881    rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
50882    nPathname = sqlite3Strlen30(zPathname);
50883    z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
50884    while( *z ){
50885      z += sqlite3Strlen30(z)+1;
50886      z += sqlite3Strlen30(z)+1;
50887    }
50888    nUri = (int)(&z[1] - zUri);
50889    assert( nUri>=0 );
50890    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
50891      /* This branch is taken when the journal path required by
50892      ** the database being opened will be more than pVfs->mxPathname
50893      ** bytes in length. This means the database cannot be opened,
50894      ** as it will not be possible to open the journal file or even
50895      ** check for a hot-journal before reading.
50896      */
50897      rc = SQLITE_CANTOPEN_BKPT;
50898    }
50899    if( rc!=SQLITE_OK ){
50900      sqlite3DbFree(0, zPathname);
50901      return rc;
50902    }
50903  }
50904
50905  /* Allocate memory for the Pager structure, PCache object, the
50906  ** three file descriptors, the database file name and the journal
50907  ** file name. The layout in memory is as follows:
50908  **
50909  **     Pager object                    (sizeof(Pager) bytes)
50910  **     PCache object                   (sqlite3PcacheSize() bytes)
50911  **     Database file handle            (pVfs->szOsFile bytes)
50912  **     Sub-journal file handle         (journalFileSize bytes)
50913  **     Main journal file handle        (journalFileSize bytes)
50914  **     Database file name              (nPathname+1 bytes)
50915  **     Journal file name               (nPathname+8+1 bytes)
50916  */
50917  pPtr = (u8 *)sqlite3MallocZero(
50918    ROUND8(sizeof(*pPager)) +      /* Pager structure */
50919    ROUND8(pcacheSize) +           /* PCache object */
50920    ROUND8(pVfs->szOsFile) +       /* The main db file */
50921    journalFileSize * 2 +          /* The two journal files */
50922    nPathname + 1 + nUri +         /* zFilename */
50923    nPathname + 8 + 2              /* zJournal */
50924#ifndef SQLITE_OMIT_WAL
50925    + nPathname + 4 + 2            /* zWal */
50926#endif
50927  );
50928  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
50929  if( !pPtr ){
50930    sqlite3DbFree(0, zPathname);
50931    return SQLITE_NOMEM_BKPT;
50932  }
50933  pPager =              (Pager*)(pPtr);
50934  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
50935  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
50936  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
50937  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
50938  pPager->zFilename =    (char*)(pPtr += journalFileSize);
50939  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
50940
50941  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
50942  if( zPathname ){
50943    assert( nPathname>0 );
50944    pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
50945    memcpy(pPager->zFilename, zPathname, nPathname);
50946    if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
50947    memcpy(pPager->zJournal, zPathname, nPathname);
50948    memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
50949    sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
50950#ifndef SQLITE_OMIT_WAL
50951    pPager->zWal = &pPager->zJournal[nPathname+8+1];
50952    memcpy(pPager->zWal, zPathname, nPathname);
50953    memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
50954    sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
50955#endif
50956    sqlite3DbFree(0, zPathname);
50957  }
50958  pPager->pVfs = pVfs;
50959  pPager->vfsFlags = vfsFlags;
50960
50961  /* Open the pager file.
50962  */
50963  if( zFilename && zFilename[0] ){
50964    int fout = 0;                    /* VFS flags returned by xOpen() */
50965    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
50966    assert( !memDb );
50967    readOnly = (fout&SQLITE_OPEN_READONLY);
50968
50969    /* If the file was successfully opened for read/write access,
50970    ** choose a default page size in case we have to create the
50971    ** database file. The default page size is the maximum of:
50972    **
50973    **    + SQLITE_DEFAULT_PAGE_SIZE,
50974    **    + The value returned by sqlite3OsSectorSize()
50975    **    + The largest page size that can be written atomically.
50976    */
50977    if( rc==SQLITE_OK ){
50978      int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
50979      if( !readOnly ){
50980        setSectorSize(pPager);
50981        assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
50982        if( szPageDflt<pPager->sectorSize ){
50983          if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
50984            szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
50985          }else{
50986            szPageDflt = (u32)pPager->sectorSize;
50987          }
50988        }
50989#ifdef SQLITE_ENABLE_ATOMIC_WRITE
50990        {
50991          int ii;
50992          assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
50993          assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
50994          assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
50995          for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
50996            if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
50997              szPageDflt = ii;
50998            }
50999          }
51000        }
51001#endif
51002      }
51003      pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
51004      if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
51005       || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
51006          vfsFlags |= SQLITE_OPEN_READONLY;
51007          goto act_like_temp_file;
51008      }
51009    }
51010  }else{
51011    /* If a temporary file is requested, it is not opened immediately.
51012    ** In this case we accept the default page size and delay actually
51013    ** opening the file until the first call to OsWrite().
51014    **
51015    ** This branch is also run for an in-memory database. An in-memory
51016    ** database is the same as a temp-file that is never written out to
51017    ** disk and uses an in-memory rollback journal.
51018    **
51019    ** This branch also runs for files marked as immutable.
51020    */
51021act_like_temp_file:
51022    tempFile = 1;
51023    pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
51024    pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE mode */
51025    pPager->noLock = 1;                /* Do no locking */
51026    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
51027  }
51028
51029  /* The following call to PagerSetPagesize() serves to set the value of
51030  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
51031  */
51032  if( rc==SQLITE_OK ){
51033    assert( pPager->memDb==0 );
51034    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
51035    testcase( rc!=SQLITE_OK );
51036  }
51037
51038  /* Initialize the PCache object. */
51039  if( rc==SQLITE_OK ){
51040    assert( nExtra<1000 );
51041    nExtra = ROUND8(nExtra);
51042    rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
51043                       !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
51044  }
51045
51046  /* If an error occurred above, free the  Pager structure and close the file.
51047  */
51048  if( rc!=SQLITE_OK ){
51049    sqlite3OsClose(pPager->fd);
51050    sqlite3PageFree(pPager->pTmpSpace);
51051    sqlite3_free(pPager);
51052    return rc;
51053  }
51054
51055  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
51056  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
51057
51058  pPager->useJournal = (u8)useJournal;
51059  /* pPager->stmtOpen = 0; */
51060  /* pPager->stmtInUse = 0; */
51061  /* pPager->nRef = 0; */
51062  /* pPager->stmtSize = 0; */
51063  /* pPager->stmtJSize = 0; */
51064  /* pPager->nPage = 0; */
51065  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
51066  /* pPager->state = PAGER_UNLOCK; */
51067  /* pPager->errMask = 0; */
51068  pPager->tempFile = (u8)tempFile;
51069  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
51070          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
51071  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
51072  pPager->exclusiveMode = (u8)tempFile;
51073  pPager->changeCountDone = pPager->tempFile;
51074  pPager->memDb = (u8)memDb;
51075  pPager->readOnly = (u8)readOnly;
51076  assert( useJournal || pPager->tempFile );
51077  pPager->noSync = pPager->tempFile;
51078  if( pPager->noSync ){
51079    assert( pPager->fullSync==0 );
51080    assert( pPager->extraSync==0 );
51081    assert( pPager->syncFlags==0 );
51082    assert( pPager->walSyncFlags==0 );
51083    assert( pPager->ckptSyncFlags==0 );
51084  }else{
51085    pPager->fullSync = 1;
51086    pPager->extraSync = 0;
51087    pPager->syncFlags = SQLITE_SYNC_NORMAL;
51088    pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
51089    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
51090  }
51091  /* pPager->pFirst = 0; */
51092  /* pPager->pFirstSynced = 0; */
51093  /* pPager->pLast = 0; */
51094  pPager->nExtra = (u16)nExtra;
51095  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
51096  assert( isOpen(pPager->fd) || tempFile );
51097  setSectorSize(pPager);
51098  if( !useJournal ){
51099    pPager->journalMode = PAGER_JOURNALMODE_OFF;
51100  }else if( memDb ){
51101    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
51102  }
51103  /* pPager->xBusyHandler = 0; */
51104  /* pPager->pBusyHandlerArg = 0; */
51105  pPager->xReiniter = xReinit;
51106  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
51107  /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
51108
51109  *ppPager = pPager;
51110  return SQLITE_OK;
51111}
51112
51113
51114/* Verify that the database file has not be deleted or renamed out from
51115** under the pager.  Return SQLITE_OK if the database is still were it ought
51116** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
51117** code from sqlite3OsAccess()) if the database has gone missing.
51118*/
51119static int databaseIsUnmoved(Pager *pPager){
51120  int bHasMoved = 0;
51121  int rc;
51122
51123  if( pPager->tempFile ) return SQLITE_OK;
51124  if( pPager->dbSize==0 ) return SQLITE_OK;
51125  assert( pPager->zFilename && pPager->zFilename[0] );
51126  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
51127  if( rc==SQLITE_NOTFOUND ){
51128    /* If the HAS_MOVED file-control is unimplemented, assume that the file
51129    ** has not been moved.  That is the historical behavior of SQLite: prior to
51130    ** version 3.8.3, it never checked */
51131    rc = SQLITE_OK;
51132  }else if( rc==SQLITE_OK && bHasMoved ){
51133    rc = SQLITE_READONLY_DBMOVED;
51134  }
51135  return rc;
51136}
51137
51138
51139/*
51140** This function is called after transitioning from PAGER_UNLOCK to
51141** PAGER_SHARED state. It tests if there is a hot journal present in
51142** the file-system for the given pager. A hot journal is one that
51143** needs to be played back. According to this function, a hot-journal
51144** file exists if the following criteria are met:
51145**
51146**   * The journal file exists in the file system, and
51147**   * No process holds a RESERVED or greater lock on the database file, and
51148**   * The database file itself is greater than 0 bytes in size, and
51149**   * The first byte of the journal file exists and is not 0x00.
51150**
51151** If the current size of the database file is 0 but a journal file
51152** exists, that is probably an old journal left over from a prior
51153** database with the same name. In this case the journal file is
51154** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
51155** is returned.
51156**
51157** This routine does not check if there is a master journal filename
51158** at the end of the file. If there is, and that master journal file
51159** does not exist, then the journal file is not really hot. In this
51160** case this routine will return a false-positive. The pager_playback()
51161** routine will discover that the journal file is not really hot and
51162** will not roll it back.
51163**
51164** If a hot-journal file is found to exist, *pExists is set to 1 and
51165** SQLITE_OK returned. If no hot-journal file is present, *pExists is
51166** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
51167** to determine whether or not a hot-journal file exists, the IO error
51168** code is returned and the value of *pExists is undefined.
51169*/
51170static int hasHotJournal(Pager *pPager, int *pExists){
51171  sqlite3_vfs * const pVfs = pPager->pVfs;
51172  int rc = SQLITE_OK;           /* Return code */
51173  int exists = 1;               /* True if a journal file is present */
51174  int jrnlOpen = !!isOpen(pPager->jfd);
51175
51176  assert( pPager->useJournal );
51177  assert( isOpen(pPager->fd) );
51178  assert( pPager->eState==PAGER_OPEN );
51179
51180  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
51181    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
51182  ));
51183
51184  *pExists = 0;
51185  if( !jrnlOpen ){
51186    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
51187  }
51188  if( rc==SQLITE_OK && exists ){
51189    int locked = 0;             /* True if some process holds a RESERVED lock */
51190
51191    /* Race condition here:  Another process might have been holding the
51192    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
51193    ** call above, but then delete the journal and drop the lock before
51194    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
51195    ** is the case, this routine might think there is a hot journal when
51196    ** in fact there is none.  This results in a false-positive which will
51197    ** be dealt with by the playback routine.  Ticket #3883.
51198    */
51199    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
51200    if( rc==SQLITE_OK && !locked ){
51201      Pgno nPage;                 /* Number of pages in database file */
51202
51203      assert( pPager->tempFile==0 );
51204      rc = pagerPagecount(pPager, &nPage);
51205      if( rc==SQLITE_OK ){
51206        /* If the database is zero pages in size, that means that either (1) the
51207        ** journal is a remnant from a prior database with the same name where
51208        ** the database file but not the journal was deleted, or (2) the initial
51209        ** transaction that populates a new database is being rolled back.
51210        ** In either case, the journal file can be deleted.  However, take care
51211        ** not to delete the journal file if it is already open due to
51212        ** journal_mode=PERSIST.
51213        */
51214        if( nPage==0 && !jrnlOpen ){
51215          sqlite3BeginBenignMalloc();
51216          if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
51217            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
51218            if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
51219          }
51220          sqlite3EndBenignMalloc();
51221        }else{
51222          /* The journal file exists and no other connection has a reserved
51223          ** or greater lock on the database file. Now check that there is
51224          ** at least one non-zero bytes at the start of the journal file.
51225          ** If there is, then we consider this journal to be hot. If not,
51226          ** it can be ignored.
51227          */
51228          if( !jrnlOpen ){
51229            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
51230            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
51231          }
51232          if( rc==SQLITE_OK ){
51233            u8 first = 0;
51234            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
51235            if( rc==SQLITE_IOERR_SHORT_READ ){
51236              rc = SQLITE_OK;
51237            }
51238            if( !jrnlOpen ){
51239              sqlite3OsClose(pPager->jfd);
51240            }
51241            *pExists = (first!=0);
51242          }else if( rc==SQLITE_CANTOPEN ){
51243            /* If we cannot open the rollback journal file in order to see if
51244            ** it has a zero header, that might be due to an I/O error, or
51245            ** it might be due to the race condition described above and in
51246            ** ticket #3883.  Either way, assume that the journal is hot.
51247            ** This might be a false positive.  But if it is, then the
51248            ** automatic journal playback and recovery mechanism will deal
51249            ** with it under an EXCLUSIVE lock where we do not need to
51250            ** worry so much with race conditions.
51251            */
51252            *pExists = 1;
51253            rc = SQLITE_OK;
51254          }
51255        }
51256      }
51257    }
51258  }
51259
51260  return rc;
51261}
51262
51263/*
51264** This function is called to obtain a shared lock on the database file.
51265** It is illegal to call sqlite3PagerGet() until after this function
51266** has been successfully called. If a shared-lock is already held when
51267** this function is called, it is a no-op.
51268**
51269** The following operations are also performed by this function.
51270**
51271**   1) If the pager is currently in PAGER_OPEN state (no lock held
51272**      on the database file), then an attempt is made to obtain a
51273**      SHARED lock on the database file. Immediately after obtaining
51274**      the SHARED lock, the file-system is checked for a hot-journal,
51275**      which is played back if present. Following any hot-journal
51276**      rollback, the contents of the cache are validated by checking
51277**      the 'change-counter' field of the database file header and
51278**      discarded if they are found to be invalid.
51279**
51280**   2) If the pager is running in exclusive-mode, and there are currently
51281**      no outstanding references to any pages, and is in the error state,
51282**      then an attempt is made to clear the error state by discarding
51283**      the contents of the page cache and rolling back any open journal
51284**      file.
51285**
51286** If everything is successful, SQLITE_OK is returned. If an IO error
51287** occurs while locking the database, checking for a hot-journal file or
51288** rolling back a journal file, the IO error code is returned.
51289*/
51290SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
51291  int rc = SQLITE_OK;                /* Return code */
51292
51293  /* This routine is only called from b-tree and only when there are no
51294  ** outstanding pages. This implies that the pager state should either
51295  ** be OPEN or READER. READER is only possible if the pager is or was in
51296  ** exclusive access mode.  */
51297  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
51298  assert( assert_pager_state(pPager) );
51299  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
51300  assert( pPager->errCode==SQLITE_OK );
51301
51302  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
51303    int bHotJournal = 1;          /* True if there exists a hot journal-file */
51304
51305    assert( !MEMDB );
51306    assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
51307
51308    rc = pager_wait_on_lock(pPager, SHARED_LOCK);
51309    if( rc!=SQLITE_OK ){
51310      assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
51311      goto failed;
51312    }
51313
51314    /* If a journal file exists, and there is no RESERVED lock on the
51315    ** database file, then it either needs to be played back or deleted.
51316    */
51317    if( pPager->eLock<=SHARED_LOCK ){
51318      rc = hasHotJournal(pPager, &bHotJournal);
51319    }
51320    if( rc!=SQLITE_OK ){
51321      goto failed;
51322    }
51323    if( bHotJournal ){
51324      if( pPager->readOnly ){
51325        rc = SQLITE_READONLY_ROLLBACK;
51326        goto failed;
51327      }
51328
51329      /* Get an EXCLUSIVE lock on the database file. At this point it is
51330      ** important that a RESERVED lock is not obtained on the way to the
51331      ** EXCLUSIVE lock. If it were, another process might open the
51332      ** database file, detect the RESERVED lock, and conclude that the
51333      ** database is safe to read while this process is still rolling the
51334      ** hot-journal back.
51335      **
51336      ** Because the intermediate RESERVED lock is not requested, any
51337      ** other process attempting to access the database file will get to
51338      ** this point in the code and fail to obtain its own EXCLUSIVE lock
51339      ** on the database file.
51340      **
51341      ** Unless the pager is in locking_mode=exclusive mode, the lock is
51342      ** downgraded to SHARED_LOCK before this function returns.
51343      */
51344      rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
51345      if( rc!=SQLITE_OK ){
51346        goto failed;
51347      }
51348
51349      /* If it is not already open and the file exists on disk, open the
51350      ** journal for read/write access. Write access is required because
51351      ** in exclusive-access mode the file descriptor will be kept open
51352      ** and possibly used for a transaction later on. Also, write-access
51353      ** is usually required to finalize the journal in journal_mode=persist
51354      ** mode (and also for journal_mode=truncate on some systems).
51355      **
51356      ** If the journal does not exist, it usually means that some
51357      ** other connection managed to get in and roll it back before
51358      ** this connection obtained the exclusive lock above. Or, it
51359      ** may mean that the pager was in the error-state when this
51360      ** function was called and the journal file does not exist.
51361      */
51362      if( !isOpen(pPager->jfd) ){
51363        sqlite3_vfs * const pVfs = pPager->pVfs;
51364        int bExists;              /* True if journal file exists */
51365        rc = sqlite3OsAccess(
51366            pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
51367        if( rc==SQLITE_OK && bExists ){
51368          int fout = 0;
51369          int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
51370          assert( !pPager->tempFile );
51371          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
51372          assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
51373          if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
51374            rc = SQLITE_CANTOPEN_BKPT;
51375            sqlite3OsClose(pPager->jfd);
51376          }
51377        }
51378      }
51379
51380      /* Playback and delete the journal.  Drop the database write
51381      ** lock and reacquire the read lock. Purge the cache before
51382      ** playing back the hot-journal so that we don't end up with
51383      ** an inconsistent cache.  Sync the hot journal before playing
51384      ** it back since the process that crashed and left the hot journal
51385      ** probably did not sync it and we are required to always sync
51386      ** the journal before playing it back.
51387      */
51388      if( isOpen(pPager->jfd) ){
51389        assert( rc==SQLITE_OK );
51390        rc = pagerSyncHotJournal(pPager);
51391        if( rc==SQLITE_OK ){
51392          rc = pager_playback(pPager, !pPager->tempFile);
51393          pPager->eState = PAGER_OPEN;
51394        }
51395      }else if( !pPager->exclusiveMode ){
51396        pagerUnlockDb(pPager, SHARED_LOCK);
51397      }
51398
51399      if( rc!=SQLITE_OK ){
51400        /* This branch is taken if an error occurs while trying to open
51401        ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
51402        ** pager_unlock() routine will be called before returning to unlock
51403        ** the file. If the unlock attempt fails, then Pager.eLock must be
51404        ** set to UNKNOWN_LOCK (see the comment above the #define for
51405        ** UNKNOWN_LOCK above for an explanation).
51406        **
51407        ** In order to get pager_unlock() to do this, set Pager.eState to
51408        ** PAGER_ERROR now. This is not actually counted as a transition
51409        ** to ERROR state in the state diagram at the top of this file,
51410        ** since we know that the same call to pager_unlock() will very
51411        ** shortly transition the pager object to the OPEN state. Calling
51412        ** assert_pager_state() would fail now, as it should not be possible
51413        ** to be in ERROR state when there are zero outstanding page
51414        ** references.
51415        */
51416        pager_error(pPager, rc);
51417        goto failed;
51418      }
51419
51420      assert( pPager->eState==PAGER_OPEN );
51421      assert( (pPager->eLock==SHARED_LOCK)
51422           || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
51423      );
51424    }
51425
51426    if( !pPager->tempFile && pPager->hasHeldSharedLock ){
51427      /* The shared-lock has just been acquired then check to
51428      ** see if the database has been modified.  If the database has changed,
51429      ** flush the cache.  The hasHeldSharedLock flag prevents this from
51430      ** occurring on the very first access to a file, in order to save a
51431      ** single unnecessary sqlite3OsRead() call at the start-up.
51432      **
51433      ** Database changes are detected by looking at 15 bytes beginning
51434      ** at offset 24 into the file.  The first 4 of these 16 bytes are
51435      ** a 32-bit counter that is incremented with each change.  The
51436      ** other bytes change randomly with each file change when
51437      ** a codec is in use.
51438      **
51439      ** There is a vanishingly small chance that a change will not be
51440      ** detected.  The chance of an undetected change is so small that
51441      ** it can be neglected.
51442      */
51443      Pgno nPage = 0;
51444      char dbFileVers[sizeof(pPager->dbFileVers)];
51445
51446      rc = pagerPagecount(pPager, &nPage);
51447      if( rc ) goto failed;
51448
51449      if( nPage>0 ){
51450        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
51451        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
51452        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
51453          goto failed;
51454        }
51455      }else{
51456        memset(dbFileVers, 0, sizeof(dbFileVers));
51457      }
51458
51459      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
51460        pager_reset(pPager);
51461
51462        /* Unmap the database file. It is possible that external processes
51463        ** may have truncated the database file and then extended it back
51464        ** to its original size while this process was not holding a lock.
51465        ** In this case there may exist a Pager.pMap mapping that appears
51466        ** to be the right size but is not actually valid. Avoid this
51467        ** possibility by unmapping the db here. */
51468        if( USEFETCH(pPager) ){
51469          sqlite3OsUnfetch(pPager->fd, 0, 0);
51470        }
51471      }
51472    }
51473
51474    /* If there is a WAL file in the file-system, open this database in WAL
51475    ** mode. Otherwise, the following function call is a no-op.
51476    */
51477    rc = pagerOpenWalIfPresent(pPager);
51478#ifndef SQLITE_OMIT_WAL
51479    assert( pPager->pWal==0 || rc==SQLITE_OK );
51480#endif
51481  }
51482
51483  if( pagerUseWal(pPager) ){
51484    assert( rc==SQLITE_OK );
51485    rc = pagerBeginReadTransaction(pPager);
51486  }
51487
51488  if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
51489    rc = pagerPagecount(pPager, &pPager->dbSize);
51490  }
51491
51492 failed:
51493  if( rc!=SQLITE_OK ){
51494    assert( !MEMDB );
51495    pager_unlock(pPager);
51496    assert( pPager->eState==PAGER_OPEN );
51497  }else{
51498    pPager->eState = PAGER_READER;
51499    pPager->hasHeldSharedLock = 1;
51500  }
51501  return rc;
51502}
51503
51504/*
51505** If the reference count has reached zero, rollback any active
51506** transaction and unlock the pager.
51507**
51508** Except, in locking_mode=EXCLUSIVE when there is nothing to in
51509** the rollback journal, the unlock is not performed and there is
51510** nothing to rollback, so this routine is a no-op.
51511*/
51512static void pagerUnlockIfUnused(Pager *pPager){
51513  if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
51514    pagerUnlockAndRollback(pPager);
51515  }
51516}
51517
51518/*
51519** Acquire a reference to page number pgno in pager pPager (a page
51520** reference has type DbPage*). If the requested reference is
51521** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
51522**
51523** If the requested page is already in the cache, it is returned.
51524** Otherwise, a new page object is allocated and populated with data
51525** read from the database file. In some cases, the pcache module may
51526** choose not to allocate a new page object and may reuse an existing
51527** object with no outstanding references.
51528**
51529** The extra data appended to a page is always initialized to zeros the
51530** first time a page is loaded into memory. If the page requested is
51531** already in the cache when this function is called, then the extra
51532** data is left as it was when the page object was last used.
51533**
51534** If the database image is smaller than the requested page or if a
51535** non-zero value is passed as the noContent parameter and the
51536** requested page is not already stored in the cache, then no
51537** actual disk read occurs. In this case the memory image of the
51538** page is initialized to all zeros.
51539**
51540** If noContent is true, it means that we do not care about the contents
51541** of the page. This occurs in two scenarios:
51542**
51543**   a) When reading a free-list leaf page from the database, and
51544**
51545**   b) When a savepoint is being rolled back and we need to load
51546**      a new page into the cache to be filled with the data read
51547**      from the savepoint journal.
51548**
51549** If noContent is true, then the data returned is zeroed instead of
51550** being read from the database. Additionally, the bits corresponding
51551** to pgno in Pager.pInJournal (bitvec of pages already written to the
51552** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
51553** savepoints are set. This means if the page is made writable at any
51554** point in the future, using a call to sqlite3PagerWrite(), its contents
51555** will not be journaled. This saves IO.
51556**
51557** The acquisition might fail for several reasons.  In all cases,
51558** an appropriate error code is returned and *ppPage is set to NULL.
51559**
51560** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
51561** to find a page in the in-memory cache first.  If the page is not already
51562** in memory, this routine goes to disk to read it in whereas Lookup()
51563** just returns 0.  This routine acquires a read-lock the first time it
51564** has to go to disk, and could also playback an old journal if necessary.
51565** Since Lookup() never goes to disk, it never has to deal with locks
51566** or journal files.
51567*/
51568SQLITE_PRIVATE int sqlite3PagerGet(
51569  Pager *pPager,      /* The pager open on the database file */
51570  Pgno pgno,          /* Page number to fetch */
51571  DbPage **ppPage,    /* Write a pointer to the page here */
51572  int flags           /* PAGER_GET_XXX flags */
51573){
51574  int rc = SQLITE_OK;
51575  PgHdr *pPg = 0;
51576  u32 iFrame = 0;                 /* Frame to read from WAL file */
51577  const int noContent = (flags & PAGER_GET_NOCONTENT);
51578
51579  /* It is acceptable to use a read-only (mmap) page for any page except
51580  ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
51581  ** flag was specified by the caller. And so long as the db is not a
51582  ** temporary or in-memory database.  */
51583  const int bMmapOk = (pgno>1 && USEFETCH(pPager)
51584   && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
51585#ifdef SQLITE_HAS_CODEC
51586   && pPager->xCodec==0
51587#endif
51588  );
51589
51590  /* Optimization note:  Adding the "pgno<=1" term before "pgno==0" here
51591  ** allows the compiler optimizer to reuse the results of the "pgno>1"
51592  ** test in the previous statement, and avoid testing pgno==0 in the
51593  ** common case where pgno is large. */
51594  if( pgno<=1 && pgno==0 ){
51595    return SQLITE_CORRUPT_BKPT;
51596  }
51597  assert( pPager->eState>=PAGER_READER );
51598  assert( assert_pager_state(pPager) );
51599  assert( noContent==0 || bMmapOk==0 );
51600
51601  assert( pPager->hasHeldSharedLock==1 );
51602
51603  /* If the pager is in the error state, return an error immediately.
51604  ** Otherwise, request the page from the PCache layer. */
51605  if( pPager->errCode!=SQLITE_OK ){
51606    rc = pPager->errCode;
51607  }else{
51608    if( bMmapOk && pagerUseWal(pPager) ){
51609      rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
51610      if( rc!=SQLITE_OK ) goto pager_acquire_err;
51611    }
51612
51613    if( bMmapOk && iFrame==0 ){
51614      void *pData = 0;
51615
51616      rc = sqlite3OsFetch(pPager->fd,
51617          (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
51618      );
51619
51620      if( rc==SQLITE_OK && pData ){
51621        if( pPager->eState>PAGER_READER || pPager->tempFile ){
51622          pPg = sqlite3PagerLookup(pPager, pgno);
51623        }
51624        if( pPg==0 ){
51625          rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
51626        }else{
51627          sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
51628        }
51629        if( pPg ){
51630          assert( rc==SQLITE_OK );
51631          *ppPage = pPg;
51632          return SQLITE_OK;
51633        }
51634      }
51635      if( rc!=SQLITE_OK ){
51636        goto pager_acquire_err;
51637      }
51638    }
51639
51640    {
51641      sqlite3_pcache_page *pBase;
51642      pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
51643      if( pBase==0 ){
51644        rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
51645        if( rc!=SQLITE_OK ) goto pager_acquire_err;
51646        if( pBase==0 ){
51647          pPg = *ppPage = 0;
51648          rc = SQLITE_NOMEM_BKPT;
51649          goto pager_acquire_err;
51650        }
51651      }
51652      pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
51653      assert( pPg!=0 );
51654    }
51655  }
51656
51657  if( rc!=SQLITE_OK ){
51658    /* Either the call to sqlite3PcacheFetch() returned an error or the
51659    ** pager was already in the error-state when this function was called.
51660    ** Set pPg to 0 and jump to the exception handler.  */
51661    pPg = 0;
51662    goto pager_acquire_err;
51663  }
51664  assert( pPg==(*ppPage) );
51665  assert( pPg->pgno==pgno );
51666  assert( pPg->pPager==pPager || pPg->pPager==0 );
51667
51668  if( pPg->pPager && !noContent ){
51669    /* In this case the pcache already contains an initialized copy of
51670    ** the page. Return without further ado.  */
51671    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
51672    pPager->aStat[PAGER_STAT_HIT]++;
51673    return SQLITE_OK;
51674
51675  }else{
51676    /* The pager cache has created a new page. Its content needs to
51677    ** be initialized.  */
51678
51679    pPg->pPager = pPager;
51680
51681    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
51682    ** number greater than this, or the unused locking-page, is requested. */
51683    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
51684      rc = SQLITE_CORRUPT_BKPT;
51685      goto pager_acquire_err;
51686    }
51687
51688    assert( !isOpen(pPager->fd) || !MEMDB );
51689    if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
51690      if( pgno>pPager->mxPgno ){
51691        rc = SQLITE_FULL;
51692        goto pager_acquire_err;
51693      }
51694      if( noContent ){
51695        /* Failure to set the bits in the InJournal bit-vectors is benign.
51696        ** It merely means that we might do some extra work to journal a
51697        ** page that does not need to be journaled.  Nevertheless, be sure
51698        ** to test the case where a malloc error occurs while trying to set
51699        ** a bit in a bit vector.
51700        */
51701        sqlite3BeginBenignMalloc();
51702        if( pgno<=pPager->dbOrigSize ){
51703          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
51704          testcase( rc==SQLITE_NOMEM );
51705        }
51706        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
51707        testcase( rc==SQLITE_NOMEM );
51708        sqlite3EndBenignMalloc();
51709      }
51710      memset(pPg->pData, 0, pPager->pageSize);
51711      IOTRACE(("ZERO %p %d\n", pPager, pgno));
51712    }else{
51713      if( pagerUseWal(pPager) && bMmapOk==0 ){
51714        rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
51715        if( rc!=SQLITE_OK ) goto pager_acquire_err;
51716      }
51717      assert( pPg->pPager==pPager );
51718      pPager->aStat[PAGER_STAT_MISS]++;
51719      rc = readDbPage(pPg, iFrame);
51720      if( rc!=SQLITE_OK ){
51721        goto pager_acquire_err;
51722      }
51723    }
51724    pager_set_pagehash(pPg);
51725  }
51726
51727  return SQLITE_OK;
51728
51729pager_acquire_err:
51730  assert( rc!=SQLITE_OK );
51731  if( pPg ){
51732    sqlite3PcacheDrop(pPg);
51733  }
51734  pagerUnlockIfUnused(pPager);
51735
51736  *ppPage = 0;
51737  return rc;
51738}
51739
51740/*
51741** Acquire a page if it is already in the in-memory cache.  Do
51742** not read the page from disk.  Return a pointer to the page,
51743** or 0 if the page is not in cache.
51744**
51745** See also sqlite3PagerGet().  The difference between this routine
51746** and sqlite3PagerGet() is that _get() will go to the disk and read
51747** in the page if the page is not already in cache.  This routine
51748** returns NULL if the page is not in cache or if a disk I/O error
51749** has ever happened.
51750*/
51751SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
51752  sqlite3_pcache_page *pPage;
51753  assert( pPager!=0 );
51754  assert( pgno!=0 );
51755  assert( pPager->pPCache!=0 );
51756  pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
51757  assert( pPage==0 || pPager->hasHeldSharedLock );
51758  if( pPage==0 ) return 0;
51759  return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
51760}
51761
51762/*
51763** Release a page reference.
51764**
51765** If the number of references to the page drop to zero, then the
51766** page is added to the LRU list.  When all references to all pages
51767** are released, a rollback occurs and the lock on the database is
51768** removed.
51769*/
51770SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
51771  Pager *pPager;
51772  assert( pPg!=0 );
51773  pPager = pPg->pPager;
51774  if( pPg->flags & PGHDR_MMAP ){
51775    pagerReleaseMapPage(pPg);
51776  }else{
51777    sqlite3PcacheRelease(pPg);
51778  }
51779  pagerUnlockIfUnused(pPager);
51780}
51781SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
51782  if( pPg ) sqlite3PagerUnrefNotNull(pPg);
51783}
51784
51785/*
51786** This function is called at the start of every write transaction.
51787** There must already be a RESERVED or EXCLUSIVE lock on the database
51788** file when this routine is called.
51789**
51790** Open the journal file for pager pPager and write a journal header
51791** to the start of it. If there are active savepoints, open the sub-journal
51792** as well. This function is only used when the journal file is being
51793** opened to write a rollback log for a transaction. It is not used
51794** when opening a hot journal file to roll it back.
51795**
51796** If the journal file is already open (as it may be in exclusive mode),
51797** then this function just writes a journal header to the start of the
51798** already open file.
51799**
51800** Whether or not the journal file is opened by this function, the
51801** Pager.pInJournal bitvec structure is allocated.
51802**
51803** Return SQLITE_OK if everything is successful. Otherwise, return
51804** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
51805** an IO error code if opening or writing the journal file fails.
51806*/
51807static int pager_open_journal(Pager *pPager){
51808  int rc = SQLITE_OK;                        /* Return code */
51809  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
51810
51811  assert( pPager->eState==PAGER_WRITER_LOCKED );
51812  assert( assert_pager_state(pPager) );
51813  assert( pPager->pInJournal==0 );
51814
51815  /* If already in the error state, this function is a no-op.  But on
51816  ** the other hand, this routine is never called if we are already in
51817  ** an error state. */
51818  if( NEVER(pPager->errCode) ) return pPager->errCode;
51819
51820  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
51821    pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
51822    if( pPager->pInJournal==0 ){
51823      return SQLITE_NOMEM_BKPT;
51824    }
51825
51826    /* Open the journal file if it is not already open. */
51827    if( !isOpen(pPager->jfd) ){
51828      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
51829        sqlite3MemJournalOpen(pPager->jfd);
51830      }else{
51831        int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
51832        int nSpill;
51833
51834        if( pPager->tempFile ){
51835          flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
51836          nSpill = sqlite3Config.nStmtSpill;
51837        }else{
51838          flags |= SQLITE_OPEN_MAIN_JOURNAL;
51839          nSpill = jrnlBufferSize(pPager);
51840        }
51841
51842        /* Verify that the database still has the same name as it did when
51843        ** it was originally opened. */
51844        rc = databaseIsUnmoved(pPager);
51845        if( rc==SQLITE_OK ){
51846          rc = sqlite3JournalOpen (
51847              pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
51848          );
51849        }
51850      }
51851      assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
51852    }
51853
51854
51855    /* Write the first journal header to the journal file and open
51856    ** the sub-journal if necessary.
51857    */
51858    if( rc==SQLITE_OK ){
51859      /* TODO: Check if all of these are really required. */
51860      pPager->nRec = 0;
51861      pPager->journalOff = 0;
51862      pPager->setMaster = 0;
51863      pPager->journalHdr = 0;
51864      rc = writeJournalHdr(pPager);
51865    }
51866  }
51867
51868  if( rc!=SQLITE_OK ){
51869    sqlite3BitvecDestroy(pPager->pInJournal);
51870    pPager->pInJournal = 0;
51871  }else{
51872    assert( pPager->eState==PAGER_WRITER_LOCKED );
51873    pPager->eState = PAGER_WRITER_CACHEMOD;
51874  }
51875
51876  return rc;
51877}
51878
51879/*
51880** Begin a write-transaction on the specified pager object. If a
51881** write-transaction has already been opened, this function is a no-op.
51882**
51883** If the exFlag argument is false, then acquire at least a RESERVED
51884** lock on the database file. If exFlag is true, then acquire at least
51885** an EXCLUSIVE lock. If such a lock is already held, no locking
51886** functions need be called.
51887**
51888** If the subjInMemory argument is non-zero, then any sub-journal opened
51889** within this transaction will be opened as an in-memory file. This
51890** has no effect if the sub-journal is already opened (as it may be when
51891** running in exclusive mode) or if the transaction does not require a
51892** sub-journal. If the subjInMemory argument is zero, then any required
51893** sub-journal is implemented in-memory if pPager is an in-memory database,
51894** or using a temporary file otherwise.
51895*/
51896SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
51897  int rc = SQLITE_OK;
51898
51899  if( pPager->errCode ) return pPager->errCode;
51900  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
51901  pPager->subjInMemory = (u8)subjInMemory;
51902
51903  if( ALWAYS(pPager->eState==PAGER_READER) ){
51904    assert( pPager->pInJournal==0 );
51905
51906    if( pagerUseWal(pPager) ){
51907      /* If the pager is configured to use locking_mode=exclusive, and an
51908      ** exclusive lock on the database is not already held, obtain it now.
51909      */
51910      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
51911        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
51912        if( rc!=SQLITE_OK ){
51913          return rc;
51914        }
51915        (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
51916      }
51917
51918      /* Grab the write lock on the log file. If successful, upgrade to
51919      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
51920      ** The busy-handler is not invoked if another connection already
51921      ** holds the write-lock. If possible, the upper layer will call it.
51922      */
51923      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
51924    }else{
51925      /* Obtain a RESERVED lock on the database file. If the exFlag parameter
51926      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
51927      ** busy-handler callback can be used when upgrading to the EXCLUSIVE
51928      ** lock, but not when obtaining the RESERVED lock.
51929      */
51930      rc = pagerLockDb(pPager, RESERVED_LOCK);
51931      if( rc==SQLITE_OK && exFlag ){
51932        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
51933      }
51934    }
51935
51936    if( rc==SQLITE_OK ){
51937      /* Change to WRITER_LOCKED state.
51938      **
51939      ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
51940      ** when it has an open transaction, but never to DBMOD or FINISHED.
51941      ** This is because in those states the code to roll back savepoint
51942      ** transactions may copy data from the sub-journal into the database
51943      ** file as well as into the page cache. Which would be incorrect in
51944      ** WAL mode.
51945      */
51946      pPager->eState = PAGER_WRITER_LOCKED;
51947      pPager->dbHintSize = pPager->dbSize;
51948      pPager->dbFileSize = pPager->dbSize;
51949      pPager->dbOrigSize = pPager->dbSize;
51950      pPager->journalOff = 0;
51951    }
51952
51953    assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
51954    assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
51955    assert( assert_pager_state(pPager) );
51956  }
51957
51958  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
51959  return rc;
51960}
51961
51962/*
51963** Write page pPg onto the end of the rollback journal.
51964*/
51965static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
51966  Pager *pPager = pPg->pPager;
51967  int rc;
51968  u32 cksum;
51969  char *pData2;
51970  i64 iOff = pPager->journalOff;
51971
51972  /* We should never write to the journal file the page that
51973  ** contains the database locks.  The following assert verifies
51974  ** that we do not. */
51975  assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
51976
51977  assert( pPager->journalHdr<=pPager->journalOff );
51978  CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
51979  cksum = pager_cksum(pPager, (u8*)pData2);
51980
51981  /* Even if an IO or diskfull error occurs while journalling the
51982  ** page in the block above, set the need-sync flag for the page.
51983  ** Otherwise, when the transaction is rolled back, the logic in
51984  ** playback_one_page() will think that the page needs to be restored
51985  ** in the database file. And if an IO error occurs while doing so,
51986  ** then corruption may follow.
51987  */
51988  pPg->flags |= PGHDR_NEED_SYNC;
51989
51990  rc = write32bits(pPager->jfd, iOff, pPg->pgno);
51991  if( rc!=SQLITE_OK ) return rc;
51992  rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
51993  if( rc!=SQLITE_OK ) return rc;
51994  rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
51995  if( rc!=SQLITE_OK ) return rc;
51996
51997  IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
51998           pPager->journalOff, pPager->pageSize));
51999  PAGER_INCR(sqlite3_pager_writej_count);
52000  PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
52001       PAGERID(pPager), pPg->pgno,
52002       ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
52003
52004  pPager->journalOff += 8 + pPager->pageSize;
52005  pPager->nRec++;
52006  assert( pPager->pInJournal!=0 );
52007  rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
52008  testcase( rc==SQLITE_NOMEM );
52009  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
52010  rc |= addToSavepointBitvecs(pPager, pPg->pgno);
52011  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
52012  return rc;
52013}
52014
52015/*
52016** Mark a single data page as writeable. The page is written into the
52017** main journal or sub-journal as required. If the page is written into
52018** one of the journals, the corresponding bit is set in the
52019** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
52020** of any open savepoints as appropriate.
52021*/
52022static int pager_write(PgHdr *pPg){
52023  Pager *pPager = pPg->pPager;
52024  int rc = SQLITE_OK;
52025
52026  /* This routine is not called unless a write-transaction has already
52027  ** been started. The journal file may or may not be open at this point.
52028  ** It is never called in the ERROR state.
52029  */
52030  assert( pPager->eState==PAGER_WRITER_LOCKED
52031       || pPager->eState==PAGER_WRITER_CACHEMOD
52032       || pPager->eState==PAGER_WRITER_DBMOD
52033  );
52034  assert( assert_pager_state(pPager) );
52035  assert( pPager->errCode==0 );
52036  assert( pPager->readOnly==0 );
52037  CHECK_PAGE(pPg);
52038
52039  /* The journal file needs to be opened. Higher level routines have already
52040  ** obtained the necessary locks to begin the write-transaction, but the
52041  ** rollback journal might not yet be open. Open it now if this is the case.
52042  **
52043  ** This is done before calling sqlite3PcacheMakeDirty() on the page.
52044  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
52045  ** an error might occur and the pager would end up in WRITER_LOCKED state
52046  ** with pages marked as dirty in the cache.
52047  */
52048  if( pPager->eState==PAGER_WRITER_LOCKED ){
52049    rc = pager_open_journal(pPager);
52050    if( rc!=SQLITE_OK ) return rc;
52051  }
52052  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
52053  assert( assert_pager_state(pPager) );
52054
52055  /* Mark the page that is about to be modified as dirty. */
52056  sqlite3PcacheMakeDirty(pPg);
52057
52058  /* If a rollback journal is in use, them make sure the page that is about
52059  ** to change is in the rollback journal, or if the page is a new page off
52060  ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
52061  */
52062  assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
52063  if( pPager->pInJournal!=0
52064   && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
52065  ){
52066    assert( pagerUseWal(pPager)==0 );
52067    if( pPg->pgno<=pPager->dbOrigSize ){
52068      rc = pagerAddPageToRollbackJournal(pPg);
52069      if( rc!=SQLITE_OK ){
52070        return rc;
52071      }
52072    }else{
52073      if( pPager->eState!=PAGER_WRITER_DBMOD ){
52074        pPg->flags |= PGHDR_NEED_SYNC;
52075      }
52076      PAGERTRACE(("APPEND %d page %d needSync=%d\n",
52077              PAGERID(pPager), pPg->pgno,
52078             ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
52079    }
52080  }
52081
52082  /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
52083  ** and before writing the page into the rollback journal.  Wait until now,
52084  ** after the page has been successfully journalled, before setting the
52085  ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
52086  */
52087  pPg->flags |= PGHDR_WRITEABLE;
52088
52089  /* If the statement journal is open and the page is not in it,
52090  ** then write the page into the statement journal.
52091  */
52092  if( pPager->nSavepoint>0 ){
52093    rc = subjournalPageIfRequired(pPg);
52094  }
52095
52096  /* Update the database size and return. */
52097  if( pPager->dbSize<pPg->pgno ){
52098    pPager->dbSize = pPg->pgno;
52099  }
52100  return rc;
52101}
52102
52103/*
52104** This is a variant of sqlite3PagerWrite() that runs when the sector size
52105** is larger than the page size.  SQLite makes the (reasonable) assumption that
52106** all bytes of a sector are written together by hardware.  Hence, all bytes of
52107** a sector need to be journalled in case of a power loss in the middle of
52108** a write.
52109**
52110** Usually, the sector size is less than or equal to the page size, in which
52111** case pages can be individually written.  This routine only runs in the
52112** exceptional case where the page size is smaller than the sector size.
52113*/
52114static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
52115  int rc = SQLITE_OK;          /* Return code */
52116  Pgno nPageCount;             /* Total number of pages in database file */
52117  Pgno pg1;                    /* First page of the sector pPg is located on. */
52118  int nPage = 0;               /* Number of pages starting at pg1 to journal */
52119  int ii;                      /* Loop counter */
52120  int needSync = 0;            /* True if any page has PGHDR_NEED_SYNC */
52121  Pager *pPager = pPg->pPager; /* The pager that owns pPg */
52122  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
52123
52124  /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
52125  ** a journal header to be written between the pages journaled by
52126  ** this function.
52127  */
52128  assert( !MEMDB );
52129  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
52130  pPager->doNotSpill |= SPILLFLAG_NOSYNC;
52131
52132  /* This trick assumes that both the page-size and sector-size are
52133  ** an integer power of 2. It sets variable pg1 to the identifier
52134  ** of the first page of the sector pPg is located on.
52135  */
52136  pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
52137
52138  nPageCount = pPager->dbSize;
52139  if( pPg->pgno>nPageCount ){
52140    nPage = (pPg->pgno - pg1)+1;
52141  }else if( (pg1+nPagePerSector-1)>nPageCount ){
52142    nPage = nPageCount+1-pg1;
52143  }else{
52144    nPage = nPagePerSector;
52145  }
52146  assert(nPage>0);
52147  assert(pg1<=pPg->pgno);
52148  assert((pg1+nPage)>pPg->pgno);
52149
52150  for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
52151    Pgno pg = pg1+ii;
52152    PgHdr *pPage;
52153    if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
52154      if( pg!=PAGER_MJ_PGNO(pPager) ){
52155        rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
52156        if( rc==SQLITE_OK ){
52157          rc = pager_write(pPage);
52158          if( pPage->flags&PGHDR_NEED_SYNC ){
52159            needSync = 1;
52160          }
52161          sqlite3PagerUnrefNotNull(pPage);
52162        }
52163      }
52164    }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
52165      if( pPage->flags&PGHDR_NEED_SYNC ){
52166        needSync = 1;
52167      }
52168      sqlite3PagerUnrefNotNull(pPage);
52169    }
52170  }
52171
52172  /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
52173  ** starting at pg1, then it needs to be set for all of them. Because
52174  ** writing to any of these nPage pages may damage the others, the
52175  ** journal file must contain sync()ed copies of all of them
52176  ** before any of them can be written out to the database file.
52177  */
52178  if( rc==SQLITE_OK && needSync ){
52179    assert( !MEMDB );
52180    for(ii=0; ii<nPage; ii++){
52181      PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
52182      if( pPage ){
52183        pPage->flags |= PGHDR_NEED_SYNC;
52184        sqlite3PagerUnrefNotNull(pPage);
52185      }
52186    }
52187  }
52188
52189  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
52190  pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
52191  return rc;
52192}
52193
52194/*
52195** Mark a data page as writeable. This routine must be called before
52196** making changes to a page. The caller must check the return value
52197** of this function and be careful not to change any page data unless
52198** this routine returns SQLITE_OK.
52199**
52200** The difference between this function and pager_write() is that this
52201** function also deals with the special case where 2 or more pages
52202** fit on a single disk sector. In this case all co-resident pages
52203** must have been written to the journal file before returning.
52204**
52205** If an error occurs, SQLITE_NOMEM or an IO error code is returned
52206** as appropriate. Otherwise, SQLITE_OK.
52207*/
52208SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
52209  Pager *pPager = pPg->pPager;
52210  assert( (pPg->flags & PGHDR_MMAP)==0 );
52211  assert( pPager->eState>=PAGER_WRITER_LOCKED );
52212  assert( assert_pager_state(pPager) );
52213  if( pPager->errCode ){
52214    return pPager->errCode;
52215  }else if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
52216    if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
52217    return SQLITE_OK;
52218  }else if( pPager->sectorSize > (u32)pPager->pageSize ){
52219    assert( pPager->tempFile==0 );
52220    return pagerWriteLargeSector(pPg);
52221  }else{
52222    return pager_write(pPg);
52223  }
52224}
52225
52226/*
52227** Return TRUE if the page given in the argument was previously passed
52228** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
52229** to change the content of the page.
52230*/
52231#ifndef NDEBUG
52232SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
52233  return pPg->flags & PGHDR_WRITEABLE;
52234}
52235#endif
52236
52237/*
52238** A call to this routine tells the pager that it is not necessary to
52239** write the information on page pPg back to the disk, even though
52240** that page might be marked as dirty.  This happens, for example, when
52241** the page has been added as a leaf of the freelist and so its
52242** content no longer matters.
52243**
52244** The overlying software layer calls this routine when all of the data
52245** on the given page is unused. The pager marks the page as clean so
52246** that it does not get written to disk.
52247**
52248** Tests show that this optimization can quadruple the speed of large
52249** DELETE operations.
52250**
52251** This optimization cannot be used with a temp-file, as the page may
52252** have been dirty at the start of the transaction. In that case, if
52253** memory pressure forces page pPg out of the cache, the data does need
52254** to be written out to disk so that it may be read back in if the
52255** current transaction is rolled back.
52256*/
52257SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
52258  Pager *pPager = pPg->pPager;
52259  if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
52260    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
52261    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
52262    pPg->flags |= PGHDR_DONT_WRITE;
52263    pPg->flags &= ~PGHDR_WRITEABLE;
52264    testcase( pPg->flags & PGHDR_NEED_SYNC );
52265    pager_set_pagehash(pPg);
52266  }
52267}
52268
52269/*
52270** This routine is called to increment the value of the database file
52271** change-counter, stored as a 4-byte big-endian integer starting at
52272** byte offset 24 of the pager file.  The secondary change counter at
52273** 92 is also updated, as is the SQLite version number at offset 96.
52274**
52275** But this only happens if the pPager->changeCountDone flag is false.
52276** To avoid excess churning of page 1, the update only happens once.
52277** See also the pager_write_changecounter() routine that does an
52278** unconditional update of the change counters.
52279**
52280** If the isDirectMode flag is zero, then this is done by calling
52281** sqlite3PagerWrite() on page 1, then modifying the contents of the
52282** page data. In this case the file will be updated when the current
52283** transaction is committed.
52284**
52285** The isDirectMode flag may only be non-zero if the library was compiled
52286** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
52287** if isDirect is non-zero, then the database file is updated directly
52288** by writing an updated version of page 1 using a call to the
52289** sqlite3OsWrite() function.
52290*/
52291static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
52292  int rc = SQLITE_OK;
52293
52294  assert( pPager->eState==PAGER_WRITER_CACHEMOD
52295       || pPager->eState==PAGER_WRITER_DBMOD
52296  );
52297  assert( assert_pager_state(pPager) );
52298
52299  /* Declare and initialize constant integer 'isDirect'. If the
52300  ** atomic-write optimization is enabled in this build, then isDirect
52301  ** is initialized to the value passed as the isDirectMode parameter
52302  ** to this function. Otherwise, it is always set to zero.
52303  **
52304  ** The idea is that if the atomic-write optimization is not
52305  ** enabled at compile time, the compiler can omit the tests of
52306  ** 'isDirect' below, as well as the block enclosed in the
52307  ** "if( isDirect )" condition.
52308  */
52309#ifndef SQLITE_ENABLE_ATOMIC_WRITE
52310# define DIRECT_MODE 0
52311  assert( isDirectMode==0 );
52312  UNUSED_PARAMETER(isDirectMode);
52313#else
52314# define DIRECT_MODE isDirectMode
52315#endif
52316
52317  if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
52318    PgHdr *pPgHdr;                /* Reference to page 1 */
52319
52320    assert( !pPager->tempFile && isOpen(pPager->fd) );
52321
52322    /* Open page 1 of the file for writing. */
52323    rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
52324    assert( pPgHdr==0 || rc==SQLITE_OK );
52325
52326    /* If page one was fetched successfully, and this function is not
52327    ** operating in direct-mode, make page 1 writable.  When not in
52328    ** direct mode, page 1 is always held in cache and hence the PagerGet()
52329    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
52330    */
52331    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
52332      rc = sqlite3PagerWrite(pPgHdr);
52333    }
52334
52335    if( rc==SQLITE_OK ){
52336      /* Actually do the update of the change counter */
52337      pager_write_changecounter(pPgHdr);
52338
52339      /* If running in direct mode, write the contents of page 1 to the file. */
52340      if( DIRECT_MODE ){
52341        const void *zBuf;
52342        assert( pPager->dbFileSize>0 );
52343        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
52344        if( rc==SQLITE_OK ){
52345          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
52346          pPager->aStat[PAGER_STAT_WRITE]++;
52347        }
52348        if( rc==SQLITE_OK ){
52349          /* Update the pager's copy of the change-counter. Otherwise, the
52350          ** next time a read transaction is opened the cache will be
52351          ** flushed (as the change-counter values will not match).  */
52352          const void *pCopy = (const void *)&((const char *)zBuf)[24];
52353          memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
52354          pPager->changeCountDone = 1;
52355        }
52356      }else{
52357        pPager->changeCountDone = 1;
52358      }
52359    }
52360
52361    /* Release the page reference. */
52362    sqlite3PagerUnref(pPgHdr);
52363  }
52364  return rc;
52365}
52366
52367/*
52368** Sync the database file to disk. This is a no-op for in-memory databases
52369** or pages with the Pager.noSync flag set.
52370**
52371** If successful, or if called on a pager for which it is a no-op, this
52372** function returns SQLITE_OK. Otherwise, an IO error code is returned.
52373*/
52374SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
52375  int rc = SQLITE_OK;
52376
52377  if( isOpen(pPager->fd) ){
52378    void *pArg = (void*)zMaster;
52379    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
52380    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
52381  }
52382  if( rc==SQLITE_OK && !pPager->noSync ){
52383    assert( !MEMDB );
52384    rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
52385  }
52386  return rc;
52387}
52388
52389/*
52390** This function may only be called while a write-transaction is active in
52391** rollback. If the connection is in WAL mode, this call is a no-op.
52392** Otherwise, if the connection does not already have an EXCLUSIVE lock on
52393** the database file, an attempt is made to obtain one.
52394**
52395** If the EXCLUSIVE lock is already held or the attempt to obtain it is
52396** successful, or the connection is in WAL mode, SQLITE_OK is returned.
52397** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
52398** returned.
52399*/
52400SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
52401  int rc = pPager->errCode;
52402  assert( assert_pager_state(pPager) );
52403  if( rc==SQLITE_OK ){
52404    assert( pPager->eState==PAGER_WRITER_CACHEMOD
52405         || pPager->eState==PAGER_WRITER_DBMOD
52406         || pPager->eState==PAGER_WRITER_LOCKED
52407    );
52408    assert( assert_pager_state(pPager) );
52409    if( 0==pagerUseWal(pPager) ){
52410      rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
52411    }
52412  }
52413  return rc;
52414}
52415
52416/*
52417** Sync the database file for the pager pPager. zMaster points to the name
52418** of a master journal file that should be written into the individual
52419** journal file. zMaster may be NULL, which is interpreted as no master
52420** journal (a single database transaction).
52421**
52422** This routine ensures that:
52423**
52424**   * The database file change-counter is updated,
52425**   * the journal is synced (unless the atomic-write optimization is used),
52426**   * all dirty pages are written to the database file,
52427**   * the database file is truncated (if required), and
52428**   * the database file synced.
52429**
52430** The only thing that remains to commit the transaction is to finalize
52431** (delete, truncate or zero the first part of) the journal file (or
52432** delete the master journal file if specified).
52433**
52434** Note that if zMaster==NULL, this does not overwrite a previous value
52435** passed to an sqlite3PagerCommitPhaseOne() call.
52436**
52437** If the final parameter - noSync - is true, then the database file itself
52438** is not synced. The caller must call sqlite3PagerSync() directly to
52439** sync the database file before calling CommitPhaseTwo() to delete the
52440** journal file in this case.
52441*/
52442SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
52443  Pager *pPager,                  /* Pager object */
52444  const char *zMaster,            /* If not NULL, the master journal name */
52445  int noSync                      /* True to omit the xSync on the db file */
52446){
52447  int rc = SQLITE_OK;             /* Return code */
52448
52449  assert( pPager->eState==PAGER_WRITER_LOCKED
52450       || pPager->eState==PAGER_WRITER_CACHEMOD
52451       || pPager->eState==PAGER_WRITER_DBMOD
52452       || pPager->eState==PAGER_ERROR
52453  );
52454  assert( assert_pager_state(pPager) );
52455
52456  /* If a prior error occurred, report that error again. */
52457  if( NEVER(pPager->errCode) ) return pPager->errCode;
52458
52459  /* Provide the ability to easily simulate an I/O error during testing */
52460  if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
52461
52462  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
52463      pPager->zFilename, zMaster, pPager->dbSize));
52464
52465  /* If no database changes have been made, return early. */
52466  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
52467
52468  assert( MEMDB==0 || pPager->tempFile );
52469  assert( isOpen(pPager->fd) || pPager->tempFile );
52470  if( 0==pagerFlushOnCommit(pPager, 1) ){
52471    /* If this is an in-memory db, or no pages have been written to, or this
52472    ** function has already been called, it is mostly a no-op.  However, any
52473    ** backup in progress needs to be restarted.  */
52474    sqlite3BackupRestart(pPager->pBackup);
52475  }else{
52476    if( pagerUseWal(pPager) ){
52477      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
52478      PgHdr *pPageOne = 0;
52479      if( pList==0 ){
52480        /* Must have at least one page for the WAL commit flag.
52481        ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
52482        rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
52483        pList = pPageOne;
52484        pList->pDirty = 0;
52485      }
52486      assert( rc==SQLITE_OK );
52487      if( ALWAYS(pList) ){
52488        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
52489      }
52490      sqlite3PagerUnref(pPageOne);
52491      if( rc==SQLITE_OK ){
52492        sqlite3PcacheCleanAll(pPager->pPCache);
52493      }
52494    }else{
52495      /* The following block updates the change-counter. Exactly how it
52496      ** does this depends on whether or not the atomic-update optimization
52497      ** was enabled at compile time, and if this transaction meets the
52498      ** runtime criteria to use the operation:
52499      **
52500      **    * The file-system supports the atomic-write property for
52501      **      blocks of size page-size, and
52502      **    * This commit is not part of a multi-file transaction, and
52503      **    * Exactly one page has been modified and store in the journal file.
52504      **
52505      ** If the optimization was not enabled at compile time, then the
52506      ** pager_incr_changecounter() function is called to update the change
52507      ** counter in 'indirect-mode'. If the optimization is compiled in but
52508      ** is not applicable to this transaction, call sqlite3JournalCreate()
52509      ** to make sure the journal file has actually been created, then call
52510      ** pager_incr_changecounter() to update the change-counter in indirect
52511      ** mode.
52512      **
52513      ** Otherwise, if the optimization is both enabled and applicable,
52514      ** then call pager_incr_changecounter() to update the change-counter
52515      ** in 'direct' mode. In this case the journal file will never be
52516      ** created for this transaction.
52517      */
52518  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
52519      PgHdr *pPg;
52520      assert( isOpen(pPager->jfd)
52521           || pPager->journalMode==PAGER_JOURNALMODE_OFF
52522           || pPager->journalMode==PAGER_JOURNALMODE_WAL
52523      );
52524      if( !zMaster && isOpen(pPager->jfd)
52525       && pPager->journalOff==jrnlBufferSize(pPager)
52526       && pPager->dbSize>=pPager->dbOrigSize
52527       && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
52528      ){
52529        /* Update the db file change counter via the direct-write method. The
52530        ** following call will modify the in-memory representation of page 1
52531        ** to include the updated change counter and then write page 1
52532        ** directly to the database file. Because of the atomic-write
52533        ** property of the host file-system, this is safe.
52534        */
52535        rc = pager_incr_changecounter(pPager, 1);
52536      }else{
52537        rc = sqlite3JournalCreate(pPager->jfd);
52538        if( rc==SQLITE_OK ){
52539          rc = pager_incr_changecounter(pPager, 0);
52540        }
52541      }
52542  #else
52543      rc = pager_incr_changecounter(pPager, 0);
52544  #endif
52545      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52546
52547      /* Write the master journal name into the journal file. If a master
52548      ** journal file name has already been written to the journal file,
52549      ** or if zMaster is NULL (no master journal), then this call is a no-op.
52550      */
52551      rc = writeMasterJournal(pPager, zMaster);
52552      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52553
52554      /* Sync the journal file and write all dirty pages to the database.
52555      ** If the atomic-update optimization is being used, this sync will not
52556      ** create the journal file or perform any real IO.
52557      **
52558      ** Because the change-counter page was just modified, unless the
52559      ** atomic-update optimization is used it is almost certain that the
52560      ** journal requires a sync here. However, in locking_mode=exclusive
52561      ** on a system under memory pressure it is just possible that this is
52562      ** not the case. In this case it is likely enough that the redundant
52563      ** xSync() call will be changed to a no-op by the OS anyhow.
52564      */
52565      rc = syncJournal(pPager, 0);
52566      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52567
52568      rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
52569      if( rc!=SQLITE_OK ){
52570        assert( rc!=SQLITE_IOERR_BLOCKED );
52571        goto commit_phase_one_exit;
52572      }
52573      sqlite3PcacheCleanAll(pPager->pPCache);
52574
52575      /* If the file on disk is smaller than the database image, use
52576      ** pager_truncate to grow the file here. This can happen if the database
52577      ** image was extended as part of the current transaction and then the
52578      ** last page in the db image moved to the free-list. In this case the
52579      ** last page is never written out to disk, leaving the database file
52580      ** undersized. Fix this now if it is the case.  */
52581      if( pPager->dbSize>pPager->dbFileSize ){
52582        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
52583        assert( pPager->eState==PAGER_WRITER_DBMOD );
52584        rc = pager_truncate(pPager, nNew);
52585        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52586      }
52587
52588      /* Finally, sync the database file. */
52589      if( !noSync ){
52590        rc = sqlite3PagerSync(pPager, zMaster);
52591      }
52592      IOTRACE(("DBSYNC %p\n", pPager))
52593    }
52594  }
52595
52596commit_phase_one_exit:
52597  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
52598    pPager->eState = PAGER_WRITER_FINISHED;
52599  }
52600  return rc;
52601}
52602
52603
52604/*
52605** When this function is called, the database file has been completely
52606** updated to reflect the changes made by the current transaction and
52607** synced to disk. The journal file still exists in the file-system
52608** though, and if a failure occurs at this point it will eventually
52609** be used as a hot-journal and the current transaction rolled back.
52610**
52611** This function finalizes the journal file, either by deleting,
52612** truncating or partially zeroing it, so that it cannot be used
52613** for hot-journal rollback. Once this is done the transaction is
52614** irrevocably committed.
52615**
52616** If an error occurs, an IO error code is returned and the pager
52617** moves into the error state. Otherwise, SQLITE_OK is returned.
52618*/
52619SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
52620  int rc = SQLITE_OK;                  /* Return code */
52621
52622  /* This routine should not be called if a prior error has occurred.
52623  ** But if (due to a coding error elsewhere in the system) it does get
52624  ** called, just return the same error code without doing anything. */
52625  if( NEVER(pPager->errCode) ) return pPager->errCode;
52626
52627  assert( pPager->eState==PAGER_WRITER_LOCKED
52628       || pPager->eState==PAGER_WRITER_FINISHED
52629       || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
52630  );
52631  assert( assert_pager_state(pPager) );
52632
52633  /* An optimization. If the database was not actually modified during
52634  ** this transaction, the pager is running in exclusive-mode and is
52635  ** using persistent journals, then this function is a no-op.
52636  **
52637  ** The start of the journal file currently contains a single journal
52638  ** header with the nRec field set to 0. If such a journal is used as
52639  ** a hot-journal during hot-journal rollback, 0 changes will be made
52640  ** to the database file. So there is no need to zero the journal
52641  ** header. Since the pager is in exclusive mode, there is no need
52642  ** to drop any locks either.
52643  */
52644  if( pPager->eState==PAGER_WRITER_LOCKED
52645   && pPager->exclusiveMode
52646   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
52647  ){
52648    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
52649    pPager->eState = PAGER_READER;
52650    return SQLITE_OK;
52651  }
52652
52653  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
52654  pPager->iDataVersion++;
52655  rc = pager_end_transaction(pPager, pPager->setMaster, 1);
52656  return pager_error(pPager, rc);
52657}
52658
52659/*
52660** If a write transaction is open, then all changes made within the
52661** transaction are reverted and the current write-transaction is closed.
52662** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
52663** state if an error occurs.
52664**
52665** If the pager is already in PAGER_ERROR state when this function is called,
52666** it returns Pager.errCode immediately. No work is performed in this case.
52667**
52668** Otherwise, in rollback mode, this function performs two functions:
52669**
52670**   1) It rolls back the journal file, restoring all database file and
52671**      in-memory cache pages to the state they were in when the transaction
52672**      was opened, and
52673**
52674**   2) It finalizes the journal file, so that it is not used for hot
52675**      rollback at any point in the future.
52676**
52677** Finalization of the journal file (task 2) is only performed if the
52678** rollback is successful.
52679**
52680** In WAL mode, all cache-entries containing data modified within the
52681** current transaction are either expelled from the cache or reverted to
52682** their pre-transaction state by re-reading data from the database or
52683** WAL files. The WAL transaction is then closed.
52684*/
52685SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
52686  int rc = SQLITE_OK;                  /* Return code */
52687  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
52688
52689  /* PagerRollback() is a no-op if called in READER or OPEN state. If
52690  ** the pager is already in the ERROR state, the rollback is not
52691  ** attempted here. Instead, the error code is returned to the caller.
52692  */
52693  assert( assert_pager_state(pPager) );
52694  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
52695  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
52696
52697  if( pagerUseWal(pPager) ){
52698    int rc2;
52699    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
52700    rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
52701    if( rc==SQLITE_OK ) rc = rc2;
52702  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
52703    int eState = pPager->eState;
52704    rc = pager_end_transaction(pPager, 0, 0);
52705    if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
52706      /* This can happen using journal_mode=off. Move the pager to the error
52707      ** state to indicate that the contents of the cache may not be trusted.
52708      ** Any active readers will get SQLITE_ABORT.
52709      */
52710      pPager->errCode = SQLITE_ABORT;
52711      pPager->eState = PAGER_ERROR;
52712      return rc;
52713    }
52714  }else{
52715    rc = pager_playback(pPager, 0);
52716  }
52717
52718  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
52719  assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
52720          || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
52721          || rc==SQLITE_CANTOPEN
52722  );
52723
52724  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
52725  ** cache. So call pager_error() on the way out to make any error persistent.
52726  */
52727  return pager_error(pPager, rc);
52728}
52729
52730/*
52731** Return TRUE if the database file is opened read-only.  Return FALSE
52732** if the database is (in theory) writable.
52733*/
52734SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
52735  return pPager->readOnly;
52736}
52737
52738#ifdef SQLITE_DEBUG
52739/*
52740** Return the sum of the reference counts for all pages held by pPager.
52741*/
52742SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
52743  return sqlite3PcacheRefCount(pPager->pPCache);
52744}
52745#endif
52746
52747/*
52748** Return the approximate number of bytes of memory currently
52749** used by the pager and its associated cache.
52750*/
52751SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
52752  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
52753                                     + 5*sizeof(void*);
52754  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
52755           + sqlite3MallocSize(pPager)
52756           + pPager->pageSize;
52757}
52758
52759/*
52760** Return the number of references to the specified page.
52761*/
52762SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
52763  return sqlite3PcachePageRefcount(pPage);
52764}
52765
52766#ifdef SQLITE_TEST
52767/*
52768** This routine is used for testing and analysis only.
52769*/
52770SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
52771  static int a[11];
52772  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
52773  a[1] = sqlite3PcachePagecount(pPager->pPCache);
52774  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
52775  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
52776  a[4] = pPager->eState;
52777  a[5] = pPager->errCode;
52778  a[6] = pPager->aStat[PAGER_STAT_HIT];
52779  a[7] = pPager->aStat[PAGER_STAT_MISS];
52780  a[8] = 0;  /* Used to be pPager->nOvfl */
52781  a[9] = pPager->nRead;
52782  a[10] = pPager->aStat[PAGER_STAT_WRITE];
52783  return a;
52784}
52785#endif
52786
52787/*
52788** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
52789** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
52790** current cache hit or miss count, according to the value of eStat. If the
52791** reset parameter is non-zero, the cache hit or miss count is zeroed before
52792** returning.
52793*/
52794SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
52795
52796  assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
52797       || eStat==SQLITE_DBSTATUS_CACHE_MISS
52798       || eStat==SQLITE_DBSTATUS_CACHE_WRITE
52799  );
52800
52801  assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
52802  assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
52803  assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
52804
52805  *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
52806  if( reset ){
52807    pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
52808  }
52809}
52810
52811/*
52812** Return true if this is an in-memory or temp-file backed pager.
52813*/
52814SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
52815  return pPager->tempFile;
52816}
52817
52818/*
52819** Check that there are at least nSavepoint savepoints open. If there are
52820** currently less than nSavepoints open, then open one or more savepoints
52821** to make up the difference. If the number of savepoints is already
52822** equal to nSavepoint, then this function is a no-op.
52823**
52824** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
52825** occurs while opening the sub-journal file, then an IO error code is
52826** returned. Otherwise, SQLITE_OK.
52827*/
52828static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
52829  int rc = SQLITE_OK;                       /* Return code */
52830  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
52831  int ii;                                   /* Iterator variable */
52832  PagerSavepoint *aNew;                     /* New Pager.aSavepoint array */
52833
52834  assert( pPager->eState>=PAGER_WRITER_LOCKED );
52835  assert( assert_pager_state(pPager) );
52836  assert( nSavepoint>nCurrent && pPager->useJournal );
52837
52838  /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
52839  ** if the allocation fails. Otherwise, zero the new portion in case a
52840  ** malloc failure occurs while populating it in the for(...) loop below.
52841  */
52842  aNew = (PagerSavepoint *)sqlite3Realloc(
52843      pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
52844  );
52845  if( !aNew ){
52846    return SQLITE_NOMEM_BKPT;
52847  }
52848  memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
52849  pPager->aSavepoint = aNew;
52850
52851  /* Populate the PagerSavepoint structures just allocated. */
52852  for(ii=nCurrent; ii<nSavepoint; ii++){
52853    aNew[ii].nOrig = pPager->dbSize;
52854    if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
52855      aNew[ii].iOffset = pPager->journalOff;
52856    }else{
52857      aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
52858    }
52859    aNew[ii].iSubRec = pPager->nSubRec;
52860    aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
52861    if( !aNew[ii].pInSavepoint ){
52862      return SQLITE_NOMEM_BKPT;
52863    }
52864    if( pagerUseWal(pPager) ){
52865      sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
52866    }
52867    pPager->nSavepoint = ii+1;
52868  }
52869  assert( pPager->nSavepoint==nSavepoint );
52870  assertTruncateConstraint(pPager);
52871  return rc;
52872}
52873SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
52874  assert( pPager->eState>=PAGER_WRITER_LOCKED );
52875  assert( assert_pager_state(pPager) );
52876
52877  if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
52878    return pagerOpenSavepoint(pPager, nSavepoint);
52879  }else{
52880    return SQLITE_OK;
52881  }
52882}
52883
52884
52885/*
52886** This function is called to rollback or release (commit) a savepoint.
52887** The savepoint to release or rollback need not be the most recently
52888** created savepoint.
52889**
52890** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
52891** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
52892** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
52893** that have occurred since the specified savepoint was created.
52894**
52895** The savepoint to rollback or release is identified by parameter
52896** iSavepoint. A value of 0 means to operate on the outermost savepoint
52897** (the first created). A value of (Pager.nSavepoint-1) means operate
52898** on the most recently created savepoint. If iSavepoint is greater than
52899** (Pager.nSavepoint-1), then this function is a no-op.
52900**
52901** If a negative value is passed to this function, then the current
52902** transaction is rolled back. This is different to calling
52903** sqlite3PagerRollback() because this function does not terminate
52904** the transaction or unlock the database, it just restores the
52905** contents of the database to its original state.
52906**
52907** In any case, all savepoints with an index greater than iSavepoint
52908** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
52909** then savepoint iSavepoint is also destroyed.
52910**
52911** This function may return SQLITE_NOMEM if a memory allocation fails,
52912** or an IO error code if an IO error occurs while rolling back a
52913** savepoint. If no errors occur, SQLITE_OK is returned.
52914*/
52915SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
52916  int rc = pPager->errCode;       /* Return code */
52917
52918  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
52919  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
52920
52921  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
52922    int ii;            /* Iterator variable */
52923    int nNew;          /* Number of remaining savepoints after this op. */
52924
52925    /* Figure out how many savepoints will still be active after this
52926    ** operation. Store this value in nNew. Then free resources associated
52927    ** with any savepoints that are destroyed by this operation.
52928    */
52929    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
52930    for(ii=nNew; ii<pPager->nSavepoint; ii++){
52931      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
52932    }
52933    pPager->nSavepoint = nNew;
52934
52935    /* If this is a release of the outermost savepoint, truncate
52936    ** the sub-journal to zero bytes in size. */
52937    if( op==SAVEPOINT_RELEASE ){
52938      if( nNew==0 && isOpen(pPager->sjfd) ){
52939        /* Only truncate if it is an in-memory sub-journal. */
52940        if( sqlite3JournalIsInMemory(pPager->sjfd) ){
52941          rc = sqlite3OsTruncate(pPager->sjfd, 0);
52942          assert( rc==SQLITE_OK );
52943        }
52944        pPager->nSubRec = 0;
52945      }
52946    }
52947    /* Else this is a rollback operation, playback the specified savepoint.
52948    ** If this is a temp-file, it is possible that the journal file has
52949    ** not yet been opened. In this case there have been no changes to
52950    ** the database file, so the playback operation can be skipped.
52951    */
52952    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
52953      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
52954      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
52955      assert(rc!=SQLITE_DONE);
52956    }
52957  }
52958
52959  return rc;
52960}
52961
52962/*
52963** Return the full pathname of the database file.
52964**
52965** Except, if the pager is in-memory only, then return an empty string if
52966** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
52967** used to report the filename to the user, for compatibility with legacy
52968** behavior.  But when the Btree needs to know the filename for matching to
52969** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
52970** participate in shared-cache.
52971*/
52972SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
52973  return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
52974}
52975
52976/*
52977** Return the VFS structure for the pager.
52978*/
52979SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
52980  return pPager->pVfs;
52981}
52982
52983/*
52984** Return the file handle for the database file associated
52985** with the pager.  This might return NULL if the file has
52986** not yet been opened.
52987*/
52988SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
52989  return pPager->fd;
52990}
52991
52992/*
52993** Return the file handle for the journal file (if it exists).
52994** This will be either the rollback journal or the WAL file.
52995*/
52996SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
52997#if SQLITE_OMIT_WAL
52998  return pPager->jfd;
52999#else
53000  return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
53001#endif
53002}
53003
53004/*
53005** Return the full pathname of the journal file.
53006*/
53007SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
53008  return pPager->zJournal;
53009}
53010
53011#ifdef SQLITE_HAS_CODEC
53012/*
53013** Set or retrieve the codec for this pager
53014*/
53015SQLITE_PRIVATE void sqlite3PagerSetCodec(
53016  Pager *pPager,
53017  void *(*xCodec)(void*,void*,Pgno,int),
53018  void (*xCodecSizeChng)(void*,int,int),
53019  void (*xCodecFree)(void*),
53020  void *pCodec
53021){
53022  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
53023  pPager->xCodec = pPager->memDb ? 0 : xCodec;
53024  pPager->xCodecSizeChng = xCodecSizeChng;
53025  pPager->xCodecFree = xCodecFree;
53026  pPager->pCodec = pCodec;
53027  pagerReportSize(pPager);
53028}
53029SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
53030  return pPager->pCodec;
53031}
53032
53033/*
53034** This function is called by the wal module when writing page content
53035** into the log file.
53036**
53037** This function returns a pointer to a buffer containing the encrypted
53038** page content. If a malloc fails, this function may return NULL.
53039*/
53040SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
53041  void *aData = 0;
53042  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
53043  return aData;
53044}
53045
53046/*
53047** Return the current pager state
53048*/
53049SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
53050  return pPager->eState;
53051}
53052#endif /* SQLITE_HAS_CODEC */
53053
53054#ifndef SQLITE_OMIT_AUTOVACUUM
53055/*
53056** Move the page pPg to location pgno in the file.
53057**
53058** There must be no references to the page previously located at
53059** pgno (which we call pPgOld) though that page is allowed to be
53060** in cache.  If the page previously located at pgno is not already
53061** in the rollback journal, it is not put there by by this routine.
53062**
53063** References to the page pPg remain valid. Updating any
53064** meta-data associated with pPg (i.e. data stored in the nExtra bytes
53065** allocated along with the page) is the responsibility of the caller.
53066**
53067** A transaction must be active when this routine is called. It used to be
53068** required that a statement transaction was not active, but this restriction
53069** has been removed (CREATE INDEX needs to move a page when a statement
53070** transaction is active).
53071**
53072** If the fourth argument, isCommit, is non-zero, then this page is being
53073** moved as part of a database reorganization just before the transaction
53074** is being committed. In this case, it is guaranteed that the database page
53075** pPg refers to will not be written to again within this transaction.
53076**
53077** This function may return SQLITE_NOMEM or an IO error code if an error
53078** occurs. Otherwise, it returns SQLITE_OK.
53079*/
53080SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
53081  PgHdr *pPgOld;               /* The page being overwritten. */
53082  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
53083  int rc;                      /* Return code */
53084  Pgno origPgno;               /* The original page number */
53085
53086  assert( pPg->nRef>0 );
53087  assert( pPager->eState==PAGER_WRITER_CACHEMOD
53088       || pPager->eState==PAGER_WRITER_DBMOD
53089  );
53090  assert( assert_pager_state(pPager) );
53091
53092  /* In order to be able to rollback, an in-memory database must journal
53093  ** the page we are moving from.
53094  */
53095  assert( pPager->tempFile || !MEMDB );
53096  if( pPager->tempFile ){
53097    rc = sqlite3PagerWrite(pPg);
53098    if( rc ) return rc;
53099  }
53100
53101  /* If the page being moved is dirty and has not been saved by the latest
53102  ** savepoint, then save the current contents of the page into the
53103  ** sub-journal now. This is required to handle the following scenario:
53104  **
53105  **   BEGIN;
53106  **     <journal page X, then modify it in memory>
53107  **     SAVEPOINT one;
53108  **       <Move page X to location Y>
53109  **     ROLLBACK TO one;
53110  **
53111  ** If page X were not written to the sub-journal here, it would not
53112  ** be possible to restore its contents when the "ROLLBACK TO one"
53113  ** statement were is processed.
53114  **
53115  ** subjournalPage() may need to allocate space to store pPg->pgno into
53116  ** one or more savepoint bitvecs. This is the reason this function
53117  ** may return SQLITE_NOMEM.
53118  */
53119  if( (pPg->flags & PGHDR_DIRTY)!=0
53120   && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
53121  ){
53122    return rc;
53123  }
53124
53125  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
53126      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
53127  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
53128
53129  /* If the journal needs to be sync()ed before page pPg->pgno can
53130  ** be written to, store pPg->pgno in local variable needSyncPgno.
53131  **
53132  ** If the isCommit flag is set, there is no need to remember that
53133  ** the journal needs to be sync()ed before database page pPg->pgno
53134  ** can be written to. The caller has already promised not to write to it.
53135  */
53136  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
53137    needSyncPgno = pPg->pgno;
53138    assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
53139            pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
53140    assert( pPg->flags&PGHDR_DIRTY );
53141  }
53142
53143  /* If the cache contains a page with page-number pgno, remove it
53144  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
53145  ** page pgno before the 'move' operation, it needs to be retained
53146  ** for the page moved there.
53147  */
53148  pPg->flags &= ~PGHDR_NEED_SYNC;
53149  pPgOld = sqlite3PagerLookup(pPager, pgno);
53150  assert( !pPgOld || pPgOld->nRef==1 );
53151  if( pPgOld ){
53152    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
53153    if( pPager->tempFile ){
53154      /* Do not discard pages from an in-memory database since we might
53155      ** need to rollback later.  Just move the page out of the way. */
53156      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
53157    }else{
53158      sqlite3PcacheDrop(pPgOld);
53159    }
53160  }
53161
53162  origPgno = pPg->pgno;
53163  sqlite3PcacheMove(pPg, pgno);
53164  sqlite3PcacheMakeDirty(pPg);
53165
53166  /* For an in-memory database, make sure the original page continues
53167  ** to exist, in case the transaction needs to roll back.  Use pPgOld
53168  ** as the original page since it has already been allocated.
53169  */
53170  if( pPager->tempFile && pPgOld ){
53171    sqlite3PcacheMove(pPgOld, origPgno);
53172    sqlite3PagerUnrefNotNull(pPgOld);
53173  }
53174
53175  if( needSyncPgno ){
53176    /* If needSyncPgno is non-zero, then the journal file needs to be
53177    ** sync()ed before any data is written to database file page needSyncPgno.
53178    ** Currently, no such page exists in the page-cache and the
53179    ** "is journaled" bitvec flag has been set. This needs to be remedied by
53180    ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
53181    ** flag.
53182    **
53183    ** If the attempt to load the page into the page-cache fails, (due
53184    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
53185    ** array. Otherwise, if the page is loaded and written again in
53186    ** this transaction, it may be written to the database file before
53187    ** it is synced into the journal file. This way, it may end up in
53188    ** the journal file twice, but that is not a problem.
53189    */
53190    PgHdr *pPgHdr;
53191    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
53192    if( rc!=SQLITE_OK ){
53193      if( needSyncPgno<=pPager->dbOrigSize ){
53194        assert( pPager->pTmpSpace!=0 );
53195        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
53196      }
53197      return rc;
53198    }
53199    pPgHdr->flags |= PGHDR_NEED_SYNC;
53200    sqlite3PcacheMakeDirty(pPgHdr);
53201    sqlite3PagerUnrefNotNull(pPgHdr);
53202  }
53203
53204  return SQLITE_OK;
53205}
53206#endif
53207
53208/*
53209** The page handle passed as the first argument refers to a dirty page
53210** with a page number other than iNew. This function changes the page's
53211** page number to iNew and sets the value of the PgHdr.flags field to
53212** the value passed as the third parameter.
53213*/
53214SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
53215  assert( pPg->pgno!=iNew );
53216  pPg->flags = flags;
53217  sqlite3PcacheMove(pPg, iNew);
53218}
53219
53220/*
53221** Return a pointer to the data for the specified page.
53222*/
53223SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
53224  assert( pPg->nRef>0 || pPg->pPager->memDb );
53225  return pPg->pData;
53226}
53227
53228/*
53229** Return a pointer to the Pager.nExtra bytes of "extra" space
53230** allocated along with the specified page.
53231*/
53232SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
53233  return pPg->pExtra;
53234}
53235
53236/*
53237** Get/set the locking-mode for this pager. Parameter eMode must be one
53238** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
53239** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
53240** the locking-mode is set to the value specified.
53241**
53242** The returned value is either PAGER_LOCKINGMODE_NORMAL or
53243** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
53244** locking-mode.
53245*/
53246SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
53247  assert( eMode==PAGER_LOCKINGMODE_QUERY
53248            || eMode==PAGER_LOCKINGMODE_NORMAL
53249            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
53250  assert( PAGER_LOCKINGMODE_QUERY<0 );
53251  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
53252  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
53253  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
53254    pPager->exclusiveMode = (u8)eMode;
53255  }
53256  return (int)pPager->exclusiveMode;
53257}
53258
53259/*
53260** Set the journal-mode for this pager. Parameter eMode must be one of:
53261**
53262**    PAGER_JOURNALMODE_DELETE
53263**    PAGER_JOURNALMODE_TRUNCATE
53264**    PAGER_JOURNALMODE_PERSIST
53265**    PAGER_JOURNALMODE_OFF
53266**    PAGER_JOURNALMODE_MEMORY
53267**    PAGER_JOURNALMODE_WAL
53268**
53269** The journalmode is set to the value specified if the change is allowed.
53270** The change may be disallowed for the following reasons:
53271**
53272**   *  An in-memory database can only have its journal_mode set to _OFF
53273**      or _MEMORY.
53274**
53275**   *  Temporary databases cannot have _WAL journalmode.
53276**
53277** The returned indicate the current (possibly updated) journal-mode.
53278*/
53279SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
53280  u8 eOld = pPager->journalMode;    /* Prior journalmode */
53281
53282#ifdef SQLITE_DEBUG
53283  /* The print_pager_state() routine is intended to be used by the debugger
53284  ** only.  We invoke it once here to suppress a compiler warning. */
53285  print_pager_state(pPager);
53286#endif
53287
53288
53289  /* The eMode parameter is always valid */
53290  assert(      eMode==PAGER_JOURNALMODE_DELETE
53291            || eMode==PAGER_JOURNALMODE_TRUNCATE
53292            || eMode==PAGER_JOURNALMODE_PERSIST
53293            || eMode==PAGER_JOURNALMODE_OFF
53294            || eMode==PAGER_JOURNALMODE_WAL
53295            || eMode==PAGER_JOURNALMODE_MEMORY );
53296
53297  /* This routine is only called from the OP_JournalMode opcode, and
53298  ** the logic there will never allow a temporary file to be changed
53299  ** to WAL mode.
53300  */
53301  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
53302
53303  /* Do allow the journalmode of an in-memory database to be set to
53304  ** anything other than MEMORY or OFF
53305  */
53306  if( MEMDB ){
53307    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
53308    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
53309      eMode = eOld;
53310    }
53311  }
53312
53313  if( eMode!=eOld ){
53314
53315    /* Change the journal mode. */
53316    assert( pPager->eState!=PAGER_ERROR );
53317    pPager->journalMode = (u8)eMode;
53318
53319    /* When transistioning from TRUNCATE or PERSIST to any other journal
53320    ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
53321    ** delete the journal file.
53322    */
53323    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
53324    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
53325    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
53326    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
53327    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
53328    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
53329
53330    assert( isOpen(pPager->fd) || pPager->exclusiveMode );
53331    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
53332
53333      /* In this case we would like to delete the journal file. If it is
53334      ** not possible, then that is not a problem. Deleting the journal file
53335      ** here is an optimization only.
53336      **
53337      ** Before deleting the journal file, obtain a RESERVED lock on the
53338      ** database file. This ensures that the journal file is not deleted
53339      ** while it is in use by some other client.
53340      */
53341      sqlite3OsClose(pPager->jfd);
53342      if( pPager->eLock>=RESERVED_LOCK ){
53343        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
53344      }else{
53345        int rc = SQLITE_OK;
53346        int state = pPager->eState;
53347        assert( state==PAGER_OPEN || state==PAGER_READER );
53348        if( state==PAGER_OPEN ){
53349          rc = sqlite3PagerSharedLock(pPager);
53350        }
53351        if( pPager->eState==PAGER_READER ){
53352          assert( rc==SQLITE_OK );
53353          rc = pagerLockDb(pPager, RESERVED_LOCK);
53354        }
53355        if( rc==SQLITE_OK ){
53356          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
53357        }
53358        if( rc==SQLITE_OK && state==PAGER_READER ){
53359          pagerUnlockDb(pPager, SHARED_LOCK);
53360        }else if( state==PAGER_OPEN ){
53361          pager_unlock(pPager);
53362        }
53363        assert( state==pPager->eState );
53364      }
53365    }else if( eMode==PAGER_JOURNALMODE_OFF ){
53366      sqlite3OsClose(pPager->jfd);
53367    }
53368  }
53369
53370  /* Return the new journal mode */
53371  return (int)pPager->journalMode;
53372}
53373
53374/*
53375** Return the current journal mode.
53376*/
53377SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
53378  return (int)pPager->journalMode;
53379}
53380
53381/*
53382** Return TRUE if the pager is in a state where it is OK to change the
53383** journalmode.  Journalmode changes can only happen when the database
53384** is unmodified.
53385*/
53386SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
53387  assert( assert_pager_state(pPager) );
53388  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
53389  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
53390  return 1;
53391}
53392
53393/*
53394** Get/set the size-limit used for persistent journal files.
53395**
53396** Setting the size limit to -1 means no limit is enforced.
53397** An attempt to set a limit smaller than -1 is a no-op.
53398*/
53399SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
53400  if( iLimit>=-1 ){
53401    pPager->journalSizeLimit = iLimit;
53402    sqlite3WalLimit(pPager->pWal, iLimit);
53403  }
53404  return pPager->journalSizeLimit;
53405}
53406
53407/*
53408** Return a pointer to the pPager->pBackup variable. The backup module
53409** in backup.c maintains the content of this variable. This module
53410** uses it opaquely as an argument to sqlite3BackupRestart() and
53411** sqlite3BackupUpdate() only.
53412*/
53413SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
53414  return &pPager->pBackup;
53415}
53416
53417#ifndef SQLITE_OMIT_VACUUM
53418/*
53419** Unless this is an in-memory or temporary database, clear the pager cache.
53420*/
53421SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
53422  assert( MEMDB==0 || pPager->tempFile );
53423  if( pPager->tempFile==0 ) pager_reset(pPager);
53424}
53425#endif
53426
53427
53428#ifndef SQLITE_OMIT_WAL
53429/*
53430** This function is called when the user invokes "PRAGMA wal_checkpoint",
53431** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
53432** or wal_blocking_checkpoint() API functions.
53433**
53434** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
53435*/
53436SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
53437  int rc = SQLITE_OK;
53438  if( pPager->pWal ){
53439    rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
53440        (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
53441        pPager->pBusyHandlerArg,
53442        pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
53443        pnLog, pnCkpt
53444    );
53445  }
53446  return rc;
53447}
53448
53449SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
53450  return sqlite3WalCallback(pPager->pWal);
53451}
53452
53453/*
53454** Return true if the underlying VFS for the given pager supports the
53455** primitives necessary for write-ahead logging.
53456*/
53457SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
53458  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
53459  if( pPager->noLock ) return 0;
53460  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
53461}
53462
53463/*
53464** Attempt to take an exclusive lock on the database file. If a PENDING lock
53465** is obtained instead, immediately release it.
53466*/
53467static int pagerExclusiveLock(Pager *pPager){
53468  int rc;                         /* Return code */
53469
53470  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
53471  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
53472  if( rc!=SQLITE_OK ){
53473    /* If the attempt to grab the exclusive lock failed, release the
53474    ** pending lock that may have been obtained instead.  */
53475    pagerUnlockDb(pPager, SHARED_LOCK);
53476  }
53477
53478  return rc;
53479}
53480
53481/*
53482** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
53483** exclusive-locking mode when this function is called, take an EXCLUSIVE
53484** lock on the database file and use heap-memory to store the wal-index
53485** in. Otherwise, use the normal shared-memory.
53486*/
53487static int pagerOpenWal(Pager *pPager){
53488  int rc = SQLITE_OK;
53489
53490  assert( pPager->pWal==0 && pPager->tempFile==0 );
53491  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
53492
53493  /* If the pager is already in exclusive-mode, the WAL module will use
53494  ** heap-memory for the wal-index instead of the VFS shared-memory
53495  ** implementation. Take the exclusive lock now, before opening the WAL
53496  ** file, to make sure this is safe.
53497  */
53498  if( pPager->exclusiveMode ){
53499    rc = pagerExclusiveLock(pPager);
53500  }
53501
53502  /* Open the connection to the log file. If this operation fails,
53503  ** (e.g. due to malloc() failure), return an error code.
53504  */
53505  if( rc==SQLITE_OK ){
53506    rc = sqlite3WalOpen(pPager->pVfs,
53507        pPager->fd, pPager->zWal, pPager->exclusiveMode,
53508        pPager->journalSizeLimit, &pPager->pWal
53509    );
53510  }
53511  pagerFixMaplimit(pPager);
53512
53513  return rc;
53514}
53515
53516
53517/*
53518** The caller must be holding a SHARED lock on the database file to call
53519** this function.
53520**
53521** If the pager passed as the first argument is open on a real database
53522** file (not a temp file or an in-memory database), and the WAL file
53523** is not already open, make an attempt to open it now. If successful,
53524** return SQLITE_OK. If an error occurs or the VFS used by the pager does
53525** not support the xShmXXX() methods, return an error code. *pbOpen is
53526** not modified in either case.
53527**
53528** If the pager is open on a temp-file (or in-memory database), or if
53529** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
53530** without doing anything.
53531*/
53532SQLITE_PRIVATE int sqlite3PagerOpenWal(
53533  Pager *pPager,                  /* Pager object */
53534  int *pbOpen                     /* OUT: Set to true if call is a no-op */
53535){
53536  int rc = SQLITE_OK;             /* Return code */
53537
53538  assert( assert_pager_state(pPager) );
53539  assert( pPager->eState==PAGER_OPEN   || pbOpen );
53540  assert( pPager->eState==PAGER_READER || !pbOpen );
53541  assert( pbOpen==0 || *pbOpen==0 );
53542  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
53543
53544  if( !pPager->tempFile && !pPager->pWal ){
53545    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
53546
53547    /* Close any rollback journal previously open */
53548    sqlite3OsClose(pPager->jfd);
53549
53550    rc = pagerOpenWal(pPager);
53551    if( rc==SQLITE_OK ){
53552      pPager->journalMode = PAGER_JOURNALMODE_WAL;
53553      pPager->eState = PAGER_OPEN;
53554    }
53555  }else{
53556    *pbOpen = 1;
53557  }
53558
53559  return rc;
53560}
53561
53562/*
53563** This function is called to close the connection to the log file prior
53564** to switching from WAL to rollback mode.
53565**
53566** Before closing the log file, this function attempts to take an
53567** EXCLUSIVE lock on the database file. If this cannot be obtained, an
53568** error (SQLITE_BUSY) is returned and the log connection is not closed.
53569** If successful, the EXCLUSIVE lock is not released before returning.
53570*/
53571SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
53572  int rc = SQLITE_OK;
53573
53574  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
53575
53576  /* If the log file is not already open, but does exist in the file-system,
53577  ** it may need to be checkpointed before the connection can switch to
53578  ** rollback mode. Open it now so this can happen.
53579  */
53580  if( !pPager->pWal ){
53581    int logexists = 0;
53582    rc = pagerLockDb(pPager, SHARED_LOCK);
53583    if( rc==SQLITE_OK ){
53584      rc = sqlite3OsAccess(
53585          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
53586      );
53587    }
53588    if( rc==SQLITE_OK && logexists ){
53589      rc = pagerOpenWal(pPager);
53590    }
53591  }
53592
53593  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
53594  ** the database file, the log and log-summary files will be deleted.
53595  */
53596  if( rc==SQLITE_OK && pPager->pWal ){
53597    rc = pagerExclusiveLock(pPager);
53598    if( rc==SQLITE_OK ){
53599      rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
53600                           pPager->pageSize, (u8*)pPager->pTmpSpace);
53601      pPager->pWal = 0;
53602      pagerFixMaplimit(pPager);
53603      if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
53604    }
53605  }
53606  return rc;
53607}
53608
53609#ifdef SQLITE_ENABLE_SNAPSHOT
53610/*
53611** If this is a WAL database, obtain a snapshot handle for the snapshot
53612** currently open. Otherwise, return an error.
53613*/
53614SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
53615  int rc = SQLITE_ERROR;
53616  if( pPager->pWal ){
53617    rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
53618  }
53619  return rc;
53620}
53621
53622/*
53623** If this is a WAL database, store a pointer to pSnapshot. Next time a
53624** read transaction is opened, attempt to read from the snapshot it
53625** identifies. If this is not a WAL database, return an error.
53626*/
53627SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
53628  int rc = SQLITE_OK;
53629  if( pPager->pWal ){
53630    sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
53631  }else{
53632    rc = SQLITE_ERROR;
53633  }
53634  return rc;
53635}
53636#endif /* SQLITE_ENABLE_SNAPSHOT */
53637#endif /* !SQLITE_OMIT_WAL */
53638
53639#ifdef SQLITE_ENABLE_ZIPVFS
53640/*
53641** A read-lock must be held on the pager when this function is called. If
53642** the pager is in WAL mode and the WAL file currently contains one or more
53643** frames, return the size in bytes of the page images stored within the
53644** WAL frames. Otherwise, if this is not a WAL database or the WAL file
53645** is empty, return 0.
53646*/
53647SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
53648  assert( pPager->eState>=PAGER_READER );
53649  return sqlite3WalFramesize(pPager->pWal);
53650}
53651#endif
53652
53653#endif /* SQLITE_OMIT_DISKIO */
53654
53655/************** End of pager.c ***********************************************/
53656/************** Begin file wal.c *********************************************/
53657/*
53658** 2010 February 1
53659**
53660** The author disclaims copyright to this source code.  In place of
53661** a legal notice, here is a blessing:
53662**
53663**    May you do good and not evil.
53664**    May you find forgiveness for yourself and forgive others.
53665**    May you share freely, never taking more than you give.
53666**
53667*************************************************************************
53668**
53669** This file contains the implementation of a write-ahead log (WAL) used in
53670** "journal_mode=WAL" mode.
53671**
53672** WRITE-AHEAD LOG (WAL) FILE FORMAT
53673**
53674** A WAL file consists of a header followed by zero or more "frames".
53675** Each frame records the revised content of a single page from the
53676** database file.  All changes to the database are recorded by writing
53677** frames into the WAL.  Transactions commit when a frame is written that
53678** contains a commit marker.  A single WAL can and usually does record
53679** multiple transactions.  Periodically, the content of the WAL is
53680** transferred back into the database file in an operation called a
53681** "checkpoint".
53682**
53683** A single WAL file can be used multiple times.  In other words, the
53684** WAL can fill up with frames and then be checkpointed and then new
53685** frames can overwrite the old ones.  A WAL always grows from beginning
53686** toward the end.  Checksums and counters attached to each frame are
53687** used to determine which frames within the WAL are valid and which
53688** are leftovers from prior checkpoints.
53689**
53690** The WAL header is 32 bytes in size and consists of the following eight
53691** big-endian 32-bit unsigned integer values:
53692**
53693**     0: Magic number.  0x377f0682 or 0x377f0683
53694**     4: File format version.  Currently 3007000
53695**     8: Database page size.  Example: 1024
53696**    12: Checkpoint sequence number
53697**    16: Salt-1, random integer incremented with each checkpoint
53698**    20: Salt-2, a different random integer changing with each ckpt
53699**    24: Checksum-1 (first part of checksum for first 24 bytes of header).
53700**    28: Checksum-2 (second part of checksum for first 24 bytes of header).
53701**
53702** Immediately following the wal-header are zero or more frames. Each
53703** frame consists of a 24-byte frame-header followed by a <page-size> bytes
53704** of page data. The frame-header is six big-endian 32-bit unsigned
53705** integer values, as follows:
53706**
53707**     0: Page number.
53708**     4: For commit records, the size of the database image in pages
53709**        after the commit. For all other records, zero.
53710**     8: Salt-1 (copied from the header)
53711**    12: Salt-2 (copied from the header)
53712**    16: Checksum-1.
53713**    20: Checksum-2.
53714**
53715** A frame is considered valid if and only if the following conditions are
53716** true:
53717**
53718**    (1) The salt-1 and salt-2 values in the frame-header match
53719**        salt values in the wal-header
53720**
53721**    (2) The checksum values in the final 8 bytes of the frame-header
53722**        exactly match the checksum computed consecutively on the
53723**        WAL header and the first 8 bytes and the content of all frames
53724**        up to and including the current frame.
53725**
53726** The checksum is computed using 32-bit big-endian integers if the
53727** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
53728** is computed using little-endian if the magic number is 0x377f0682.
53729** The checksum values are always stored in the frame header in a
53730** big-endian format regardless of which byte order is used to compute
53731** the checksum.  The checksum is computed by interpreting the input as
53732** an even number of unsigned 32-bit integers: x[0] through x[N].  The
53733** algorithm used for the checksum is as follows:
53734**
53735**   for i from 0 to n-1 step 2:
53736**     s0 += x[i] + s1;
53737**     s1 += x[i+1] + s0;
53738**   endfor
53739**
53740** Note that s0 and s1 are both weighted checksums using fibonacci weights
53741** in reverse order (the largest fibonacci weight occurs on the first element
53742** of the sequence being summed.)  The s1 value spans all 32-bit
53743** terms of the sequence whereas s0 omits the final term.
53744**
53745** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
53746** WAL is transferred into the database, then the database is VFS.xSync-ed.
53747** The VFS.xSync operations serve as write barriers - all writes launched
53748** before the xSync must complete before any write that launches after the
53749** xSync begins.
53750**
53751** After each checkpoint, the salt-1 value is incremented and the salt-2
53752** value is randomized.  This prevents old and new frames in the WAL from
53753** being considered valid at the same time and being checkpointing together
53754** following a crash.
53755**
53756** READER ALGORITHM
53757**
53758** To read a page from the database (call it page number P), a reader
53759** first checks the WAL to see if it contains page P.  If so, then the
53760** last valid instance of page P that is a followed by a commit frame
53761** or is a commit frame itself becomes the value read.  If the WAL
53762** contains no copies of page P that are valid and which are a commit
53763** frame or are followed by a commit frame, then page P is read from
53764** the database file.
53765**
53766** To start a read transaction, the reader records the index of the last
53767** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
53768** for all subsequent read operations.  New transactions can be appended
53769** to the WAL, but as long as the reader uses its original mxFrame value
53770** and ignores the newly appended content, it will see a consistent snapshot
53771** of the database from a single point in time.  This technique allows
53772** multiple concurrent readers to view different versions of the database
53773** content simultaneously.
53774**
53775** The reader algorithm in the previous paragraphs works correctly, but
53776** because frames for page P can appear anywhere within the WAL, the
53777** reader has to scan the entire WAL looking for page P frames.  If the
53778** WAL is large (multiple megabytes is typical) that scan can be slow,
53779** and read performance suffers.  To overcome this problem, a separate
53780** data structure called the wal-index is maintained to expedite the
53781** search for frames of a particular page.
53782**
53783** WAL-INDEX FORMAT
53784**
53785** Conceptually, the wal-index is shared memory, though VFS implementations
53786** might choose to implement the wal-index using a mmapped file.  Because
53787** the wal-index is shared memory, SQLite does not support journal_mode=WAL
53788** on a network filesystem.  All users of the database must be able to
53789** share memory.
53790**
53791** The wal-index is transient.  After a crash, the wal-index can (and should
53792** be) reconstructed from the original WAL file.  In fact, the VFS is required
53793** to either truncate or zero the header of the wal-index when the last
53794** connection to it closes.  Because the wal-index is transient, it can
53795** use an architecture-specific format; it does not have to be cross-platform.
53796** Hence, unlike the database and WAL file formats which store all values
53797** as big endian, the wal-index can store multi-byte values in the native
53798** byte order of the host computer.
53799**
53800** The purpose of the wal-index is to answer this question quickly:  Given
53801** a page number P and a maximum frame index M, return the index of the
53802** last frame in the wal before frame M for page P in the WAL, or return
53803** NULL if there are no frames for page P in the WAL prior to M.
53804**
53805** The wal-index consists of a header region, followed by an one or
53806** more index blocks.
53807**
53808** The wal-index header contains the total number of frames within the WAL
53809** in the mxFrame field.
53810**
53811** Each index block except for the first contains information on
53812** HASHTABLE_NPAGE frames. The first index block contains information on
53813** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
53814** HASHTABLE_NPAGE are selected so that together the wal-index header and
53815** first index block are the same size as all other index blocks in the
53816** wal-index.
53817**
53818** Each index block contains two sections, a page-mapping that contains the
53819** database page number associated with each wal frame, and a hash-table
53820** that allows readers to query an index block for a specific page number.
53821** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
53822** for the first index block) 32-bit page numbers. The first entry in the
53823** first index-block contains the database page number corresponding to the
53824** first frame in the WAL file. The first entry in the second index block
53825** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
53826** the log, and so on.
53827**
53828** The last index block in a wal-index usually contains less than the full
53829** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
53830** depending on the contents of the WAL file. This does not change the
53831** allocated size of the page-mapping array - the page-mapping array merely
53832** contains unused entries.
53833**
53834** Even without using the hash table, the last frame for page P
53835** can be found by scanning the page-mapping sections of each index block
53836** starting with the last index block and moving toward the first, and
53837** within each index block, starting at the end and moving toward the
53838** beginning.  The first entry that equals P corresponds to the frame
53839** holding the content for that page.
53840**
53841** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
53842** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
53843** hash table for each page number in the mapping section, so the hash
53844** table is never more than half full.  The expected number of collisions
53845** prior to finding a match is 1.  Each entry of the hash table is an
53846** 1-based index of an entry in the mapping section of the same
53847** index block.   Let K be the 1-based index of the largest entry in
53848** the mapping section.  (For index blocks other than the last, K will
53849** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
53850** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
53851** contain a value of 0.
53852**
53853** To look for page P in the hash table, first compute a hash iKey on
53854** P as follows:
53855**
53856**      iKey = (P * 383) % HASHTABLE_NSLOT
53857**
53858** Then start scanning entries of the hash table, starting with iKey
53859** (wrapping around to the beginning when the end of the hash table is
53860** reached) until an unused hash slot is found. Let the first unused slot
53861** be at index iUnused.  (iUnused might be less than iKey if there was
53862** wrap-around.) Because the hash table is never more than half full,
53863** the search is guaranteed to eventually hit an unused entry.  Let
53864** iMax be the value between iKey and iUnused, closest to iUnused,
53865** where aHash[iMax]==P.  If there is no iMax entry (if there exists
53866** no hash slot such that aHash[i]==p) then page P is not in the
53867** current index block.  Otherwise the iMax-th mapping entry of the
53868** current index block corresponds to the last entry that references
53869** page P.
53870**
53871** A hash search begins with the last index block and moves toward the
53872** first index block, looking for entries corresponding to page P.  On
53873** average, only two or three slots in each index block need to be
53874** examined in order to either find the last entry for page P, or to
53875** establish that no such entry exists in the block.  Each index block
53876** holds over 4000 entries.  So two or three index blocks are sufficient
53877** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
53878** comparisons (on average) suffice to either locate a frame in the
53879** WAL or to establish that the frame does not exist in the WAL.  This
53880** is much faster than scanning the entire 10MB WAL.
53881**
53882** Note that entries are added in order of increasing K.  Hence, one
53883** reader might be using some value K0 and a second reader that started
53884** at a later time (after additional transactions were added to the WAL
53885** and to the wal-index) might be using a different value K1, where K1>K0.
53886** Both readers can use the same hash table and mapping section to get
53887** the correct result.  There may be entries in the hash table with
53888** K>K0 but to the first reader, those entries will appear to be unused
53889** slots in the hash table and so the first reader will get an answer as
53890** if no values greater than K0 had ever been inserted into the hash table
53891** in the first place - which is what reader one wants.  Meanwhile, the
53892** second reader using K1 will see additional values that were inserted
53893** later, which is exactly what reader two wants.
53894**
53895** When a rollback occurs, the value of K is decreased. Hash table entries
53896** that correspond to frames greater than the new K value are removed
53897** from the hash table at this point.
53898*/
53899#ifndef SQLITE_OMIT_WAL
53900
53901/* #include "wal.h" */
53902
53903/*
53904** Trace output macros
53905*/
53906#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
53907SQLITE_PRIVATE int sqlite3WalTrace = 0;
53908# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
53909#else
53910# define WALTRACE(X)
53911#endif
53912
53913/*
53914** The maximum (and only) versions of the wal and wal-index formats
53915** that may be interpreted by this version of SQLite.
53916**
53917** If a client begins recovering a WAL file and finds that (a) the checksum
53918** values in the wal-header are correct and (b) the version field is not
53919** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
53920**
53921** Similarly, if a client successfully reads a wal-index header (i.e. the
53922** checksum test is successful) and finds that the version field is not
53923** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
53924** returns SQLITE_CANTOPEN.
53925*/
53926#define WAL_MAX_VERSION      3007000
53927#define WALINDEX_MAX_VERSION 3007000
53928
53929/*
53930** Indices of various locking bytes.   WAL_NREADER is the number
53931** of available reader locks and should be at least 3.  The default
53932** is SQLITE_SHM_NLOCK==8 and  WAL_NREADER==5.
53933*/
53934#define WAL_WRITE_LOCK         0
53935#define WAL_ALL_BUT_WRITE      1
53936#define WAL_CKPT_LOCK          1
53937#define WAL_RECOVER_LOCK       2
53938#define WAL_READ_LOCK(I)       (3+(I))
53939#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
53940
53941
53942/* Object declarations */
53943typedef struct WalIndexHdr WalIndexHdr;
53944typedef struct WalIterator WalIterator;
53945typedef struct WalCkptInfo WalCkptInfo;
53946
53947
53948/*
53949** The following object holds a copy of the wal-index header content.
53950**
53951** The actual header in the wal-index consists of two copies of this
53952** object followed by one instance of the WalCkptInfo object.
53953** For all versions of SQLite through 3.10.0 and probably beyond,
53954** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
53955** the total header size is 136 bytes.
53956**
53957** The szPage value can be any power of 2 between 512 and 32768, inclusive.
53958** Or it can be 1 to represent a 65536-byte page.  The latter case was
53959** added in 3.7.1 when support for 64K pages was added.
53960*/
53961struct WalIndexHdr {
53962  u32 iVersion;                   /* Wal-index version */
53963  u32 unused;                     /* Unused (padding) field */
53964  u32 iChange;                    /* Counter incremented each transaction */
53965  u8 isInit;                      /* 1 when initialized */
53966  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
53967  u16 szPage;                     /* Database page size in bytes. 1==64K */
53968  u32 mxFrame;                    /* Index of last valid frame in the WAL */
53969  u32 nPage;                      /* Size of database in pages */
53970  u32 aFrameCksum[2];             /* Checksum of last frame in log */
53971  u32 aSalt[2];                   /* Two salt values copied from WAL header */
53972  u32 aCksum[2];                  /* Checksum over all prior fields */
53973};
53974
53975/*
53976** A copy of the following object occurs in the wal-index immediately
53977** following the second copy of the WalIndexHdr.  This object stores
53978** information used by checkpoint.
53979**
53980** nBackfill is the number of frames in the WAL that have been written
53981** back into the database. (We call the act of moving content from WAL to
53982** database "backfilling".)  The nBackfill number is never greater than
53983** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
53984** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
53985** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
53986** mxFrame back to zero when the WAL is reset.
53987**
53988** nBackfillAttempted is the largest value of nBackfill that a checkpoint
53989** has attempted to achieve.  Normally nBackfill==nBackfillAtempted, however
53990** the nBackfillAttempted is set before any backfilling is done and the
53991** nBackfill is only set after all backfilling completes.  So if a checkpoint
53992** crashes, nBackfillAttempted might be larger than nBackfill.  The
53993** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
53994**
53995** The aLock[] field is a set of bytes used for locking.  These bytes should
53996** never be read or written.
53997**
53998** There is one entry in aReadMark[] for each reader lock.  If a reader
53999** holds read-lock K, then the value in aReadMark[K] is no greater than
54000** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
54001** for any aReadMark[] means that entry is unused.  aReadMark[0] is
54002** a special case; its value is never used and it exists as a place-holder
54003** to avoid having to offset aReadMark[] indexs by one.  Readers holding
54004** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
54005** directly from the database.
54006**
54007** The value of aReadMark[K] may only be changed by a thread that
54008** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
54009** aReadMark[K] cannot changed while there is a reader is using that mark
54010** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
54011**
54012** The checkpointer may only transfer frames from WAL to database where
54013** the frame numbers are less than or equal to every aReadMark[] that is
54014** in use (that is, every aReadMark[j] for which there is a corresponding
54015** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
54016** largest value and will increase an unused aReadMark[] to mxFrame if there
54017** is not already an aReadMark[] equal to mxFrame.  The exception to the
54018** previous sentence is when nBackfill equals mxFrame (meaning that everything
54019** in the WAL has been backfilled into the database) then new readers
54020** will choose aReadMark[0] which has value 0 and hence such reader will
54021** get all their all content directly from the database file and ignore
54022** the WAL.
54023**
54024** Writers normally append new frames to the end of the WAL.  However,
54025** if nBackfill equals mxFrame (meaning that all WAL content has been
54026** written back into the database) and if no readers are using the WAL
54027** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
54028** the writer will first "reset" the WAL back to the beginning and start
54029** writing new content beginning at frame 1.
54030**
54031** We assume that 32-bit loads are atomic and so no locks are needed in
54032** order to read from any aReadMark[] entries.
54033*/
54034struct WalCkptInfo {
54035  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
54036  u32 aReadMark[WAL_NREADER];     /* Reader marks */
54037  u8 aLock[SQLITE_SHM_NLOCK];     /* Reserved space for locks */
54038  u32 nBackfillAttempted;         /* WAL frames perhaps written, or maybe not */
54039  u32 notUsed0;                   /* Available for future enhancements */
54040};
54041#define READMARK_NOT_USED  0xffffffff
54042
54043
54044/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
54045** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
54046** only support mandatory file-locks, we do not read or write data
54047** from the region of the file on which locks are applied.
54048*/
54049#define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
54050#define WALINDEX_HDR_SIZE    (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
54051
54052/* Size of header before each frame in wal */
54053#define WAL_FRAME_HDRSIZE 24
54054
54055/* Size of write ahead log header, including checksum. */
54056/* #define WAL_HDRSIZE 24 */
54057#define WAL_HDRSIZE 32
54058
54059/* WAL magic value. Either this value, or the same value with the least
54060** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
54061** big-endian format in the first 4 bytes of a WAL file.
54062**
54063** If the LSB is set, then the checksums for each frame within the WAL
54064** file are calculated by treating all data as an array of 32-bit
54065** big-endian words. Otherwise, they are calculated by interpreting
54066** all data as 32-bit little-endian words.
54067*/
54068#define WAL_MAGIC 0x377f0682
54069
54070/*
54071** Return the offset of frame iFrame in the write-ahead log file,
54072** assuming a database page size of szPage bytes. The offset returned
54073** is to the start of the write-ahead log frame-header.
54074*/
54075#define walFrameOffset(iFrame, szPage) (                               \
54076  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
54077)
54078
54079/*
54080** An open write-ahead log file is represented by an instance of the
54081** following object.
54082*/
54083struct Wal {
54084  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
54085  sqlite3_file *pDbFd;       /* File handle for the database file */
54086  sqlite3_file *pWalFd;      /* File handle for WAL file */
54087  u32 iCallback;             /* Value to pass to log callback (or 0) */
54088  i64 mxWalSize;             /* Truncate WAL to this size upon reset */
54089  int nWiData;               /* Size of array apWiData */
54090  int szFirstBlock;          /* Size of first block written to WAL file */
54091  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
54092  u32 szPage;                /* Database page size */
54093  i16 readLock;              /* Which read lock is being held.  -1 for none */
54094  u8 syncFlags;              /* Flags to use to sync header writes */
54095  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
54096  u8 writeLock;              /* True if in a write transaction */
54097  u8 ckptLock;               /* True if holding a checkpoint lock */
54098  u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
54099  u8 truncateOnCommit;       /* True to truncate WAL file on commit */
54100  u8 syncHeader;             /* Fsync the WAL header if true */
54101  u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
54102  WalIndexHdr hdr;           /* Wal-index header for current transaction */
54103  u32 minFrame;              /* Ignore wal frames before this one */
54104  u32 iReCksum;              /* On commit, recalculate checksums from here */
54105  const char *zWalName;      /* Name of WAL file */
54106  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
54107#ifdef SQLITE_DEBUG
54108  u8 lockError;              /* True if a locking error has occurred */
54109#endif
54110#ifdef SQLITE_ENABLE_SNAPSHOT
54111  WalIndexHdr *pSnapshot;    /* Start transaction here if not NULL */
54112#endif
54113};
54114
54115/*
54116** Candidate values for Wal.exclusiveMode.
54117*/
54118#define WAL_NORMAL_MODE     0
54119#define WAL_EXCLUSIVE_MODE  1
54120#define WAL_HEAPMEMORY_MODE 2
54121
54122/*
54123** Possible values for WAL.readOnly
54124*/
54125#define WAL_RDWR        0    /* Normal read/write connection */
54126#define WAL_RDONLY      1    /* The WAL file is readonly */
54127#define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
54128
54129/*
54130** Each page of the wal-index mapping contains a hash-table made up of
54131** an array of HASHTABLE_NSLOT elements of the following type.
54132*/
54133typedef u16 ht_slot;
54134
54135/*
54136** This structure is used to implement an iterator that loops through
54137** all frames in the WAL in database page order. Where two or more frames
54138** correspond to the same database page, the iterator visits only the
54139** frame most recently written to the WAL (in other words, the frame with
54140** the largest index).
54141**
54142** The internals of this structure are only accessed by:
54143**
54144**   walIteratorInit() - Create a new iterator,
54145**   walIteratorNext() - Step an iterator,
54146**   walIteratorFree() - Free an iterator.
54147**
54148** This functionality is used by the checkpoint code (see walCheckpoint()).
54149*/
54150struct WalIterator {
54151  int iPrior;                     /* Last result returned from the iterator */
54152  int nSegment;                   /* Number of entries in aSegment[] */
54153  struct WalSegment {
54154    int iNext;                    /* Next slot in aIndex[] not yet returned */
54155    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
54156    u32 *aPgno;                   /* Array of page numbers. */
54157    int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
54158    int iZero;                    /* Frame number associated with aPgno[0] */
54159  } aSegment[1];                  /* One for every 32KB page in the wal-index */
54160};
54161
54162/*
54163** Define the parameters of the hash tables in the wal-index file. There
54164** is a hash-table following every HASHTABLE_NPAGE page numbers in the
54165** wal-index.
54166**
54167** Changing any of these constants will alter the wal-index format and
54168** create incompatibilities.
54169*/
54170#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
54171#define HASHTABLE_HASH_1     383                  /* Should be prime */
54172#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
54173
54174/*
54175** The block of page numbers associated with the first hash-table in a
54176** wal-index is smaller than usual. This is so that there is a complete
54177** hash-table on each aligned 32KB page of the wal-index.
54178*/
54179#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
54180
54181/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
54182#define WALINDEX_PGSZ   (                                         \
54183    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
54184)
54185
54186/*
54187** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
54188** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
54189** numbered from zero.
54190**
54191** If this call is successful, *ppPage is set to point to the wal-index
54192** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
54193** then an SQLite error code is returned and *ppPage is set to 0.
54194*/
54195static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
54196  int rc = SQLITE_OK;
54197
54198  /* Enlarge the pWal->apWiData[] array if required */
54199  if( pWal->nWiData<=iPage ){
54200    int nByte = sizeof(u32*)*(iPage+1);
54201    volatile u32 **apNew;
54202    apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
54203    if( !apNew ){
54204      *ppPage = 0;
54205      return SQLITE_NOMEM_BKPT;
54206    }
54207    memset((void*)&apNew[pWal->nWiData], 0,
54208           sizeof(u32*)*(iPage+1-pWal->nWiData));
54209    pWal->apWiData = apNew;
54210    pWal->nWiData = iPage+1;
54211  }
54212
54213  /* Request a pointer to the required page from the VFS */
54214  if( pWal->apWiData[iPage]==0 ){
54215    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
54216      pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
54217      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
54218    }else{
54219      rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
54220          pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
54221      );
54222      if( rc==SQLITE_READONLY ){
54223        pWal->readOnly |= WAL_SHM_RDONLY;
54224        rc = SQLITE_OK;
54225      }
54226    }
54227  }
54228
54229  *ppPage = pWal->apWiData[iPage];
54230  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
54231  return rc;
54232}
54233
54234/*
54235** Return a pointer to the WalCkptInfo structure in the wal-index.
54236*/
54237static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
54238  assert( pWal->nWiData>0 && pWal->apWiData[0] );
54239  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
54240}
54241
54242/*
54243** Return a pointer to the WalIndexHdr structure in the wal-index.
54244*/
54245static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
54246  assert( pWal->nWiData>0 && pWal->apWiData[0] );
54247  return (volatile WalIndexHdr*)pWal->apWiData[0];
54248}
54249
54250/*
54251** The argument to this macro must be of type u32. On a little-endian
54252** architecture, it returns the u32 value that results from interpreting
54253** the 4 bytes as a big-endian value. On a big-endian architecture, it
54254** returns the value that would be produced by interpreting the 4 bytes
54255** of the input value as a little-endian integer.
54256*/
54257#define BYTESWAP32(x) ( \
54258    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
54259  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
54260)
54261
54262/*
54263** Generate or extend an 8 byte checksum based on the data in
54264** array aByte[] and the initial values of aIn[0] and aIn[1] (or
54265** initial values of 0 and 0 if aIn==NULL).
54266**
54267** The checksum is written back into aOut[] before returning.
54268**
54269** nByte must be a positive multiple of 8.
54270*/
54271static void walChecksumBytes(
54272  int nativeCksum, /* True for native byte-order, false for non-native */
54273  u8 *a,           /* Content to be checksummed */
54274  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
54275  const u32 *aIn,  /* Initial checksum value input */
54276  u32 *aOut        /* OUT: Final checksum value output */
54277){
54278  u32 s1, s2;
54279  u32 *aData = (u32 *)a;
54280  u32 *aEnd = (u32 *)&a[nByte];
54281
54282  if( aIn ){
54283    s1 = aIn[0];
54284    s2 = aIn[1];
54285  }else{
54286    s1 = s2 = 0;
54287  }
54288
54289  assert( nByte>=8 );
54290  assert( (nByte&0x00000007)==0 );
54291
54292  if( nativeCksum ){
54293    do {
54294      s1 += *aData++ + s2;
54295      s2 += *aData++ + s1;
54296    }while( aData<aEnd );
54297  }else{
54298    do {
54299      s1 += BYTESWAP32(aData[0]) + s2;
54300      s2 += BYTESWAP32(aData[1]) + s1;
54301      aData += 2;
54302    }while( aData<aEnd );
54303  }
54304
54305  aOut[0] = s1;
54306  aOut[1] = s2;
54307}
54308
54309static void walShmBarrier(Wal *pWal){
54310  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
54311    sqlite3OsShmBarrier(pWal->pDbFd);
54312  }
54313}
54314
54315/*
54316** Write the header information in pWal->hdr into the wal-index.
54317**
54318** The checksum on pWal->hdr is updated before it is written.
54319*/
54320static void walIndexWriteHdr(Wal *pWal){
54321  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
54322  const int nCksum = offsetof(WalIndexHdr, aCksum);
54323
54324  assert( pWal->writeLock );
54325  pWal->hdr.isInit = 1;
54326  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
54327  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
54328  memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
54329  walShmBarrier(pWal);
54330  memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
54331}
54332
54333/*
54334** This function encodes a single frame header and writes it to a buffer
54335** supplied by the caller. A frame-header is made up of a series of
54336** 4-byte big-endian integers, as follows:
54337**
54338**     0: Page number.
54339**     4: For commit records, the size of the database image in pages
54340**        after the commit. For all other records, zero.
54341**     8: Salt-1 (copied from the wal-header)
54342**    12: Salt-2 (copied from the wal-header)
54343**    16: Checksum-1.
54344**    20: Checksum-2.
54345*/
54346static void walEncodeFrame(
54347  Wal *pWal,                      /* The write-ahead log */
54348  u32 iPage,                      /* Database page number for frame */
54349  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
54350  u8 *aData,                      /* Pointer to page data */
54351  u8 *aFrame                      /* OUT: Write encoded frame here */
54352){
54353  int nativeCksum;                /* True for native byte-order checksums */
54354  u32 *aCksum = pWal->hdr.aFrameCksum;
54355  assert( WAL_FRAME_HDRSIZE==24 );
54356  sqlite3Put4byte(&aFrame[0], iPage);
54357  sqlite3Put4byte(&aFrame[4], nTruncate);
54358  if( pWal->iReCksum==0 ){
54359    memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
54360
54361    nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
54362    walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
54363    walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
54364
54365    sqlite3Put4byte(&aFrame[16], aCksum[0]);
54366    sqlite3Put4byte(&aFrame[20], aCksum[1]);
54367  }else{
54368    memset(&aFrame[8], 0, 16);
54369  }
54370}
54371
54372/*
54373** Check to see if the frame with header in aFrame[] and content
54374** in aData[] is valid.  If it is a valid frame, fill *piPage and
54375** *pnTruncate and return true.  Return if the frame is not valid.
54376*/
54377static int walDecodeFrame(
54378  Wal *pWal,                      /* The write-ahead log */
54379  u32 *piPage,                    /* OUT: Database page number for frame */
54380  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
54381  u8 *aData,                      /* Pointer to page data (for checksum) */
54382  u8 *aFrame                      /* Frame data */
54383){
54384  int nativeCksum;                /* True for native byte-order checksums */
54385  u32 *aCksum = pWal->hdr.aFrameCksum;
54386  u32 pgno;                       /* Page number of the frame */
54387  assert( WAL_FRAME_HDRSIZE==24 );
54388
54389  /* A frame is only valid if the salt values in the frame-header
54390  ** match the salt values in the wal-header.
54391  */
54392  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
54393    return 0;
54394  }
54395
54396  /* A frame is only valid if the page number is creater than zero.
54397  */
54398  pgno = sqlite3Get4byte(&aFrame[0]);
54399  if( pgno==0 ){
54400    return 0;
54401  }
54402
54403  /* A frame is only valid if a checksum of the WAL header,
54404  ** all prior frams, the first 16 bytes of this frame-header,
54405  ** and the frame-data matches the checksum in the last 8
54406  ** bytes of this frame-header.
54407  */
54408  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
54409  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
54410  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
54411  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
54412   || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
54413  ){
54414    /* Checksum failed. */
54415    return 0;
54416  }
54417
54418  /* If we reach this point, the frame is valid.  Return the page number
54419  ** and the new database size.
54420  */
54421  *piPage = pgno;
54422  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
54423  return 1;
54424}
54425
54426
54427#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
54428/*
54429** Names of locks.  This routine is used to provide debugging output and is not
54430** a part of an ordinary build.
54431*/
54432static const char *walLockName(int lockIdx){
54433  if( lockIdx==WAL_WRITE_LOCK ){
54434    return "WRITE-LOCK";
54435  }else if( lockIdx==WAL_CKPT_LOCK ){
54436    return "CKPT-LOCK";
54437  }else if( lockIdx==WAL_RECOVER_LOCK ){
54438    return "RECOVER-LOCK";
54439  }else{
54440    static char zName[15];
54441    sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
54442                     lockIdx-WAL_READ_LOCK(0));
54443    return zName;
54444  }
54445}
54446#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
54447
54448
54449/*
54450** Set or release locks on the WAL.  Locks are either shared or exclusive.
54451** A lock cannot be moved directly between shared and exclusive - it must go
54452** through the unlocked state first.
54453**
54454** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
54455*/
54456static int walLockShared(Wal *pWal, int lockIdx){
54457  int rc;
54458  if( pWal->exclusiveMode ) return SQLITE_OK;
54459  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
54460                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
54461  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
54462            walLockName(lockIdx), rc ? "failed" : "ok"));
54463  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
54464  return rc;
54465}
54466static void walUnlockShared(Wal *pWal, int lockIdx){
54467  if( pWal->exclusiveMode ) return;
54468  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
54469                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
54470  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
54471}
54472static int walLockExclusive(Wal *pWal, int lockIdx, int n){
54473  int rc;
54474  if( pWal->exclusiveMode ) return SQLITE_OK;
54475  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
54476                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
54477  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
54478            walLockName(lockIdx), n, rc ? "failed" : "ok"));
54479  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
54480  return rc;
54481}
54482static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
54483  if( pWal->exclusiveMode ) return;
54484  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
54485                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
54486  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
54487             walLockName(lockIdx), n));
54488}
54489
54490/*
54491** Compute a hash on a page number.  The resulting hash value must land
54492** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
54493** the hash to the next value in the event of a collision.
54494*/
54495static int walHash(u32 iPage){
54496  assert( iPage>0 );
54497  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
54498  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
54499}
54500static int walNextHash(int iPriorHash){
54501  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
54502}
54503
54504/*
54505** Return pointers to the hash table and page number array stored on
54506** page iHash of the wal-index. The wal-index is broken into 32KB pages
54507** numbered starting from 0.
54508**
54509** Set output variable *paHash to point to the start of the hash table
54510** in the wal-index file. Set *piZero to one less than the frame
54511** number of the first frame indexed by this hash table. If a
54512** slot in the hash table is set to N, it refers to frame number
54513** (*piZero+N) in the log.
54514**
54515** Finally, set *paPgno so that *paPgno[1] is the page number of the
54516** first frame indexed by the hash table, frame (*piZero+1).
54517*/
54518static int walHashGet(
54519  Wal *pWal,                      /* WAL handle */
54520  int iHash,                      /* Find the iHash'th table */
54521  volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
54522  volatile u32 **paPgno,          /* OUT: Pointer to page number array */
54523  u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
54524){
54525  int rc;                         /* Return code */
54526  volatile u32 *aPgno;
54527
54528  rc = walIndexPage(pWal, iHash, &aPgno);
54529  assert( rc==SQLITE_OK || iHash>0 );
54530
54531  if( rc==SQLITE_OK ){
54532    u32 iZero;
54533    volatile ht_slot *aHash;
54534
54535    aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
54536    if( iHash==0 ){
54537      aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
54538      iZero = 0;
54539    }else{
54540      iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
54541    }
54542
54543    *paPgno = &aPgno[-1];
54544    *paHash = aHash;
54545    *piZero = iZero;
54546  }
54547  return rc;
54548}
54549
54550/*
54551** Return the number of the wal-index page that contains the hash-table
54552** and page-number array that contain entries corresponding to WAL frame
54553** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
54554** are numbered starting from 0.
54555*/
54556static int walFramePage(u32 iFrame){
54557  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
54558  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
54559       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
54560       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
54561       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
54562       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
54563  );
54564  return iHash;
54565}
54566
54567/*
54568** Return the page number associated with frame iFrame in this WAL.
54569*/
54570static u32 walFramePgno(Wal *pWal, u32 iFrame){
54571  int iHash = walFramePage(iFrame);
54572  if( iHash==0 ){
54573    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
54574  }
54575  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
54576}
54577
54578/*
54579** Remove entries from the hash table that point to WAL slots greater
54580** than pWal->hdr.mxFrame.
54581**
54582** This function is called whenever pWal->hdr.mxFrame is decreased due
54583** to a rollback or savepoint.
54584**
54585** At most only the hash table containing pWal->hdr.mxFrame needs to be
54586** updated.  Any later hash tables will be automatically cleared when
54587** pWal->hdr.mxFrame advances to the point where those hash tables are
54588** actually needed.
54589*/
54590static void walCleanupHash(Wal *pWal){
54591  volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
54592  volatile u32 *aPgno = 0;        /* Page number array for hash table */
54593  u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
54594  int iLimit = 0;                 /* Zero values greater than this */
54595  int nByte;                      /* Number of bytes to zero in aPgno[] */
54596  int i;                          /* Used to iterate through aHash[] */
54597
54598  assert( pWal->writeLock );
54599  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
54600  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
54601  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
54602
54603  if( pWal->hdr.mxFrame==0 ) return;
54604
54605  /* Obtain pointers to the hash-table and page-number array containing
54606  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
54607  ** that the page said hash-table and array reside on is already mapped.
54608  */
54609  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
54610  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
54611  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
54612
54613  /* Zero all hash-table entries that correspond to frame numbers greater
54614  ** than pWal->hdr.mxFrame.
54615  */
54616  iLimit = pWal->hdr.mxFrame - iZero;
54617  assert( iLimit>0 );
54618  for(i=0; i<HASHTABLE_NSLOT; i++){
54619    if( aHash[i]>iLimit ){
54620      aHash[i] = 0;
54621    }
54622  }
54623
54624  /* Zero the entries in the aPgno array that correspond to frames with
54625  ** frame numbers greater than pWal->hdr.mxFrame.
54626  */
54627  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
54628  memset((void *)&aPgno[iLimit+1], 0, nByte);
54629
54630#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
54631  /* Verify that the every entry in the mapping region is still reachable
54632  ** via the hash table even after the cleanup.
54633  */
54634  if( iLimit ){
54635    int j;           /* Loop counter */
54636    int iKey;        /* Hash key */
54637    for(j=1; j<=iLimit; j++){
54638      for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
54639        if( aHash[iKey]==j ) break;
54640      }
54641      assert( aHash[iKey]==j );
54642    }
54643  }
54644#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
54645}
54646
54647
54648/*
54649** Set an entry in the wal-index that will map database page number
54650** pPage into WAL frame iFrame.
54651*/
54652static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
54653  int rc;                         /* Return code */
54654  u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
54655  volatile u32 *aPgno = 0;        /* Page number array */
54656  volatile ht_slot *aHash = 0;    /* Hash table */
54657
54658  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
54659
54660  /* Assuming the wal-index file was successfully mapped, populate the
54661  ** page number array and hash table entry.
54662  */
54663  if( rc==SQLITE_OK ){
54664    int iKey;                     /* Hash table key */
54665    int idx;                      /* Value to write to hash-table slot */
54666    int nCollide;                 /* Number of hash collisions */
54667
54668    idx = iFrame - iZero;
54669    assert( idx <= HASHTABLE_NSLOT/2 + 1 );
54670
54671    /* If this is the first entry to be added to this hash-table, zero the
54672    ** entire hash table and aPgno[] array before proceeding.
54673    */
54674    if( idx==1 ){
54675      int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
54676      memset((void*)&aPgno[1], 0, nByte);
54677    }
54678
54679    /* If the entry in aPgno[] is already set, then the previous writer
54680    ** must have exited unexpectedly in the middle of a transaction (after
54681    ** writing one or more dirty pages to the WAL to free up memory).
54682    ** Remove the remnants of that writers uncommitted transaction from
54683    ** the hash-table before writing any new entries.
54684    */
54685    if( aPgno[idx] ){
54686      walCleanupHash(pWal);
54687      assert( !aPgno[idx] );
54688    }
54689
54690    /* Write the aPgno[] array entry and the hash-table slot. */
54691    nCollide = idx;
54692    for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
54693      if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
54694    }
54695    aPgno[idx] = iPage;
54696    aHash[iKey] = (ht_slot)idx;
54697
54698#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
54699    /* Verify that the number of entries in the hash table exactly equals
54700    ** the number of entries in the mapping region.
54701    */
54702    {
54703      int i;           /* Loop counter */
54704      int nEntry = 0;  /* Number of entries in the hash table */
54705      for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
54706      assert( nEntry==idx );
54707    }
54708
54709    /* Verify that the every entry in the mapping region is reachable
54710    ** via the hash table.  This turns out to be a really, really expensive
54711    ** thing to check, so only do this occasionally - not on every
54712    ** iteration.
54713    */
54714    if( (idx&0x3ff)==0 ){
54715      int i;           /* Loop counter */
54716      for(i=1; i<=idx; i++){
54717        for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
54718          if( aHash[iKey]==i ) break;
54719        }
54720        assert( aHash[iKey]==i );
54721      }
54722    }
54723#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
54724  }
54725
54726
54727  return rc;
54728}
54729
54730
54731/*
54732** Recover the wal-index by reading the write-ahead log file.
54733**
54734** This routine first tries to establish an exclusive lock on the
54735** wal-index to prevent other threads/processes from doing anything
54736** with the WAL or wal-index while recovery is running.  The
54737** WAL_RECOVER_LOCK is also held so that other threads will know
54738** that this thread is running recovery.  If unable to establish
54739** the necessary locks, this routine returns SQLITE_BUSY.
54740*/
54741static int walIndexRecover(Wal *pWal){
54742  int rc;                         /* Return Code */
54743  i64 nSize;                      /* Size of log file */
54744  u32 aFrameCksum[2] = {0, 0};
54745  int iLock;                      /* Lock offset to lock for checkpoint */
54746  int nLock;                      /* Number of locks to hold */
54747
54748  /* Obtain an exclusive lock on all byte in the locking range not already
54749  ** locked by the caller. The caller is guaranteed to have locked the
54750  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
54751  ** If successful, the same bytes that are locked here are unlocked before
54752  ** this function returns.
54753  */
54754  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
54755  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
54756  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
54757  assert( pWal->writeLock );
54758  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
54759  nLock = SQLITE_SHM_NLOCK - iLock;
54760  rc = walLockExclusive(pWal, iLock, nLock);
54761  if( rc ){
54762    return rc;
54763  }
54764  WALTRACE(("WAL%p: recovery begin...\n", pWal));
54765
54766  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
54767
54768  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
54769  if( rc!=SQLITE_OK ){
54770    goto recovery_error;
54771  }
54772
54773  if( nSize>WAL_HDRSIZE ){
54774    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
54775    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
54776    int szFrame;                  /* Number of bytes in buffer aFrame[] */
54777    u8 *aData;                    /* Pointer to data part of aFrame buffer */
54778    int iFrame;                   /* Index of last frame read */
54779    i64 iOffset;                  /* Next offset to read from log file */
54780    int szPage;                   /* Page size according to the log */
54781    u32 magic;                    /* Magic value read from WAL header */
54782    u32 version;                  /* Magic value read from WAL header */
54783    int isValid;                  /* True if this frame is valid */
54784
54785    /* Read in the WAL header. */
54786    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
54787    if( rc!=SQLITE_OK ){
54788      goto recovery_error;
54789    }
54790
54791    /* If the database page size is not a power of two, or is greater than
54792    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
54793    ** data. Similarly, if the 'magic' value is invalid, ignore the whole
54794    ** WAL file.
54795    */
54796    magic = sqlite3Get4byte(&aBuf[0]);
54797    szPage = sqlite3Get4byte(&aBuf[8]);
54798    if( (magic&0xFFFFFFFE)!=WAL_MAGIC
54799     || szPage&(szPage-1)
54800     || szPage>SQLITE_MAX_PAGE_SIZE
54801     || szPage<512
54802    ){
54803      goto finished;
54804    }
54805    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
54806    pWal->szPage = szPage;
54807    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
54808    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
54809
54810    /* Verify that the WAL header checksum is correct */
54811    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
54812        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
54813    );
54814    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
54815     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
54816    ){
54817      goto finished;
54818    }
54819
54820    /* Verify that the version number on the WAL format is one that
54821    ** are able to understand */
54822    version = sqlite3Get4byte(&aBuf[4]);
54823    if( version!=WAL_MAX_VERSION ){
54824      rc = SQLITE_CANTOPEN_BKPT;
54825      goto finished;
54826    }
54827
54828    /* Malloc a buffer to read frames into. */
54829    szFrame = szPage + WAL_FRAME_HDRSIZE;
54830    aFrame = (u8 *)sqlite3_malloc64(szFrame);
54831    if( !aFrame ){
54832      rc = SQLITE_NOMEM_BKPT;
54833      goto recovery_error;
54834    }
54835    aData = &aFrame[WAL_FRAME_HDRSIZE];
54836
54837    /* Read all frames from the log file. */
54838    iFrame = 0;
54839    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
54840      u32 pgno;                   /* Database page number for frame */
54841      u32 nTruncate;              /* dbsize field from frame header */
54842
54843      /* Read and decode the next log frame. */
54844      iFrame++;
54845      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
54846      if( rc!=SQLITE_OK ) break;
54847      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
54848      if( !isValid ) break;
54849      rc = walIndexAppend(pWal, iFrame, pgno);
54850      if( rc!=SQLITE_OK ) break;
54851
54852      /* If nTruncate is non-zero, this is a commit record. */
54853      if( nTruncate ){
54854        pWal->hdr.mxFrame = iFrame;
54855        pWal->hdr.nPage = nTruncate;
54856        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
54857        testcase( szPage<=32768 );
54858        testcase( szPage>=65536 );
54859        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
54860        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
54861      }
54862    }
54863
54864    sqlite3_free(aFrame);
54865  }
54866
54867finished:
54868  if( rc==SQLITE_OK ){
54869    volatile WalCkptInfo *pInfo;
54870    int i;
54871    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
54872    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
54873    walIndexWriteHdr(pWal);
54874
54875    /* Reset the checkpoint-header. This is safe because this thread is
54876    ** currently holding locks that exclude all other readers, writers and
54877    ** checkpointers.
54878    */
54879    pInfo = walCkptInfo(pWal);
54880    pInfo->nBackfill = 0;
54881    pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
54882    pInfo->aReadMark[0] = 0;
54883    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
54884    if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
54885
54886    /* If more than one frame was recovered from the log file, report an
54887    ** event via sqlite3_log(). This is to help with identifying performance
54888    ** problems caused by applications routinely shutting down without
54889    ** checkpointing the log file.
54890    */
54891    if( pWal->hdr.nPage ){
54892      sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
54893          "recovered %d frames from WAL file %s",
54894          pWal->hdr.mxFrame, pWal->zWalName
54895      );
54896    }
54897  }
54898
54899recovery_error:
54900  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
54901  walUnlockExclusive(pWal, iLock, nLock);
54902  return rc;
54903}
54904
54905/*
54906** Close an open wal-index.
54907*/
54908static void walIndexClose(Wal *pWal, int isDelete){
54909  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
54910    int i;
54911    for(i=0; i<pWal->nWiData; i++){
54912      sqlite3_free((void *)pWal->apWiData[i]);
54913      pWal->apWiData[i] = 0;
54914    }
54915  }else{
54916    sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
54917  }
54918}
54919
54920/*
54921** Open a connection to the WAL file zWalName. The database file must
54922** already be opened on connection pDbFd. The buffer that zWalName points
54923** to must remain valid for the lifetime of the returned Wal* handle.
54924**
54925** A SHARED lock should be held on the database file when this function
54926** is called. The purpose of this SHARED lock is to prevent any other
54927** client from unlinking the WAL or wal-index file. If another process
54928** were to do this just after this client opened one of these files, the
54929** system would be badly broken.
54930**
54931** If the log file is successfully opened, SQLITE_OK is returned and
54932** *ppWal is set to point to a new WAL handle. If an error occurs,
54933** an SQLite error code is returned and *ppWal is left unmodified.
54934*/
54935SQLITE_PRIVATE int sqlite3WalOpen(
54936  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
54937  sqlite3_file *pDbFd,            /* The open database file */
54938  const char *zWalName,           /* Name of the WAL file */
54939  int bNoShm,                     /* True to run in heap-memory mode */
54940  i64 mxWalSize,                  /* Truncate WAL to this size on reset */
54941  Wal **ppWal                     /* OUT: Allocated Wal handle */
54942){
54943  int rc;                         /* Return Code */
54944  Wal *pRet;                      /* Object to allocate and return */
54945  int flags;                      /* Flags passed to OsOpen() */
54946
54947  assert( zWalName && zWalName[0] );
54948  assert( pDbFd );
54949
54950  /* In the amalgamation, the os_unix.c and os_win.c source files come before
54951  ** this source file.  Verify that the #defines of the locking byte offsets
54952  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
54953  ** For that matter, if the lock offset ever changes from its initial design
54954  ** value of 120, we need to know that so there is an assert() to check it.
54955  */
54956  assert( 120==WALINDEX_LOCK_OFFSET );
54957  assert( 136==WALINDEX_HDR_SIZE );
54958#ifdef WIN_SHM_BASE
54959  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
54960#endif
54961#ifdef UNIX_SHM_BASE
54962  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
54963#endif
54964
54965
54966  /* Allocate an instance of struct Wal to return. */
54967  *ppWal = 0;
54968  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
54969  if( !pRet ){
54970    return SQLITE_NOMEM_BKPT;
54971  }
54972
54973  pRet->pVfs = pVfs;
54974  pRet->pWalFd = (sqlite3_file *)&pRet[1];
54975  pRet->pDbFd = pDbFd;
54976  pRet->readLock = -1;
54977  pRet->mxWalSize = mxWalSize;
54978  pRet->zWalName = zWalName;
54979  pRet->syncHeader = 1;
54980  pRet->padToSectorBoundary = 1;
54981  pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
54982
54983  /* Open file handle on the write-ahead log file. */
54984  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
54985  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
54986  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
54987    pRet->readOnly = WAL_RDONLY;
54988  }
54989
54990  if( rc!=SQLITE_OK ){
54991    walIndexClose(pRet, 0);
54992    sqlite3OsClose(pRet->pWalFd);
54993    sqlite3_free(pRet);
54994  }else{
54995    int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
54996    if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
54997    if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
54998      pRet->padToSectorBoundary = 0;
54999    }
55000    *ppWal = pRet;
55001    WALTRACE(("WAL%d: opened\n", pRet));
55002  }
55003  return rc;
55004}
55005
55006/*
55007** Change the size to which the WAL file is trucated on each reset.
55008*/
55009SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
55010  if( pWal ) pWal->mxWalSize = iLimit;
55011}
55012
55013/*
55014** Find the smallest page number out of all pages held in the WAL that
55015** has not been returned by any prior invocation of this method on the
55016** same WalIterator object.   Write into *piFrame the frame index where
55017** that page was last written into the WAL.  Write into *piPage the page
55018** number.
55019**
55020** Return 0 on success.  If there are no pages in the WAL with a page
55021** number larger than *piPage, then return 1.
55022*/
55023static int walIteratorNext(
55024  WalIterator *p,               /* Iterator */
55025  u32 *piPage,                  /* OUT: The page number of the next page */
55026  u32 *piFrame                  /* OUT: Wal frame index of next page */
55027){
55028  u32 iMin;                     /* Result pgno must be greater than iMin */
55029  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
55030  int i;                        /* For looping through segments */
55031
55032  iMin = p->iPrior;
55033  assert( iMin<0xffffffff );
55034  for(i=p->nSegment-1; i>=0; i--){
55035    struct WalSegment *pSegment = &p->aSegment[i];
55036    while( pSegment->iNext<pSegment->nEntry ){
55037      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
55038      if( iPg>iMin ){
55039        if( iPg<iRet ){
55040          iRet = iPg;
55041          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
55042        }
55043        break;
55044      }
55045      pSegment->iNext++;
55046    }
55047  }
55048
55049  *piPage = p->iPrior = iRet;
55050  return (iRet==0xFFFFFFFF);
55051}
55052
55053/*
55054** This function merges two sorted lists into a single sorted list.
55055**
55056** aLeft[] and aRight[] are arrays of indices.  The sort key is
55057** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
55058** is guaranteed for all J<K:
55059**
55060**        aContent[aLeft[J]] < aContent[aLeft[K]]
55061**        aContent[aRight[J]] < aContent[aRight[K]]
55062**
55063** This routine overwrites aRight[] with a new (probably longer) sequence
55064** of indices such that the aRight[] contains every index that appears in
55065** either aLeft[] or the old aRight[] and such that the second condition
55066** above is still met.
55067**
55068** The aContent[aLeft[X]] values will be unique for all X.  And the
55069** aContent[aRight[X]] values will be unique too.  But there might be
55070** one or more combinations of X and Y such that
55071**
55072**      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
55073**
55074** When that happens, omit the aLeft[X] and use the aRight[Y] index.
55075*/
55076static void walMerge(
55077  const u32 *aContent,            /* Pages in wal - keys for the sort */
55078  ht_slot *aLeft,                 /* IN: Left hand input list */
55079  int nLeft,                      /* IN: Elements in array *paLeft */
55080  ht_slot **paRight,              /* IN/OUT: Right hand input list */
55081  int *pnRight,                   /* IN/OUT: Elements in *paRight */
55082  ht_slot *aTmp                   /* Temporary buffer */
55083){
55084  int iLeft = 0;                  /* Current index in aLeft */
55085  int iRight = 0;                 /* Current index in aRight */
55086  int iOut = 0;                   /* Current index in output buffer */
55087  int nRight = *pnRight;
55088  ht_slot *aRight = *paRight;
55089
55090  assert( nLeft>0 && nRight>0 );
55091  while( iRight<nRight || iLeft<nLeft ){
55092    ht_slot logpage;
55093    Pgno dbpage;
55094
55095    if( (iLeft<nLeft)
55096     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
55097    ){
55098      logpage = aLeft[iLeft++];
55099    }else{
55100      logpage = aRight[iRight++];
55101    }
55102    dbpage = aContent[logpage];
55103
55104    aTmp[iOut++] = logpage;
55105    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
55106
55107    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
55108    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
55109  }
55110
55111  *paRight = aLeft;
55112  *pnRight = iOut;
55113  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
55114}
55115
55116/*
55117** Sort the elements in list aList using aContent[] as the sort key.
55118** Remove elements with duplicate keys, preferring to keep the
55119** larger aList[] values.
55120**
55121** The aList[] entries are indices into aContent[].  The values in
55122** aList[] are to be sorted so that for all J<K:
55123**
55124**      aContent[aList[J]] < aContent[aList[K]]
55125**
55126** For any X and Y such that
55127**
55128**      aContent[aList[X]] == aContent[aList[Y]]
55129**
55130** Keep the larger of the two values aList[X] and aList[Y] and discard
55131** the smaller.
55132*/
55133static void walMergesort(
55134  const u32 *aContent,            /* Pages in wal */
55135  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
55136  ht_slot *aList,                 /* IN/OUT: List to sort */
55137  int *pnList                     /* IN/OUT: Number of elements in aList[] */
55138){
55139  struct Sublist {
55140    int nList;                    /* Number of elements in aList */
55141    ht_slot *aList;               /* Pointer to sub-list content */
55142  };
55143
55144  const int nList = *pnList;      /* Size of input list */
55145  int nMerge = 0;                 /* Number of elements in list aMerge */
55146  ht_slot *aMerge = 0;            /* List to be merged */
55147  int iList;                      /* Index into input list */
55148  u32 iSub = 0;                   /* Index into aSub array */
55149  struct Sublist aSub[13];        /* Array of sub-lists */
55150
55151  memset(aSub, 0, sizeof(aSub));
55152  assert( nList<=HASHTABLE_NPAGE && nList>0 );
55153  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
55154
55155  for(iList=0; iList<nList; iList++){
55156    nMerge = 1;
55157    aMerge = &aList[iList];
55158    for(iSub=0; iList & (1<<iSub); iSub++){
55159      struct Sublist *p;
55160      assert( iSub<ArraySize(aSub) );
55161      p = &aSub[iSub];
55162      assert( p->aList && p->nList<=(1<<iSub) );
55163      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
55164      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
55165    }
55166    aSub[iSub].aList = aMerge;
55167    aSub[iSub].nList = nMerge;
55168  }
55169
55170  for(iSub++; iSub<ArraySize(aSub); iSub++){
55171    if( nList & (1<<iSub) ){
55172      struct Sublist *p;
55173      assert( iSub<ArraySize(aSub) );
55174      p = &aSub[iSub];
55175      assert( p->nList<=(1<<iSub) );
55176      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
55177      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
55178    }
55179  }
55180  assert( aMerge==aList );
55181  *pnList = nMerge;
55182
55183#ifdef SQLITE_DEBUG
55184  {
55185    int i;
55186    for(i=1; i<*pnList; i++){
55187      assert( aContent[aList[i]] > aContent[aList[i-1]] );
55188    }
55189  }
55190#endif
55191}
55192
55193/*
55194** Free an iterator allocated by walIteratorInit().
55195*/
55196static void walIteratorFree(WalIterator *p){
55197  sqlite3_free(p);
55198}
55199
55200/*
55201** Construct a WalInterator object that can be used to loop over all
55202** pages in the WAL in ascending order. The caller must hold the checkpoint
55203** lock.
55204**
55205** On success, make *pp point to the newly allocated WalInterator object
55206** return SQLITE_OK. Otherwise, return an error code. If this routine
55207** returns an error, the value of *pp is undefined.
55208**
55209** The calling routine should invoke walIteratorFree() to destroy the
55210** WalIterator object when it has finished with it.
55211*/
55212static int walIteratorInit(Wal *pWal, WalIterator **pp){
55213  WalIterator *p;                 /* Return value */
55214  int nSegment;                   /* Number of segments to merge */
55215  u32 iLast;                      /* Last frame in log */
55216  int nByte;                      /* Number of bytes to allocate */
55217  int i;                          /* Iterator variable */
55218  ht_slot *aTmp;                  /* Temp space used by merge-sort */
55219  int rc = SQLITE_OK;             /* Return Code */
55220
55221  /* This routine only runs while holding the checkpoint lock. And
55222  ** it only runs if there is actually content in the log (mxFrame>0).
55223  */
55224  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
55225  iLast = pWal->hdr.mxFrame;
55226
55227  /* Allocate space for the WalIterator object. */
55228  nSegment = walFramePage(iLast) + 1;
55229  nByte = sizeof(WalIterator)
55230        + (nSegment-1)*sizeof(struct WalSegment)
55231        + iLast*sizeof(ht_slot);
55232  p = (WalIterator *)sqlite3_malloc64(nByte);
55233  if( !p ){
55234    return SQLITE_NOMEM_BKPT;
55235  }
55236  memset(p, 0, nByte);
55237  p->nSegment = nSegment;
55238
55239  /* Allocate temporary space used by the merge-sort routine. This block
55240  ** of memory will be freed before this function returns.
55241  */
55242  aTmp = (ht_slot *)sqlite3_malloc64(
55243      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
55244  );
55245  if( !aTmp ){
55246    rc = SQLITE_NOMEM_BKPT;
55247  }
55248
55249  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
55250    volatile ht_slot *aHash;
55251    u32 iZero;
55252    volatile u32 *aPgno;
55253
55254    rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
55255    if( rc==SQLITE_OK ){
55256      int j;                      /* Counter variable */
55257      int nEntry;                 /* Number of entries in this segment */
55258      ht_slot *aIndex;            /* Sorted index for this segment */
55259
55260      aPgno++;
55261      if( (i+1)==nSegment ){
55262        nEntry = (int)(iLast - iZero);
55263      }else{
55264        nEntry = (int)((u32*)aHash - (u32*)aPgno);
55265      }
55266      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
55267      iZero++;
55268
55269      for(j=0; j<nEntry; j++){
55270        aIndex[j] = (ht_slot)j;
55271      }
55272      walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
55273      p->aSegment[i].iZero = iZero;
55274      p->aSegment[i].nEntry = nEntry;
55275      p->aSegment[i].aIndex = aIndex;
55276      p->aSegment[i].aPgno = (u32 *)aPgno;
55277    }
55278  }
55279  sqlite3_free(aTmp);
55280
55281  if( rc!=SQLITE_OK ){
55282    walIteratorFree(p);
55283  }
55284  *pp = p;
55285  return rc;
55286}
55287
55288/*
55289** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
55290** n. If the attempt fails and parameter xBusy is not NULL, then it is a
55291** busy-handler function. Invoke it and retry the lock until either the
55292** lock is successfully obtained or the busy-handler returns 0.
55293*/
55294static int walBusyLock(
55295  Wal *pWal,                      /* WAL connection */
55296  int (*xBusy)(void*),            /* Function to call when busy */
55297  void *pBusyArg,                 /* Context argument for xBusyHandler */
55298  int lockIdx,                    /* Offset of first byte to lock */
55299  int n                           /* Number of bytes to lock */
55300){
55301  int rc;
55302  do {
55303    rc = walLockExclusive(pWal, lockIdx, n);
55304  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
55305  return rc;
55306}
55307
55308/*
55309** The cache of the wal-index header must be valid to call this function.
55310** Return the page-size in bytes used by the database.
55311*/
55312static int walPagesize(Wal *pWal){
55313  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
55314}
55315
55316/*
55317** The following is guaranteed when this function is called:
55318**
55319**   a) the WRITER lock is held,
55320**   b) the entire log file has been checkpointed, and
55321**   c) any existing readers are reading exclusively from the database
55322**      file - there are no readers that may attempt to read a frame from
55323**      the log file.
55324**
55325** This function updates the shared-memory structures so that the next
55326** client to write to the database (which may be this one) does so by
55327** writing frames into the start of the log file.
55328**
55329** The value of parameter salt1 is used as the aSalt[1] value in the
55330** new wal-index header. It should be passed a pseudo-random value (i.e.
55331** one obtained from sqlite3_randomness()).
55332*/
55333static void walRestartHdr(Wal *pWal, u32 salt1){
55334  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
55335  int i;                          /* Loop counter */
55336  u32 *aSalt = pWal->hdr.aSalt;   /* Big-endian salt values */
55337  pWal->nCkpt++;
55338  pWal->hdr.mxFrame = 0;
55339  sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
55340  memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
55341  walIndexWriteHdr(pWal);
55342  pInfo->nBackfill = 0;
55343  pInfo->nBackfillAttempted = 0;
55344  pInfo->aReadMark[1] = 0;
55345  for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
55346  assert( pInfo->aReadMark[0]==0 );
55347}
55348
55349/*
55350** Copy as much content as we can from the WAL back into the database file
55351** in response to an sqlite3_wal_checkpoint() request or the equivalent.
55352**
55353** The amount of information copies from WAL to database might be limited
55354** by active readers.  This routine will never overwrite a database page
55355** that a concurrent reader might be using.
55356**
55357** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
55358** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
55359** checkpoints are always run by a background thread or background
55360** process, foreground threads will never block on a lengthy fsync call.
55361**
55362** Fsync is called on the WAL before writing content out of the WAL and
55363** into the database.  This ensures that if the new content is persistent
55364** in the WAL and can be recovered following a power-loss or hard reset.
55365**
55366** Fsync is also called on the database file if (and only if) the entire
55367** WAL content is copied into the database file.  This second fsync makes
55368** it safe to delete the WAL since the new content will persist in the
55369** database file.
55370**
55371** This routine uses and updates the nBackfill field of the wal-index header.
55372** This is the only routine that will increase the value of nBackfill.
55373** (A WAL reset or recovery will revert nBackfill to zero, but not increase
55374** its value.)
55375**
55376** The caller must be holding sufficient locks to ensure that no other
55377** checkpoint is running (in any other thread or process) at the same
55378** time.
55379*/
55380static int walCheckpoint(
55381  Wal *pWal,                      /* Wal connection */
55382  int eMode,                      /* One of PASSIVE, FULL or RESTART */
55383  int (*xBusy)(void*),            /* Function to call when busy */
55384  void *pBusyArg,                 /* Context argument for xBusyHandler */
55385  int sync_flags,                 /* Flags for OsSync() (or 0) */
55386  u8 *zBuf                        /* Temporary buffer to use */
55387){
55388  int rc = SQLITE_OK;             /* Return code */
55389  int szPage;                     /* Database page-size */
55390  WalIterator *pIter = 0;         /* Wal iterator context */
55391  u32 iDbpage = 0;                /* Next database page to write */
55392  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
55393  u32 mxSafeFrame;                /* Max frame that can be backfilled */
55394  u32 mxPage;                     /* Max database page to write */
55395  int i;                          /* Loop counter */
55396  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
55397
55398  szPage = walPagesize(pWal);
55399  testcase( szPage<=32768 );
55400  testcase( szPage>=65536 );
55401  pInfo = walCkptInfo(pWal);
55402  if( pInfo->nBackfill<pWal->hdr.mxFrame ){
55403
55404    /* Allocate the iterator */
55405    rc = walIteratorInit(pWal, &pIter);
55406    if( rc!=SQLITE_OK ){
55407      return rc;
55408    }
55409    assert( pIter );
55410
55411    /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
55412    ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
55413    assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
55414
55415    /* Compute in mxSafeFrame the index of the last frame of the WAL that is
55416    ** safe to write into the database.  Frames beyond mxSafeFrame might
55417    ** overwrite database pages that are in use by active readers and thus
55418    ** cannot be backfilled from the WAL.
55419    */
55420    mxSafeFrame = pWal->hdr.mxFrame;
55421    mxPage = pWal->hdr.nPage;
55422    for(i=1; i<WAL_NREADER; i++){
55423      /* Thread-sanitizer reports that the following is an unsafe read,
55424      ** as some other thread may be in the process of updating the value
55425      ** of the aReadMark[] slot. The assumption here is that if that is
55426      ** happening, the other client may only be increasing the value,
55427      ** not decreasing it. So assuming either that either the "old" or
55428      ** "new" version of the value is read, and not some arbitrary value
55429      ** that would never be written by a real client, things are still
55430      ** safe.  */
55431      u32 y = pInfo->aReadMark[i];
55432      if( mxSafeFrame>y ){
55433        assert( y<=pWal->hdr.mxFrame );
55434        rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
55435        if( rc==SQLITE_OK ){
55436          pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
55437          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
55438        }else if( rc==SQLITE_BUSY ){
55439          mxSafeFrame = y;
55440          xBusy = 0;
55441        }else{
55442          goto walcheckpoint_out;
55443        }
55444      }
55445    }
55446
55447    if( pInfo->nBackfill<mxSafeFrame
55448     && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
55449    ){
55450      i64 nSize;                    /* Current size of database file */
55451      u32 nBackfill = pInfo->nBackfill;
55452
55453      pInfo->nBackfillAttempted = mxSafeFrame;
55454
55455      /* Sync the WAL to disk */
55456      if( sync_flags ){
55457        rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
55458      }
55459
55460      /* If the database may grow as a result of this checkpoint, hint
55461      ** about the eventual size of the db file to the VFS layer.
55462      */
55463      if( rc==SQLITE_OK ){
55464        i64 nReq = ((i64)mxPage * szPage);
55465        rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
55466        if( rc==SQLITE_OK && nSize<nReq ){
55467          sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
55468        }
55469      }
55470
55471
55472      /* Iterate through the contents of the WAL, copying data to the db file */
55473      while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
55474        i64 iOffset;
55475        assert( walFramePgno(pWal, iFrame)==iDbpage );
55476        if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
55477          continue;
55478        }
55479        iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
55480        /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
55481        rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
55482        if( rc!=SQLITE_OK ) break;
55483        iOffset = (iDbpage-1)*(i64)szPage;
55484        testcase( IS_BIG_INT(iOffset) );
55485        rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
55486        if( rc!=SQLITE_OK ) break;
55487      }
55488
55489      /* If work was actually accomplished... */
55490      if( rc==SQLITE_OK ){
55491        if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
55492          i64 szDb = pWal->hdr.nPage*(i64)szPage;
55493          testcase( IS_BIG_INT(szDb) );
55494          rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
55495          if( rc==SQLITE_OK && sync_flags ){
55496            rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
55497          }
55498        }
55499        if( rc==SQLITE_OK ){
55500          pInfo->nBackfill = mxSafeFrame;
55501        }
55502      }
55503
55504      /* Release the reader lock held while backfilling */
55505      walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
55506    }
55507
55508    if( rc==SQLITE_BUSY ){
55509      /* Reset the return code so as not to report a checkpoint failure
55510      ** just because there are active readers.  */
55511      rc = SQLITE_OK;
55512    }
55513  }
55514
55515  /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
55516  ** entire wal file has been copied into the database file, then block
55517  ** until all readers have finished using the wal file. This ensures that
55518  ** the next process to write to the database restarts the wal file.
55519  */
55520  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
55521    assert( pWal->writeLock );
55522    if( pInfo->nBackfill<pWal->hdr.mxFrame ){
55523      rc = SQLITE_BUSY;
55524    }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
55525      u32 salt1;
55526      sqlite3_randomness(4, &salt1);
55527      assert( pInfo->nBackfill==pWal->hdr.mxFrame );
55528      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
55529      if( rc==SQLITE_OK ){
55530        if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
55531          /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
55532          ** SQLITE_CHECKPOINT_RESTART with the addition that it also
55533          ** truncates the log file to zero bytes just prior to a
55534          ** successful return.
55535          **
55536          ** In theory, it might be safe to do this without updating the
55537          ** wal-index header in shared memory, as all subsequent reader or
55538          ** writer clients should see that the entire log file has been
55539          ** checkpointed and behave accordingly. This seems unsafe though,
55540          ** as it would leave the system in a state where the contents of
55541          ** the wal-index header do not match the contents of the
55542          ** file-system. To avoid this, update the wal-index header to
55543          ** indicate that the log file contains zero valid frames.  */
55544          walRestartHdr(pWal, salt1);
55545          rc = sqlite3OsTruncate(pWal->pWalFd, 0);
55546        }
55547        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
55548      }
55549    }
55550  }
55551
55552 walcheckpoint_out:
55553  walIteratorFree(pIter);
55554  return rc;
55555}
55556
55557/*
55558** If the WAL file is currently larger than nMax bytes in size, truncate
55559** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
55560*/
55561static void walLimitSize(Wal *pWal, i64 nMax){
55562  i64 sz;
55563  int rx;
55564  sqlite3BeginBenignMalloc();
55565  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
55566  if( rx==SQLITE_OK && (sz > nMax ) ){
55567    rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
55568  }
55569  sqlite3EndBenignMalloc();
55570  if( rx ){
55571    sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
55572  }
55573}
55574
55575/*
55576** Close a connection to a log file.
55577*/
55578SQLITE_PRIVATE int sqlite3WalClose(
55579  Wal *pWal,                      /* Wal to close */
55580  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
55581  int nBuf,
55582  u8 *zBuf                        /* Buffer of at least nBuf bytes */
55583){
55584  int rc = SQLITE_OK;
55585  if( pWal ){
55586    int isDelete = 0;             /* True to unlink wal and wal-index files */
55587
55588    /* If an EXCLUSIVE lock can be obtained on the database file (using the
55589    ** ordinary, rollback-mode locking methods, this guarantees that the
55590    ** connection associated with this log file is the only connection to
55591    ** the database. In this case checkpoint the database and unlink both
55592    ** the wal and wal-index files.
55593    **
55594    ** The EXCLUSIVE lock is not released before returning.
55595    */
55596    rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
55597    if( rc==SQLITE_OK ){
55598      if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
55599        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
55600      }
55601      rc = sqlite3WalCheckpoint(
55602          pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
55603      );
55604      if( rc==SQLITE_OK ){
55605        int bPersist = -1;
55606        sqlite3OsFileControlHint(
55607            pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
55608        );
55609        if( bPersist!=1 ){
55610          /* Try to delete the WAL file if the checkpoint completed and
55611          ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
55612          ** mode (!bPersist) */
55613          isDelete = 1;
55614        }else if( pWal->mxWalSize>=0 ){
55615          /* Try to truncate the WAL file to zero bytes if the checkpoint
55616          ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
55617          ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
55618          ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
55619          ** to zero bytes as truncating to the journal_size_limit might
55620          ** leave a corrupt WAL file on disk. */
55621          walLimitSize(pWal, 0);
55622        }
55623      }
55624    }
55625
55626    walIndexClose(pWal, isDelete);
55627    sqlite3OsClose(pWal->pWalFd);
55628    if( isDelete ){
55629      sqlite3BeginBenignMalloc();
55630      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
55631      sqlite3EndBenignMalloc();
55632    }
55633    WALTRACE(("WAL%p: closed\n", pWal));
55634    sqlite3_free((void *)pWal->apWiData);
55635    sqlite3_free(pWal);
55636  }
55637  return rc;
55638}
55639
55640/*
55641** Try to read the wal-index header.  Return 0 on success and 1 if
55642** there is a problem.
55643**
55644** The wal-index is in shared memory.  Another thread or process might
55645** be writing the header at the same time this procedure is trying to
55646** read it, which might result in inconsistency.  A dirty read is detected
55647** by verifying that both copies of the header are the same and also by
55648** a checksum on the header.
55649**
55650** If and only if the read is consistent and the header is different from
55651** pWal->hdr, then pWal->hdr is updated to the content of the new header
55652** and *pChanged is set to 1.
55653**
55654** If the checksum cannot be verified return non-zero. If the header
55655** is read successfully and the checksum verified, return zero.
55656*/
55657static int walIndexTryHdr(Wal *pWal, int *pChanged){
55658  u32 aCksum[2];                  /* Checksum on the header content */
55659  WalIndexHdr h1, h2;             /* Two copies of the header content */
55660  WalIndexHdr volatile *aHdr;     /* Header in shared memory */
55661
55662  /* The first page of the wal-index must be mapped at this point. */
55663  assert( pWal->nWiData>0 && pWal->apWiData[0] );
55664
55665  /* Read the header. This might happen concurrently with a write to the
55666  ** same area of shared memory on a different CPU in a SMP,
55667  ** meaning it is possible that an inconsistent snapshot is read
55668  ** from the file. If this happens, return non-zero.
55669  **
55670  ** There are two copies of the header at the beginning of the wal-index.
55671  ** When reading, read [0] first then [1].  Writes are in the reverse order.
55672  ** Memory barriers are used to prevent the compiler or the hardware from
55673  ** reordering the reads and writes.
55674  */
55675  aHdr = walIndexHdr(pWal);
55676  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
55677  walShmBarrier(pWal);
55678  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
55679
55680  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
55681    return 1;   /* Dirty read */
55682  }
55683  if( h1.isInit==0 ){
55684    return 1;   /* Malformed header - probably all zeros */
55685  }
55686  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
55687  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
55688    return 1;   /* Checksum does not match */
55689  }
55690
55691  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
55692    *pChanged = 1;
55693    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
55694    pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
55695    testcase( pWal->szPage<=32768 );
55696    testcase( pWal->szPage>=65536 );
55697  }
55698
55699  /* The header was successfully read. Return zero. */
55700  return 0;
55701}
55702
55703/*
55704** Read the wal-index header from the wal-index and into pWal->hdr.
55705** If the wal-header appears to be corrupt, try to reconstruct the
55706** wal-index from the WAL before returning.
55707**
55708** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
55709** changed by this operation.  If pWal->hdr is unchanged, set *pChanged
55710** to 0.
55711**
55712** If the wal-index header is successfully read, return SQLITE_OK.
55713** Otherwise an SQLite error code.
55714*/
55715static int walIndexReadHdr(Wal *pWal, int *pChanged){
55716  int rc;                         /* Return code */
55717  int badHdr;                     /* True if a header read failed */
55718  volatile u32 *page0;            /* Chunk of wal-index containing header */
55719
55720  /* Ensure that page 0 of the wal-index (the page that contains the
55721  ** wal-index header) is mapped. Return early if an error occurs here.
55722  */
55723  assert( pChanged );
55724  rc = walIndexPage(pWal, 0, &page0);
55725  if( rc!=SQLITE_OK ){
55726    return rc;
55727  };
55728  assert( page0 || pWal->writeLock==0 );
55729
55730  /* If the first page of the wal-index has been mapped, try to read the
55731  ** wal-index header immediately, without holding any lock. This usually
55732  ** works, but may fail if the wal-index header is corrupt or currently
55733  ** being modified by another thread or process.
55734  */
55735  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
55736
55737  /* If the first attempt failed, it might have been due to a race
55738  ** with a writer.  So get a WRITE lock and try again.
55739  */
55740  assert( badHdr==0 || pWal->writeLock==0 );
55741  if( badHdr ){
55742    if( pWal->readOnly & WAL_SHM_RDONLY ){
55743      if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
55744        walUnlockShared(pWal, WAL_WRITE_LOCK);
55745        rc = SQLITE_READONLY_RECOVERY;
55746      }
55747    }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
55748      pWal->writeLock = 1;
55749      if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
55750        badHdr = walIndexTryHdr(pWal, pChanged);
55751        if( badHdr ){
55752          /* If the wal-index header is still malformed even while holding
55753          ** a WRITE lock, it can only mean that the header is corrupted and
55754          ** needs to be reconstructed.  So run recovery to do exactly that.
55755          */
55756          rc = walIndexRecover(pWal);
55757          *pChanged = 1;
55758        }
55759      }
55760      pWal->writeLock = 0;
55761      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
55762    }
55763  }
55764
55765  /* If the header is read successfully, check the version number to make
55766  ** sure the wal-index was not constructed with some future format that
55767  ** this version of SQLite cannot understand.
55768  */
55769  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
55770    rc = SQLITE_CANTOPEN_BKPT;
55771  }
55772
55773  return rc;
55774}
55775
55776/*
55777** This is the value that walTryBeginRead returns when it needs to
55778** be retried.
55779*/
55780#define WAL_RETRY  (-1)
55781
55782/*
55783** Attempt to start a read transaction.  This might fail due to a race or
55784** other transient condition.  When that happens, it returns WAL_RETRY to
55785** indicate to the caller that it is safe to retry immediately.
55786**
55787** On success return SQLITE_OK.  On a permanent failure (such an
55788** I/O error or an SQLITE_BUSY because another process is running
55789** recovery) return a positive error code.
55790**
55791** The useWal parameter is true to force the use of the WAL and disable
55792** the case where the WAL is bypassed because it has been completely
55793** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
55794** to make a copy of the wal-index header into pWal->hdr.  If the
55795** wal-index header has changed, *pChanged is set to 1 (as an indication
55796** to the caller that the local paget cache is obsolete and needs to be
55797** flushed.)  When useWal==1, the wal-index header is assumed to already
55798** be loaded and the pChanged parameter is unused.
55799**
55800** The caller must set the cnt parameter to the number of prior calls to
55801** this routine during the current read attempt that returned WAL_RETRY.
55802** This routine will start taking more aggressive measures to clear the
55803** race conditions after multiple WAL_RETRY returns, and after an excessive
55804** number of errors will ultimately return SQLITE_PROTOCOL.  The
55805** SQLITE_PROTOCOL return indicates that some other process has gone rogue
55806** and is not honoring the locking protocol.  There is a vanishingly small
55807** chance that SQLITE_PROTOCOL could be returned because of a run of really
55808** bad luck when there is lots of contention for the wal-index, but that
55809** possibility is so small that it can be safely neglected, we believe.
55810**
55811** On success, this routine obtains a read lock on
55812** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
55813** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
55814** that means the Wal does not hold any read lock.  The reader must not
55815** access any database page that is modified by a WAL frame up to and
55816** including frame number aReadMark[pWal->readLock].  The reader will
55817** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
55818** Or if pWal->readLock==0, then the reader will ignore the WAL
55819** completely and get all content directly from the database file.
55820** If the useWal parameter is 1 then the WAL will never be ignored and
55821** this routine will always set pWal->readLock>0 on success.
55822** When the read transaction is completed, the caller must release the
55823** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
55824**
55825** This routine uses the nBackfill and aReadMark[] fields of the header
55826** to select a particular WAL_READ_LOCK() that strives to let the
55827** checkpoint process do as much work as possible.  This routine might
55828** update values of the aReadMark[] array in the header, but if it does
55829** so it takes care to hold an exclusive lock on the corresponding
55830** WAL_READ_LOCK() while changing values.
55831*/
55832static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
55833  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
55834  u32 mxReadMark;                 /* Largest aReadMark[] value */
55835  int mxI;                        /* Index of largest aReadMark[] value */
55836  int i;                          /* Loop counter */
55837  int rc = SQLITE_OK;             /* Return code  */
55838  u32 mxFrame;                    /* Wal frame to lock to */
55839
55840  assert( pWal->readLock<0 );     /* Not currently locked */
55841
55842  /* Take steps to avoid spinning forever if there is a protocol error.
55843  **
55844  ** Circumstances that cause a RETRY should only last for the briefest
55845  ** instances of time.  No I/O or other system calls are done while the
55846  ** locks are held, so the locks should not be held for very long. But
55847  ** if we are unlucky, another process that is holding a lock might get
55848  ** paged out or take a page-fault that is time-consuming to resolve,
55849  ** during the few nanoseconds that it is holding the lock.  In that case,
55850  ** it might take longer than normal for the lock to free.
55851  **
55852  ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
55853  ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
55854  ** is more of a scheduler yield than an actual delay.  But on the 10th
55855  ** an subsequent retries, the delays start becoming longer and longer,
55856  ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
55857  ** The total delay time before giving up is less than 10 seconds.
55858  */
55859  if( cnt>5 ){
55860    int nDelay = 1;                      /* Pause time in microseconds */
55861    if( cnt>100 ){
55862      VVA_ONLY( pWal->lockError = 1; )
55863      return SQLITE_PROTOCOL;
55864    }
55865    if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
55866    sqlite3OsSleep(pWal->pVfs, nDelay);
55867  }
55868
55869  if( !useWal ){
55870    rc = walIndexReadHdr(pWal, pChanged);
55871    if( rc==SQLITE_BUSY ){
55872      /* If there is not a recovery running in another thread or process
55873      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
55874      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
55875      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
55876      ** would be technically correct.  But the race is benign since with
55877      ** WAL_RETRY this routine will be called again and will probably be
55878      ** right on the second iteration.
55879      */
55880      if( pWal->apWiData[0]==0 ){
55881        /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
55882        ** We assume this is a transient condition, so return WAL_RETRY. The
55883        ** xShmMap() implementation used by the default unix and win32 VFS
55884        ** modules may return SQLITE_BUSY due to a race condition in the
55885        ** code that determines whether or not the shared-memory region
55886        ** must be zeroed before the requested page is returned.
55887        */
55888        rc = WAL_RETRY;
55889      }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
55890        walUnlockShared(pWal, WAL_RECOVER_LOCK);
55891        rc = WAL_RETRY;
55892      }else if( rc==SQLITE_BUSY ){
55893        rc = SQLITE_BUSY_RECOVERY;
55894      }
55895    }
55896    if( rc!=SQLITE_OK ){
55897      return rc;
55898    }
55899  }
55900
55901  pInfo = walCkptInfo(pWal);
55902  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
55903#ifdef SQLITE_ENABLE_SNAPSHOT
55904   && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0
55905     || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr)))
55906#endif
55907  ){
55908    /* The WAL has been completely backfilled (or it is empty).
55909    ** and can be safely ignored.
55910    */
55911    rc = walLockShared(pWal, WAL_READ_LOCK(0));
55912    walShmBarrier(pWal);
55913    if( rc==SQLITE_OK ){
55914      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
55915        /* It is not safe to allow the reader to continue here if frames
55916        ** may have been appended to the log before READ_LOCK(0) was obtained.
55917        ** When holding READ_LOCK(0), the reader ignores the entire log file,
55918        ** which implies that the database file contains a trustworthy
55919        ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
55920        ** happening, this is usually correct.
55921        **
55922        ** However, if frames have been appended to the log (or if the log
55923        ** is wrapped and written for that matter) before the READ_LOCK(0)
55924        ** is obtained, that is not necessarily true. A checkpointer may
55925        ** have started to backfill the appended frames but crashed before
55926        ** it finished. Leaving a corrupt image in the database file.
55927        */
55928        walUnlockShared(pWal, WAL_READ_LOCK(0));
55929        return WAL_RETRY;
55930      }
55931      pWal->readLock = 0;
55932      return SQLITE_OK;
55933    }else if( rc!=SQLITE_BUSY ){
55934      return rc;
55935    }
55936  }
55937
55938  /* If we get this far, it means that the reader will want to use
55939  ** the WAL to get at content from recent commits.  The job now is
55940  ** to select one of the aReadMark[] entries that is closest to
55941  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
55942  */
55943  mxReadMark = 0;
55944  mxI = 0;
55945  mxFrame = pWal->hdr.mxFrame;
55946#ifdef SQLITE_ENABLE_SNAPSHOT
55947  if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
55948    mxFrame = pWal->pSnapshot->mxFrame;
55949  }
55950#endif
55951  for(i=1; i<WAL_NREADER; i++){
55952    u32 thisMark = pInfo->aReadMark[i];
55953    if( mxReadMark<=thisMark && thisMark<=mxFrame ){
55954      assert( thisMark!=READMARK_NOT_USED );
55955      mxReadMark = thisMark;
55956      mxI = i;
55957    }
55958  }
55959  if( (pWal->readOnly & WAL_SHM_RDONLY)==0
55960   && (mxReadMark<mxFrame || mxI==0)
55961  ){
55962    for(i=1; i<WAL_NREADER; i++){
55963      rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
55964      if( rc==SQLITE_OK ){
55965        mxReadMark = pInfo->aReadMark[i] = mxFrame;
55966        mxI = i;
55967        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
55968        break;
55969      }else if( rc!=SQLITE_BUSY ){
55970        return rc;
55971      }
55972    }
55973  }
55974  if( mxI==0 ){
55975    assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
55976    return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
55977  }
55978
55979  rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
55980  if( rc ){
55981    return rc==SQLITE_BUSY ? WAL_RETRY : rc;
55982  }
55983  /* Now that the read-lock has been obtained, check that neither the
55984  ** value in the aReadMark[] array or the contents of the wal-index
55985  ** header have changed.
55986  **
55987  ** It is necessary to check that the wal-index header did not change
55988  ** between the time it was read and when the shared-lock was obtained
55989  ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
55990  ** that the log file may have been wrapped by a writer, or that frames
55991  ** that occur later in the log than pWal->hdr.mxFrame may have been
55992  ** copied into the database by a checkpointer. If either of these things
55993  ** happened, then reading the database with the current value of
55994  ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
55995  ** instead.
55996  **
55997  ** Before checking that the live wal-index header has not changed
55998  ** since it was read, set Wal.minFrame to the first frame in the wal
55999  ** file that has not yet been checkpointed. This client will not need
56000  ** to read any frames earlier than minFrame from the wal file - they
56001  ** can be safely read directly from the database file.
56002  **
56003  ** Because a ShmBarrier() call is made between taking the copy of
56004  ** nBackfill and checking that the wal-header in shared-memory still
56005  ** matches the one cached in pWal->hdr, it is guaranteed that the
56006  ** checkpointer that set nBackfill was not working with a wal-index
56007  ** header newer than that cached in pWal->hdr. If it were, that could
56008  ** cause a problem. The checkpointer could omit to checkpoint
56009  ** a version of page X that lies before pWal->minFrame (call that version
56010  ** A) on the basis that there is a newer version (version B) of the same
56011  ** page later in the wal file. But if version B happens to like past
56012  ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
56013  ** that it can read version A from the database file. However, since
56014  ** we can guarantee that the checkpointer that set nBackfill could not
56015  ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
56016  */
56017  pWal->minFrame = pInfo->nBackfill+1;
56018  walShmBarrier(pWal);
56019  if( pInfo->aReadMark[mxI]!=mxReadMark
56020   || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
56021  ){
56022    walUnlockShared(pWal, WAL_READ_LOCK(mxI));
56023    return WAL_RETRY;
56024  }else{
56025    assert( mxReadMark<=pWal->hdr.mxFrame );
56026    pWal->readLock = (i16)mxI;
56027  }
56028  return rc;
56029}
56030
56031/*
56032** Begin a read transaction on the database.
56033**
56034** This routine used to be called sqlite3OpenSnapshot() and with good reason:
56035** it takes a snapshot of the state of the WAL and wal-index for the current
56036** instant in time.  The current thread will continue to use this snapshot.
56037** Other threads might append new content to the WAL and wal-index but
56038** that extra content is ignored by the current thread.
56039**
56040** If the database contents have changes since the previous read
56041** transaction, then *pChanged is set to 1 before returning.  The
56042** Pager layer will use this to know that is cache is stale and
56043** needs to be flushed.
56044*/
56045SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
56046  int rc;                         /* Return code */
56047  int cnt = 0;                    /* Number of TryBeginRead attempts */
56048
56049#ifdef SQLITE_ENABLE_SNAPSHOT
56050  int bChanged = 0;
56051  WalIndexHdr *pSnapshot = pWal->pSnapshot;
56052  if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
56053    bChanged = 1;
56054  }
56055#endif
56056
56057  do{
56058    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
56059  }while( rc==WAL_RETRY );
56060  testcase( (rc&0xff)==SQLITE_BUSY );
56061  testcase( (rc&0xff)==SQLITE_IOERR );
56062  testcase( rc==SQLITE_PROTOCOL );
56063  testcase( rc==SQLITE_OK );
56064
56065#ifdef SQLITE_ENABLE_SNAPSHOT
56066  if( rc==SQLITE_OK ){
56067    if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
56068      /* At this point the client has a lock on an aReadMark[] slot holding
56069      ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
56070      ** is populated with the wal-index header corresponding to the head
56071      ** of the wal file. Verify that pSnapshot is still valid before
56072      ** continuing.  Reasons why pSnapshot might no longer be valid:
56073      **
56074      **    (1)  The WAL file has been reset since the snapshot was taken.
56075      **         In this case, the salt will have changed.
56076      **
56077      **    (2)  A checkpoint as been attempted that wrote frames past
56078      **         pSnapshot->mxFrame into the database file.  Note that the
56079      **         checkpoint need not have completed for this to cause problems.
56080      */
56081      volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
56082
56083      assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
56084      assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
56085
56086      /* It is possible that there is a checkpointer thread running
56087      ** concurrent with this code. If this is the case, it may be that the
56088      ** checkpointer has already determined that it will checkpoint
56089      ** snapshot X, where X is later in the wal file than pSnapshot, but
56090      ** has not yet set the pInfo->nBackfillAttempted variable to indicate
56091      ** its intent. To avoid the race condition this leads to, ensure that
56092      ** there is no checkpointer process by taking a shared CKPT lock
56093      ** before checking pInfo->nBackfillAttempted.  */
56094      rc = walLockShared(pWal, WAL_CKPT_LOCK);
56095
56096      if( rc==SQLITE_OK ){
56097        /* Check that the wal file has not been wrapped. Assuming that it has
56098        ** not, also check that no checkpointer has attempted to checkpoint any
56099        ** frames beyond pSnapshot->mxFrame. If either of these conditions are
56100        ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
56101        ** with *pSnapshot and set *pChanged as appropriate for opening the
56102        ** snapshot.  */
56103        if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
56104         && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
56105        ){
56106          assert( pWal->readLock>0 );
56107          memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
56108          *pChanged = bChanged;
56109        }else{
56110          rc = SQLITE_BUSY_SNAPSHOT;
56111        }
56112
56113        /* Release the shared CKPT lock obtained above. */
56114        walUnlockShared(pWal, WAL_CKPT_LOCK);
56115      }
56116
56117
56118      if( rc!=SQLITE_OK ){
56119        sqlite3WalEndReadTransaction(pWal);
56120      }
56121    }
56122  }
56123#endif
56124  return rc;
56125}
56126
56127/*
56128** Finish with a read transaction.  All this does is release the
56129** read-lock.
56130*/
56131SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
56132  sqlite3WalEndWriteTransaction(pWal);
56133  if( pWal->readLock>=0 ){
56134    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
56135    pWal->readLock = -1;
56136  }
56137}
56138
56139/*
56140** Search the wal file for page pgno. If found, set *piRead to the frame that
56141** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
56142** to zero.
56143**
56144** Return SQLITE_OK if successful, or an error code if an error occurs. If an
56145** error does occur, the final value of *piRead is undefined.
56146*/
56147SQLITE_PRIVATE int sqlite3WalFindFrame(
56148  Wal *pWal,                      /* WAL handle */
56149  Pgno pgno,                      /* Database page number to read data for */
56150  u32 *piRead                     /* OUT: Frame number (or zero) */
56151){
56152  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
56153  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
56154  int iHash;                      /* Used to loop through N hash tables */
56155  int iMinHash;
56156
56157  /* This routine is only be called from within a read transaction. */
56158  assert( pWal->readLock>=0 || pWal->lockError );
56159
56160  /* If the "last page" field of the wal-index header snapshot is 0, then
56161  ** no data will be read from the wal under any circumstances. Return early
56162  ** in this case as an optimization.  Likewise, if pWal->readLock==0,
56163  ** then the WAL is ignored by the reader so return early, as if the
56164  ** WAL were empty.
56165  */
56166  if( iLast==0 || pWal->readLock==0 ){
56167    *piRead = 0;
56168    return SQLITE_OK;
56169  }
56170
56171  /* Search the hash table or tables for an entry matching page number
56172  ** pgno. Each iteration of the following for() loop searches one
56173  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
56174  **
56175  ** This code might run concurrently to the code in walIndexAppend()
56176  ** that adds entries to the wal-index (and possibly to this hash
56177  ** table). This means the value just read from the hash
56178  ** slot (aHash[iKey]) may have been added before or after the
56179  ** current read transaction was opened. Values added after the
56180  ** read transaction was opened may have been written incorrectly -
56181  ** i.e. these slots may contain garbage data. However, we assume
56182  ** that any slots written before the current read transaction was
56183  ** opened remain unmodified.
56184  **
56185  ** For the reasons above, the if(...) condition featured in the inner
56186  ** loop of the following block is more stringent that would be required
56187  ** if we had exclusive access to the hash-table:
56188  **
56189  **   (aPgno[iFrame]==pgno):
56190  **     This condition filters out normal hash-table collisions.
56191  **
56192  **   (iFrame<=iLast):
56193  **     This condition filters out entries that were added to the hash
56194  **     table after the current read-transaction had started.
56195  */
56196  iMinHash = walFramePage(pWal->minFrame);
56197  for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
56198    volatile ht_slot *aHash;      /* Pointer to hash table */
56199    volatile u32 *aPgno;          /* Pointer to array of page numbers */
56200    u32 iZero;                    /* Frame number corresponding to aPgno[0] */
56201    int iKey;                     /* Hash slot index */
56202    int nCollide;                 /* Number of hash collisions remaining */
56203    int rc;                       /* Error code */
56204
56205    rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
56206    if( rc!=SQLITE_OK ){
56207      return rc;
56208    }
56209    nCollide = HASHTABLE_NSLOT;
56210    for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
56211      u32 iFrame = aHash[iKey] + iZero;
56212      if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
56213        assert( iFrame>iRead || CORRUPT_DB );
56214        iRead = iFrame;
56215      }
56216      if( (nCollide--)==0 ){
56217        return SQLITE_CORRUPT_BKPT;
56218      }
56219    }
56220  }
56221
56222#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
56223  /* If expensive assert() statements are available, do a linear search
56224  ** of the wal-index file content. Make sure the results agree with the
56225  ** result obtained using the hash indexes above.  */
56226  {
56227    u32 iRead2 = 0;
56228    u32 iTest;
56229    assert( pWal->minFrame>0 );
56230    for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
56231      if( walFramePgno(pWal, iTest)==pgno ){
56232        iRead2 = iTest;
56233        break;
56234      }
56235    }
56236    assert( iRead==iRead2 );
56237  }
56238#endif
56239
56240  *piRead = iRead;
56241  return SQLITE_OK;
56242}
56243
56244/*
56245** Read the contents of frame iRead from the wal file into buffer pOut
56246** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
56247** error code otherwise.
56248*/
56249SQLITE_PRIVATE int sqlite3WalReadFrame(
56250  Wal *pWal,                      /* WAL handle */
56251  u32 iRead,                      /* Frame to read */
56252  int nOut,                       /* Size of buffer pOut in bytes */
56253  u8 *pOut                        /* Buffer to write page data to */
56254){
56255  int sz;
56256  i64 iOffset;
56257  sz = pWal->hdr.szPage;
56258  sz = (sz&0xfe00) + ((sz&0x0001)<<16);
56259  testcase( sz<=32768 );
56260  testcase( sz>=65536 );
56261  iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
56262  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
56263  return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
56264}
56265
56266/*
56267** Return the size of the database in pages (or zero, if unknown).
56268*/
56269SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
56270  if( pWal && ALWAYS(pWal->readLock>=0) ){
56271    return pWal->hdr.nPage;
56272  }
56273  return 0;
56274}
56275
56276
56277/*
56278** This function starts a write transaction on the WAL.
56279**
56280** A read transaction must have already been started by a prior call
56281** to sqlite3WalBeginReadTransaction().
56282**
56283** If another thread or process has written into the database since
56284** the read transaction was started, then it is not possible for this
56285** thread to write as doing so would cause a fork.  So this routine
56286** returns SQLITE_BUSY in that case and no write transaction is started.
56287**
56288** There can only be a single writer active at a time.
56289*/
56290SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
56291  int rc;
56292
56293  /* Cannot start a write transaction without first holding a read
56294  ** transaction. */
56295  assert( pWal->readLock>=0 );
56296  assert( pWal->writeLock==0 && pWal->iReCksum==0 );
56297
56298  if( pWal->readOnly ){
56299    return SQLITE_READONLY;
56300  }
56301
56302  /* Only one writer allowed at a time.  Get the write lock.  Return
56303  ** SQLITE_BUSY if unable.
56304  */
56305  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
56306  if( rc ){
56307    return rc;
56308  }
56309  pWal->writeLock = 1;
56310
56311  /* If another connection has written to the database file since the
56312  ** time the read transaction on this connection was started, then
56313  ** the write is disallowed.
56314  */
56315  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
56316    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
56317    pWal->writeLock = 0;
56318    rc = SQLITE_BUSY_SNAPSHOT;
56319  }
56320
56321  return rc;
56322}
56323
56324/*
56325** End a write transaction.  The commit has already been done.  This
56326** routine merely releases the lock.
56327*/
56328SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
56329  if( pWal->writeLock ){
56330    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
56331    pWal->writeLock = 0;
56332    pWal->iReCksum = 0;
56333    pWal->truncateOnCommit = 0;
56334  }
56335  return SQLITE_OK;
56336}
56337
56338/*
56339** If any data has been written (but not committed) to the log file, this
56340** function moves the write-pointer back to the start of the transaction.
56341**
56342** Additionally, the callback function is invoked for each frame written
56343** to the WAL since the start of the transaction. If the callback returns
56344** other than SQLITE_OK, it is not invoked again and the error code is
56345** returned to the caller.
56346**
56347** Otherwise, if the callback function does not return an error, this
56348** function returns SQLITE_OK.
56349*/
56350SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
56351  int rc = SQLITE_OK;
56352  if( ALWAYS(pWal->writeLock) ){
56353    Pgno iMax = pWal->hdr.mxFrame;
56354    Pgno iFrame;
56355
56356    /* Restore the clients cache of the wal-index header to the state it
56357    ** was in before the client began writing to the database.
56358    */
56359    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
56360
56361    for(iFrame=pWal->hdr.mxFrame+1;
56362        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
56363        iFrame++
56364    ){
56365      /* This call cannot fail. Unless the page for which the page number
56366      ** is passed as the second argument is (a) in the cache and
56367      ** (b) has an outstanding reference, then xUndo is either a no-op
56368      ** (if (a) is false) or simply expels the page from the cache (if (b)
56369      ** is false).
56370      **
56371      ** If the upper layer is doing a rollback, it is guaranteed that there
56372      ** are no outstanding references to any page other than page 1. And
56373      ** page 1 is never written to the log until the transaction is
56374      ** committed. As a result, the call to xUndo may not fail.
56375      */
56376      assert( walFramePgno(pWal, iFrame)!=1 );
56377      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
56378    }
56379    if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
56380  }
56381  return rc;
56382}
56383
56384/*
56385** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
56386** values. This function populates the array with values required to
56387** "rollback" the write position of the WAL handle back to the current
56388** point in the event of a savepoint rollback (via WalSavepointUndo()).
56389*/
56390SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
56391  assert( pWal->writeLock );
56392  aWalData[0] = pWal->hdr.mxFrame;
56393  aWalData[1] = pWal->hdr.aFrameCksum[0];
56394  aWalData[2] = pWal->hdr.aFrameCksum[1];
56395  aWalData[3] = pWal->nCkpt;
56396}
56397
56398/*
56399** Move the write position of the WAL back to the point identified by
56400** the values in the aWalData[] array. aWalData must point to an array
56401** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
56402** by a call to WalSavepoint().
56403*/
56404SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
56405  int rc = SQLITE_OK;
56406
56407  assert( pWal->writeLock );
56408  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
56409
56410  if( aWalData[3]!=pWal->nCkpt ){
56411    /* This savepoint was opened immediately after the write-transaction
56412    ** was started. Right after that, the writer decided to wrap around
56413    ** to the start of the log. Update the savepoint values to match.
56414    */
56415    aWalData[0] = 0;
56416    aWalData[3] = pWal->nCkpt;
56417  }
56418
56419  if( aWalData[0]<pWal->hdr.mxFrame ){
56420    pWal->hdr.mxFrame = aWalData[0];
56421    pWal->hdr.aFrameCksum[0] = aWalData[1];
56422    pWal->hdr.aFrameCksum[1] = aWalData[2];
56423    walCleanupHash(pWal);
56424  }
56425
56426  return rc;
56427}
56428
56429/*
56430** This function is called just before writing a set of frames to the log
56431** file (see sqlite3WalFrames()). It checks to see if, instead of appending
56432** to the current log file, it is possible to overwrite the start of the
56433** existing log file with the new frames (i.e. "reset" the log). If so,
56434** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
56435** unchanged.
56436**
56437** SQLITE_OK is returned if no error is encountered (regardless of whether
56438** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
56439** if an error occurs.
56440*/
56441static int walRestartLog(Wal *pWal){
56442  int rc = SQLITE_OK;
56443  int cnt;
56444
56445  if( pWal->readLock==0 ){
56446    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
56447    assert( pInfo->nBackfill==pWal->hdr.mxFrame );
56448    if( pInfo->nBackfill>0 ){
56449      u32 salt1;
56450      sqlite3_randomness(4, &salt1);
56451      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
56452      if( rc==SQLITE_OK ){
56453        /* If all readers are using WAL_READ_LOCK(0) (in other words if no
56454        ** readers are currently using the WAL), then the transactions
56455        ** frames will overwrite the start of the existing log. Update the
56456        ** wal-index header to reflect this.
56457        **
56458        ** In theory it would be Ok to update the cache of the header only
56459        ** at this point. But updating the actual wal-index header is also
56460        ** safe and means there is no special case for sqlite3WalUndo()
56461        ** to handle if this transaction is rolled back.  */
56462        walRestartHdr(pWal, salt1);
56463        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
56464      }else if( rc!=SQLITE_BUSY ){
56465        return rc;
56466      }
56467    }
56468    walUnlockShared(pWal, WAL_READ_LOCK(0));
56469    pWal->readLock = -1;
56470    cnt = 0;
56471    do{
56472      int notUsed;
56473      rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
56474    }while( rc==WAL_RETRY );
56475    assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
56476    testcase( (rc&0xff)==SQLITE_IOERR );
56477    testcase( rc==SQLITE_PROTOCOL );
56478    testcase( rc==SQLITE_OK );
56479  }
56480  return rc;
56481}
56482
56483/*
56484** Information about the current state of the WAL file and where
56485** the next fsync should occur - passed from sqlite3WalFrames() into
56486** walWriteToLog().
56487*/
56488typedef struct WalWriter {
56489  Wal *pWal;                   /* The complete WAL information */
56490  sqlite3_file *pFd;           /* The WAL file to which we write */
56491  sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
56492  int syncFlags;               /* Flags for the fsync */
56493  int szPage;                  /* Size of one page */
56494} WalWriter;
56495
56496/*
56497** Write iAmt bytes of content into the WAL file beginning at iOffset.
56498** Do a sync when crossing the p->iSyncPoint boundary.
56499**
56500** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
56501** first write the part before iSyncPoint, then sync, then write the
56502** rest.
56503*/
56504static int walWriteToLog(
56505  WalWriter *p,              /* WAL to write to */
56506  void *pContent,            /* Content to be written */
56507  int iAmt,                  /* Number of bytes to write */
56508  sqlite3_int64 iOffset      /* Start writing at this offset */
56509){
56510  int rc;
56511  if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
56512    int iFirstAmt = (int)(p->iSyncPoint - iOffset);
56513    rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
56514    if( rc ) return rc;
56515    iOffset += iFirstAmt;
56516    iAmt -= iFirstAmt;
56517    pContent = (void*)(iFirstAmt + (char*)pContent);
56518    assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
56519    rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
56520    if( iAmt==0 || rc ) return rc;
56521  }
56522  rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
56523  return rc;
56524}
56525
56526/*
56527** Write out a single frame of the WAL
56528*/
56529static int walWriteOneFrame(
56530  WalWriter *p,               /* Where to write the frame */
56531  PgHdr *pPage,               /* The page of the frame to be written */
56532  int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
56533  sqlite3_int64 iOffset       /* Byte offset at which to write */
56534){
56535  int rc;                         /* Result code from subfunctions */
56536  void *pData;                    /* Data actually written */
56537  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
56538#if defined(SQLITE_HAS_CODEC)
56539  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
56540#else
56541  pData = pPage->pData;
56542#endif
56543  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
56544  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
56545  if( rc ) return rc;
56546  /* Write the page data */
56547  rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
56548  return rc;
56549}
56550
56551/*
56552** This function is called as part of committing a transaction within which
56553** one or more frames have been overwritten. It updates the checksums for
56554** all frames written to the wal file by the current transaction starting
56555** with the earliest to have been overwritten.
56556**
56557** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
56558*/
56559static int walRewriteChecksums(Wal *pWal, u32 iLast){
56560  const int szPage = pWal->szPage;/* Database page size */
56561  int rc = SQLITE_OK;             /* Return code */
56562  u8 *aBuf;                       /* Buffer to load data from wal file into */
56563  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-headers in */
56564  u32 iRead;                      /* Next frame to read from wal file */
56565  i64 iCksumOff;
56566
56567  aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
56568  if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
56569
56570  /* Find the checksum values to use as input for the recalculating the
56571  ** first checksum. If the first frame is frame 1 (implying that the current
56572  ** transaction restarted the wal file), these values must be read from the
56573  ** wal-file header. Otherwise, read them from the frame header of the
56574  ** previous frame.  */
56575  assert( pWal->iReCksum>0 );
56576  if( pWal->iReCksum==1 ){
56577    iCksumOff = 24;
56578  }else{
56579    iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
56580  }
56581  rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
56582  pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
56583  pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
56584
56585  iRead = pWal->iReCksum;
56586  pWal->iReCksum = 0;
56587  for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
56588    i64 iOff = walFrameOffset(iRead, szPage);
56589    rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
56590    if( rc==SQLITE_OK ){
56591      u32 iPgno, nDbSize;
56592      iPgno = sqlite3Get4byte(aBuf);
56593      nDbSize = sqlite3Get4byte(&aBuf[4]);
56594
56595      walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
56596      rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
56597    }
56598  }
56599
56600  sqlite3_free(aBuf);
56601  return rc;
56602}
56603
56604/*
56605** Write a set of frames to the log. The caller must hold the write-lock
56606** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
56607*/
56608SQLITE_PRIVATE int sqlite3WalFrames(
56609  Wal *pWal,                      /* Wal handle to write to */
56610  int szPage,                     /* Database page-size in bytes */
56611  PgHdr *pList,                   /* List of dirty pages to write */
56612  Pgno nTruncate,                 /* Database size after this commit */
56613  int isCommit,                   /* True if this is a commit */
56614  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
56615){
56616  int rc;                         /* Used to catch return codes */
56617  u32 iFrame;                     /* Next frame address */
56618  PgHdr *p;                       /* Iterator to run through pList with. */
56619  PgHdr *pLast = 0;               /* Last frame in list */
56620  int nExtra = 0;                 /* Number of extra copies of last page */
56621  int szFrame;                    /* The size of a single frame */
56622  i64 iOffset;                    /* Next byte to write in WAL file */
56623  WalWriter w;                    /* The writer */
56624  u32 iFirst = 0;                 /* First frame that may be overwritten */
56625  WalIndexHdr *pLive;             /* Pointer to shared header */
56626
56627  assert( pList );
56628  assert( pWal->writeLock );
56629
56630  /* If this frame set completes a transaction, then nTruncate>0.  If
56631  ** nTruncate==0 then this frame set does not complete the transaction. */
56632  assert( (isCommit!=0)==(nTruncate!=0) );
56633
56634#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
56635  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
56636    WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
56637              pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
56638  }
56639#endif
56640
56641  pLive = (WalIndexHdr*)walIndexHdr(pWal);
56642  if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
56643    iFirst = pLive->mxFrame+1;
56644  }
56645
56646  /* See if it is possible to write these frames into the start of the
56647  ** log file, instead of appending to it at pWal->hdr.mxFrame.
56648  */
56649  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
56650    return rc;
56651  }
56652
56653  /* If this is the first frame written into the log, write the WAL
56654  ** header to the start of the WAL file. See comments at the top of
56655  ** this source file for a description of the WAL header format.
56656  */
56657  iFrame = pWal->hdr.mxFrame;
56658  if( iFrame==0 ){
56659    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
56660    u32 aCksum[2];                /* Checksum for wal-header */
56661
56662    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
56663    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
56664    sqlite3Put4byte(&aWalHdr[8], szPage);
56665    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
56666    if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
56667    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
56668    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
56669    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
56670    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
56671
56672    pWal->szPage = szPage;
56673    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
56674    pWal->hdr.aFrameCksum[0] = aCksum[0];
56675    pWal->hdr.aFrameCksum[1] = aCksum[1];
56676    pWal->truncateOnCommit = 1;
56677
56678    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
56679    WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
56680    if( rc!=SQLITE_OK ){
56681      return rc;
56682    }
56683
56684    /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
56685    ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
56686    ** an out-of-order write following a WAL restart could result in
56687    ** database corruption.  See the ticket:
56688    **
56689    **     http://localhost:591/sqlite/info/ff5be73dee
56690    */
56691    if( pWal->syncHeader && sync_flags ){
56692      rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
56693      if( rc ) return rc;
56694    }
56695  }
56696  assert( (int)pWal->szPage==szPage );
56697
56698  /* Setup information needed to write frames into the WAL */
56699  w.pWal = pWal;
56700  w.pFd = pWal->pWalFd;
56701  w.iSyncPoint = 0;
56702  w.syncFlags = sync_flags;
56703  w.szPage = szPage;
56704  iOffset = walFrameOffset(iFrame+1, szPage);
56705  szFrame = szPage + WAL_FRAME_HDRSIZE;
56706
56707  /* Write all frames into the log file exactly once */
56708  for(p=pList; p; p=p->pDirty){
56709    int nDbSize;   /* 0 normally.  Positive == commit flag */
56710
56711    /* Check if this page has already been written into the wal file by
56712    ** the current transaction. If so, overwrite the existing frame and
56713    ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
56714    ** checksums must be recomputed when the transaction is committed.  */
56715    if( iFirst && (p->pDirty || isCommit==0) ){
56716      u32 iWrite = 0;
56717      VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
56718      assert( rc==SQLITE_OK || iWrite==0 );
56719      if( iWrite>=iFirst ){
56720        i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
56721        void *pData;
56722        if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
56723          pWal->iReCksum = iWrite;
56724        }
56725#if defined(SQLITE_HAS_CODEC)
56726        if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
56727#else
56728        pData = p->pData;
56729#endif
56730        rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
56731        if( rc ) return rc;
56732        p->flags &= ~PGHDR_WAL_APPEND;
56733        continue;
56734      }
56735    }
56736
56737    iFrame++;
56738    assert( iOffset==walFrameOffset(iFrame, szPage) );
56739    nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
56740    rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
56741    if( rc ) return rc;
56742    pLast = p;
56743    iOffset += szFrame;
56744    p->flags |= PGHDR_WAL_APPEND;
56745  }
56746
56747  /* Recalculate checksums within the wal file if required. */
56748  if( isCommit && pWal->iReCksum ){
56749    rc = walRewriteChecksums(pWal, iFrame);
56750    if( rc ) return rc;
56751  }
56752
56753  /* If this is the end of a transaction, then we might need to pad
56754  ** the transaction and/or sync the WAL file.
56755  **
56756  ** Padding and syncing only occur if this set of frames complete a
56757  ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
56758  ** or synchronous==OFF, then no padding or syncing are needed.
56759  **
56760  ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
56761  ** needed and only the sync is done.  If padding is needed, then the
56762  ** final frame is repeated (with its commit mark) until the next sector
56763  ** boundary is crossed.  Only the part of the WAL prior to the last
56764  ** sector boundary is synced; the part of the last frame that extends
56765  ** past the sector boundary is written after the sync.
56766  */
56767  if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
56768    int bSync = 1;
56769    if( pWal->padToSectorBoundary ){
56770      int sectorSize = sqlite3SectorSize(pWal->pWalFd);
56771      w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
56772      bSync = (w.iSyncPoint==iOffset);
56773      testcase( bSync );
56774      while( iOffset<w.iSyncPoint ){
56775        rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
56776        if( rc ) return rc;
56777        iOffset += szFrame;
56778        nExtra++;
56779      }
56780    }
56781    if( bSync ){
56782      assert( rc==SQLITE_OK );
56783      rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
56784    }
56785  }
56786
56787  /* If this frame set completes the first transaction in the WAL and
56788  ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
56789  ** journal size limit, if possible.
56790  */
56791  if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
56792    i64 sz = pWal->mxWalSize;
56793    if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
56794      sz = walFrameOffset(iFrame+nExtra+1, szPage);
56795    }
56796    walLimitSize(pWal, sz);
56797    pWal->truncateOnCommit = 0;
56798  }
56799
56800  /* Append data to the wal-index. It is not necessary to lock the
56801  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
56802  ** guarantees that there are no other writers, and no data that may
56803  ** be in use by existing readers is being overwritten.
56804  */
56805  iFrame = pWal->hdr.mxFrame;
56806  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
56807    if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
56808    iFrame++;
56809    rc = walIndexAppend(pWal, iFrame, p->pgno);
56810  }
56811  while( rc==SQLITE_OK && nExtra>0 ){
56812    iFrame++;
56813    nExtra--;
56814    rc = walIndexAppend(pWal, iFrame, pLast->pgno);
56815  }
56816
56817  if( rc==SQLITE_OK ){
56818    /* Update the private copy of the header. */
56819    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
56820    testcase( szPage<=32768 );
56821    testcase( szPage>=65536 );
56822    pWal->hdr.mxFrame = iFrame;
56823    if( isCommit ){
56824      pWal->hdr.iChange++;
56825      pWal->hdr.nPage = nTruncate;
56826    }
56827    /* If this is a commit, update the wal-index header too. */
56828    if( isCommit ){
56829      walIndexWriteHdr(pWal);
56830      pWal->iCallback = iFrame;
56831    }
56832  }
56833
56834  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
56835  return rc;
56836}
56837
56838/*
56839** This routine is called to implement sqlite3_wal_checkpoint() and
56840** related interfaces.
56841**
56842** Obtain a CHECKPOINT lock and then backfill as much information as
56843** we can from WAL into the database.
56844**
56845** If parameter xBusy is not NULL, it is a pointer to a busy-handler
56846** callback. In this case this function runs a blocking checkpoint.
56847*/
56848SQLITE_PRIVATE int sqlite3WalCheckpoint(
56849  Wal *pWal,                      /* Wal connection */
56850  int eMode,                      /* PASSIVE, FULL, RESTART, or TRUNCATE */
56851  int (*xBusy)(void*),            /* Function to call when busy */
56852  void *pBusyArg,                 /* Context argument for xBusyHandler */
56853  int sync_flags,                 /* Flags to sync db file with (or 0) */
56854  int nBuf,                       /* Size of temporary buffer */
56855  u8 *zBuf,                       /* Temporary buffer to use */
56856  int *pnLog,                     /* OUT: Number of frames in WAL */
56857  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
56858){
56859  int rc;                         /* Return code */
56860  int isChanged = 0;              /* True if a new wal-index header is loaded */
56861  int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
56862  int (*xBusy2)(void*) = xBusy;   /* Busy handler for eMode2 */
56863
56864  assert( pWal->ckptLock==0 );
56865  assert( pWal->writeLock==0 );
56866
56867  /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
56868  ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
56869  assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
56870
56871  if( pWal->readOnly ) return SQLITE_READONLY;
56872  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
56873
56874  /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
56875  ** "checkpoint" lock on the database file. */
56876  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
56877  if( rc ){
56878    /* EVIDENCE-OF: R-10421-19736 If any other process is running a
56879    ** checkpoint operation at the same time, the lock cannot be obtained and
56880    ** SQLITE_BUSY is returned.
56881    ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
56882    ** it will not be invoked in this case.
56883    */
56884    testcase( rc==SQLITE_BUSY );
56885    testcase( xBusy!=0 );
56886    return rc;
56887  }
56888  pWal->ckptLock = 1;
56889
56890  /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
56891  ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
56892  ** file.
56893  **
56894  ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
56895  ** immediately, and a busy-handler is configured, it is invoked and the
56896  ** writer lock retried until either the busy-handler returns 0 or the
56897  ** lock is successfully obtained.
56898  */
56899  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
56900    rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
56901    if( rc==SQLITE_OK ){
56902      pWal->writeLock = 1;
56903    }else if( rc==SQLITE_BUSY ){
56904      eMode2 = SQLITE_CHECKPOINT_PASSIVE;
56905      xBusy2 = 0;
56906      rc = SQLITE_OK;
56907    }
56908  }
56909
56910  /* Read the wal-index header. */
56911  if( rc==SQLITE_OK ){
56912    rc = walIndexReadHdr(pWal, &isChanged);
56913    if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
56914      sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
56915    }
56916  }
56917
56918  /* Copy data from the log to the database file. */
56919  if( rc==SQLITE_OK ){
56920
56921    if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
56922      rc = SQLITE_CORRUPT_BKPT;
56923    }else{
56924      rc = walCheckpoint(pWal, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
56925    }
56926
56927    /* If no error occurred, set the output variables. */
56928    if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
56929      if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
56930      if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
56931    }
56932  }
56933
56934  if( isChanged ){
56935    /* If a new wal-index header was loaded before the checkpoint was
56936    ** performed, then the pager-cache associated with pWal is now
56937    ** out of date. So zero the cached wal-index header to ensure that
56938    ** next time the pager opens a snapshot on this database it knows that
56939    ** the cache needs to be reset.
56940    */
56941    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
56942  }
56943
56944  /* Release the locks. */
56945  sqlite3WalEndWriteTransaction(pWal);
56946  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
56947  pWal->ckptLock = 0;
56948  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
56949  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
56950}
56951
56952/* Return the value to pass to a sqlite3_wal_hook callback, the
56953** number of frames in the WAL at the point of the last commit since
56954** sqlite3WalCallback() was called.  If no commits have occurred since
56955** the last call, then return 0.
56956*/
56957SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
56958  u32 ret = 0;
56959  if( pWal ){
56960    ret = pWal->iCallback;
56961    pWal->iCallback = 0;
56962  }
56963  return (int)ret;
56964}
56965
56966/*
56967** This function is called to change the WAL subsystem into or out
56968** of locking_mode=EXCLUSIVE.
56969**
56970** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
56971** into locking_mode=NORMAL.  This means that we must acquire a lock
56972** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
56973** or if the acquisition of the lock fails, then return 0.  If the
56974** transition out of exclusive-mode is successful, return 1.  This
56975** operation must occur while the pager is still holding the exclusive
56976** lock on the main database file.
56977**
56978** If op is one, then change from locking_mode=NORMAL into
56979** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
56980** be released.  Return 1 if the transition is made and 0 if the
56981** WAL is already in exclusive-locking mode - meaning that this
56982** routine is a no-op.  The pager must already hold the exclusive lock
56983** on the main database file before invoking this operation.
56984**
56985** If op is negative, then do a dry-run of the op==1 case but do
56986** not actually change anything. The pager uses this to see if it
56987** should acquire the database exclusive lock prior to invoking
56988** the op==1 case.
56989*/
56990SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
56991  int rc;
56992  assert( pWal->writeLock==0 );
56993  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
56994
56995  /* pWal->readLock is usually set, but might be -1 if there was a
56996  ** prior error while attempting to acquire are read-lock. This cannot
56997  ** happen if the connection is actually in exclusive mode (as no xShmLock
56998  ** locks are taken in this case). Nor should the pager attempt to
56999  ** upgrade to exclusive-mode following such an error.
57000  */
57001  assert( pWal->readLock>=0 || pWal->lockError );
57002  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
57003
57004  if( op==0 ){
57005    if( pWal->exclusiveMode ){
57006      pWal->exclusiveMode = 0;
57007      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
57008        pWal->exclusiveMode = 1;
57009      }
57010      rc = pWal->exclusiveMode==0;
57011    }else{
57012      /* Already in locking_mode=NORMAL */
57013      rc = 0;
57014    }
57015  }else if( op>0 ){
57016    assert( pWal->exclusiveMode==0 );
57017    assert( pWal->readLock>=0 );
57018    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
57019    pWal->exclusiveMode = 1;
57020    rc = 1;
57021  }else{
57022    rc = pWal->exclusiveMode==0;
57023  }
57024  return rc;
57025}
57026
57027/*
57028** Return true if the argument is non-NULL and the WAL module is using
57029** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
57030** WAL module is using shared-memory, return false.
57031*/
57032SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
57033  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
57034}
57035
57036#ifdef SQLITE_ENABLE_SNAPSHOT
57037/* Create a snapshot object.  The content of a snapshot is opaque to
57038** every other subsystem, so the WAL module can put whatever it needs
57039** in the object.
57040*/
57041SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
57042  int rc = SQLITE_OK;
57043  WalIndexHdr *pRet;
57044
57045  assert( pWal->readLock>=0 && pWal->writeLock==0 );
57046
57047  pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
57048  if( pRet==0 ){
57049    rc = SQLITE_NOMEM_BKPT;
57050  }else{
57051    memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
57052    *ppSnapshot = (sqlite3_snapshot*)pRet;
57053  }
57054
57055  return rc;
57056}
57057
57058/* Try to open on pSnapshot when the next read-transaction starts
57059*/
57060SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
57061  pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
57062}
57063
57064/*
57065** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
57066** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
57067*/
57068SQLITE_API int SQLITE_STDCALL sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
57069  WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
57070  WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
57071
57072  /* aSalt[0] is a copy of the value stored in the wal file header. It
57073  ** is incremented each time the wal file is restarted.  */
57074  if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
57075  if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
57076  if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
57077  if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
57078  return 0;
57079}
57080#endif /* SQLITE_ENABLE_SNAPSHOT */
57081
57082#ifdef SQLITE_ENABLE_ZIPVFS
57083/*
57084** If the argument is not NULL, it points to a Wal object that holds a
57085** read-lock. This function returns the database page-size if it is known,
57086** or zero if it is not (or if pWal is NULL).
57087*/
57088SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
57089  assert( pWal==0 || pWal->readLock>=0 );
57090  return (pWal ? pWal->szPage : 0);
57091}
57092#endif
57093
57094/* Return the sqlite3_file object for the WAL file
57095*/
57096SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
57097  return pWal->pWalFd;
57098}
57099
57100#endif /* #ifndef SQLITE_OMIT_WAL */
57101
57102/************** End of wal.c *************************************************/
57103/************** Begin file btmutex.c *****************************************/
57104/*
57105** 2007 August 27
57106**
57107** The author disclaims copyright to this source code.  In place of
57108** a legal notice, here is a blessing:
57109**
57110**    May you do good and not evil.
57111**    May you find forgiveness for yourself and forgive others.
57112**    May you share freely, never taking more than you give.
57113**
57114*************************************************************************
57115**
57116** This file contains code used to implement mutexes on Btree objects.
57117** This code really belongs in btree.c.  But btree.c is getting too
57118** big and we want to break it down some.  This packaged seemed like
57119** a good breakout.
57120*/
57121/************** Include btreeInt.h in the middle of btmutex.c ****************/
57122/************** Begin file btreeInt.h ****************************************/
57123/*
57124** 2004 April 6
57125**
57126** The author disclaims copyright to this source code.  In place of
57127** a legal notice, here is a blessing:
57128**
57129**    May you do good and not evil.
57130**    May you find forgiveness for yourself and forgive others.
57131**    May you share freely, never taking more than you give.
57132**
57133*************************************************************************
57134** This file implements an external (disk-based) database using BTrees.
57135** For a detailed discussion of BTrees, refer to
57136**
57137**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
57138**     "Sorting And Searching", pages 473-480. Addison-Wesley
57139**     Publishing Company, Reading, Massachusetts.
57140**
57141** The basic idea is that each page of the file contains N database
57142** entries and N+1 pointers to subpages.
57143**
57144**   ----------------------------------------------------------------
57145**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
57146**   ----------------------------------------------------------------
57147**
57148** All of the keys on the page that Ptr(0) points to have values less
57149** than Key(0).  All of the keys on page Ptr(1) and its subpages have
57150** values greater than Key(0) and less than Key(1).  All of the keys
57151** on Ptr(N) and its subpages have values greater than Key(N-1).  And
57152** so forth.
57153**
57154** Finding a particular key requires reading O(log(M)) pages from the
57155** disk where M is the number of entries in the tree.
57156**
57157** In this implementation, a single file can hold one or more separate
57158** BTrees.  Each BTree is identified by the index of its root page.  The
57159** key and data for any entry are combined to form the "payload".  A
57160** fixed amount of payload can be carried directly on the database
57161** page.  If the payload is larger than the preset amount then surplus
57162** bytes are stored on overflow pages.  The payload for an entry
57163** and the preceding pointer are combined to form a "Cell".  Each
57164** page has a small header which contains the Ptr(N) pointer and other
57165** information such as the size of key and data.
57166**
57167** FORMAT DETAILS
57168**
57169** The file is divided into pages.  The first page is called page 1,
57170** the second is page 2, and so forth.  A page number of zero indicates
57171** "no such page".  The page size can be any power of 2 between 512 and 65536.
57172** Each page can be either a btree page, a freelist page, an overflow
57173** page, or a pointer-map page.
57174**
57175** The first page is always a btree page.  The first 100 bytes of the first
57176** page contain a special header (the "file header") that describes the file.
57177** The format of the file header is as follows:
57178**
57179**   OFFSET   SIZE    DESCRIPTION
57180**      0      16     Header string: "SQLite format 3\000"
57181**     16       2     Page size in bytes.  (1 means 65536)
57182**     18       1     File format write version
57183**     19       1     File format read version
57184**     20       1     Bytes of unused space at the end of each page
57185**     21       1     Max embedded payload fraction (must be 64)
57186**     22       1     Min embedded payload fraction (must be 32)
57187**     23       1     Min leaf payload fraction (must be 32)
57188**     24       4     File change counter
57189**     28       4     Reserved for future use
57190**     32       4     First freelist page
57191**     36       4     Number of freelist pages in the file
57192**     40      60     15 4-byte meta values passed to higher layers
57193**
57194**     40       4     Schema cookie
57195**     44       4     File format of schema layer
57196**     48       4     Size of page cache
57197**     52       4     Largest root-page (auto/incr_vacuum)
57198**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
57199**     60       4     User version
57200**     64       4     Incremental vacuum mode
57201**     68       4     Application-ID
57202**     72      20     unused
57203**     92       4     The version-valid-for number
57204**     96       4     SQLITE_VERSION_NUMBER
57205**
57206** All of the integer values are big-endian (most significant byte first).
57207**
57208** The file change counter is incremented when the database is changed
57209** This counter allows other processes to know when the file has changed
57210** and thus when they need to flush their cache.
57211**
57212** The max embedded payload fraction is the amount of the total usable
57213** space in a page that can be consumed by a single cell for standard
57214** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
57215** is to limit the maximum cell size so that at least 4 cells will fit
57216** on one page.  Thus the default max embedded payload fraction is 64.
57217**
57218** If the payload for a cell is larger than the max payload, then extra
57219** payload is spilled to overflow pages.  Once an overflow page is allocated,
57220** as many bytes as possible are moved into the overflow pages without letting
57221** the cell size drop below the min embedded payload fraction.
57222**
57223** The min leaf payload fraction is like the min embedded payload fraction
57224** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
57225** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
57226** not specified in the header.
57227**
57228** Each btree pages is divided into three sections:  The header, the
57229** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
57230** file header that occurs before the page header.
57231**
57232**      |----------------|
57233**      | file header    |   100 bytes.  Page 1 only.
57234**      |----------------|
57235**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
57236**      |----------------|
57237**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
57238**      | array          |   |  Grows downward
57239**      |                |   v
57240**      |----------------|
57241**      | unallocated    |
57242**      | space          |
57243**      |----------------|   ^  Grows upwards
57244**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
57245**      | area           |   |  and free space fragments.
57246**      |----------------|
57247**
57248** The page headers looks like this:
57249**
57250**   OFFSET   SIZE     DESCRIPTION
57251**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
57252**      1       2      byte offset to the first freeblock
57253**      3       2      number of cells on this page
57254**      5       2      first byte of the cell content area
57255**      7       1      number of fragmented free bytes
57256**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
57257**
57258** The flags define the format of this btree page.  The leaf flag means that
57259** this page has no children.  The zerodata flag means that this page carries
57260** only keys and no data.  The intkey flag means that the key is an integer
57261** which is stored in the key size entry of the cell header rather than in
57262** the payload area.
57263**
57264** The cell pointer array begins on the first byte after the page header.
57265** The cell pointer array contains zero or more 2-byte numbers which are
57266** offsets from the beginning of the page to the cell content in the cell
57267** content area.  The cell pointers occur in sorted order.  The system strives
57268** to keep free space after the last cell pointer so that new cells can
57269** be easily added without having to defragment the page.
57270**
57271** Cell content is stored at the very end of the page and grows toward the
57272** beginning of the page.
57273**
57274** Unused space within the cell content area is collected into a linked list of
57275** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
57276** to the first freeblock is given in the header.  Freeblocks occur in
57277** increasing order.  Because a freeblock must be at least 4 bytes in size,
57278** any group of 3 or fewer unused bytes in the cell content area cannot
57279** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
57280** a fragment.  The total number of bytes in all fragments is recorded.
57281** in the page header at offset 7.
57282**
57283**    SIZE    DESCRIPTION
57284**      2     Byte offset of the next freeblock
57285**      2     Bytes in this freeblock
57286**
57287** Cells are of variable length.  Cells are stored in the cell content area at
57288** the end of the page.  Pointers to the cells are in the cell pointer array
57289** that immediately follows the page header.  Cells is not necessarily
57290** contiguous or in order, but cell pointers are contiguous and in order.
57291**
57292** Cell content makes use of variable length integers.  A variable
57293** length integer is 1 to 9 bytes where the lower 7 bits of each
57294** byte are used.  The integer consists of all bytes that have bit 8 set and
57295** the first byte with bit 8 clear.  The most significant byte of the integer
57296** appears first.  A variable-length integer may not be more than 9 bytes long.
57297** As a special case, all 8 bytes of the 9th byte are used as data.  This
57298** allows a 64-bit integer to be encoded in 9 bytes.
57299**
57300**    0x00                      becomes  0x00000000
57301**    0x7f                      becomes  0x0000007f
57302**    0x81 0x00                 becomes  0x00000080
57303**    0x82 0x00                 becomes  0x00000100
57304**    0x80 0x7f                 becomes  0x0000007f
57305**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
57306**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
57307**
57308** Variable length integers are used for rowids and to hold the number of
57309** bytes of key and data in a btree cell.
57310**
57311** The content of a cell looks like this:
57312**
57313**    SIZE    DESCRIPTION
57314**      4     Page number of the left child. Omitted if leaf flag is set.
57315**     var    Number of bytes of data. Omitted if the zerodata flag is set.
57316**     var    Number of bytes of key. Or the key itself if intkey flag is set.
57317**      *     Payload
57318**      4     First page of the overflow chain.  Omitted if no overflow
57319**
57320** Overflow pages form a linked list.  Each page except the last is completely
57321** filled with data (pagesize - 4 bytes).  The last page can have as little
57322** as 1 byte of data.
57323**
57324**    SIZE    DESCRIPTION
57325**      4     Page number of next overflow page
57326**      *     Data
57327**
57328** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
57329** file header points to the first in a linked list of trunk page.  Each trunk
57330** page points to multiple leaf pages.  The content of a leaf page is
57331** unspecified.  A trunk page looks like this:
57332**
57333**    SIZE    DESCRIPTION
57334**      4     Page number of next trunk page
57335**      4     Number of leaf pointers on this page
57336**      *     zero or more pages numbers of leaves
57337*/
57338/* #include "sqliteInt.h" */
57339
57340
57341/* The following value is the maximum cell size assuming a maximum page
57342** size give above.
57343*/
57344#define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
57345
57346/* The maximum number of cells on a single page of the database.  This
57347** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
57348** plus 2 bytes for the index to the cell in the page header).  Such
57349** small cells will be rare, but they are possible.
57350*/
57351#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
57352
57353/* Forward declarations */
57354typedef struct MemPage MemPage;
57355typedef struct BtLock BtLock;
57356typedef struct CellInfo CellInfo;
57357
57358/*
57359** This is a magic string that appears at the beginning of every
57360** SQLite database in order to identify the file as a real database.
57361**
57362** You can change this value at compile-time by specifying a
57363** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
57364** header must be exactly 16 bytes including the zero-terminator so
57365** the string itself should be 15 characters long.  If you change
57366** the header, then your custom library will not be able to read
57367** databases generated by the standard tools and the standard tools
57368** will not be able to read databases created by your custom library.
57369*/
57370#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
57371#  define SQLITE_FILE_HEADER "SQLite format 3"
57372#endif
57373
57374/*
57375** Page type flags.  An ORed combination of these flags appear as the
57376** first byte of on-disk image of every BTree page.
57377*/
57378#define PTF_INTKEY    0x01
57379#define PTF_ZERODATA  0x02
57380#define PTF_LEAFDATA  0x04
57381#define PTF_LEAF      0x08
57382
57383/*
57384** As each page of the file is loaded into memory, an instance of the following
57385** structure is appended and initialized to zero.  This structure stores
57386** information about the page that is decoded from the raw file page.
57387**
57388** The pParent field points back to the parent page.  This allows us to
57389** walk up the BTree from any leaf to the root.  Care must be taken to
57390** unref() the parent page pointer when this page is no longer referenced.
57391** The pageDestructor() routine handles that chore.
57392**
57393** Access to all fields of this structure is controlled by the mutex
57394** stored in MemPage.pBt->mutex.
57395*/
57396struct MemPage {
57397  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
57398  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
57399  u8 intKey;           /* True if table b-trees.  False for index b-trees */
57400  u8 intKeyLeaf;       /* True if the leaf of an intKey table */
57401  u8 leaf;             /* True if a leaf page */
57402  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
57403  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
57404  u8 max1bytePayload;  /* min(maxLocal,127) */
57405  u8 bBusy;            /* Prevent endless loops on corrupt database files */
57406  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
57407  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
57408  u16 cellOffset;      /* Index in aData of first cell pointer */
57409  u16 nFree;           /* Number of free bytes on the page */
57410  u16 nCell;           /* Number of cells on this page, local and ovfl */
57411  u16 maskPage;        /* Mask for page offset */
57412  u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
57413                       ** non-overflow cell */
57414  u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
57415  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
57416  u8 *aData;           /* Pointer to disk image of the page data */
57417  u8 *aDataEnd;        /* One byte past the end of usable data */
57418  u8 *aCellIdx;        /* The cell index area */
57419  u8 *aDataOfst;       /* Same as aData for leaves.  aData+4 for interior */
57420  DbPage *pDbPage;     /* Pager page handle */
57421  u16 (*xCellSize)(MemPage*,u8*);             /* cellSizePtr method */
57422  void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
57423  Pgno pgno;           /* Page number for this page */
57424};
57425
57426/*
57427** The in-memory image of a disk page has the auxiliary information appended
57428** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
57429** that extra information.
57430*/
57431#define EXTRA_SIZE sizeof(MemPage)
57432
57433/*
57434** A linked list of the following structures is stored at BtShared.pLock.
57435** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
57436** is opened on the table with root page BtShared.iTable. Locks are removed
57437** from this list when a transaction is committed or rolled back, or when
57438** a btree handle is closed.
57439*/
57440struct BtLock {
57441  Btree *pBtree;        /* Btree handle holding this lock */
57442  Pgno iTable;          /* Root page of table */
57443  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
57444  BtLock *pNext;        /* Next in BtShared.pLock list */
57445};
57446
57447/* Candidate values for BtLock.eLock */
57448#define READ_LOCK     1
57449#define WRITE_LOCK    2
57450
57451/* A Btree handle
57452**
57453** A database connection contains a pointer to an instance of
57454** this object for every database file that it has open.  This structure
57455** is opaque to the database connection.  The database connection cannot
57456** see the internals of this structure and only deals with pointers to
57457** this structure.
57458**
57459** For some database files, the same underlying database cache might be
57460** shared between multiple connections.  In that case, each connection
57461** has it own instance of this object.  But each instance of this object
57462** points to the same BtShared object.  The database cache and the
57463** schema associated with the database file are all contained within
57464** the BtShared object.
57465**
57466** All fields in this structure are accessed under sqlite3.mutex.
57467** The pBt pointer itself may not be changed while there exists cursors
57468** in the referenced BtShared that point back to this Btree since those
57469** cursors have to go through this Btree to find their BtShared and
57470** they often do so without holding sqlite3.mutex.
57471*/
57472struct Btree {
57473  sqlite3 *db;       /* The database connection holding this btree */
57474  BtShared *pBt;     /* Sharable content of this btree */
57475  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
57476  u8 sharable;       /* True if we can share pBt with another db */
57477  u8 locked;         /* True if db currently has pBt locked */
57478  u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
57479  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
57480  int nBackup;       /* Number of backup operations reading this btree */
57481  u32 iDataVersion;  /* Combines with pBt->pPager->iDataVersion */
57482  Btree *pNext;      /* List of other sharable Btrees from the same db */
57483  Btree *pPrev;      /* Back pointer of the same list */
57484#ifndef SQLITE_OMIT_SHARED_CACHE
57485  BtLock lock;       /* Object used to lock page 1 */
57486#endif
57487};
57488
57489/*
57490** Btree.inTrans may take one of the following values.
57491**
57492** If the shared-data extension is enabled, there may be multiple users
57493** of the Btree structure. At most one of these may open a write transaction,
57494** but any number may have active read transactions.
57495*/
57496#define TRANS_NONE  0
57497#define TRANS_READ  1
57498#define TRANS_WRITE 2
57499
57500/*
57501** An instance of this object represents a single database file.
57502**
57503** A single database file can be in use at the same time by two
57504** or more database connections.  When two or more connections are
57505** sharing the same database file, each connection has it own
57506** private Btree object for the file and each of those Btrees points
57507** to this one BtShared object.  BtShared.nRef is the number of
57508** connections currently sharing this database file.
57509**
57510** Fields in this structure are accessed under the BtShared.mutex
57511** mutex, except for nRef and pNext which are accessed under the
57512** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
57513** may not be modified once it is initially set as long as nRef>0.
57514** The pSchema field may be set once under BtShared.mutex and
57515** thereafter is unchanged as long as nRef>0.
57516**
57517** isPending:
57518**
57519**   If a BtShared client fails to obtain a write-lock on a database
57520**   table (because there exists one or more read-locks on the table),
57521**   the shared-cache enters 'pending-lock' state and isPending is
57522**   set to true.
57523**
57524**   The shared-cache leaves the 'pending lock' state when either of
57525**   the following occur:
57526**
57527**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
57528**     2) The number of locks held by other connections drops to zero.
57529**
57530**   while in the 'pending-lock' state, no connection may start a new
57531**   transaction.
57532**
57533**   This feature is included to help prevent writer-starvation.
57534*/
57535struct BtShared {
57536  Pager *pPager;        /* The page cache */
57537  sqlite3 *db;          /* Database connection currently using this Btree */
57538  BtCursor *pCursor;    /* A list of all open cursors */
57539  MemPage *pPage1;      /* First page of the database */
57540  u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
57541#ifndef SQLITE_OMIT_AUTOVACUUM
57542  u8 autoVacuum;        /* True if auto-vacuum is enabled */
57543  u8 incrVacuum;        /* True if incr-vacuum is enabled */
57544  u8 bDoTruncate;       /* True to truncate db on commit */
57545#endif
57546  u8 inTransaction;     /* Transaction state */
57547  u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
57548#ifdef SQLITE_HAS_CODEC
57549  u8 optimalReserve;    /* Desired amount of reserved space per page */
57550#endif
57551  u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
57552  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
57553  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
57554  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
57555  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
57556  u32 pageSize;         /* Total number of bytes on a page */
57557  u32 usableSize;       /* Number of usable bytes on each page */
57558  int nTransaction;     /* Number of open transactions (read + write) */
57559  u32 nPage;            /* Number of pages in the database */
57560  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
57561  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
57562  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
57563  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
57564#ifndef SQLITE_OMIT_SHARED_CACHE
57565  int nRef;             /* Number of references to this structure */
57566  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
57567  BtLock *pLock;        /* List of locks held on this shared-btree struct */
57568  Btree *pWriter;       /* Btree with currently open write transaction */
57569#endif
57570  u8 *pTmpSpace;        /* Temp space sufficient to hold a single cell */
57571};
57572
57573/*
57574** Allowed values for BtShared.btsFlags
57575*/
57576#define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
57577#define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
57578#define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
57579#define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
57580#define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
57581#define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
57582#define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
57583
57584/*
57585** An instance of the following structure is used to hold information
57586** about a cell.  The parseCellPtr() function fills in this structure
57587** based on information extract from the raw disk page.
57588*/
57589struct CellInfo {
57590  i64 nKey;      /* The key for INTKEY tables, or nPayload otherwise */
57591  u8 *pPayload;  /* Pointer to the start of payload */
57592  u32 nPayload;  /* Bytes of payload */
57593  u16 nLocal;    /* Amount of payload held locally, not on overflow */
57594  u16 nSize;     /* Size of the cell content on the main b-tree page */
57595};
57596
57597/*
57598** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
57599** this will be declared corrupt. This value is calculated based on a
57600** maximum database size of 2^31 pages a minimum fanout of 2 for a
57601** root-node and 3 for all other internal nodes.
57602**
57603** If a tree that appears to be taller than this is encountered, it is
57604** assumed that the database is corrupt.
57605*/
57606#define BTCURSOR_MAX_DEPTH 20
57607
57608/*
57609** A cursor is a pointer to a particular entry within a particular
57610** b-tree within a database file.
57611**
57612** The entry is identified by its MemPage and the index in
57613** MemPage.aCell[] of the entry.
57614**
57615** A single database file can be shared by two more database connections,
57616** but cursors cannot be shared.  Each cursor is associated with a
57617** particular database connection identified BtCursor.pBtree.db.
57618**
57619** Fields in this structure are accessed under the BtShared.mutex
57620** found at self->pBt->mutex.
57621**
57622** skipNext meaning:
57623**    eState==SKIPNEXT && skipNext>0:  Next sqlite3BtreeNext() is no-op.
57624**    eState==SKIPNEXT && skipNext<0:  Next sqlite3BtreePrevious() is no-op.
57625**    eState==FAULT:                   Cursor fault with skipNext as error code.
57626*/
57627struct BtCursor {
57628  Btree *pBtree;            /* The Btree to which this cursor belongs */
57629  BtShared *pBt;            /* The BtShared this cursor points to */
57630  BtCursor *pNext;          /* Forms a linked list of all cursors */
57631  Pgno *aOverflow;          /* Cache of overflow page locations */
57632  CellInfo info;            /* A parse of the cell we are pointing at */
57633  i64 nKey;                 /* Size of pKey, or last integer key */
57634  void *pKey;               /* Saved key that was cursor last known position */
57635  Pgno pgnoRoot;            /* The root page of this tree */
57636  int nOvflAlloc;           /* Allocated size of aOverflow[] array */
57637  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive.
57638                   ** Error code if eState==CURSOR_FAULT */
57639  u8 curFlags;              /* zero or more BTCF_* flags defined below */
57640  u8 curPagerFlags;         /* Flags to send to sqlite3PagerGet() */
57641  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
57642  u8 hints;                 /* As configured by CursorSetHints() */
57643  /* All fields above are zeroed when the cursor is allocated.  See
57644  ** sqlite3BtreeCursorZero().  Fields that follow must be manually
57645  ** initialized. */
57646  i8 iPage;                 /* Index of current page in apPage */
57647  u8 curIntKey;             /* Value of apPage[0]->intKey */
57648  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
57649  void *padding1;           /* Make object size a multiple of 16 */
57650  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
57651  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
57652};
57653
57654/*
57655** Legal values for BtCursor.curFlags
57656*/
57657#define BTCF_WriteFlag    0x01   /* True if a write cursor */
57658#define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
57659#define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
57660#define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
57661#define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
57662#define BTCF_Multiple     0x20   /* Maybe another cursor on the same btree */
57663
57664/*
57665** Potential values for BtCursor.eState.
57666**
57667** CURSOR_INVALID:
57668**   Cursor does not point to a valid entry. This can happen (for example)
57669**   because the table is empty or because BtreeCursorFirst() has not been
57670**   called.
57671**
57672** CURSOR_VALID:
57673**   Cursor points to a valid entry. getPayload() etc. may be called.
57674**
57675** CURSOR_SKIPNEXT:
57676**   Cursor is valid except that the Cursor.skipNext field is non-zero
57677**   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
57678**   operation should be a no-op.
57679**
57680** CURSOR_REQUIRESEEK:
57681**   The table that this cursor was opened on still exists, but has been
57682**   modified since the cursor was last used. The cursor position is saved
57683**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
57684**   this state, restoreCursorPosition() can be called to attempt to
57685**   seek the cursor to the saved position.
57686**
57687** CURSOR_FAULT:
57688**   An unrecoverable error (an I/O error or a malloc failure) has occurred
57689**   on a different connection that shares the BtShared cache with this
57690**   cursor.  The error has left the cache in an inconsistent state.
57691**   Do nothing else with this cursor.  Any attempt to use the cursor
57692**   should return the error code stored in BtCursor.skipNext
57693*/
57694#define CURSOR_INVALID           0
57695#define CURSOR_VALID             1
57696#define CURSOR_SKIPNEXT          2
57697#define CURSOR_REQUIRESEEK       3
57698#define CURSOR_FAULT             4
57699
57700/*
57701** The database page the PENDING_BYTE occupies. This page is never used.
57702*/
57703# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
57704
57705/*
57706** These macros define the location of the pointer-map entry for a
57707** database page. The first argument to each is the number of usable
57708** bytes on each page of the database (often 1024). The second is the
57709** page number to look up in the pointer map.
57710**
57711** PTRMAP_PAGENO returns the database page number of the pointer-map
57712** page that stores the required pointer. PTRMAP_PTROFFSET returns
57713** the offset of the requested map entry.
57714**
57715** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
57716** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
57717** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
57718** this test.
57719*/
57720#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
57721#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
57722#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
57723
57724/*
57725** The pointer map is a lookup table that identifies the parent page for
57726** each child page in the database file.  The parent page is the page that
57727** contains a pointer to the child.  Every page in the database contains
57728** 0 or 1 parent pages.  (In this context 'database page' refers
57729** to any page that is not part of the pointer map itself.)  Each pointer map
57730** entry consists of a single byte 'type' and a 4 byte parent page number.
57731** The PTRMAP_XXX identifiers below are the valid types.
57732**
57733** The purpose of the pointer map is to facility moving pages from one
57734** position in the file to another as part of autovacuum.  When a page
57735** is moved, the pointer in its parent must be updated to point to the
57736** new location.  The pointer map is used to locate the parent page quickly.
57737**
57738** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
57739**                  used in this case.
57740**
57741** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
57742**                  is not used in this case.
57743**
57744** PTRMAP_OVERFLOW1: The database page is the first page in a list of
57745**                   overflow pages. The page number identifies the page that
57746**                   contains the cell with a pointer to this overflow page.
57747**
57748** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
57749**                   overflow pages. The page-number identifies the previous
57750**                   page in the overflow page list.
57751**
57752** PTRMAP_BTREE: The database page is a non-root btree page. The page number
57753**               identifies the parent page in the btree.
57754*/
57755#define PTRMAP_ROOTPAGE 1
57756#define PTRMAP_FREEPAGE 2
57757#define PTRMAP_OVERFLOW1 3
57758#define PTRMAP_OVERFLOW2 4
57759#define PTRMAP_BTREE 5
57760
57761/* A bunch of assert() statements to check the transaction state variables
57762** of handle p (type Btree*) are internally consistent.
57763*/
57764#define btreeIntegrity(p) \
57765  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
57766  assert( p->pBt->inTransaction>=p->inTrans );
57767
57768
57769/*
57770** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
57771** if the database supports auto-vacuum or not. Because it is used
57772** within an expression that is an argument to another macro
57773** (sqliteMallocRaw), it is not possible to use conditional compilation.
57774** So, this macro is defined instead.
57775*/
57776#ifndef SQLITE_OMIT_AUTOVACUUM
57777#define ISAUTOVACUUM (pBt->autoVacuum)
57778#else
57779#define ISAUTOVACUUM 0
57780#endif
57781
57782
57783/*
57784** This structure is passed around through all the sanity checking routines
57785** in order to keep track of some global state information.
57786**
57787** The aRef[] array is allocated so that there is 1 bit for each page in
57788** the database. As the integrity-check proceeds, for each page used in
57789** the database the corresponding bit is set. This allows integrity-check to
57790** detect pages that are used twice and orphaned pages (both of which
57791** indicate corruption).
57792*/
57793typedef struct IntegrityCk IntegrityCk;
57794struct IntegrityCk {
57795  BtShared *pBt;    /* The tree being checked out */
57796  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
57797  u8 *aPgRef;       /* 1 bit per page in the db (see above) */
57798  Pgno nPage;       /* Number of pages in the database */
57799  int mxErr;        /* Stop accumulating errors when this reaches zero */
57800  int nErr;         /* Number of messages written to zErrMsg so far */
57801  int mallocFailed; /* A memory allocation error has occurred */
57802  const char *zPfx; /* Error message prefix */
57803  int v1, v2;       /* Values for up to two %d fields in zPfx */
57804  StrAccum errMsg;  /* Accumulate the error message text here */
57805  u32 *heap;        /* Min-heap used for analyzing cell coverage */
57806};
57807
57808/*
57809** Routines to read or write a two- and four-byte big-endian integer values.
57810*/
57811#define get2byte(x)   ((x)[0]<<8 | (x)[1])
57812#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
57813#define get4byte sqlite3Get4byte
57814#define put4byte sqlite3Put4byte
57815
57816/*
57817** get2byteAligned(), unlike get2byte(), requires that its argument point to a
57818** two-byte aligned address.  get2bytea() is only used for accessing the
57819** cell addresses in a btree header.
57820*/
57821#if SQLITE_BYTEORDER==4321
57822# define get2byteAligned(x)  (*(u16*)(x))
57823#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
57824    && GCC_VERSION>=4008000
57825# define get2byteAligned(x)  __builtin_bswap16(*(u16*)(x))
57826#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
57827    && defined(_MSC_VER) && _MSC_VER>=1300
57828# define get2byteAligned(x)  _byteswap_ushort(*(u16*)(x))
57829#else
57830# define get2byteAligned(x)  ((x)[0]<<8 | (x)[1])
57831#endif
57832
57833/************** End of btreeInt.h ********************************************/
57834/************** Continuing where we left off in btmutex.c ********************/
57835#ifndef SQLITE_OMIT_SHARED_CACHE
57836#if SQLITE_THREADSAFE
57837
57838/*
57839** Obtain the BtShared mutex associated with B-Tree handle p. Also,
57840** set BtShared.db to the database handle associated with p and the
57841** p->locked boolean to true.
57842*/
57843static void lockBtreeMutex(Btree *p){
57844  assert( p->locked==0 );
57845  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
57846  assert( sqlite3_mutex_held(p->db->mutex) );
57847
57848  sqlite3_mutex_enter(p->pBt->mutex);
57849  p->pBt->db = p->db;
57850  p->locked = 1;
57851}
57852
57853/*
57854** Release the BtShared mutex associated with B-Tree handle p and
57855** clear the p->locked boolean.
57856*/
57857static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
57858  BtShared *pBt = p->pBt;
57859  assert( p->locked==1 );
57860  assert( sqlite3_mutex_held(pBt->mutex) );
57861  assert( sqlite3_mutex_held(p->db->mutex) );
57862  assert( p->db==pBt->db );
57863
57864  sqlite3_mutex_leave(pBt->mutex);
57865  p->locked = 0;
57866}
57867
57868/* Forward reference */
57869static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
57870
57871/*
57872** Enter a mutex on the given BTree object.
57873**
57874** If the object is not sharable, then no mutex is ever required
57875** and this routine is a no-op.  The underlying mutex is non-recursive.
57876** But we keep a reference count in Btree.wantToLock so the behavior
57877** of this interface is recursive.
57878**
57879** To avoid deadlocks, multiple Btrees are locked in the same order
57880** by all database connections.  The p->pNext is a list of other
57881** Btrees belonging to the same database connection as the p Btree
57882** which need to be locked after p.  If we cannot get a lock on
57883** p, then first unlock all of the others on p->pNext, then wait
57884** for the lock to become available on p, then relock all of the
57885** subsequent Btrees that desire a lock.
57886*/
57887SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
57888  /* Some basic sanity checking on the Btree.  The list of Btrees
57889  ** connected by pNext and pPrev should be in sorted order by
57890  ** Btree.pBt value. All elements of the list should belong to
57891  ** the same connection. Only shared Btrees are on the list. */
57892  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
57893  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
57894  assert( p->pNext==0 || p->pNext->db==p->db );
57895  assert( p->pPrev==0 || p->pPrev->db==p->db );
57896  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
57897
57898  /* Check for locking consistency */
57899  assert( !p->locked || p->wantToLock>0 );
57900  assert( p->sharable || p->wantToLock==0 );
57901
57902  /* We should already hold a lock on the database connection */
57903  assert( sqlite3_mutex_held(p->db->mutex) );
57904
57905  /* Unless the database is sharable and unlocked, then BtShared.db
57906  ** should already be set correctly. */
57907  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
57908
57909  if( !p->sharable ) return;
57910  p->wantToLock++;
57911  if( p->locked ) return;
57912  btreeLockCarefully(p);
57913}
57914
57915/* This is a helper function for sqlite3BtreeLock(). By moving
57916** complex, but seldom used logic, out of sqlite3BtreeLock() and
57917** into this routine, we avoid unnecessary stack pointer changes
57918** and thus help the sqlite3BtreeLock() routine to run much faster
57919** in the common case.
57920*/
57921static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
57922  Btree *pLater;
57923
57924  /* In most cases, we should be able to acquire the lock we
57925  ** want without having to go through the ascending lock
57926  ** procedure that follows.  Just be sure not to block.
57927  */
57928  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
57929    p->pBt->db = p->db;
57930    p->locked = 1;
57931    return;
57932  }
57933
57934  /* To avoid deadlock, first release all locks with a larger
57935  ** BtShared address.  Then acquire our lock.  Then reacquire
57936  ** the other BtShared locks that we used to hold in ascending
57937  ** order.
57938  */
57939  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
57940    assert( pLater->sharable );
57941    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
57942    assert( !pLater->locked || pLater->wantToLock>0 );
57943    if( pLater->locked ){
57944      unlockBtreeMutex(pLater);
57945    }
57946  }
57947  lockBtreeMutex(p);
57948  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
57949    if( pLater->wantToLock ){
57950      lockBtreeMutex(pLater);
57951    }
57952  }
57953}
57954
57955
57956/*
57957** Exit the recursive mutex on a Btree.
57958*/
57959SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
57960  assert( sqlite3_mutex_held(p->db->mutex) );
57961  if( p->sharable ){
57962    assert( p->wantToLock>0 );
57963    p->wantToLock--;
57964    if( p->wantToLock==0 ){
57965      unlockBtreeMutex(p);
57966    }
57967  }
57968}
57969
57970#ifndef NDEBUG
57971/*
57972** Return true if the BtShared mutex is held on the btree, or if the
57973** B-Tree is not marked as sharable.
57974**
57975** This routine is used only from within assert() statements.
57976*/
57977SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
57978  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
57979  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
57980  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
57981  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
57982
57983  return (p->sharable==0 || p->locked);
57984}
57985#endif
57986
57987
57988/*
57989** Enter the mutex on every Btree associated with a database
57990** connection.  This is needed (for example) prior to parsing
57991** a statement since we will be comparing table and column names
57992** against all schemas and we do not want those schemas being
57993** reset out from under us.
57994**
57995** There is a corresponding leave-all procedures.
57996**
57997** Enter the mutexes in accending order by BtShared pointer address
57998** to avoid the possibility of deadlock when two threads with
57999** two or more btrees in common both try to lock all their btrees
58000** at the same instant.
58001*/
58002SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
58003  int i;
58004  Btree *p;
58005  assert( sqlite3_mutex_held(db->mutex) );
58006  for(i=0; i<db->nDb; i++){
58007    p = db->aDb[i].pBt;
58008    if( p ) sqlite3BtreeEnter(p);
58009  }
58010}
58011SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
58012  int i;
58013  Btree *p;
58014  assert( sqlite3_mutex_held(db->mutex) );
58015  for(i=0; i<db->nDb; i++){
58016    p = db->aDb[i].pBt;
58017    if( p ) sqlite3BtreeLeave(p);
58018  }
58019}
58020
58021#ifndef NDEBUG
58022/*
58023** Return true if the current thread holds the database connection
58024** mutex and all required BtShared mutexes.
58025**
58026** This routine is used inside assert() statements only.
58027*/
58028SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
58029  int i;
58030  if( !sqlite3_mutex_held(db->mutex) ){
58031    return 0;
58032  }
58033  for(i=0; i<db->nDb; i++){
58034    Btree *p;
58035    p = db->aDb[i].pBt;
58036    if( p && p->sharable &&
58037         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
58038      return 0;
58039    }
58040  }
58041  return 1;
58042}
58043#endif /* NDEBUG */
58044
58045#ifndef NDEBUG
58046/*
58047** Return true if the correct mutexes are held for accessing the
58048** db->aDb[iDb].pSchema structure.  The mutexes required for schema
58049** access are:
58050**
58051**   (1) The mutex on db
58052**   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
58053**
58054** If pSchema is not NULL, then iDb is computed from pSchema and
58055** db using sqlite3SchemaToIndex().
58056*/
58057SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
58058  Btree *p;
58059  assert( db!=0 );
58060  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
58061  assert( iDb>=0 && iDb<db->nDb );
58062  if( !sqlite3_mutex_held(db->mutex) ) return 0;
58063  if( iDb==1 ) return 1;
58064  p = db->aDb[iDb].pBt;
58065  assert( p!=0 );
58066  return p->sharable==0 || p->locked==1;
58067}
58068#endif /* NDEBUG */
58069
58070#else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
58071/*
58072** The following are special cases for mutex enter routines for use
58073** in single threaded applications that use shared cache.  Except for
58074** these two routines, all mutex operations are no-ops in that case and
58075** are null #defines in btree.h.
58076**
58077** If shared cache is disabled, then all btree mutex routines, including
58078** the ones below, are no-ops and are null #defines in btree.h.
58079*/
58080
58081SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
58082  p->pBt->db = p->db;
58083}
58084SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
58085  int i;
58086  for(i=0; i<db->nDb; i++){
58087    Btree *p = db->aDb[i].pBt;
58088    if( p ){
58089      p->pBt->db = p->db;
58090    }
58091  }
58092}
58093#endif /* if SQLITE_THREADSAFE */
58094
58095#ifndef SQLITE_OMIT_INCRBLOB
58096/*
58097** Enter a mutex on a Btree given a cursor owned by that Btree.
58098**
58099** These entry points are used by incremental I/O only. Enter() is required
58100** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
58101** the build is threadsafe. Leave() is only required by threadsafe builds.
58102*/
58103SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
58104  sqlite3BtreeEnter(pCur->pBtree);
58105}
58106# if SQLITE_THREADSAFE
58107SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
58108  sqlite3BtreeLeave(pCur->pBtree);
58109}
58110# endif
58111#endif /* ifndef SQLITE_OMIT_INCRBLOB */
58112
58113#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
58114
58115/************** End of btmutex.c *********************************************/
58116/************** Begin file btree.c *******************************************/
58117/*
58118** 2004 April 6
58119**
58120** The author disclaims copyright to this source code.  In place of
58121** a legal notice, here is a blessing:
58122**
58123**    May you do good and not evil.
58124**    May you find forgiveness for yourself and forgive others.
58125**    May you share freely, never taking more than you give.
58126**
58127*************************************************************************
58128** This file implements an external (disk-based) database using BTrees.
58129** See the header comment on "btreeInt.h" for additional information.
58130** Including a description of file format and an overview of operation.
58131*/
58132/* #include "btreeInt.h" */
58133
58134/*
58135** The header string that appears at the beginning of every
58136** SQLite database.
58137*/
58138static const char zMagicHeader[] = SQLITE_FILE_HEADER;
58139
58140/*
58141** Set this global variable to 1 to enable tracing using the TRACE
58142** macro.
58143*/
58144#if 0
58145int sqlite3BtreeTrace=1;  /* True to enable tracing */
58146# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
58147#else
58148# define TRACE(X)
58149#endif
58150
58151/*
58152** Extract a 2-byte big-endian integer from an array of unsigned bytes.
58153** But if the value is zero, make it 65536.
58154**
58155** This routine is used to extract the "offset to cell content area" value
58156** from the header of a btree page.  If the page size is 65536 and the page
58157** is empty, the offset should be 65536, but the 2-byte value stores zero.
58158** This routine makes the necessary adjustment to 65536.
58159*/
58160#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
58161
58162/*
58163** Values passed as the 5th argument to allocateBtreePage()
58164*/
58165#define BTALLOC_ANY   0           /* Allocate any page */
58166#define BTALLOC_EXACT 1           /* Allocate exact page if possible */
58167#define BTALLOC_LE    2           /* Allocate any page <= the parameter */
58168
58169/*
58170** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
58171** defined, or 0 if it is. For example:
58172**
58173**   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
58174*/
58175#ifndef SQLITE_OMIT_AUTOVACUUM
58176#define IfNotOmitAV(expr) (expr)
58177#else
58178#define IfNotOmitAV(expr) 0
58179#endif
58180
58181#ifndef SQLITE_OMIT_SHARED_CACHE
58182/*
58183** A list of BtShared objects that are eligible for participation
58184** in shared cache.  This variable has file scope during normal builds,
58185** but the test harness needs to access it so we make it global for
58186** test builds.
58187**
58188** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
58189*/
58190#ifdef SQLITE_TEST
58191SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
58192#else
58193static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
58194#endif
58195#endif /* SQLITE_OMIT_SHARED_CACHE */
58196
58197#ifndef SQLITE_OMIT_SHARED_CACHE
58198/*
58199** Enable or disable the shared pager and schema features.
58200**
58201** This routine has no effect on existing database connections.
58202** The shared cache setting effects only future calls to
58203** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
58204*/
58205SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int enable){
58206  sqlite3GlobalConfig.sharedCacheEnabled = enable;
58207  return SQLITE_OK;
58208}
58209#endif
58210
58211
58212
58213#ifdef SQLITE_OMIT_SHARED_CACHE
58214  /*
58215  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
58216  ** and clearAllSharedCacheTableLocks()
58217  ** manipulate entries in the BtShared.pLock linked list used to store
58218  ** shared-cache table level locks. If the library is compiled with the
58219  ** shared-cache feature disabled, then there is only ever one user
58220  ** of each BtShared structure and so this locking is not necessary.
58221  ** So define the lock related functions as no-ops.
58222  */
58223  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
58224  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
58225  #define clearAllSharedCacheTableLocks(a)
58226  #define downgradeAllSharedCacheTableLocks(a)
58227  #define hasSharedCacheTableLock(a,b,c,d) 1
58228  #define hasReadConflicts(a, b) 0
58229#endif
58230
58231#ifndef SQLITE_OMIT_SHARED_CACHE
58232
58233#ifdef SQLITE_DEBUG
58234/*
58235**** This function is only used as part of an assert() statement. ***
58236**
58237** Check to see if pBtree holds the required locks to read or write to the
58238** table with root page iRoot.   Return 1 if it does and 0 if not.
58239**
58240** For example, when writing to a table with root-page iRoot via
58241** Btree connection pBtree:
58242**
58243**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
58244**
58245** When writing to an index that resides in a sharable database, the
58246** caller should have first obtained a lock specifying the root page of
58247** the corresponding table. This makes things a bit more complicated,
58248** as this module treats each table as a separate structure. To determine
58249** the table corresponding to the index being written, this
58250** function has to search through the database schema.
58251**
58252** Instead of a lock on the table/index rooted at page iRoot, the caller may
58253** hold a write-lock on the schema table (root page 1). This is also
58254** acceptable.
58255*/
58256static int hasSharedCacheTableLock(
58257  Btree *pBtree,         /* Handle that must hold lock */
58258  Pgno iRoot,            /* Root page of b-tree */
58259  int isIndex,           /* True if iRoot is the root of an index b-tree */
58260  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
58261){
58262  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
58263  Pgno iTab = 0;
58264  BtLock *pLock;
58265
58266  /* If this database is not shareable, or if the client is reading
58267  ** and has the read-uncommitted flag set, then no lock is required.
58268  ** Return true immediately.
58269  */
58270  if( (pBtree->sharable==0)
58271   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
58272  ){
58273    return 1;
58274  }
58275
58276  /* If the client is reading  or writing an index and the schema is
58277  ** not loaded, then it is too difficult to actually check to see if
58278  ** the correct locks are held.  So do not bother - just return true.
58279  ** This case does not come up very often anyhow.
58280  */
58281  if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
58282    return 1;
58283  }
58284
58285  /* Figure out the root-page that the lock should be held on. For table
58286  ** b-trees, this is just the root page of the b-tree being read or
58287  ** written. For index b-trees, it is the root page of the associated
58288  ** table.  */
58289  if( isIndex ){
58290    HashElem *p;
58291    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
58292      Index *pIdx = (Index *)sqliteHashData(p);
58293      if( pIdx->tnum==(int)iRoot ){
58294        if( iTab ){
58295          /* Two or more indexes share the same root page.  There must
58296          ** be imposter tables.  So just return true.  The assert is not
58297          ** useful in that case. */
58298          return 1;
58299        }
58300        iTab = pIdx->pTable->tnum;
58301      }
58302    }
58303  }else{
58304    iTab = iRoot;
58305  }
58306
58307  /* Search for the required lock. Either a write-lock on root-page iTab, a
58308  ** write-lock on the schema table, or (if the client is reading) a
58309  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
58310  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
58311    if( pLock->pBtree==pBtree
58312     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
58313     && pLock->eLock>=eLockType
58314    ){
58315      return 1;
58316    }
58317  }
58318
58319  /* Failed to find the required lock. */
58320  return 0;
58321}
58322#endif /* SQLITE_DEBUG */
58323
58324#ifdef SQLITE_DEBUG
58325/*
58326**** This function may be used as part of assert() statements only. ****
58327**
58328** Return true if it would be illegal for pBtree to write into the
58329** table or index rooted at iRoot because other shared connections are
58330** simultaneously reading that same table or index.
58331**
58332** It is illegal for pBtree to write if some other Btree object that
58333** shares the same BtShared object is currently reading or writing
58334** the iRoot table.  Except, if the other Btree object has the
58335** read-uncommitted flag set, then it is OK for the other object to
58336** have a read cursor.
58337**
58338** For example, before writing to any part of the table or index
58339** rooted at page iRoot, one should call:
58340**
58341**    assert( !hasReadConflicts(pBtree, iRoot) );
58342*/
58343static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
58344  BtCursor *p;
58345  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
58346    if( p->pgnoRoot==iRoot
58347     && p->pBtree!=pBtree
58348     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
58349    ){
58350      return 1;
58351    }
58352  }
58353  return 0;
58354}
58355#endif    /* #ifdef SQLITE_DEBUG */
58356
58357/*
58358** Query to see if Btree handle p may obtain a lock of type eLock
58359** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
58360** SQLITE_OK if the lock may be obtained (by calling
58361** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
58362*/
58363static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
58364  BtShared *pBt = p->pBt;
58365  BtLock *pIter;
58366
58367  assert( sqlite3BtreeHoldsMutex(p) );
58368  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
58369  assert( p->db!=0 );
58370  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
58371
58372  /* If requesting a write-lock, then the Btree must have an open write
58373  ** transaction on this file. And, obviously, for this to be so there
58374  ** must be an open write transaction on the file itself.
58375  */
58376  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
58377  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
58378
58379  /* This routine is a no-op if the shared-cache is not enabled */
58380  if( !p->sharable ){
58381    return SQLITE_OK;
58382  }
58383
58384  /* If some other connection is holding an exclusive lock, the
58385  ** requested lock may not be obtained.
58386  */
58387  if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
58388    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
58389    return SQLITE_LOCKED_SHAREDCACHE;
58390  }
58391
58392  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
58393    /* The condition (pIter->eLock!=eLock) in the following if(...)
58394    ** statement is a simplification of:
58395    **
58396    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
58397    **
58398    ** since we know that if eLock==WRITE_LOCK, then no other connection
58399    ** may hold a WRITE_LOCK on any table in this file (since there can
58400    ** only be a single writer).
58401    */
58402    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
58403    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
58404    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
58405      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
58406      if( eLock==WRITE_LOCK ){
58407        assert( p==pBt->pWriter );
58408        pBt->btsFlags |= BTS_PENDING;
58409      }
58410      return SQLITE_LOCKED_SHAREDCACHE;
58411    }
58412  }
58413  return SQLITE_OK;
58414}
58415#endif /* !SQLITE_OMIT_SHARED_CACHE */
58416
58417#ifndef SQLITE_OMIT_SHARED_CACHE
58418/*
58419** Add a lock on the table with root-page iTable to the shared-btree used
58420** by Btree handle p. Parameter eLock must be either READ_LOCK or
58421** WRITE_LOCK.
58422**
58423** This function assumes the following:
58424**
58425**   (a) The specified Btree object p is connected to a sharable
58426**       database (one with the BtShared.sharable flag set), and
58427**
58428**   (b) No other Btree objects hold a lock that conflicts
58429**       with the requested lock (i.e. querySharedCacheTableLock() has
58430**       already been called and returned SQLITE_OK).
58431**
58432** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
58433** is returned if a malloc attempt fails.
58434*/
58435static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
58436  BtShared *pBt = p->pBt;
58437  BtLock *pLock = 0;
58438  BtLock *pIter;
58439
58440  assert( sqlite3BtreeHoldsMutex(p) );
58441  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
58442  assert( p->db!=0 );
58443
58444  /* A connection with the read-uncommitted flag set will never try to
58445  ** obtain a read-lock using this function. The only read-lock obtained
58446  ** by a connection in read-uncommitted mode is on the sqlite_master
58447  ** table, and that lock is obtained in BtreeBeginTrans().  */
58448  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
58449
58450  /* This function should only be called on a sharable b-tree after it
58451  ** has been determined that no other b-tree holds a conflicting lock.  */
58452  assert( p->sharable );
58453  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
58454
58455  /* First search the list for an existing lock on this table. */
58456  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
58457    if( pIter->iTable==iTable && pIter->pBtree==p ){
58458      pLock = pIter;
58459      break;
58460    }
58461  }
58462
58463  /* If the above search did not find a BtLock struct associating Btree p
58464  ** with table iTable, allocate one and link it into the list.
58465  */
58466  if( !pLock ){
58467    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
58468    if( !pLock ){
58469      return SQLITE_NOMEM_BKPT;
58470    }
58471    pLock->iTable = iTable;
58472    pLock->pBtree = p;
58473    pLock->pNext = pBt->pLock;
58474    pBt->pLock = pLock;
58475  }
58476
58477  /* Set the BtLock.eLock variable to the maximum of the current lock
58478  ** and the requested lock. This means if a write-lock was already held
58479  ** and a read-lock requested, we don't incorrectly downgrade the lock.
58480  */
58481  assert( WRITE_LOCK>READ_LOCK );
58482  if( eLock>pLock->eLock ){
58483    pLock->eLock = eLock;
58484  }
58485
58486  return SQLITE_OK;
58487}
58488#endif /* !SQLITE_OMIT_SHARED_CACHE */
58489
58490#ifndef SQLITE_OMIT_SHARED_CACHE
58491/*
58492** Release all the table locks (locks obtained via calls to
58493** the setSharedCacheTableLock() procedure) held by Btree object p.
58494**
58495** This function assumes that Btree p has an open read or write
58496** transaction. If it does not, then the BTS_PENDING flag
58497** may be incorrectly cleared.
58498*/
58499static void clearAllSharedCacheTableLocks(Btree *p){
58500  BtShared *pBt = p->pBt;
58501  BtLock **ppIter = &pBt->pLock;
58502
58503  assert( sqlite3BtreeHoldsMutex(p) );
58504  assert( p->sharable || 0==*ppIter );
58505  assert( p->inTrans>0 );
58506
58507  while( *ppIter ){
58508    BtLock *pLock = *ppIter;
58509    assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
58510    assert( pLock->pBtree->inTrans>=pLock->eLock );
58511    if( pLock->pBtree==p ){
58512      *ppIter = pLock->pNext;
58513      assert( pLock->iTable!=1 || pLock==&p->lock );
58514      if( pLock->iTable!=1 ){
58515        sqlite3_free(pLock);
58516      }
58517    }else{
58518      ppIter = &pLock->pNext;
58519    }
58520  }
58521
58522  assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
58523  if( pBt->pWriter==p ){
58524    pBt->pWriter = 0;
58525    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
58526  }else if( pBt->nTransaction==2 ){
58527    /* This function is called when Btree p is concluding its
58528    ** transaction. If there currently exists a writer, and p is not
58529    ** that writer, then the number of locks held by connections other
58530    ** than the writer must be about to drop to zero. In this case
58531    ** set the BTS_PENDING flag to 0.
58532    **
58533    ** If there is not currently a writer, then BTS_PENDING must
58534    ** be zero already. So this next line is harmless in that case.
58535    */
58536    pBt->btsFlags &= ~BTS_PENDING;
58537  }
58538}
58539
58540/*
58541** This function changes all write-locks held by Btree p into read-locks.
58542*/
58543static void downgradeAllSharedCacheTableLocks(Btree *p){
58544  BtShared *pBt = p->pBt;
58545  if( pBt->pWriter==p ){
58546    BtLock *pLock;
58547    pBt->pWriter = 0;
58548    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
58549    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
58550      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
58551      pLock->eLock = READ_LOCK;
58552    }
58553  }
58554}
58555
58556#endif /* SQLITE_OMIT_SHARED_CACHE */
58557
58558static void releasePage(MemPage *pPage);  /* Forward reference */
58559
58560/*
58561***** This routine is used inside of assert() only ****
58562**
58563** Verify that the cursor holds the mutex on its BtShared
58564*/
58565#ifdef SQLITE_DEBUG
58566static int cursorHoldsMutex(BtCursor *p){
58567  return sqlite3_mutex_held(p->pBt->mutex);
58568}
58569
58570/* Verify that the cursor and the BtShared agree about what is the current
58571** database connetion. This is important in shared-cache mode. If the database
58572** connection pointers get out-of-sync, it is possible for routines like
58573** btreeInitPage() to reference an stale connection pointer that references a
58574** a connection that has already closed.  This routine is used inside assert()
58575** statements only and for the purpose of double-checking that the btree code
58576** does keep the database connection pointers up-to-date.
58577*/
58578static int cursorOwnsBtShared(BtCursor *p){
58579  assert( cursorHoldsMutex(p) );
58580  return (p->pBtree->db==p->pBt->db);
58581}
58582#endif
58583
58584/*
58585** Invalidate the overflow cache of the cursor passed as the first argument.
58586** on the shared btree structure pBt.
58587*/
58588#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
58589
58590/*
58591** Invalidate the overflow page-list cache for all cursors opened
58592** on the shared btree structure pBt.
58593*/
58594static void invalidateAllOverflowCache(BtShared *pBt){
58595  BtCursor *p;
58596  assert( sqlite3_mutex_held(pBt->mutex) );
58597  for(p=pBt->pCursor; p; p=p->pNext){
58598    invalidateOverflowCache(p);
58599  }
58600}
58601
58602#ifndef SQLITE_OMIT_INCRBLOB
58603/*
58604** This function is called before modifying the contents of a table
58605** to invalidate any incrblob cursors that are open on the
58606** row or one of the rows being modified.
58607**
58608** If argument isClearTable is true, then the entire contents of the
58609** table is about to be deleted. In this case invalidate all incrblob
58610** cursors open on any row within the table with root-page pgnoRoot.
58611**
58612** Otherwise, if argument isClearTable is false, then the row with
58613** rowid iRow is being replaced or deleted. In this case invalidate
58614** only those incrblob cursors open on that specific row.
58615*/
58616static void invalidateIncrblobCursors(
58617  Btree *pBtree,          /* The database file to check */
58618  i64 iRow,               /* The rowid that might be changing */
58619  int isClearTable        /* True if all rows are being deleted */
58620){
58621  BtCursor *p;
58622  if( pBtree->hasIncrblobCur==0 ) return;
58623  assert( sqlite3BtreeHoldsMutex(pBtree) );
58624  pBtree->hasIncrblobCur = 0;
58625  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
58626    if( (p->curFlags & BTCF_Incrblob)!=0 ){
58627      pBtree->hasIncrblobCur = 1;
58628      if( isClearTable || p->info.nKey==iRow ){
58629        p->eState = CURSOR_INVALID;
58630      }
58631    }
58632  }
58633}
58634
58635#else
58636  /* Stub function when INCRBLOB is omitted */
58637  #define invalidateIncrblobCursors(x,y,z)
58638#endif /* SQLITE_OMIT_INCRBLOB */
58639
58640/*
58641** Set bit pgno of the BtShared.pHasContent bitvec. This is called
58642** when a page that previously contained data becomes a free-list leaf
58643** page.
58644**
58645** The BtShared.pHasContent bitvec exists to work around an obscure
58646** bug caused by the interaction of two useful IO optimizations surrounding
58647** free-list leaf pages:
58648**
58649**   1) When all data is deleted from a page and the page becomes
58650**      a free-list leaf page, the page is not written to the database
58651**      (as free-list leaf pages contain no meaningful data). Sometimes
58652**      such a page is not even journalled (as it will not be modified,
58653**      why bother journalling it?).
58654**
58655**   2) When a free-list leaf page is reused, its content is not read
58656**      from the database or written to the journal file (why should it
58657**      be, if it is not at all meaningful?).
58658**
58659** By themselves, these optimizations work fine and provide a handy
58660** performance boost to bulk delete or insert operations. However, if
58661** a page is moved to the free-list and then reused within the same
58662** transaction, a problem comes up. If the page is not journalled when
58663** it is moved to the free-list and it is also not journalled when it
58664** is extracted from the free-list and reused, then the original data
58665** may be lost. In the event of a rollback, it may not be possible
58666** to restore the database to its original configuration.
58667**
58668** The solution is the BtShared.pHasContent bitvec. Whenever a page is
58669** moved to become a free-list leaf page, the corresponding bit is
58670** set in the bitvec. Whenever a leaf page is extracted from the free-list,
58671** optimization 2 above is omitted if the corresponding bit is already
58672** set in BtShared.pHasContent. The contents of the bitvec are cleared
58673** at the end of every transaction.
58674*/
58675static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
58676  int rc = SQLITE_OK;
58677  if( !pBt->pHasContent ){
58678    assert( pgno<=pBt->nPage );
58679    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
58680    if( !pBt->pHasContent ){
58681      rc = SQLITE_NOMEM_BKPT;
58682    }
58683  }
58684  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
58685    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
58686  }
58687  return rc;
58688}
58689
58690/*
58691** Query the BtShared.pHasContent vector.
58692**
58693** This function is called when a free-list leaf page is removed from the
58694** free-list for reuse. It returns false if it is safe to retrieve the
58695** page from the pager layer with the 'no-content' flag set. True otherwise.
58696*/
58697static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
58698  Bitvec *p = pBt->pHasContent;
58699  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
58700}
58701
58702/*
58703** Clear (destroy) the BtShared.pHasContent bitvec. This should be
58704** invoked at the conclusion of each write-transaction.
58705*/
58706static void btreeClearHasContent(BtShared *pBt){
58707  sqlite3BitvecDestroy(pBt->pHasContent);
58708  pBt->pHasContent = 0;
58709}
58710
58711/*
58712** Release all of the apPage[] pages for a cursor.
58713*/
58714static void btreeReleaseAllCursorPages(BtCursor *pCur){
58715  int i;
58716  for(i=0; i<=pCur->iPage; i++){
58717    releasePage(pCur->apPage[i]);
58718    pCur->apPage[i] = 0;
58719  }
58720  pCur->iPage = -1;
58721}
58722
58723/*
58724** The cursor passed as the only argument must point to a valid entry
58725** when this function is called (i.e. have eState==CURSOR_VALID). This
58726** function saves the current cursor key in variables pCur->nKey and
58727** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
58728** code otherwise.
58729**
58730** If the cursor is open on an intkey table, then the integer key
58731** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
58732** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
58733** set to point to a malloced buffer pCur->nKey bytes in size containing
58734** the key.
58735*/
58736static int saveCursorKey(BtCursor *pCur){
58737  int rc = SQLITE_OK;
58738  assert( CURSOR_VALID==pCur->eState );
58739  assert( 0==pCur->pKey );
58740  assert( cursorHoldsMutex(pCur) );
58741
58742  if( pCur->curIntKey ){
58743    /* Only the rowid is required for a table btree */
58744    pCur->nKey = sqlite3BtreeIntegerKey(pCur);
58745  }else{
58746    /* For an index btree, save the complete key content */
58747    void *pKey;
58748    pCur->nKey = sqlite3BtreePayloadSize(pCur);
58749    pKey = sqlite3Malloc( pCur->nKey );
58750    if( pKey ){
58751      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
58752      if( rc==SQLITE_OK ){
58753        pCur->pKey = pKey;
58754      }else{
58755        sqlite3_free(pKey);
58756      }
58757    }else{
58758      rc = SQLITE_NOMEM_BKPT;
58759    }
58760  }
58761  assert( !pCur->curIntKey || !pCur->pKey );
58762  return rc;
58763}
58764
58765/*
58766** Save the current cursor position in the variables BtCursor.nKey
58767** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
58768**
58769** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
58770** prior to calling this routine.
58771*/
58772static int saveCursorPosition(BtCursor *pCur){
58773  int rc;
58774
58775  assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
58776  assert( 0==pCur->pKey );
58777  assert( cursorHoldsMutex(pCur) );
58778
58779  if( pCur->eState==CURSOR_SKIPNEXT ){
58780    pCur->eState = CURSOR_VALID;
58781  }else{
58782    pCur->skipNext = 0;
58783  }
58784
58785  rc = saveCursorKey(pCur);
58786  if( rc==SQLITE_OK ){
58787    btreeReleaseAllCursorPages(pCur);
58788    pCur->eState = CURSOR_REQUIRESEEK;
58789  }
58790
58791  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
58792  return rc;
58793}
58794
58795/* Forward reference */
58796static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
58797
58798/*
58799** Save the positions of all cursors (except pExcept) that are open on
58800** the table with root-page iRoot.  "Saving the cursor position" means that
58801** the location in the btree is remembered in such a way that it can be
58802** moved back to the same spot after the btree has been modified.  This
58803** routine is called just before cursor pExcept is used to modify the
58804** table, for example in BtreeDelete() or BtreeInsert().
58805**
58806** If there are two or more cursors on the same btree, then all such
58807** cursors should have their BTCF_Multiple flag set.  The btreeCursor()
58808** routine enforces that rule.  This routine only needs to be called in
58809** the uncommon case when pExpect has the BTCF_Multiple flag set.
58810**
58811** If pExpect!=NULL and if no other cursors are found on the same root-page,
58812** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
58813** pointless call to this routine.
58814**
58815** Implementation note:  This routine merely checks to see if any cursors
58816** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)
58817** event that cursors are in need to being saved.
58818*/
58819static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
58820  BtCursor *p;
58821  assert( sqlite3_mutex_held(pBt->mutex) );
58822  assert( pExcept==0 || pExcept->pBt==pBt );
58823  for(p=pBt->pCursor; p; p=p->pNext){
58824    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
58825  }
58826  if( p ) return saveCursorsOnList(p, iRoot, pExcept);
58827  if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
58828  return SQLITE_OK;
58829}
58830
58831/* This helper routine to saveAllCursors does the actual work of saving
58832** the cursors if and when a cursor is found that actually requires saving.
58833** The common case is that no cursors need to be saved, so this routine is
58834** broken out from its caller to avoid unnecessary stack pointer movement.
58835*/
58836static int SQLITE_NOINLINE saveCursorsOnList(
58837  BtCursor *p,         /* The first cursor that needs saving */
58838  Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
58839  BtCursor *pExcept    /* Do not save this cursor */
58840){
58841  do{
58842    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
58843      if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
58844        int rc = saveCursorPosition(p);
58845        if( SQLITE_OK!=rc ){
58846          return rc;
58847        }
58848      }else{
58849        testcase( p->iPage>0 );
58850        btreeReleaseAllCursorPages(p);
58851      }
58852    }
58853    p = p->pNext;
58854  }while( p );
58855  return SQLITE_OK;
58856}
58857
58858/*
58859** Clear the current cursor position.
58860*/
58861SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
58862  assert( cursorHoldsMutex(pCur) );
58863  sqlite3_free(pCur->pKey);
58864  pCur->pKey = 0;
58865  pCur->eState = CURSOR_INVALID;
58866}
58867
58868/*
58869** In this version of BtreeMoveto, pKey is a packed index record
58870** such as is generated by the OP_MakeRecord opcode.  Unpack the
58871** record and then call BtreeMovetoUnpacked() to do the work.
58872*/
58873static int btreeMoveto(
58874  BtCursor *pCur,     /* Cursor open on the btree to be searched */
58875  const void *pKey,   /* Packed key if the btree is an index */
58876  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
58877  int bias,           /* Bias search to the high end */
58878  int *pRes           /* Write search results here */
58879){
58880  int rc;                    /* Status code */
58881  UnpackedRecord *pIdxKey;   /* Unpacked index key */
58882  char aSpace[200];          /* Temp space for pIdxKey - to avoid a malloc */
58883  char *pFree = 0;
58884
58885  if( pKey ){
58886    assert( nKey==(i64)(int)nKey );
58887    pIdxKey = sqlite3VdbeAllocUnpackedRecord(
58888        pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
58889    );
58890    if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
58891    sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
58892    if( pIdxKey->nField==0 ){
58893      sqlite3DbFree(pCur->pKeyInfo->db, pFree);
58894      return SQLITE_CORRUPT_BKPT;
58895    }
58896  }else{
58897    pIdxKey = 0;
58898  }
58899  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
58900  if( pFree ){
58901    sqlite3DbFree(pCur->pKeyInfo->db, pFree);
58902  }
58903  return rc;
58904}
58905
58906/*
58907** Restore the cursor to the position it was in (or as close to as possible)
58908** when saveCursorPosition() was called. Note that this call deletes the
58909** saved position info stored by saveCursorPosition(), so there can be
58910** at most one effective restoreCursorPosition() call after each
58911** saveCursorPosition().
58912*/
58913static int btreeRestoreCursorPosition(BtCursor *pCur){
58914  int rc;
58915  int skipNext;
58916  assert( cursorOwnsBtShared(pCur) );
58917  assert( pCur->eState>=CURSOR_REQUIRESEEK );
58918  if( pCur->eState==CURSOR_FAULT ){
58919    return pCur->skipNext;
58920  }
58921  pCur->eState = CURSOR_INVALID;
58922  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
58923  if( rc==SQLITE_OK ){
58924    sqlite3_free(pCur->pKey);
58925    pCur->pKey = 0;
58926    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
58927    pCur->skipNext |= skipNext;
58928    if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
58929      pCur->eState = CURSOR_SKIPNEXT;
58930    }
58931  }
58932  return rc;
58933}
58934
58935#define restoreCursorPosition(p) \
58936  (p->eState>=CURSOR_REQUIRESEEK ? \
58937         btreeRestoreCursorPosition(p) : \
58938         SQLITE_OK)
58939
58940/*
58941** Determine whether or not a cursor has moved from the position where
58942** it was last placed, or has been invalidated for any other reason.
58943** Cursors can move when the row they are pointing at is deleted out
58944** from under them, for example.  Cursor might also move if a btree
58945** is rebalanced.
58946**
58947** Calling this routine with a NULL cursor pointer returns false.
58948**
58949** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
58950** back to where it ought to be if this routine returns true.
58951*/
58952SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
58953  return pCur->eState!=CURSOR_VALID;
58954}
58955
58956/*
58957** This routine restores a cursor back to its original position after it
58958** has been moved by some outside activity (such as a btree rebalance or
58959** a row having been deleted out from under the cursor).
58960**
58961** On success, the *pDifferentRow parameter is false if the cursor is left
58962** pointing at exactly the same row.  *pDifferntRow is the row the cursor
58963** was pointing to has been deleted, forcing the cursor to point to some
58964** nearby row.
58965**
58966** This routine should only be called for a cursor that just returned
58967** TRUE from sqlite3BtreeCursorHasMoved().
58968*/
58969SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
58970  int rc;
58971
58972  assert( pCur!=0 );
58973  assert( pCur->eState!=CURSOR_VALID );
58974  rc = restoreCursorPosition(pCur);
58975  if( rc ){
58976    *pDifferentRow = 1;
58977    return rc;
58978  }
58979  if( pCur->eState!=CURSOR_VALID ){
58980    *pDifferentRow = 1;
58981  }else{
58982    assert( pCur->skipNext==0 );
58983    *pDifferentRow = 0;
58984  }
58985  return SQLITE_OK;
58986}
58987
58988#ifdef SQLITE_ENABLE_CURSOR_HINTS
58989/*
58990** Provide hints to the cursor.  The particular hint given (and the type
58991** and number of the varargs parameters) is determined by the eHintType
58992** parameter.  See the definitions of the BTREE_HINT_* macros for details.
58993*/
58994SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
58995  /* Used only by system that substitute their own storage engine */
58996}
58997#endif
58998
58999/*
59000** Provide flag hints to the cursor.
59001*/
59002SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
59003  assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
59004  pCur->hints = x;
59005}
59006
59007
59008#ifndef SQLITE_OMIT_AUTOVACUUM
59009/*
59010** Given a page number of a regular database page, return the page
59011** number for the pointer-map page that contains the entry for the
59012** input page number.
59013**
59014** Return 0 (not a valid page) for pgno==1 since there is
59015** no pointer map associated with page 1.  The integrity_check logic
59016** requires that ptrmapPageno(*,1)!=1.
59017*/
59018static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
59019  int nPagesPerMapPage;
59020  Pgno iPtrMap, ret;
59021  assert( sqlite3_mutex_held(pBt->mutex) );
59022  if( pgno<2 ) return 0;
59023  nPagesPerMapPage = (pBt->usableSize/5)+1;
59024  iPtrMap = (pgno-2)/nPagesPerMapPage;
59025  ret = (iPtrMap*nPagesPerMapPage) + 2;
59026  if( ret==PENDING_BYTE_PAGE(pBt) ){
59027    ret++;
59028  }
59029  return ret;
59030}
59031
59032/*
59033** Write an entry into the pointer map.
59034**
59035** This routine updates the pointer map entry for page number 'key'
59036** so that it maps to type 'eType' and parent page number 'pgno'.
59037**
59038** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
59039** a no-op.  If an error occurs, the appropriate error code is written
59040** into *pRC.
59041*/
59042static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
59043  DbPage *pDbPage;  /* The pointer map page */
59044  u8 *pPtrmap;      /* The pointer map data */
59045  Pgno iPtrmap;     /* The pointer map page number */
59046  int offset;       /* Offset in pointer map page */
59047  int rc;           /* Return code from subfunctions */
59048
59049  if( *pRC ) return;
59050
59051  assert( sqlite3_mutex_held(pBt->mutex) );
59052  /* The master-journal page number must never be used as a pointer map page */
59053  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
59054
59055  assert( pBt->autoVacuum );
59056  if( key==0 ){
59057    *pRC = SQLITE_CORRUPT_BKPT;
59058    return;
59059  }
59060  iPtrmap = PTRMAP_PAGENO(pBt, key);
59061  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
59062  if( rc!=SQLITE_OK ){
59063    *pRC = rc;
59064    return;
59065  }
59066  offset = PTRMAP_PTROFFSET(iPtrmap, key);
59067  if( offset<0 ){
59068    *pRC = SQLITE_CORRUPT_BKPT;
59069    goto ptrmap_exit;
59070  }
59071  assert( offset <= (int)pBt->usableSize-5 );
59072  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
59073
59074  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
59075    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
59076    *pRC= rc = sqlite3PagerWrite(pDbPage);
59077    if( rc==SQLITE_OK ){
59078      pPtrmap[offset] = eType;
59079      put4byte(&pPtrmap[offset+1], parent);
59080    }
59081  }
59082
59083ptrmap_exit:
59084  sqlite3PagerUnref(pDbPage);
59085}
59086
59087/*
59088** Read an entry from the pointer map.
59089**
59090** This routine retrieves the pointer map entry for page 'key', writing
59091** the type and parent page number to *pEType and *pPgno respectively.
59092** An error code is returned if something goes wrong, otherwise SQLITE_OK.
59093*/
59094static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
59095  DbPage *pDbPage;   /* The pointer map page */
59096  int iPtrmap;       /* Pointer map page index */
59097  u8 *pPtrmap;       /* Pointer map page data */
59098  int offset;        /* Offset of entry in pointer map */
59099  int rc;
59100
59101  assert( sqlite3_mutex_held(pBt->mutex) );
59102
59103  iPtrmap = PTRMAP_PAGENO(pBt, key);
59104  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
59105  if( rc!=0 ){
59106    return rc;
59107  }
59108  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
59109
59110  offset = PTRMAP_PTROFFSET(iPtrmap, key);
59111  if( offset<0 ){
59112    sqlite3PagerUnref(pDbPage);
59113    return SQLITE_CORRUPT_BKPT;
59114  }
59115  assert( offset <= (int)pBt->usableSize-5 );
59116  assert( pEType!=0 );
59117  *pEType = pPtrmap[offset];
59118  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
59119
59120  sqlite3PagerUnref(pDbPage);
59121  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
59122  return SQLITE_OK;
59123}
59124
59125#else /* if defined SQLITE_OMIT_AUTOVACUUM */
59126  #define ptrmapPut(w,x,y,z,rc)
59127  #define ptrmapGet(w,x,y,z) SQLITE_OK
59128  #define ptrmapPutOvflPtr(x, y, rc)
59129#endif
59130
59131/*
59132** Given a btree page and a cell index (0 means the first cell on
59133** the page, 1 means the second cell, and so forth) return a pointer
59134** to the cell content.
59135**
59136** findCellPastPtr() does the same except it skips past the initial
59137** 4-byte child pointer found on interior pages, if there is one.
59138**
59139** This routine works only for pages that do not contain overflow cells.
59140*/
59141#define findCell(P,I) \
59142  ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
59143#define findCellPastPtr(P,I) \
59144  ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
59145
59146
59147/*
59148** This is common tail processing for btreeParseCellPtr() and
59149** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
59150** on a single B-tree page.  Make necessary adjustments to the CellInfo
59151** structure.
59152*/
59153static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
59154  MemPage *pPage,         /* Page containing the cell */
59155  u8 *pCell,              /* Pointer to the cell text. */
59156  CellInfo *pInfo         /* Fill in this structure */
59157){
59158  /* If the payload will not fit completely on the local page, we have
59159  ** to decide how much to store locally and how much to spill onto
59160  ** overflow pages.  The strategy is to minimize the amount of unused
59161  ** space on overflow pages while keeping the amount of local storage
59162  ** in between minLocal and maxLocal.
59163  **
59164  ** Warning:  changing the way overflow payload is distributed in any
59165  ** way will result in an incompatible file format.
59166  */
59167  int minLocal;  /* Minimum amount of payload held locally */
59168  int maxLocal;  /* Maximum amount of payload held locally */
59169  int surplus;   /* Overflow payload available for local storage */
59170
59171  minLocal = pPage->minLocal;
59172  maxLocal = pPage->maxLocal;
59173  surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
59174  testcase( surplus==maxLocal );
59175  testcase( surplus==maxLocal+1 );
59176  if( surplus <= maxLocal ){
59177    pInfo->nLocal = (u16)surplus;
59178  }else{
59179    pInfo->nLocal = (u16)minLocal;
59180  }
59181  pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
59182}
59183
59184/*
59185** The following routines are implementations of the MemPage.xParseCell()
59186** method.
59187**
59188** Parse a cell content block and fill in the CellInfo structure.
59189**
59190** btreeParseCellPtr()        =>   table btree leaf nodes
59191** btreeParseCellNoPayload()  =>   table btree internal nodes
59192** btreeParseCellPtrIndex()   =>   index btree nodes
59193**
59194** There is also a wrapper function btreeParseCell() that works for
59195** all MemPage types and that references the cell by index rather than
59196** by pointer.
59197*/
59198static void btreeParseCellPtrNoPayload(
59199  MemPage *pPage,         /* Page containing the cell */
59200  u8 *pCell,              /* Pointer to the cell text. */
59201  CellInfo *pInfo         /* Fill in this structure */
59202){
59203  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59204  assert( pPage->leaf==0 );
59205  assert( pPage->childPtrSize==4 );
59206#ifndef SQLITE_DEBUG
59207  UNUSED_PARAMETER(pPage);
59208#endif
59209  pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
59210  pInfo->nPayload = 0;
59211  pInfo->nLocal = 0;
59212  pInfo->pPayload = 0;
59213  return;
59214}
59215static void btreeParseCellPtr(
59216  MemPage *pPage,         /* Page containing the cell */
59217  u8 *pCell,              /* Pointer to the cell text. */
59218  CellInfo *pInfo         /* Fill in this structure */
59219){
59220  u8 *pIter;              /* For scanning through pCell */
59221  u32 nPayload;           /* Number of bytes of cell payload */
59222  u64 iKey;               /* Extracted Key value */
59223
59224  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59225  assert( pPage->leaf==0 || pPage->leaf==1 );
59226  assert( pPage->intKeyLeaf );
59227  assert( pPage->childPtrSize==0 );
59228  pIter = pCell;
59229
59230  /* The next block of code is equivalent to:
59231  **
59232  **     pIter += getVarint32(pIter, nPayload);
59233  **
59234  ** The code is inlined to avoid a function call.
59235  */
59236  nPayload = *pIter;
59237  if( nPayload>=0x80 ){
59238    u8 *pEnd = &pIter[8];
59239    nPayload &= 0x7f;
59240    do{
59241      nPayload = (nPayload<<7) | (*++pIter & 0x7f);
59242    }while( (*pIter)>=0x80 && pIter<pEnd );
59243  }
59244  pIter++;
59245
59246  /* The next block of code is equivalent to:
59247  **
59248  **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
59249  **
59250  ** The code is inlined to avoid a function call.
59251  */
59252  iKey = *pIter;
59253  if( iKey>=0x80 ){
59254    u8 *pEnd = &pIter[7];
59255    iKey &= 0x7f;
59256    while(1){
59257      iKey = (iKey<<7) | (*++pIter & 0x7f);
59258      if( (*pIter)<0x80 ) break;
59259      if( pIter>=pEnd ){
59260        iKey = (iKey<<8) | *++pIter;
59261        break;
59262      }
59263    }
59264  }
59265  pIter++;
59266
59267  pInfo->nKey = *(i64*)&iKey;
59268  pInfo->nPayload = nPayload;
59269  pInfo->pPayload = pIter;
59270  testcase( nPayload==pPage->maxLocal );
59271  testcase( nPayload==pPage->maxLocal+1 );
59272  if( nPayload<=pPage->maxLocal ){
59273    /* This is the (easy) common case where the entire payload fits
59274    ** on the local page.  No overflow is required.
59275    */
59276    pInfo->nSize = nPayload + (u16)(pIter - pCell);
59277    if( pInfo->nSize<4 ) pInfo->nSize = 4;
59278    pInfo->nLocal = (u16)nPayload;
59279  }else{
59280    btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
59281  }
59282}
59283static void btreeParseCellPtrIndex(
59284  MemPage *pPage,         /* Page containing the cell */
59285  u8 *pCell,              /* Pointer to the cell text. */
59286  CellInfo *pInfo         /* Fill in this structure */
59287){
59288  u8 *pIter;              /* For scanning through pCell */
59289  u32 nPayload;           /* Number of bytes of cell payload */
59290
59291  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59292  assert( pPage->leaf==0 || pPage->leaf==1 );
59293  assert( pPage->intKeyLeaf==0 );
59294  pIter = pCell + pPage->childPtrSize;
59295  nPayload = *pIter;
59296  if( nPayload>=0x80 ){
59297    u8 *pEnd = &pIter[8];
59298    nPayload &= 0x7f;
59299    do{
59300      nPayload = (nPayload<<7) | (*++pIter & 0x7f);
59301    }while( *(pIter)>=0x80 && pIter<pEnd );
59302  }
59303  pIter++;
59304  pInfo->nKey = nPayload;
59305  pInfo->nPayload = nPayload;
59306  pInfo->pPayload = pIter;
59307  testcase( nPayload==pPage->maxLocal );
59308  testcase( nPayload==pPage->maxLocal+1 );
59309  if( nPayload<=pPage->maxLocal ){
59310    /* This is the (easy) common case where the entire payload fits
59311    ** on the local page.  No overflow is required.
59312    */
59313    pInfo->nSize = nPayload + (u16)(pIter - pCell);
59314    if( pInfo->nSize<4 ) pInfo->nSize = 4;
59315    pInfo->nLocal = (u16)nPayload;
59316  }else{
59317    btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
59318  }
59319}
59320static void btreeParseCell(
59321  MemPage *pPage,         /* Page containing the cell */
59322  int iCell,              /* The cell index.  First cell is 0 */
59323  CellInfo *pInfo         /* Fill in this structure */
59324){
59325  pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
59326}
59327
59328/*
59329** The following routines are implementations of the MemPage.xCellSize
59330** method.
59331**
59332** Compute the total number of bytes that a Cell needs in the cell
59333** data area of the btree-page.  The return number includes the cell
59334** data header and the local payload, but not any overflow page or
59335** the space used by the cell pointer.
59336**
59337** cellSizePtrNoPayload()    =>   table internal nodes
59338** cellSizePtr()             =>   all index nodes & table leaf nodes
59339*/
59340static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
59341  u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
59342  u8 *pEnd;                                /* End mark for a varint */
59343  u32 nSize;                               /* Size value to return */
59344
59345#ifdef SQLITE_DEBUG
59346  /* The value returned by this function should always be the same as
59347  ** the (CellInfo.nSize) value found by doing a full parse of the
59348  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
59349  ** this function verifies that this invariant is not violated. */
59350  CellInfo debuginfo;
59351  pPage->xParseCell(pPage, pCell, &debuginfo);
59352#endif
59353
59354  nSize = *pIter;
59355  if( nSize>=0x80 ){
59356    pEnd = &pIter[8];
59357    nSize &= 0x7f;
59358    do{
59359      nSize = (nSize<<7) | (*++pIter & 0x7f);
59360    }while( *(pIter)>=0x80 && pIter<pEnd );
59361  }
59362  pIter++;
59363  if( pPage->intKey ){
59364    /* pIter now points at the 64-bit integer key value, a variable length
59365    ** integer. The following block moves pIter to point at the first byte
59366    ** past the end of the key value. */
59367    pEnd = &pIter[9];
59368    while( (*pIter++)&0x80 && pIter<pEnd );
59369  }
59370  testcase( nSize==pPage->maxLocal );
59371  testcase( nSize==pPage->maxLocal+1 );
59372  if( nSize<=pPage->maxLocal ){
59373    nSize += (u32)(pIter - pCell);
59374    if( nSize<4 ) nSize = 4;
59375  }else{
59376    int minLocal = pPage->minLocal;
59377    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
59378    testcase( nSize==pPage->maxLocal );
59379    testcase( nSize==pPage->maxLocal+1 );
59380    if( nSize>pPage->maxLocal ){
59381      nSize = minLocal;
59382    }
59383    nSize += 4 + (u16)(pIter - pCell);
59384  }
59385  assert( nSize==debuginfo.nSize || CORRUPT_DB );
59386  return (u16)nSize;
59387}
59388static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
59389  u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
59390  u8 *pEnd;              /* End mark for a varint */
59391
59392#ifdef SQLITE_DEBUG
59393  /* The value returned by this function should always be the same as
59394  ** the (CellInfo.nSize) value found by doing a full parse of the
59395  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
59396  ** this function verifies that this invariant is not violated. */
59397  CellInfo debuginfo;
59398  pPage->xParseCell(pPage, pCell, &debuginfo);
59399#else
59400  UNUSED_PARAMETER(pPage);
59401#endif
59402
59403  assert( pPage->childPtrSize==4 );
59404  pEnd = pIter + 9;
59405  while( (*pIter++)&0x80 && pIter<pEnd );
59406  assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
59407  return (u16)(pIter - pCell);
59408}
59409
59410
59411#ifdef SQLITE_DEBUG
59412/* This variation on cellSizePtr() is used inside of assert() statements
59413** only. */
59414static u16 cellSize(MemPage *pPage, int iCell){
59415  return pPage->xCellSize(pPage, findCell(pPage, iCell));
59416}
59417#endif
59418
59419#ifndef SQLITE_OMIT_AUTOVACUUM
59420/*
59421** If the cell pCell, part of page pPage contains a pointer
59422** to an overflow page, insert an entry into the pointer-map
59423** for the overflow page.
59424*/
59425static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
59426  CellInfo info;
59427  if( *pRC ) return;
59428  assert( pCell!=0 );
59429  pPage->xParseCell(pPage, pCell, &info);
59430  if( info.nLocal<info.nPayload ){
59431    Pgno ovfl = get4byte(&pCell[info.nSize-4]);
59432    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
59433  }
59434}
59435#endif
59436
59437
59438/*
59439** Defragment the page given.  All Cells are moved to the
59440** end of the page and all free space is collected into one
59441** big FreeBlk that occurs in between the header and cell
59442** pointer array and the cell content area.
59443**
59444** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
59445** b-tree page so that there are no freeblocks or fragment bytes, all
59446** unused bytes are contained in the unallocated space region, and all
59447** cells are packed tightly at the end of the page.
59448*/
59449static int defragmentPage(MemPage *pPage){
59450  int i;                     /* Loop counter */
59451  int pc;                    /* Address of the i-th cell */
59452  int hdr;                   /* Offset to the page header */
59453  int size;                  /* Size of a cell */
59454  int usableSize;            /* Number of usable bytes on a page */
59455  int cellOffset;            /* Offset to the cell pointer array */
59456  int cbrk;                  /* Offset to the cell content area */
59457  int nCell;                 /* Number of cells on the page */
59458  unsigned char *data;       /* The page data */
59459  unsigned char *temp;       /* Temp area for cell content */
59460  unsigned char *src;        /* Source of content */
59461  int iCellFirst;            /* First allowable cell index */
59462  int iCellLast;             /* Last possible cell index */
59463
59464
59465  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59466  assert( pPage->pBt!=0 );
59467  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
59468  assert( pPage->nOverflow==0 );
59469  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59470  temp = 0;
59471  src = data = pPage->aData;
59472  hdr = pPage->hdrOffset;
59473  cellOffset = pPage->cellOffset;
59474  nCell = pPage->nCell;
59475  assert( nCell==get2byte(&data[hdr+3]) );
59476  usableSize = pPage->pBt->usableSize;
59477  cbrk = usableSize;
59478  iCellFirst = cellOffset + 2*nCell;
59479  iCellLast = usableSize - 4;
59480  for(i=0; i<nCell; i++){
59481    u8 *pAddr;     /* The i-th cell pointer */
59482    pAddr = &data[cellOffset + i*2];
59483    pc = get2byte(pAddr);
59484    testcase( pc==iCellFirst );
59485    testcase( pc==iCellLast );
59486    /* These conditions have already been verified in btreeInitPage()
59487    ** if PRAGMA cell_size_check=ON.
59488    */
59489    if( pc<iCellFirst || pc>iCellLast ){
59490      return SQLITE_CORRUPT_BKPT;
59491    }
59492    assert( pc>=iCellFirst && pc<=iCellLast );
59493    size = pPage->xCellSize(pPage, &src[pc]);
59494    cbrk -= size;
59495    if( cbrk<iCellFirst || pc+size>usableSize ){
59496      return SQLITE_CORRUPT_BKPT;
59497    }
59498    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
59499    testcase( cbrk+size==usableSize );
59500    testcase( pc+size==usableSize );
59501    put2byte(pAddr, cbrk);
59502    if( temp==0 ){
59503      int x;
59504      if( cbrk==pc ) continue;
59505      temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
59506      x = get2byte(&data[hdr+5]);
59507      memcpy(&temp[x], &data[x], (cbrk+size) - x);
59508      src = temp;
59509    }
59510    memcpy(&data[cbrk], &src[pc], size);
59511  }
59512  assert( cbrk>=iCellFirst );
59513  put2byte(&data[hdr+5], cbrk);
59514  data[hdr+1] = 0;
59515  data[hdr+2] = 0;
59516  data[hdr+7] = 0;
59517  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
59518  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59519  if( cbrk-iCellFirst!=pPage->nFree ){
59520    return SQLITE_CORRUPT_BKPT;
59521  }
59522  return SQLITE_OK;
59523}
59524
59525/*
59526** Search the free-list on page pPg for space to store a cell nByte bytes in
59527** size. If one can be found, return a pointer to the space and remove it
59528** from the free-list.
59529**
59530** If no suitable space can be found on the free-list, return NULL.
59531**
59532** This function may detect corruption within pPg.  If corruption is
59533** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
59534**
59535** Slots on the free list that are between 1 and 3 bytes larger than nByte
59536** will be ignored if adding the extra space to the fragmentation count
59537** causes the fragmentation count to exceed 60.
59538*/
59539static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
59540  const int hdr = pPg->hdrOffset;
59541  u8 * const aData = pPg->aData;
59542  int iAddr = hdr + 1;
59543  int pc = get2byte(&aData[iAddr]);
59544  int x;
59545  int usableSize = pPg->pBt->usableSize;
59546
59547  assert( pc>0 );
59548  do{
59549    int size;            /* Size of the free slot */
59550    /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
59551    ** increasing offset. */
59552    if( pc>usableSize-4 || pc<iAddr+4 ){
59553      *pRc = SQLITE_CORRUPT_BKPT;
59554      return 0;
59555    }
59556    /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
59557    ** freeblock form a big-endian integer which is the size of the freeblock
59558    ** in bytes, including the 4-byte header. */
59559    size = get2byte(&aData[pc+2]);
59560    if( (x = size - nByte)>=0 ){
59561      testcase( x==4 );
59562      testcase( x==3 );
59563      if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
59564        *pRc = SQLITE_CORRUPT_BKPT;
59565        return 0;
59566      }else if( x<4 ){
59567        /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
59568        ** number of bytes in fragments may not exceed 60. */
59569        if( aData[hdr+7]>57 ) return 0;
59570
59571        /* Remove the slot from the free-list. Update the number of
59572        ** fragmented bytes within the page. */
59573        memcpy(&aData[iAddr], &aData[pc], 2);
59574        aData[hdr+7] += (u8)x;
59575      }else{
59576        /* The slot remains on the free-list. Reduce its size to account
59577         ** for the portion used by the new allocation. */
59578        put2byte(&aData[pc+2], x);
59579      }
59580      return &aData[pc + x];
59581    }
59582    iAddr = pc;
59583    pc = get2byte(&aData[pc]);
59584  }while( pc );
59585
59586  return 0;
59587}
59588
59589/*
59590** Allocate nByte bytes of space from within the B-Tree page passed
59591** as the first argument. Write into *pIdx the index into pPage->aData[]
59592** of the first byte of allocated space. Return either SQLITE_OK or
59593** an error code (usually SQLITE_CORRUPT).
59594**
59595** The caller guarantees that there is sufficient space to make the
59596** allocation.  This routine might need to defragment in order to bring
59597** all the space together, however.  This routine will avoid using
59598** the first two bytes past the cell pointer area since presumably this
59599** allocation is being made in order to insert a new cell, so we will
59600** also end up needing a new cell pointer.
59601*/
59602static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
59603  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
59604  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
59605  int top;                             /* First byte of cell content area */
59606  int rc = SQLITE_OK;                  /* Integer return code */
59607  int gap;        /* First byte of gap between cell pointers and cell content */
59608
59609  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59610  assert( pPage->pBt );
59611  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59612  assert( nByte>=0 );  /* Minimum cell size is 4 */
59613  assert( pPage->nFree>=nByte );
59614  assert( pPage->nOverflow==0 );
59615  assert( nByte < (int)(pPage->pBt->usableSize-8) );
59616
59617  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
59618  gap = pPage->cellOffset + 2*pPage->nCell;
59619  assert( gap<=65536 );
59620  /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
59621  ** and the reserved space is zero (the usual value for reserved space)
59622  ** then the cell content offset of an empty page wants to be 65536.
59623  ** However, that integer is too large to be stored in a 2-byte unsigned
59624  ** integer, so a value of 0 is used in its place. */
59625  top = get2byte(&data[hdr+5]);
59626  assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
59627  if( gap>top ){
59628    if( top==0 && pPage->pBt->usableSize==65536 ){
59629      top = 65536;
59630    }else{
59631      return SQLITE_CORRUPT_BKPT;
59632    }
59633  }
59634
59635  /* If there is enough space between gap and top for one more cell pointer
59636  ** array entry offset, and if the freelist is not empty, then search the
59637  ** freelist looking for a free slot big enough to satisfy the request.
59638  */
59639  testcase( gap+2==top );
59640  testcase( gap+1==top );
59641  testcase( gap==top );
59642  if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
59643    u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
59644    if( pSpace ){
59645      assert( pSpace>=data && (pSpace - data)<65536 );
59646      *pIdx = (int)(pSpace - data);
59647      return SQLITE_OK;
59648    }else if( rc ){
59649      return rc;
59650    }
59651  }
59652
59653  /* The request could not be fulfilled using a freelist slot.  Check
59654  ** to see if defragmentation is necessary.
59655  */
59656  testcase( gap+2+nByte==top );
59657  if( gap+2+nByte>top ){
59658    assert( pPage->nCell>0 || CORRUPT_DB );
59659    rc = defragmentPage(pPage);
59660    if( rc ) return rc;
59661    top = get2byteNotZero(&data[hdr+5]);
59662    assert( gap+nByte<=top );
59663  }
59664
59665
59666  /* Allocate memory from the gap in between the cell pointer array
59667  ** and the cell content area.  The btreeInitPage() call has already
59668  ** validated the freelist.  Given that the freelist is valid, there
59669  ** is no way that the allocation can extend off the end of the page.
59670  ** The assert() below verifies the previous sentence.
59671  */
59672  top -= nByte;
59673  put2byte(&data[hdr+5], top);
59674  assert( top+nByte <= (int)pPage->pBt->usableSize );
59675  *pIdx = top;
59676  return SQLITE_OK;
59677}
59678
59679/*
59680** Return a section of the pPage->aData to the freelist.
59681** The first byte of the new free block is pPage->aData[iStart]
59682** and the size of the block is iSize bytes.
59683**
59684** Adjacent freeblocks are coalesced.
59685**
59686** Note that even though the freeblock list was checked by btreeInitPage(),
59687** that routine will not detect overlap between cells or freeblocks.  Nor
59688** does it detect cells or freeblocks that encrouch into the reserved bytes
59689** at the end of the page.  So do additional corruption checks inside this
59690** routine and return SQLITE_CORRUPT if any problems are found.
59691*/
59692static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
59693  u16 iPtr;                             /* Address of ptr to next freeblock */
59694  u16 iFreeBlk;                         /* Address of the next freeblock */
59695  u8 hdr;                               /* Page header size.  0 or 100 */
59696  u8 nFrag = 0;                         /* Reduction in fragmentation */
59697  u16 iOrigSize = iSize;                /* Original value of iSize */
59698  u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
59699  u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
59700  unsigned char *data = pPage->aData;   /* Page content */
59701
59702  assert( pPage->pBt!=0 );
59703  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59704  assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
59705  assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
59706  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59707  assert( iSize>=4 );   /* Minimum cell size is 4 */
59708  assert( iStart<=iLast );
59709
59710  /* Overwrite deleted information with zeros when the secure_delete
59711  ** option is enabled */
59712  if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
59713    memset(&data[iStart], 0, iSize);
59714  }
59715
59716  /* The list of freeblocks must be in ascending order.  Find the
59717  ** spot on the list where iStart should be inserted.
59718  */
59719  hdr = pPage->hdrOffset;
59720  iPtr = hdr + 1;
59721  if( data[iPtr+1]==0 && data[iPtr]==0 ){
59722    iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
59723  }else{
59724    while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
59725      if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
59726      iPtr = iFreeBlk;
59727    }
59728    if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
59729    assert( iFreeBlk>iPtr || iFreeBlk==0 );
59730
59731    /* At this point:
59732    **    iFreeBlk:   First freeblock after iStart, or zero if none
59733    **    iPtr:       The address of a pointer to iFreeBlk
59734    **
59735    ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
59736    */
59737    if( iFreeBlk && iEnd+3>=iFreeBlk ){
59738      nFrag = iFreeBlk - iEnd;
59739      if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
59740      iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
59741      if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT;
59742      iSize = iEnd - iStart;
59743      iFreeBlk = get2byte(&data[iFreeBlk]);
59744    }
59745
59746    /* If iPtr is another freeblock (that is, if iPtr is not the freelist
59747    ** pointer in the page header) then check to see if iStart should be
59748    ** coalesced onto the end of iPtr.
59749    */
59750    if( iPtr>hdr+1 ){
59751      int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
59752      if( iPtrEnd+3>=iStart ){
59753        if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
59754        nFrag += iStart - iPtrEnd;
59755        iSize = iEnd - iPtr;
59756        iStart = iPtr;
59757      }
59758    }
59759    if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
59760    data[hdr+7] -= nFrag;
59761  }
59762  if( iStart==get2byte(&data[hdr+5]) ){
59763    /* The new freeblock is at the beginning of the cell content area,
59764    ** so just extend the cell content area rather than create another
59765    ** freelist entry */
59766    if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
59767    put2byte(&data[hdr+1], iFreeBlk);
59768    put2byte(&data[hdr+5], iEnd);
59769  }else{
59770    /* Insert the new freeblock into the freelist */
59771    put2byte(&data[iPtr], iStart);
59772    put2byte(&data[iStart], iFreeBlk);
59773    put2byte(&data[iStart+2], iSize);
59774  }
59775  pPage->nFree += iOrigSize;
59776  return SQLITE_OK;
59777}
59778
59779/*
59780** Decode the flags byte (the first byte of the header) for a page
59781** and initialize fields of the MemPage structure accordingly.
59782**
59783** Only the following combinations are supported.  Anything different
59784** indicates a corrupt database files:
59785**
59786**         PTF_ZERODATA
59787**         PTF_ZERODATA | PTF_LEAF
59788**         PTF_LEAFDATA | PTF_INTKEY
59789**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
59790*/
59791static int decodeFlags(MemPage *pPage, int flagByte){
59792  BtShared *pBt;     /* A copy of pPage->pBt */
59793
59794  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
59795  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59796  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
59797  flagByte &= ~PTF_LEAF;
59798  pPage->childPtrSize = 4-4*pPage->leaf;
59799  pPage->xCellSize = cellSizePtr;
59800  pBt = pPage->pBt;
59801  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
59802    /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
59803    ** interior table b-tree page. */
59804    assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
59805    /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
59806    ** leaf table b-tree page. */
59807    assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
59808    pPage->intKey = 1;
59809    if( pPage->leaf ){
59810      pPage->intKeyLeaf = 1;
59811      pPage->xParseCell = btreeParseCellPtr;
59812    }else{
59813      pPage->intKeyLeaf = 0;
59814      pPage->xCellSize = cellSizePtrNoPayload;
59815      pPage->xParseCell = btreeParseCellPtrNoPayload;
59816    }
59817    pPage->maxLocal = pBt->maxLeaf;
59818    pPage->minLocal = pBt->minLeaf;
59819  }else if( flagByte==PTF_ZERODATA ){
59820    /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
59821    ** interior index b-tree page. */
59822    assert( (PTF_ZERODATA)==2 );
59823    /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
59824    ** leaf index b-tree page. */
59825    assert( (PTF_ZERODATA|PTF_LEAF)==10 );
59826    pPage->intKey = 0;
59827    pPage->intKeyLeaf = 0;
59828    pPage->xParseCell = btreeParseCellPtrIndex;
59829    pPage->maxLocal = pBt->maxLocal;
59830    pPage->minLocal = pBt->minLocal;
59831  }else{
59832    /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
59833    ** an error. */
59834    return SQLITE_CORRUPT_BKPT;
59835  }
59836  pPage->max1bytePayload = pBt->max1bytePayload;
59837  return SQLITE_OK;
59838}
59839
59840/*
59841** Initialize the auxiliary information for a disk block.
59842**
59843** Return SQLITE_OK on success.  If we see that the page does
59844** not contain a well-formed database page, then return
59845** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
59846** guarantee that the page is well-formed.  It only shows that
59847** we failed to detect any corruption.
59848*/
59849static int btreeInitPage(MemPage *pPage){
59850
59851  assert( pPage->pBt!=0 );
59852  assert( pPage->pBt->db!=0 );
59853  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59854  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
59855  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
59856  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
59857
59858  if( !pPage->isInit ){
59859    u16 pc;            /* Address of a freeblock within pPage->aData[] */
59860    u8 hdr;            /* Offset to beginning of page header */
59861    u8 *data;          /* Equal to pPage->aData */
59862    BtShared *pBt;        /* The main btree structure */
59863    int usableSize;    /* Amount of usable space on each page */
59864    u16 cellOffset;    /* Offset from start of page to first cell pointer */
59865    int nFree;         /* Number of unused bytes on the page */
59866    int top;           /* First byte of the cell content area */
59867    int iCellFirst;    /* First allowable cell or freeblock offset */
59868    int iCellLast;     /* Last possible cell or freeblock offset */
59869
59870    pBt = pPage->pBt;
59871
59872    hdr = pPage->hdrOffset;
59873    data = pPage->aData;
59874    /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
59875    ** the b-tree page type. */
59876    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
59877    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
59878    pPage->maskPage = (u16)(pBt->pageSize - 1);
59879    pPage->nOverflow = 0;
59880    usableSize = pBt->usableSize;
59881    pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
59882    pPage->aDataEnd = &data[usableSize];
59883    pPage->aCellIdx = &data[cellOffset];
59884    pPage->aDataOfst = &data[pPage->childPtrSize];
59885    /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
59886    ** the start of the cell content area. A zero value for this integer is
59887    ** interpreted as 65536. */
59888    top = get2byteNotZero(&data[hdr+5]);
59889    /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
59890    ** number of cells on the page. */
59891    pPage->nCell = get2byte(&data[hdr+3]);
59892    if( pPage->nCell>MX_CELL(pBt) ){
59893      /* To many cells for a single page.  The page must be corrupt */
59894      return SQLITE_CORRUPT_BKPT;
59895    }
59896    testcase( pPage->nCell==MX_CELL(pBt) );
59897    /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
59898    ** possible for a root page of a table that contains no rows) then the
59899    ** offset to the cell content area will equal the page size minus the
59900    ** bytes of reserved space. */
59901    assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
59902
59903    /* A malformed database page might cause us to read past the end
59904    ** of page when parsing a cell.
59905    **
59906    ** The following block of code checks early to see if a cell extends
59907    ** past the end of a page boundary and causes SQLITE_CORRUPT to be
59908    ** returned if it does.
59909    */
59910    iCellFirst = cellOffset + 2*pPage->nCell;
59911    iCellLast = usableSize - 4;
59912    if( pBt->db->flags & SQLITE_CellSizeCk ){
59913      int i;            /* Index into the cell pointer array */
59914      int sz;           /* Size of a cell */
59915
59916      if( !pPage->leaf ) iCellLast--;
59917      for(i=0; i<pPage->nCell; i++){
59918        pc = get2byteAligned(&data[cellOffset+i*2]);
59919        testcase( pc==iCellFirst );
59920        testcase( pc==iCellLast );
59921        if( pc<iCellFirst || pc>iCellLast ){
59922          return SQLITE_CORRUPT_BKPT;
59923        }
59924        sz = pPage->xCellSize(pPage, &data[pc]);
59925        testcase( pc+sz==usableSize );
59926        if( pc+sz>usableSize ){
59927          return SQLITE_CORRUPT_BKPT;
59928        }
59929      }
59930      if( !pPage->leaf ) iCellLast++;
59931    }
59932
59933    /* Compute the total free space on the page
59934    ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
59935    ** start of the first freeblock on the page, or is zero if there are no
59936    ** freeblocks. */
59937    pc = get2byte(&data[hdr+1]);
59938    nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
59939    while( pc>0 ){
59940      u16 next, size;
59941      if( pc<iCellFirst || pc>iCellLast ){
59942        /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
59943        ** always be at least one cell before the first freeblock.
59944        **
59945        ** Or, the freeblock is off the end of the page
59946        */
59947        return SQLITE_CORRUPT_BKPT;
59948      }
59949      next = get2byte(&data[pc]);
59950      size = get2byte(&data[pc+2]);
59951      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
59952        /* Free blocks must be in ascending order. And the last byte of
59953        ** the free-block must lie on the database page.  */
59954        return SQLITE_CORRUPT_BKPT;
59955      }
59956      nFree = nFree + size;
59957      pc = next;
59958    }
59959
59960    /* At this point, nFree contains the sum of the offset to the start
59961    ** of the cell-content area plus the number of free bytes within
59962    ** the cell-content area. If this is greater than the usable-size
59963    ** of the page, then the page must be corrupted. This check also
59964    ** serves to verify that the offset to the start of the cell-content
59965    ** area, according to the page header, lies within the page.
59966    */
59967    if( nFree>usableSize ){
59968      return SQLITE_CORRUPT_BKPT;
59969    }
59970    pPage->nFree = (u16)(nFree - iCellFirst);
59971    pPage->isInit = 1;
59972  }
59973  return SQLITE_OK;
59974}
59975
59976/*
59977** Set up a raw page so that it looks like a database page holding
59978** no entries.
59979*/
59980static void zeroPage(MemPage *pPage, int flags){
59981  unsigned char *data = pPage->aData;
59982  BtShared *pBt = pPage->pBt;
59983  u8 hdr = pPage->hdrOffset;
59984  u16 first;
59985
59986  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
59987  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
59988  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
59989  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59990  assert( sqlite3_mutex_held(pBt->mutex) );
59991  if( pBt->btsFlags & BTS_SECURE_DELETE ){
59992    memset(&data[hdr], 0, pBt->usableSize - hdr);
59993  }
59994  data[hdr] = (char)flags;
59995  first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
59996  memset(&data[hdr+1], 0, 4);
59997  data[hdr+7] = 0;
59998  put2byte(&data[hdr+5], pBt->usableSize);
59999  pPage->nFree = (u16)(pBt->usableSize - first);
60000  decodeFlags(pPage, flags);
60001  pPage->cellOffset = first;
60002  pPage->aDataEnd = &data[pBt->usableSize];
60003  pPage->aCellIdx = &data[first];
60004  pPage->aDataOfst = &data[pPage->childPtrSize];
60005  pPage->nOverflow = 0;
60006  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
60007  pPage->maskPage = (u16)(pBt->pageSize - 1);
60008  pPage->nCell = 0;
60009  pPage->isInit = 1;
60010}
60011
60012
60013/*
60014** Convert a DbPage obtained from the pager into a MemPage used by
60015** the btree layer.
60016*/
60017static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
60018  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
60019  if( pgno!=pPage->pgno ){
60020    pPage->aData = sqlite3PagerGetData(pDbPage);
60021    pPage->pDbPage = pDbPage;
60022    pPage->pBt = pBt;
60023    pPage->pgno = pgno;
60024    pPage->hdrOffset = pgno==1 ? 100 : 0;
60025  }
60026  assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
60027  return pPage;
60028}
60029
60030/*
60031** Get a page from the pager.  Initialize the MemPage.pBt and
60032** MemPage.aData elements if needed.  See also: btreeGetUnusedPage().
60033**
60034** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
60035** about the content of the page at this time.  So do not go to the disk
60036** to fetch the content.  Just fill in the content with zeros for now.
60037** If in the future we call sqlite3PagerWrite() on this page, that
60038** means we have started to be concerned about content and the disk
60039** read should occur at that point.
60040*/
60041static int btreeGetPage(
60042  BtShared *pBt,       /* The btree */
60043  Pgno pgno,           /* Number of the page to fetch */
60044  MemPage **ppPage,    /* Return the page in this parameter */
60045  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
60046){
60047  int rc;
60048  DbPage *pDbPage;
60049
60050  assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
60051  assert( sqlite3_mutex_held(pBt->mutex) );
60052  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
60053  if( rc ) return rc;
60054  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
60055  return SQLITE_OK;
60056}
60057
60058/*
60059** Retrieve a page from the pager cache. If the requested page is not
60060** already in the pager cache return NULL. Initialize the MemPage.pBt and
60061** MemPage.aData elements if needed.
60062*/
60063static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
60064  DbPage *pDbPage;
60065  assert( sqlite3_mutex_held(pBt->mutex) );
60066  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
60067  if( pDbPage ){
60068    return btreePageFromDbPage(pDbPage, pgno, pBt);
60069  }
60070  return 0;
60071}
60072
60073/*
60074** Return the size of the database file in pages. If there is any kind of
60075** error, return ((unsigned int)-1).
60076*/
60077static Pgno btreePagecount(BtShared *pBt){
60078  return pBt->nPage;
60079}
60080SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
60081  assert( sqlite3BtreeHoldsMutex(p) );
60082  assert( ((p->pBt->nPage)&0x8000000)==0 );
60083  return btreePagecount(p->pBt);
60084}
60085
60086/*
60087** Get a page from the pager and initialize it.
60088**
60089** If pCur!=0 then the page is being fetched as part of a moveToChild()
60090** call.  Do additional sanity checking on the page in this case.
60091** And if the fetch fails, this routine must decrement pCur->iPage.
60092**
60093** The page is fetched as read-write unless pCur is not NULL and is
60094** a read-only cursor.
60095**
60096** If an error occurs, then *ppPage is undefined. It
60097** may remain unchanged, or it may be set to an invalid value.
60098*/
60099static int getAndInitPage(
60100  BtShared *pBt,                  /* The database file */
60101  Pgno pgno,                      /* Number of the page to get */
60102  MemPage **ppPage,               /* Write the page pointer here */
60103  BtCursor *pCur,                 /* Cursor to receive the page, or NULL */
60104  int bReadOnly                   /* True for a read-only page */
60105){
60106  int rc;
60107  DbPage *pDbPage;
60108  assert( sqlite3_mutex_held(pBt->mutex) );
60109  assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
60110  assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
60111  assert( pCur==0 || pCur->iPage>0 );
60112
60113  if( pgno>btreePagecount(pBt) ){
60114    rc = SQLITE_CORRUPT_BKPT;
60115    goto getAndInitPage_error;
60116  }
60117  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
60118  if( rc ){
60119    goto getAndInitPage_error;
60120  }
60121  *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
60122  if( (*ppPage)->isInit==0 ){
60123    btreePageFromDbPage(pDbPage, pgno, pBt);
60124    rc = btreeInitPage(*ppPage);
60125    if( rc!=SQLITE_OK ){
60126      releasePage(*ppPage);
60127      goto getAndInitPage_error;
60128    }
60129  }
60130  assert( (*ppPage)->pgno==pgno );
60131  assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
60132
60133  /* If obtaining a child page for a cursor, we must verify that the page is
60134  ** compatible with the root page. */
60135  if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
60136    rc = SQLITE_CORRUPT_BKPT;
60137    releasePage(*ppPage);
60138    goto getAndInitPage_error;
60139  }
60140  return SQLITE_OK;
60141
60142getAndInitPage_error:
60143  if( pCur ) pCur->iPage--;
60144  testcase( pgno==0 );
60145  assert( pgno!=0 || rc==SQLITE_CORRUPT );
60146  return rc;
60147}
60148
60149/*
60150** Release a MemPage.  This should be called once for each prior
60151** call to btreeGetPage.
60152*/
60153static void releasePageNotNull(MemPage *pPage){
60154  assert( pPage->aData );
60155  assert( pPage->pBt );
60156  assert( pPage->pDbPage!=0 );
60157  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
60158  assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
60159  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60160  sqlite3PagerUnrefNotNull(pPage->pDbPage);
60161}
60162static void releasePage(MemPage *pPage){
60163  if( pPage ) releasePageNotNull(pPage);
60164}
60165
60166/*
60167** Get an unused page.
60168**
60169** This works just like btreeGetPage() with the addition:
60170**
60171**   *  If the page is already in use for some other purpose, immediately
60172**      release it and return an SQLITE_CURRUPT error.
60173**   *  Make sure the isInit flag is clear
60174*/
60175static int btreeGetUnusedPage(
60176  BtShared *pBt,       /* The btree */
60177  Pgno pgno,           /* Number of the page to fetch */
60178  MemPage **ppPage,    /* Return the page in this parameter */
60179  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
60180){
60181  int rc = btreeGetPage(pBt, pgno, ppPage, flags);
60182  if( rc==SQLITE_OK ){
60183    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
60184      releasePage(*ppPage);
60185      *ppPage = 0;
60186      return SQLITE_CORRUPT_BKPT;
60187    }
60188    (*ppPage)->isInit = 0;
60189  }else{
60190    *ppPage = 0;
60191  }
60192  return rc;
60193}
60194
60195
60196/*
60197** During a rollback, when the pager reloads information into the cache
60198** so that the cache is restored to its original state at the start of
60199** the transaction, for each page restored this routine is called.
60200**
60201** This routine needs to reset the extra data section at the end of the
60202** page to agree with the restored data.
60203*/
60204static void pageReinit(DbPage *pData){
60205  MemPage *pPage;
60206  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
60207  assert( sqlite3PagerPageRefcount(pData)>0 );
60208  if( pPage->isInit ){
60209    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60210    pPage->isInit = 0;
60211    if( sqlite3PagerPageRefcount(pData)>1 ){
60212      /* pPage might not be a btree page;  it might be an overflow page
60213      ** or ptrmap page or a free page.  In those cases, the following
60214      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
60215      ** But no harm is done by this.  And it is very important that
60216      ** btreeInitPage() be called on every btree page so we make
60217      ** the call for every page that comes in for re-initing. */
60218      btreeInitPage(pPage);
60219    }
60220  }
60221}
60222
60223/*
60224** Invoke the busy handler for a btree.
60225*/
60226static int btreeInvokeBusyHandler(void *pArg){
60227  BtShared *pBt = (BtShared*)pArg;
60228  assert( pBt->db );
60229  assert( sqlite3_mutex_held(pBt->db->mutex) );
60230  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
60231}
60232
60233/*
60234** Open a database file.
60235**
60236** zFilename is the name of the database file.  If zFilename is NULL
60237** then an ephemeral database is created.  The ephemeral database might
60238** be exclusively in memory, or it might use a disk-based memory cache.
60239** Either way, the ephemeral database will be automatically deleted
60240** when sqlite3BtreeClose() is called.
60241**
60242** If zFilename is ":memory:" then an in-memory database is created
60243** that is automatically destroyed when it is closed.
60244**
60245** The "flags" parameter is a bitmask that might contain bits like
60246** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
60247**
60248** If the database is already opened in the same database connection
60249** and we are in shared cache mode, then the open will fail with an
60250** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
60251** objects in the same database connection since doing so will lead
60252** to problems with locking.
60253*/
60254SQLITE_PRIVATE int sqlite3BtreeOpen(
60255  sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
60256  const char *zFilename,  /* Name of the file containing the BTree database */
60257  sqlite3 *db,            /* Associated database handle */
60258  Btree **ppBtree,        /* Pointer to new Btree object written here */
60259  int flags,              /* Options */
60260  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
60261){
60262  BtShared *pBt = 0;             /* Shared part of btree structure */
60263  Btree *p;                      /* Handle to return */
60264  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
60265  int rc = SQLITE_OK;            /* Result code from this function */
60266  u8 nReserve;                   /* Byte of unused space on each page */
60267  unsigned char zDbHeader[100];  /* Database header content */
60268
60269  /* True if opening an ephemeral, temporary database */
60270  const int isTempDb = zFilename==0 || zFilename[0]==0;
60271
60272  /* Set the variable isMemdb to true for an in-memory database, or
60273  ** false for a file-based database.
60274  */
60275#ifdef SQLITE_OMIT_MEMORYDB
60276  const int isMemdb = 0;
60277#else
60278  const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
60279                       || (isTempDb && sqlite3TempInMemory(db))
60280                       || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
60281#endif
60282
60283  assert( db!=0 );
60284  assert( pVfs!=0 );
60285  assert( sqlite3_mutex_held(db->mutex) );
60286  assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
60287
60288  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
60289  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
60290
60291  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
60292  assert( (flags & BTREE_SINGLE)==0 || isTempDb );
60293
60294  if( isMemdb ){
60295    flags |= BTREE_MEMORY;
60296  }
60297  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
60298    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
60299  }
60300  p = sqlite3MallocZero(sizeof(Btree));
60301  if( !p ){
60302    return SQLITE_NOMEM_BKPT;
60303  }
60304  p->inTrans = TRANS_NONE;
60305  p->db = db;
60306#ifndef SQLITE_OMIT_SHARED_CACHE
60307  p->lock.pBtree = p;
60308  p->lock.iTable = 1;
60309#endif
60310
60311#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
60312  /*
60313  ** If this Btree is a candidate for shared cache, try to find an
60314  ** existing BtShared object that we can share with
60315  */
60316  if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
60317    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
60318      int nFilename = sqlite3Strlen30(zFilename)+1;
60319      int nFullPathname = pVfs->mxPathname+1;
60320      char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
60321      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
60322
60323      p->sharable = 1;
60324      if( !zFullPathname ){
60325        sqlite3_free(p);
60326        return SQLITE_NOMEM_BKPT;
60327      }
60328      if( isMemdb ){
60329        memcpy(zFullPathname, zFilename, nFilename);
60330      }else{
60331        rc = sqlite3OsFullPathname(pVfs, zFilename,
60332                                   nFullPathname, zFullPathname);
60333        if( rc ){
60334          sqlite3_free(zFullPathname);
60335          sqlite3_free(p);
60336          return rc;
60337        }
60338      }
60339#if SQLITE_THREADSAFE
60340      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
60341      sqlite3_mutex_enter(mutexOpen);
60342      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
60343      sqlite3_mutex_enter(mutexShared);
60344#endif
60345      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
60346        assert( pBt->nRef>0 );
60347        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
60348                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
60349          int iDb;
60350          for(iDb=db->nDb-1; iDb>=0; iDb--){
60351            Btree *pExisting = db->aDb[iDb].pBt;
60352            if( pExisting && pExisting->pBt==pBt ){
60353              sqlite3_mutex_leave(mutexShared);
60354              sqlite3_mutex_leave(mutexOpen);
60355              sqlite3_free(zFullPathname);
60356              sqlite3_free(p);
60357              return SQLITE_CONSTRAINT;
60358            }
60359          }
60360          p->pBt = pBt;
60361          pBt->nRef++;
60362          break;
60363        }
60364      }
60365      sqlite3_mutex_leave(mutexShared);
60366      sqlite3_free(zFullPathname);
60367    }
60368#ifdef SQLITE_DEBUG
60369    else{
60370      /* In debug mode, we mark all persistent databases as sharable
60371      ** even when they are not.  This exercises the locking code and
60372      ** gives more opportunity for asserts(sqlite3_mutex_held())
60373      ** statements to find locking problems.
60374      */
60375      p->sharable = 1;
60376    }
60377#endif
60378  }
60379#endif
60380  if( pBt==0 ){
60381    /*
60382    ** The following asserts make sure that structures used by the btree are
60383    ** the right size.  This is to guard against size changes that result
60384    ** when compiling on a different architecture.
60385    */
60386    assert( sizeof(i64)==8 );
60387    assert( sizeof(u64)==8 );
60388    assert( sizeof(u32)==4 );
60389    assert( sizeof(u16)==2 );
60390    assert( sizeof(Pgno)==4 );
60391
60392    pBt = sqlite3MallocZero( sizeof(*pBt) );
60393    if( pBt==0 ){
60394      rc = SQLITE_NOMEM_BKPT;
60395      goto btree_open_out;
60396    }
60397    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
60398                          EXTRA_SIZE, flags, vfsFlags, pageReinit);
60399    if( rc==SQLITE_OK ){
60400      sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
60401      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
60402    }
60403    if( rc!=SQLITE_OK ){
60404      goto btree_open_out;
60405    }
60406    pBt->openFlags = (u8)flags;
60407    pBt->db = db;
60408    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
60409    p->pBt = pBt;
60410
60411    pBt->pCursor = 0;
60412    pBt->pPage1 = 0;
60413    if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
60414#ifdef SQLITE_SECURE_DELETE
60415    pBt->btsFlags |= BTS_SECURE_DELETE;
60416#endif
60417    /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
60418    ** determined by the 2-byte integer located at an offset of 16 bytes from
60419    ** the beginning of the database file. */
60420    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
60421    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
60422         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
60423      pBt->pageSize = 0;
60424#ifndef SQLITE_OMIT_AUTOVACUUM
60425      /* If the magic name ":memory:" will create an in-memory database, then
60426      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
60427      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
60428      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
60429      ** regular file-name. In this case the auto-vacuum applies as per normal.
60430      */
60431      if( zFilename && !isMemdb ){
60432        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
60433        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
60434      }
60435#endif
60436      nReserve = 0;
60437    }else{
60438      /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
60439      ** determined by the one-byte unsigned integer found at an offset of 20
60440      ** into the database file header. */
60441      nReserve = zDbHeader[20];
60442      pBt->btsFlags |= BTS_PAGESIZE_FIXED;
60443#ifndef SQLITE_OMIT_AUTOVACUUM
60444      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
60445      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
60446#endif
60447    }
60448    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
60449    if( rc ) goto btree_open_out;
60450    pBt->usableSize = pBt->pageSize - nReserve;
60451    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
60452
60453#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
60454    /* Add the new BtShared object to the linked list sharable BtShareds.
60455    */
60456    pBt->nRef = 1;
60457    if( p->sharable ){
60458      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
60459      MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
60460      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
60461        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
60462        if( pBt->mutex==0 ){
60463          rc = SQLITE_NOMEM_BKPT;
60464          goto btree_open_out;
60465        }
60466      }
60467      sqlite3_mutex_enter(mutexShared);
60468      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
60469      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
60470      sqlite3_mutex_leave(mutexShared);
60471    }
60472#endif
60473  }
60474
60475#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
60476  /* If the new Btree uses a sharable pBtShared, then link the new
60477  ** Btree into the list of all sharable Btrees for the same connection.
60478  ** The list is kept in ascending order by pBt address.
60479  */
60480  if( p->sharable ){
60481    int i;
60482    Btree *pSib;
60483    for(i=0; i<db->nDb; i++){
60484      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
60485        while( pSib->pPrev ){ pSib = pSib->pPrev; }
60486        if( (uptr)p->pBt<(uptr)pSib->pBt ){
60487          p->pNext = pSib;
60488          p->pPrev = 0;
60489          pSib->pPrev = p;
60490        }else{
60491          while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
60492            pSib = pSib->pNext;
60493          }
60494          p->pNext = pSib->pNext;
60495          p->pPrev = pSib;
60496          if( p->pNext ){
60497            p->pNext->pPrev = p;
60498          }
60499          pSib->pNext = p;
60500        }
60501        break;
60502      }
60503    }
60504  }
60505#endif
60506  *ppBtree = p;
60507
60508btree_open_out:
60509  if( rc!=SQLITE_OK ){
60510    if( pBt && pBt->pPager ){
60511      sqlite3PagerClose(pBt->pPager);
60512    }
60513    sqlite3_free(pBt);
60514    sqlite3_free(p);
60515    *ppBtree = 0;
60516  }else{
60517    /* If the B-Tree was successfully opened, set the pager-cache size to the
60518    ** default value. Except, when opening on an existing shared pager-cache,
60519    ** do not change the pager-cache size.
60520    */
60521    if( sqlite3BtreeSchema(p, 0, 0)==0 ){
60522      sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
60523    }
60524  }
60525  if( mutexOpen ){
60526    assert( sqlite3_mutex_held(mutexOpen) );
60527    sqlite3_mutex_leave(mutexOpen);
60528  }
60529  assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
60530  return rc;
60531}
60532
60533/*
60534** Decrement the BtShared.nRef counter.  When it reaches zero,
60535** remove the BtShared structure from the sharing list.  Return
60536** true if the BtShared.nRef counter reaches zero and return
60537** false if it is still positive.
60538*/
60539static int removeFromSharingList(BtShared *pBt){
60540#ifndef SQLITE_OMIT_SHARED_CACHE
60541  MUTEX_LOGIC( sqlite3_mutex *pMaster; )
60542  BtShared *pList;
60543  int removed = 0;
60544
60545  assert( sqlite3_mutex_notheld(pBt->mutex) );
60546  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
60547  sqlite3_mutex_enter(pMaster);
60548  pBt->nRef--;
60549  if( pBt->nRef<=0 ){
60550    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
60551      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
60552    }else{
60553      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
60554      while( ALWAYS(pList) && pList->pNext!=pBt ){
60555        pList=pList->pNext;
60556      }
60557      if( ALWAYS(pList) ){
60558        pList->pNext = pBt->pNext;
60559      }
60560    }
60561    if( SQLITE_THREADSAFE ){
60562      sqlite3_mutex_free(pBt->mutex);
60563    }
60564    removed = 1;
60565  }
60566  sqlite3_mutex_leave(pMaster);
60567  return removed;
60568#else
60569  return 1;
60570#endif
60571}
60572
60573/*
60574** Make sure pBt->pTmpSpace points to an allocation of
60575** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
60576** pointer.
60577*/
60578static void allocateTempSpace(BtShared *pBt){
60579  if( !pBt->pTmpSpace ){
60580    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
60581
60582    /* One of the uses of pBt->pTmpSpace is to format cells before
60583    ** inserting them into a leaf page (function fillInCell()). If
60584    ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
60585    ** by the various routines that manipulate binary cells. Which
60586    ** can mean that fillInCell() only initializes the first 2 or 3
60587    ** bytes of pTmpSpace, but that the first 4 bytes are copied from
60588    ** it into a database page. This is not actually a problem, but it
60589    ** does cause a valgrind error when the 1 or 2 bytes of unitialized
60590    ** data is passed to system call write(). So to avoid this error,
60591    ** zero the first 4 bytes of temp space here.
60592    **
60593    ** Also:  Provide four bytes of initialized space before the
60594    ** beginning of pTmpSpace as an area available to prepend the
60595    ** left-child pointer to the beginning of a cell.
60596    */
60597    if( pBt->pTmpSpace ){
60598      memset(pBt->pTmpSpace, 0, 8);
60599      pBt->pTmpSpace += 4;
60600    }
60601  }
60602}
60603
60604/*
60605** Free the pBt->pTmpSpace allocation
60606*/
60607static void freeTempSpace(BtShared *pBt){
60608  if( pBt->pTmpSpace ){
60609    pBt->pTmpSpace -= 4;
60610    sqlite3PageFree(pBt->pTmpSpace);
60611    pBt->pTmpSpace = 0;
60612  }
60613}
60614
60615/*
60616** Close an open database and invalidate all cursors.
60617*/
60618SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
60619  BtShared *pBt = p->pBt;
60620  BtCursor *pCur;
60621
60622  /* Close all cursors opened via this handle.  */
60623  assert( sqlite3_mutex_held(p->db->mutex) );
60624  sqlite3BtreeEnter(p);
60625  pCur = pBt->pCursor;
60626  while( pCur ){
60627    BtCursor *pTmp = pCur;
60628    pCur = pCur->pNext;
60629    if( pTmp->pBtree==p ){
60630      sqlite3BtreeCloseCursor(pTmp);
60631    }
60632  }
60633
60634  /* Rollback any active transaction and free the handle structure.
60635  ** The call to sqlite3BtreeRollback() drops any table-locks held by
60636  ** this handle.
60637  */
60638  sqlite3BtreeRollback(p, SQLITE_OK, 0);
60639  sqlite3BtreeLeave(p);
60640
60641  /* If there are still other outstanding references to the shared-btree
60642  ** structure, return now. The remainder of this procedure cleans
60643  ** up the shared-btree.
60644  */
60645  assert( p->wantToLock==0 && p->locked==0 );
60646  if( !p->sharable || removeFromSharingList(pBt) ){
60647    /* The pBt is no longer on the sharing list, so we can access
60648    ** it without having to hold the mutex.
60649    **
60650    ** Clean out and delete the BtShared object.
60651    */
60652    assert( !pBt->pCursor );
60653    sqlite3PagerClose(pBt->pPager);
60654    if( pBt->xFreeSchema && pBt->pSchema ){
60655      pBt->xFreeSchema(pBt->pSchema);
60656    }
60657    sqlite3DbFree(0, pBt->pSchema);
60658    freeTempSpace(pBt);
60659    sqlite3_free(pBt);
60660  }
60661
60662#ifndef SQLITE_OMIT_SHARED_CACHE
60663  assert( p->wantToLock==0 );
60664  assert( p->locked==0 );
60665  if( p->pPrev ) p->pPrev->pNext = p->pNext;
60666  if( p->pNext ) p->pNext->pPrev = p->pPrev;
60667#endif
60668
60669  sqlite3_free(p);
60670  return SQLITE_OK;
60671}
60672
60673/*
60674** Change the "soft" limit on the number of pages in the cache.
60675** Unused and unmodified pages will be recycled when the number of
60676** pages in the cache exceeds this soft limit.  But the size of the
60677** cache is allowed to grow larger than this limit if it contains
60678** dirty pages or pages still in active use.
60679*/
60680SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
60681  BtShared *pBt = p->pBt;
60682  assert( sqlite3_mutex_held(p->db->mutex) );
60683  sqlite3BtreeEnter(p);
60684  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
60685  sqlite3BtreeLeave(p);
60686  return SQLITE_OK;
60687}
60688
60689/*
60690** Change the "spill" limit on the number of pages in the cache.
60691** If the number of pages exceeds this limit during a write transaction,
60692** the pager might attempt to "spill" pages to the journal early in
60693** order to free up memory.
60694**
60695** The value returned is the current spill size.  If zero is passed
60696** as an argument, no changes are made to the spill size setting, so
60697** using mxPage of 0 is a way to query the current spill size.
60698*/
60699SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
60700  BtShared *pBt = p->pBt;
60701  int res;
60702  assert( sqlite3_mutex_held(p->db->mutex) );
60703  sqlite3BtreeEnter(p);
60704  res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
60705  sqlite3BtreeLeave(p);
60706  return res;
60707}
60708
60709#if SQLITE_MAX_MMAP_SIZE>0
60710/*
60711** Change the limit on the amount of the database file that may be
60712** memory mapped.
60713*/
60714SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
60715  BtShared *pBt = p->pBt;
60716  assert( sqlite3_mutex_held(p->db->mutex) );
60717  sqlite3BtreeEnter(p);
60718  sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
60719  sqlite3BtreeLeave(p);
60720  return SQLITE_OK;
60721}
60722#endif /* SQLITE_MAX_MMAP_SIZE>0 */
60723
60724/*
60725** Change the way data is synced to disk in order to increase or decrease
60726** how well the database resists damage due to OS crashes and power
60727** failures.  Level 1 is the same as asynchronous (no syncs() occur and
60728** there is a high probability of damage)  Level 2 is the default.  There
60729** is a very low but non-zero probability of damage.  Level 3 reduces the
60730** probability of damage to near zero but with a write performance reduction.
60731*/
60732#ifndef SQLITE_OMIT_PAGER_PRAGMAS
60733SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
60734  Btree *p,              /* The btree to set the safety level on */
60735  unsigned pgFlags       /* Various PAGER_* flags */
60736){
60737  BtShared *pBt = p->pBt;
60738  assert( sqlite3_mutex_held(p->db->mutex) );
60739  sqlite3BtreeEnter(p);
60740  sqlite3PagerSetFlags(pBt->pPager, pgFlags);
60741  sqlite3BtreeLeave(p);
60742  return SQLITE_OK;
60743}
60744#endif
60745
60746/*
60747** Change the default pages size and the number of reserved bytes per page.
60748** Or, if the page size has already been fixed, return SQLITE_READONLY
60749** without changing anything.
60750**
60751** The page size must be a power of 2 between 512 and 65536.  If the page
60752** size supplied does not meet this constraint then the page size is not
60753** changed.
60754**
60755** Page sizes are constrained to be a power of two so that the region
60756** of the database file used for locking (beginning at PENDING_BYTE,
60757** the first byte past the 1GB boundary, 0x40000000) needs to occur
60758** at the beginning of a page.
60759**
60760** If parameter nReserve is less than zero, then the number of reserved
60761** bytes per page is left unchanged.
60762**
60763** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
60764** and autovacuum mode can no longer be changed.
60765*/
60766SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
60767  int rc = SQLITE_OK;
60768  BtShared *pBt = p->pBt;
60769  assert( nReserve>=-1 && nReserve<=255 );
60770  sqlite3BtreeEnter(p);
60771#if SQLITE_HAS_CODEC
60772  if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
60773#endif
60774  if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
60775    sqlite3BtreeLeave(p);
60776    return SQLITE_READONLY;
60777  }
60778  if( nReserve<0 ){
60779    nReserve = pBt->pageSize - pBt->usableSize;
60780  }
60781  assert( nReserve>=0 && nReserve<=255 );
60782  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
60783        ((pageSize-1)&pageSize)==0 ){
60784    assert( (pageSize & 7)==0 );
60785    assert( !pBt->pCursor );
60786    pBt->pageSize = (u32)pageSize;
60787    freeTempSpace(pBt);
60788  }
60789  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
60790  pBt->usableSize = pBt->pageSize - (u16)nReserve;
60791  if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
60792  sqlite3BtreeLeave(p);
60793  return rc;
60794}
60795
60796/*
60797** Return the currently defined page size
60798*/
60799SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
60800  return p->pBt->pageSize;
60801}
60802
60803/*
60804** This function is similar to sqlite3BtreeGetReserve(), except that it
60805** may only be called if it is guaranteed that the b-tree mutex is already
60806** held.
60807**
60808** This is useful in one special case in the backup API code where it is
60809** known that the shared b-tree mutex is held, but the mutex on the
60810** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
60811** were to be called, it might collide with some other operation on the
60812** database handle that owns *p, causing undefined behavior.
60813*/
60814SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
60815  int n;
60816  assert( sqlite3_mutex_held(p->pBt->mutex) );
60817  n = p->pBt->pageSize - p->pBt->usableSize;
60818  return n;
60819}
60820
60821/*
60822** Return the number of bytes of space at the end of every page that
60823** are intentually left unused.  This is the "reserved" space that is
60824** sometimes used by extensions.
60825**
60826** If SQLITE_HAS_MUTEX is defined then the number returned is the
60827** greater of the current reserved space and the maximum requested
60828** reserve space.
60829*/
60830SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
60831  int n;
60832  sqlite3BtreeEnter(p);
60833  n = sqlite3BtreeGetReserveNoMutex(p);
60834#ifdef SQLITE_HAS_CODEC
60835  if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
60836#endif
60837  sqlite3BtreeLeave(p);
60838  return n;
60839}
60840
60841
60842/*
60843** Set the maximum page count for a database if mxPage is positive.
60844** No changes are made if mxPage is 0 or negative.
60845** Regardless of the value of mxPage, return the maximum page count.
60846*/
60847SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
60848  int n;
60849  sqlite3BtreeEnter(p);
60850  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
60851  sqlite3BtreeLeave(p);
60852  return n;
60853}
60854
60855/*
60856** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
60857** then make no changes.  Always return the value of the BTS_SECURE_DELETE
60858** setting after the change.
60859*/
60860SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
60861  int b;
60862  if( p==0 ) return 0;
60863  sqlite3BtreeEnter(p);
60864  if( newFlag>=0 ){
60865    p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
60866    if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
60867  }
60868  b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
60869  sqlite3BtreeLeave(p);
60870  return b;
60871}
60872
60873/*
60874** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
60875** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
60876** is disabled. The default value for the auto-vacuum property is
60877** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
60878*/
60879SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
60880#ifdef SQLITE_OMIT_AUTOVACUUM
60881  return SQLITE_READONLY;
60882#else
60883  BtShared *pBt = p->pBt;
60884  int rc = SQLITE_OK;
60885  u8 av = (u8)autoVacuum;
60886
60887  sqlite3BtreeEnter(p);
60888  if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
60889    rc = SQLITE_READONLY;
60890  }else{
60891    pBt->autoVacuum = av ?1:0;
60892    pBt->incrVacuum = av==2 ?1:0;
60893  }
60894  sqlite3BtreeLeave(p);
60895  return rc;
60896#endif
60897}
60898
60899/*
60900** Return the value of the 'auto-vacuum' property. If auto-vacuum is
60901** enabled 1 is returned. Otherwise 0.
60902*/
60903SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
60904#ifdef SQLITE_OMIT_AUTOVACUUM
60905  return BTREE_AUTOVACUUM_NONE;
60906#else
60907  int rc;
60908  sqlite3BtreeEnter(p);
60909  rc = (
60910    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
60911    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
60912    BTREE_AUTOVACUUM_INCR
60913  );
60914  sqlite3BtreeLeave(p);
60915  return rc;
60916#endif
60917}
60918
60919
60920/*
60921** Get a reference to pPage1 of the database file.  This will
60922** also acquire a readlock on that file.
60923**
60924** SQLITE_OK is returned on success.  If the file is not a
60925** well-formed database file, then SQLITE_CORRUPT is returned.
60926** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
60927** is returned if we run out of memory.
60928*/
60929static int lockBtree(BtShared *pBt){
60930  int rc;              /* Result code from subfunctions */
60931  MemPage *pPage1;     /* Page 1 of the database file */
60932  int nPage;           /* Number of pages in the database */
60933  int nPageFile = 0;   /* Number of pages in the database file */
60934  int nPageHeader;     /* Number of pages in the database according to hdr */
60935
60936  assert( sqlite3_mutex_held(pBt->mutex) );
60937  assert( pBt->pPage1==0 );
60938  rc = sqlite3PagerSharedLock(pBt->pPager);
60939  if( rc!=SQLITE_OK ) return rc;
60940  rc = btreeGetPage(pBt, 1, &pPage1, 0);
60941  if( rc!=SQLITE_OK ) return rc;
60942
60943  /* Do some checking to help insure the file we opened really is
60944  ** a valid database file.
60945  */
60946  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
60947  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
60948  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
60949    nPage = nPageFile;
60950  }
60951  if( nPage>0 ){
60952    u32 pageSize;
60953    u32 usableSize;
60954    u8 *page1 = pPage1->aData;
60955    rc = SQLITE_NOTADB;
60956    /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
60957    ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
60958    ** 61 74 20 33 00. */
60959    if( memcmp(page1, zMagicHeader, 16)!=0 ){
60960      goto page1_init_failed;
60961    }
60962
60963#ifdef SQLITE_OMIT_WAL
60964    if( page1[18]>1 ){
60965      pBt->btsFlags |= BTS_READ_ONLY;
60966    }
60967    if( page1[19]>1 ){
60968      goto page1_init_failed;
60969    }
60970#else
60971    if( page1[18]>2 ){
60972      pBt->btsFlags |= BTS_READ_ONLY;
60973    }
60974    if( page1[19]>2 ){
60975      goto page1_init_failed;
60976    }
60977
60978    /* If the write version is set to 2, this database should be accessed
60979    ** in WAL mode. If the log is not already open, open it now. Then
60980    ** return SQLITE_OK and return without populating BtShared.pPage1.
60981    ** The caller detects this and calls this function again. This is
60982    ** required as the version of page 1 currently in the page1 buffer
60983    ** may not be the latest version - there may be a newer one in the log
60984    ** file.
60985    */
60986    if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
60987      int isOpen = 0;
60988      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
60989      if( rc!=SQLITE_OK ){
60990        goto page1_init_failed;
60991      }else{
60992#if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS
60993        sqlite3 *db;
60994        Db *pDb;
60995        if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
60996          while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
60997          if( pDb->bSyncSet==0
60998           && pDb->safety_level==SQLITE_DEFAULT_SYNCHRONOUS+1
60999          ){
61000            pDb->safety_level = SQLITE_DEFAULT_WAL_SYNCHRONOUS+1;
61001            sqlite3PagerSetFlags(pBt->pPager,
61002               pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
61003          }
61004        }
61005#endif
61006        if( isOpen==0 ){
61007          releasePage(pPage1);
61008          return SQLITE_OK;
61009        }
61010      }
61011      rc = SQLITE_NOTADB;
61012    }
61013#endif
61014
61015    /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
61016    ** fractions and the leaf payload fraction values must be 64, 32, and 32.
61017    **
61018    ** The original design allowed these amounts to vary, but as of
61019    ** version 3.6.0, we require them to be fixed.
61020    */
61021    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
61022      goto page1_init_failed;
61023    }
61024    /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
61025    ** determined by the 2-byte integer located at an offset of 16 bytes from
61026    ** the beginning of the database file. */
61027    pageSize = (page1[16]<<8) | (page1[17]<<16);
61028    /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
61029    ** between 512 and 65536 inclusive. */
61030    if( ((pageSize-1)&pageSize)!=0
61031     || pageSize>SQLITE_MAX_PAGE_SIZE
61032     || pageSize<=256
61033    ){
61034      goto page1_init_failed;
61035    }
61036    assert( (pageSize & 7)==0 );
61037    /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
61038    ** integer at offset 20 is the number of bytes of space at the end of
61039    ** each page to reserve for extensions.
61040    **
61041    ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
61042    ** determined by the one-byte unsigned integer found at an offset of 20
61043    ** into the database file header. */
61044    usableSize = pageSize - page1[20];
61045    if( (u32)pageSize!=pBt->pageSize ){
61046      /* After reading the first page of the database assuming a page size
61047      ** of BtShared.pageSize, we have discovered that the page-size is
61048      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
61049      ** zero and return SQLITE_OK. The caller will call this function
61050      ** again with the correct page-size.
61051      */
61052      releasePage(pPage1);
61053      pBt->usableSize = usableSize;
61054      pBt->pageSize = pageSize;
61055      freeTempSpace(pBt);
61056      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
61057                                   pageSize-usableSize);
61058      return rc;
61059    }
61060    if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
61061      rc = SQLITE_CORRUPT_BKPT;
61062      goto page1_init_failed;
61063    }
61064    /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
61065    ** be less than 480. In other words, if the page size is 512, then the
61066    ** reserved space size cannot exceed 32. */
61067    if( usableSize<480 ){
61068      goto page1_init_failed;
61069    }
61070    pBt->pageSize = pageSize;
61071    pBt->usableSize = usableSize;
61072#ifndef SQLITE_OMIT_AUTOVACUUM
61073    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
61074    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
61075#endif
61076  }
61077
61078  /* maxLocal is the maximum amount of payload to store locally for
61079  ** a cell.  Make sure it is small enough so that at least minFanout
61080  ** cells can will fit on one page.  We assume a 10-byte page header.
61081  ** Besides the payload, the cell must store:
61082  **     2-byte pointer to the cell
61083  **     4-byte child pointer
61084  **     9-byte nKey value
61085  **     4-byte nData value
61086  **     4-byte overflow page pointer
61087  ** So a cell consists of a 2-byte pointer, a header which is as much as
61088  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
61089  ** page pointer.
61090  */
61091  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
61092  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
61093  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
61094  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
61095  if( pBt->maxLocal>127 ){
61096    pBt->max1bytePayload = 127;
61097  }else{
61098    pBt->max1bytePayload = (u8)pBt->maxLocal;
61099  }
61100  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
61101  pBt->pPage1 = pPage1;
61102  pBt->nPage = nPage;
61103  return SQLITE_OK;
61104
61105page1_init_failed:
61106  releasePage(pPage1);
61107  pBt->pPage1 = 0;
61108  return rc;
61109}
61110
61111#ifndef NDEBUG
61112/*
61113** Return the number of cursors open on pBt. This is for use
61114** in assert() expressions, so it is only compiled if NDEBUG is not
61115** defined.
61116**
61117** Only write cursors are counted if wrOnly is true.  If wrOnly is
61118** false then all cursors are counted.
61119**
61120** For the purposes of this routine, a cursor is any cursor that
61121** is capable of reading or writing to the database.  Cursors that
61122** have been tripped into the CURSOR_FAULT state are not counted.
61123*/
61124static int countValidCursors(BtShared *pBt, int wrOnly){
61125  BtCursor *pCur;
61126  int r = 0;
61127  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
61128    if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
61129     && pCur->eState!=CURSOR_FAULT ) r++;
61130  }
61131  return r;
61132}
61133#endif
61134
61135/*
61136** If there are no outstanding cursors and we are not in the middle
61137** of a transaction but there is a read lock on the database, then
61138** this routine unrefs the first page of the database file which
61139** has the effect of releasing the read lock.
61140**
61141** If there is a transaction in progress, this routine is a no-op.
61142*/
61143static void unlockBtreeIfUnused(BtShared *pBt){
61144  assert( sqlite3_mutex_held(pBt->mutex) );
61145  assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
61146  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
61147    MemPage *pPage1 = pBt->pPage1;
61148    assert( pPage1->aData );
61149    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
61150    pBt->pPage1 = 0;
61151    releasePageNotNull(pPage1);
61152  }
61153}
61154
61155/*
61156** If pBt points to an empty file then convert that empty file
61157** into a new empty database by initializing the first page of
61158** the database.
61159*/
61160static int newDatabase(BtShared *pBt){
61161  MemPage *pP1;
61162  unsigned char *data;
61163  int rc;
61164
61165  assert( sqlite3_mutex_held(pBt->mutex) );
61166  if( pBt->nPage>0 ){
61167    return SQLITE_OK;
61168  }
61169  pP1 = pBt->pPage1;
61170  assert( pP1!=0 );
61171  data = pP1->aData;
61172  rc = sqlite3PagerWrite(pP1->pDbPage);
61173  if( rc ) return rc;
61174  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
61175  assert( sizeof(zMagicHeader)==16 );
61176  data[16] = (u8)((pBt->pageSize>>8)&0xff);
61177  data[17] = (u8)((pBt->pageSize>>16)&0xff);
61178  data[18] = 1;
61179  data[19] = 1;
61180  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
61181  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
61182  data[21] = 64;
61183  data[22] = 32;
61184  data[23] = 32;
61185  memset(&data[24], 0, 100-24);
61186  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
61187  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
61188#ifndef SQLITE_OMIT_AUTOVACUUM
61189  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
61190  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
61191  put4byte(&data[36 + 4*4], pBt->autoVacuum);
61192  put4byte(&data[36 + 7*4], pBt->incrVacuum);
61193#endif
61194  pBt->nPage = 1;
61195  data[31] = 1;
61196  return SQLITE_OK;
61197}
61198
61199/*
61200** Initialize the first page of the database file (creating a database
61201** consisting of a single page and no schema objects). Return SQLITE_OK
61202** if successful, or an SQLite error code otherwise.
61203*/
61204SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
61205  int rc;
61206  sqlite3BtreeEnter(p);
61207  p->pBt->nPage = 0;
61208  rc = newDatabase(p->pBt);
61209  sqlite3BtreeLeave(p);
61210  return rc;
61211}
61212
61213/*
61214** Attempt to start a new transaction. A write-transaction
61215** is started if the second argument is nonzero, otherwise a read-
61216** transaction.  If the second argument is 2 or more and exclusive
61217** transaction is started, meaning that no other process is allowed
61218** to access the database.  A preexisting transaction may not be
61219** upgraded to exclusive by calling this routine a second time - the
61220** exclusivity flag only works for a new transaction.
61221**
61222** A write-transaction must be started before attempting any
61223** changes to the database.  None of the following routines
61224** will work unless a transaction is started first:
61225**
61226**      sqlite3BtreeCreateTable()
61227**      sqlite3BtreeCreateIndex()
61228**      sqlite3BtreeClearTable()
61229**      sqlite3BtreeDropTable()
61230**      sqlite3BtreeInsert()
61231**      sqlite3BtreeDelete()
61232**      sqlite3BtreeUpdateMeta()
61233**
61234** If an initial attempt to acquire the lock fails because of lock contention
61235** and the database was previously unlocked, then invoke the busy handler
61236** if there is one.  But if there was previously a read-lock, do not
61237** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
61238** returned when there is already a read-lock in order to avoid a deadlock.
61239**
61240** Suppose there are two processes A and B.  A has a read lock and B has
61241** a reserved lock.  B tries to promote to exclusive but is blocked because
61242** of A's read lock.  A tries to promote to reserved but is blocked by B.
61243** One or the other of the two processes must give way or there can be
61244** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
61245** when A already has a read lock, we encourage A to give up and let B
61246** proceed.
61247*/
61248SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
61249  BtShared *pBt = p->pBt;
61250  int rc = SQLITE_OK;
61251
61252  sqlite3BtreeEnter(p);
61253  btreeIntegrity(p);
61254
61255  /* If the btree is already in a write-transaction, or it
61256  ** is already in a read-transaction and a read-transaction
61257  ** is requested, this is a no-op.
61258  */
61259  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
61260    goto trans_begun;
61261  }
61262  assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
61263
61264  /* Write transactions are not possible on a read-only database */
61265  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
61266    rc = SQLITE_READONLY;
61267    goto trans_begun;
61268  }
61269
61270#ifndef SQLITE_OMIT_SHARED_CACHE
61271  {
61272    sqlite3 *pBlock = 0;
61273    /* If another database handle has already opened a write transaction
61274    ** on this shared-btree structure and a second write transaction is
61275    ** requested, return SQLITE_LOCKED.
61276    */
61277    if( (wrflag && pBt->inTransaction==TRANS_WRITE)
61278     || (pBt->btsFlags & BTS_PENDING)!=0
61279    ){
61280      pBlock = pBt->pWriter->db;
61281    }else if( wrflag>1 ){
61282      BtLock *pIter;
61283      for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
61284        if( pIter->pBtree!=p ){
61285          pBlock = pIter->pBtree->db;
61286          break;
61287        }
61288      }
61289    }
61290    if( pBlock ){
61291      sqlite3ConnectionBlocked(p->db, pBlock);
61292      rc = SQLITE_LOCKED_SHAREDCACHE;
61293      goto trans_begun;
61294    }
61295  }
61296#endif
61297
61298  /* Any read-only or read-write transaction implies a read-lock on
61299  ** page 1. So if some other shared-cache client already has a write-lock
61300  ** on page 1, the transaction cannot be opened. */
61301  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
61302  if( SQLITE_OK!=rc ) goto trans_begun;
61303
61304  pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
61305  if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
61306  do {
61307    /* Call lockBtree() until either pBt->pPage1 is populated or
61308    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
61309    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
61310    ** reading page 1 it discovers that the page-size of the database
61311    ** file is not pBt->pageSize. In this case lockBtree() will update
61312    ** pBt->pageSize to the page-size of the file on disk.
61313    */
61314    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
61315
61316    if( rc==SQLITE_OK && wrflag ){
61317      if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
61318        rc = SQLITE_READONLY;
61319      }else{
61320        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
61321        if( rc==SQLITE_OK ){
61322          rc = newDatabase(pBt);
61323        }
61324      }
61325    }
61326
61327    if( rc!=SQLITE_OK ){
61328      unlockBtreeIfUnused(pBt);
61329    }
61330  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
61331          btreeInvokeBusyHandler(pBt) );
61332
61333  if( rc==SQLITE_OK ){
61334    if( p->inTrans==TRANS_NONE ){
61335      pBt->nTransaction++;
61336#ifndef SQLITE_OMIT_SHARED_CACHE
61337      if( p->sharable ){
61338        assert( p->lock.pBtree==p && p->lock.iTable==1 );
61339        p->lock.eLock = READ_LOCK;
61340        p->lock.pNext = pBt->pLock;
61341        pBt->pLock = &p->lock;
61342      }
61343#endif
61344    }
61345    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
61346    if( p->inTrans>pBt->inTransaction ){
61347      pBt->inTransaction = p->inTrans;
61348    }
61349    if( wrflag ){
61350      MemPage *pPage1 = pBt->pPage1;
61351#ifndef SQLITE_OMIT_SHARED_CACHE
61352      assert( !pBt->pWriter );
61353      pBt->pWriter = p;
61354      pBt->btsFlags &= ~BTS_EXCLUSIVE;
61355      if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
61356#endif
61357
61358      /* If the db-size header field is incorrect (as it may be if an old
61359      ** client has been writing the database file), update it now. Doing
61360      ** this sooner rather than later means the database size can safely
61361      ** re-read the database size from page 1 if a savepoint or transaction
61362      ** rollback occurs within the transaction.
61363      */
61364      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
61365        rc = sqlite3PagerWrite(pPage1->pDbPage);
61366        if( rc==SQLITE_OK ){
61367          put4byte(&pPage1->aData[28], pBt->nPage);
61368        }
61369      }
61370    }
61371  }
61372
61373
61374trans_begun:
61375  if( rc==SQLITE_OK && wrflag ){
61376    /* This call makes sure that the pager has the correct number of
61377    ** open savepoints. If the second parameter is greater than 0 and
61378    ** the sub-journal is not already open, then it will be opened here.
61379    */
61380    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
61381  }
61382
61383  btreeIntegrity(p);
61384  sqlite3BtreeLeave(p);
61385  return rc;
61386}
61387
61388#ifndef SQLITE_OMIT_AUTOVACUUM
61389
61390/*
61391** Set the pointer-map entries for all children of page pPage. Also, if
61392** pPage contains cells that point to overflow pages, set the pointer
61393** map entries for the overflow pages as well.
61394*/
61395static int setChildPtrmaps(MemPage *pPage){
61396  int i;                             /* Counter variable */
61397  int nCell;                         /* Number of cells in page pPage */
61398  int rc;                            /* Return code */
61399  BtShared *pBt = pPage->pBt;
61400  u8 isInitOrig = pPage->isInit;
61401  Pgno pgno = pPage->pgno;
61402
61403  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61404  rc = btreeInitPage(pPage);
61405  if( rc!=SQLITE_OK ){
61406    goto set_child_ptrmaps_out;
61407  }
61408  nCell = pPage->nCell;
61409
61410  for(i=0; i<nCell; i++){
61411    u8 *pCell = findCell(pPage, i);
61412
61413    ptrmapPutOvflPtr(pPage, pCell, &rc);
61414
61415    if( !pPage->leaf ){
61416      Pgno childPgno = get4byte(pCell);
61417      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
61418    }
61419  }
61420
61421  if( !pPage->leaf ){
61422    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
61423    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
61424  }
61425
61426set_child_ptrmaps_out:
61427  pPage->isInit = isInitOrig;
61428  return rc;
61429}
61430
61431/*
61432** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
61433** that it points to iTo. Parameter eType describes the type of pointer to
61434** be modified, as  follows:
61435**
61436** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
61437**                   page of pPage.
61438**
61439** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
61440**                   page pointed to by one of the cells on pPage.
61441**
61442** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
61443**                   overflow page in the list.
61444*/
61445static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
61446  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61447  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
61448  if( eType==PTRMAP_OVERFLOW2 ){
61449    /* The pointer is always the first 4 bytes of the page in this case.  */
61450    if( get4byte(pPage->aData)!=iFrom ){
61451      return SQLITE_CORRUPT_BKPT;
61452    }
61453    put4byte(pPage->aData, iTo);
61454  }else{
61455    u8 isInitOrig = pPage->isInit;
61456    int i;
61457    int nCell;
61458    int rc;
61459
61460    rc = btreeInitPage(pPage);
61461    if( rc ) return rc;
61462    nCell = pPage->nCell;
61463
61464    for(i=0; i<nCell; i++){
61465      u8 *pCell = findCell(pPage, i);
61466      if( eType==PTRMAP_OVERFLOW1 ){
61467        CellInfo info;
61468        pPage->xParseCell(pPage, pCell, &info);
61469        if( info.nLocal<info.nPayload
61470         && pCell+info.nSize-1<=pPage->aData+pPage->maskPage
61471         && iFrom==get4byte(pCell+info.nSize-4)
61472        ){
61473          put4byte(pCell+info.nSize-4, iTo);
61474          break;
61475        }
61476      }else{
61477        if( get4byte(pCell)==iFrom ){
61478          put4byte(pCell, iTo);
61479          break;
61480        }
61481      }
61482    }
61483
61484    if( i==nCell ){
61485      if( eType!=PTRMAP_BTREE ||
61486          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
61487        return SQLITE_CORRUPT_BKPT;
61488      }
61489      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
61490    }
61491
61492    pPage->isInit = isInitOrig;
61493  }
61494  return SQLITE_OK;
61495}
61496
61497
61498/*
61499** Move the open database page pDbPage to location iFreePage in the
61500** database. The pDbPage reference remains valid.
61501**
61502** The isCommit flag indicates that there is no need to remember that
61503** the journal needs to be sync()ed before database page pDbPage->pgno
61504** can be written to. The caller has already promised not to write to that
61505** page.
61506*/
61507static int relocatePage(
61508  BtShared *pBt,           /* Btree */
61509  MemPage *pDbPage,        /* Open page to move */
61510  u8 eType,                /* Pointer map 'type' entry for pDbPage */
61511  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
61512  Pgno iFreePage,          /* The location to move pDbPage to */
61513  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
61514){
61515  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
61516  Pgno iDbPage = pDbPage->pgno;
61517  Pager *pPager = pBt->pPager;
61518  int rc;
61519
61520  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
61521      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
61522  assert( sqlite3_mutex_held(pBt->mutex) );
61523  assert( pDbPage->pBt==pBt );
61524
61525  /* Move page iDbPage from its current location to page number iFreePage */
61526  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
61527      iDbPage, iFreePage, iPtrPage, eType));
61528  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
61529  if( rc!=SQLITE_OK ){
61530    return rc;
61531  }
61532  pDbPage->pgno = iFreePage;
61533
61534  /* If pDbPage was a btree-page, then it may have child pages and/or cells
61535  ** that point to overflow pages. The pointer map entries for all these
61536  ** pages need to be changed.
61537  **
61538  ** If pDbPage is an overflow page, then the first 4 bytes may store a
61539  ** pointer to a subsequent overflow page. If this is the case, then
61540  ** the pointer map needs to be updated for the subsequent overflow page.
61541  */
61542  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
61543    rc = setChildPtrmaps(pDbPage);
61544    if( rc!=SQLITE_OK ){
61545      return rc;
61546    }
61547  }else{
61548    Pgno nextOvfl = get4byte(pDbPage->aData);
61549    if( nextOvfl!=0 ){
61550      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
61551      if( rc!=SQLITE_OK ){
61552        return rc;
61553      }
61554    }
61555  }
61556
61557  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
61558  ** that it points at iFreePage. Also fix the pointer map entry for
61559  ** iPtrPage.
61560  */
61561  if( eType!=PTRMAP_ROOTPAGE ){
61562    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
61563    if( rc!=SQLITE_OK ){
61564      return rc;
61565    }
61566    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
61567    if( rc!=SQLITE_OK ){
61568      releasePage(pPtrPage);
61569      return rc;
61570    }
61571    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
61572    releasePage(pPtrPage);
61573    if( rc==SQLITE_OK ){
61574      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
61575    }
61576  }
61577  return rc;
61578}
61579
61580/* Forward declaration required by incrVacuumStep(). */
61581static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
61582
61583/*
61584** Perform a single step of an incremental-vacuum. If successful, return
61585** SQLITE_OK. If there is no work to do (and therefore no point in
61586** calling this function again), return SQLITE_DONE. Or, if an error
61587** occurs, return some other error code.
61588**
61589** More specifically, this function attempts to re-organize the database so
61590** that the last page of the file currently in use is no longer in use.
61591**
61592** Parameter nFin is the number of pages that this database would contain
61593** were this function called until it returns SQLITE_DONE.
61594**
61595** If the bCommit parameter is non-zero, this function assumes that the
61596** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
61597** or an error. bCommit is passed true for an auto-vacuum-on-commit
61598** operation, or false for an incremental vacuum.
61599*/
61600static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
61601  Pgno nFreeList;           /* Number of pages still on the free-list */
61602  int rc;
61603
61604  assert( sqlite3_mutex_held(pBt->mutex) );
61605  assert( iLastPg>nFin );
61606
61607  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
61608    u8 eType;
61609    Pgno iPtrPage;
61610
61611    nFreeList = get4byte(&pBt->pPage1->aData[36]);
61612    if( nFreeList==0 ){
61613      return SQLITE_DONE;
61614    }
61615
61616    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
61617    if( rc!=SQLITE_OK ){
61618      return rc;
61619    }
61620    if( eType==PTRMAP_ROOTPAGE ){
61621      return SQLITE_CORRUPT_BKPT;
61622    }
61623
61624    if( eType==PTRMAP_FREEPAGE ){
61625      if( bCommit==0 ){
61626        /* Remove the page from the files free-list. This is not required
61627        ** if bCommit is non-zero. In that case, the free-list will be
61628        ** truncated to zero after this function returns, so it doesn't
61629        ** matter if it still contains some garbage entries.
61630        */
61631        Pgno iFreePg;
61632        MemPage *pFreePg;
61633        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
61634        if( rc!=SQLITE_OK ){
61635          return rc;
61636        }
61637        assert( iFreePg==iLastPg );
61638        releasePage(pFreePg);
61639      }
61640    } else {
61641      Pgno iFreePg;             /* Index of free page to move pLastPg to */
61642      MemPage *pLastPg;
61643      u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
61644      Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
61645
61646      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
61647      if( rc!=SQLITE_OK ){
61648        return rc;
61649      }
61650
61651      /* If bCommit is zero, this loop runs exactly once and page pLastPg
61652      ** is swapped with the first free page pulled off the free list.
61653      **
61654      ** On the other hand, if bCommit is greater than zero, then keep
61655      ** looping until a free-page located within the first nFin pages
61656      ** of the file is found.
61657      */
61658      if( bCommit==0 ){
61659        eMode = BTALLOC_LE;
61660        iNear = nFin;
61661      }
61662      do {
61663        MemPage *pFreePg;
61664        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
61665        if( rc!=SQLITE_OK ){
61666          releasePage(pLastPg);
61667          return rc;
61668        }
61669        releasePage(pFreePg);
61670      }while( bCommit && iFreePg>nFin );
61671      assert( iFreePg<iLastPg );
61672
61673      rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
61674      releasePage(pLastPg);
61675      if( rc!=SQLITE_OK ){
61676        return rc;
61677      }
61678    }
61679  }
61680
61681  if( bCommit==0 ){
61682    do {
61683      iLastPg--;
61684    }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
61685    pBt->bDoTruncate = 1;
61686    pBt->nPage = iLastPg;
61687  }
61688  return SQLITE_OK;
61689}
61690
61691/*
61692** The database opened by the first argument is an auto-vacuum database
61693** nOrig pages in size containing nFree free pages. Return the expected
61694** size of the database in pages following an auto-vacuum operation.
61695*/
61696static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
61697  int nEntry;                     /* Number of entries on one ptrmap page */
61698  Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
61699  Pgno nFin;                      /* Return value */
61700
61701  nEntry = pBt->usableSize/5;
61702  nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
61703  nFin = nOrig - nFree - nPtrmap;
61704  if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
61705    nFin--;
61706  }
61707  while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
61708    nFin--;
61709  }
61710
61711  return nFin;
61712}
61713
61714/*
61715** A write-transaction must be opened before calling this function.
61716** It performs a single unit of work towards an incremental vacuum.
61717**
61718** If the incremental vacuum is finished after this function has run,
61719** SQLITE_DONE is returned. If it is not finished, but no error occurred,
61720** SQLITE_OK is returned. Otherwise an SQLite error code.
61721*/
61722SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
61723  int rc;
61724  BtShared *pBt = p->pBt;
61725
61726  sqlite3BtreeEnter(p);
61727  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
61728  if( !pBt->autoVacuum ){
61729    rc = SQLITE_DONE;
61730  }else{
61731    Pgno nOrig = btreePagecount(pBt);
61732    Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
61733    Pgno nFin = finalDbSize(pBt, nOrig, nFree);
61734
61735    if( nOrig<nFin ){
61736      rc = SQLITE_CORRUPT_BKPT;
61737    }else if( nFree>0 ){
61738      rc = saveAllCursors(pBt, 0, 0);
61739      if( rc==SQLITE_OK ){
61740        invalidateAllOverflowCache(pBt);
61741        rc = incrVacuumStep(pBt, nFin, nOrig, 0);
61742      }
61743      if( rc==SQLITE_OK ){
61744        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
61745        put4byte(&pBt->pPage1->aData[28], pBt->nPage);
61746      }
61747    }else{
61748      rc = SQLITE_DONE;
61749    }
61750  }
61751  sqlite3BtreeLeave(p);
61752  return rc;
61753}
61754
61755/*
61756** This routine is called prior to sqlite3PagerCommit when a transaction
61757** is committed for an auto-vacuum database.
61758**
61759** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
61760** the database file should be truncated to during the commit process.
61761** i.e. the database has been reorganized so that only the first *pnTrunc
61762** pages are in use.
61763*/
61764static int autoVacuumCommit(BtShared *pBt){
61765  int rc = SQLITE_OK;
61766  Pager *pPager = pBt->pPager;
61767  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
61768
61769  assert( sqlite3_mutex_held(pBt->mutex) );
61770  invalidateAllOverflowCache(pBt);
61771  assert(pBt->autoVacuum);
61772  if( !pBt->incrVacuum ){
61773    Pgno nFin;         /* Number of pages in database after autovacuuming */
61774    Pgno nFree;        /* Number of pages on the freelist initially */
61775    Pgno iFree;        /* The next page to be freed */
61776    Pgno nOrig;        /* Database size before freeing */
61777
61778    nOrig = btreePagecount(pBt);
61779    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
61780      /* It is not possible to create a database for which the final page
61781      ** is either a pointer-map page or the pending-byte page. If one
61782      ** is encountered, this indicates corruption.
61783      */
61784      return SQLITE_CORRUPT_BKPT;
61785    }
61786
61787    nFree = get4byte(&pBt->pPage1->aData[36]);
61788    nFin = finalDbSize(pBt, nOrig, nFree);
61789    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
61790    if( nFin<nOrig ){
61791      rc = saveAllCursors(pBt, 0, 0);
61792    }
61793    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
61794      rc = incrVacuumStep(pBt, nFin, iFree, 1);
61795    }
61796    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
61797      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
61798      put4byte(&pBt->pPage1->aData[32], 0);
61799      put4byte(&pBt->pPage1->aData[36], 0);
61800      put4byte(&pBt->pPage1->aData[28], nFin);
61801      pBt->bDoTruncate = 1;
61802      pBt->nPage = nFin;
61803    }
61804    if( rc!=SQLITE_OK ){
61805      sqlite3PagerRollback(pPager);
61806    }
61807  }
61808
61809  assert( nRef>=sqlite3PagerRefcount(pPager) );
61810  return rc;
61811}
61812
61813#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
61814# define setChildPtrmaps(x) SQLITE_OK
61815#endif
61816
61817/*
61818** This routine does the first phase of a two-phase commit.  This routine
61819** causes a rollback journal to be created (if it does not already exist)
61820** and populated with enough information so that if a power loss occurs
61821** the database can be restored to its original state by playing back
61822** the journal.  Then the contents of the journal are flushed out to
61823** the disk.  After the journal is safely on oxide, the changes to the
61824** database are written into the database file and flushed to oxide.
61825** At the end of this call, the rollback journal still exists on the
61826** disk and we are still holding all locks, so the transaction has not
61827** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
61828** commit process.
61829**
61830** This call is a no-op if no write-transaction is currently active on pBt.
61831**
61832** Otherwise, sync the database file for the btree pBt. zMaster points to
61833** the name of a master journal file that should be written into the
61834** individual journal file, or is NULL, indicating no master journal file
61835** (single database transaction).
61836**
61837** When this is called, the master journal should already have been
61838** created, populated with this journal pointer and synced to disk.
61839**
61840** Once this is routine has returned, the only thing required to commit
61841** the write-transaction for this database file is to delete the journal.
61842*/
61843SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
61844  int rc = SQLITE_OK;
61845  if( p->inTrans==TRANS_WRITE ){
61846    BtShared *pBt = p->pBt;
61847    sqlite3BtreeEnter(p);
61848#ifndef SQLITE_OMIT_AUTOVACUUM
61849    if( pBt->autoVacuum ){
61850      rc = autoVacuumCommit(pBt);
61851      if( rc!=SQLITE_OK ){
61852        sqlite3BtreeLeave(p);
61853        return rc;
61854      }
61855    }
61856    if( pBt->bDoTruncate ){
61857      sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
61858    }
61859#endif
61860    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
61861    sqlite3BtreeLeave(p);
61862  }
61863  return rc;
61864}
61865
61866/*
61867** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
61868** at the conclusion of a transaction.
61869*/
61870static void btreeEndTransaction(Btree *p){
61871  BtShared *pBt = p->pBt;
61872  sqlite3 *db = p->db;
61873  assert( sqlite3BtreeHoldsMutex(p) );
61874
61875#ifndef SQLITE_OMIT_AUTOVACUUM
61876  pBt->bDoTruncate = 0;
61877#endif
61878  if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
61879    /* If there are other active statements that belong to this database
61880    ** handle, downgrade to a read-only transaction. The other statements
61881    ** may still be reading from the database.  */
61882    downgradeAllSharedCacheTableLocks(p);
61883    p->inTrans = TRANS_READ;
61884  }else{
61885    /* If the handle had any kind of transaction open, decrement the
61886    ** transaction count of the shared btree. If the transaction count
61887    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
61888    ** call below will unlock the pager.  */
61889    if( p->inTrans!=TRANS_NONE ){
61890      clearAllSharedCacheTableLocks(p);
61891      pBt->nTransaction--;
61892      if( 0==pBt->nTransaction ){
61893        pBt->inTransaction = TRANS_NONE;
61894      }
61895    }
61896
61897    /* Set the current transaction state to TRANS_NONE and unlock the
61898    ** pager if this call closed the only read or write transaction.  */
61899    p->inTrans = TRANS_NONE;
61900    unlockBtreeIfUnused(pBt);
61901  }
61902
61903  btreeIntegrity(p);
61904}
61905
61906/*
61907** Commit the transaction currently in progress.
61908**
61909** This routine implements the second phase of a 2-phase commit.  The
61910** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
61911** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
61912** routine did all the work of writing information out to disk and flushing the
61913** contents so that they are written onto the disk platter.  All this
61914** routine has to do is delete or truncate or zero the header in the
61915** the rollback journal (which causes the transaction to commit) and
61916** drop locks.
61917**
61918** Normally, if an error occurs while the pager layer is attempting to
61919** finalize the underlying journal file, this function returns an error and
61920** the upper layer will attempt a rollback. However, if the second argument
61921** is non-zero then this b-tree transaction is part of a multi-file
61922** transaction. In this case, the transaction has already been committed
61923** (by deleting a master journal file) and the caller will ignore this
61924** functions return code. So, even if an error occurs in the pager layer,
61925** reset the b-tree objects internal state to indicate that the write
61926** transaction has been closed. This is quite safe, as the pager will have
61927** transitioned to the error state.
61928**
61929** This will release the write lock on the database file.  If there
61930** are no active cursors, it also releases the read lock.
61931*/
61932SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
61933
61934  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
61935  sqlite3BtreeEnter(p);
61936  btreeIntegrity(p);
61937
61938  /* If the handle has a write-transaction open, commit the shared-btrees
61939  ** transaction and set the shared state to TRANS_READ.
61940  */
61941  if( p->inTrans==TRANS_WRITE ){
61942    int rc;
61943    BtShared *pBt = p->pBt;
61944    assert( pBt->inTransaction==TRANS_WRITE );
61945    assert( pBt->nTransaction>0 );
61946    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
61947    if( rc!=SQLITE_OK && bCleanup==0 ){
61948      sqlite3BtreeLeave(p);
61949      return rc;
61950    }
61951    p->iDataVersion--;  /* Compensate for pPager->iDataVersion++; */
61952    pBt->inTransaction = TRANS_READ;
61953    btreeClearHasContent(pBt);
61954  }
61955
61956  btreeEndTransaction(p);
61957  sqlite3BtreeLeave(p);
61958  return SQLITE_OK;
61959}
61960
61961/*
61962** Do both phases of a commit.
61963*/
61964SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
61965  int rc;
61966  sqlite3BtreeEnter(p);
61967  rc = sqlite3BtreeCommitPhaseOne(p, 0);
61968  if( rc==SQLITE_OK ){
61969    rc = sqlite3BtreeCommitPhaseTwo(p, 0);
61970  }
61971  sqlite3BtreeLeave(p);
61972  return rc;
61973}
61974
61975/*
61976** This routine sets the state to CURSOR_FAULT and the error
61977** code to errCode for every cursor on any BtShared that pBtree
61978** references.  Or if the writeOnly flag is set to 1, then only
61979** trip write cursors and leave read cursors unchanged.
61980**
61981** Every cursor is a candidate to be tripped, including cursors
61982** that belong to other database connections that happen to be
61983** sharing the cache with pBtree.
61984**
61985** This routine gets called when a rollback occurs. If the writeOnly
61986** flag is true, then only write-cursors need be tripped - read-only
61987** cursors save their current positions so that they may continue
61988** following the rollback. Or, if writeOnly is false, all cursors are
61989** tripped. In general, writeOnly is false if the transaction being
61990** rolled back modified the database schema. In this case b-tree root
61991** pages may be moved or deleted from the database altogether, making
61992** it unsafe for read cursors to continue.
61993**
61994** If the writeOnly flag is true and an error is encountered while
61995** saving the current position of a read-only cursor, all cursors,
61996** including all read-cursors are tripped.
61997**
61998** SQLITE_OK is returned if successful, or if an error occurs while
61999** saving a cursor position, an SQLite error code.
62000*/
62001SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
62002  BtCursor *p;
62003  int rc = SQLITE_OK;
62004
62005  assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
62006  if( pBtree ){
62007    sqlite3BtreeEnter(pBtree);
62008    for(p=pBtree->pBt->pCursor; p; p=p->pNext){
62009      int i;
62010      if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
62011        if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
62012          rc = saveCursorPosition(p);
62013          if( rc!=SQLITE_OK ){
62014            (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
62015            break;
62016          }
62017        }
62018      }else{
62019        sqlite3BtreeClearCursor(p);
62020        p->eState = CURSOR_FAULT;
62021        p->skipNext = errCode;
62022      }
62023      for(i=0; i<=p->iPage; i++){
62024        releasePage(p->apPage[i]);
62025        p->apPage[i] = 0;
62026      }
62027    }
62028    sqlite3BtreeLeave(pBtree);
62029  }
62030  return rc;
62031}
62032
62033/*
62034** Rollback the transaction in progress.
62035**
62036** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
62037** Only write cursors are tripped if writeOnly is true but all cursors are
62038** tripped if writeOnly is false.  Any attempt to use
62039** a tripped cursor will result in an error.
62040**
62041** This will release the write lock on the database file.  If there
62042** are no active cursors, it also releases the read lock.
62043*/
62044SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
62045  int rc;
62046  BtShared *pBt = p->pBt;
62047  MemPage *pPage1;
62048
62049  assert( writeOnly==1 || writeOnly==0 );
62050  assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
62051  sqlite3BtreeEnter(p);
62052  if( tripCode==SQLITE_OK ){
62053    rc = tripCode = saveAllCursors(pBt, 0, 0);
62054    if( rc ) writeOnly = 0;
62055  }else{
62056    rc = SQLITE_OK;
62057  }
62058  if( tripCode ){
62059    int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
62060    assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
62061    if( rc2!=SQLITE_OK ) rc = rc2;
62062  }
62063  btreeIntegrity(p);
62064
62065  if( p->inTrans==TRANS_WRITE ){
62066    int rc2;
62067
62068    assert( TRANS_WRITE==pBt->inTransaction );
62069    rc2 = sqlite3PagerRollback(pBt->pPager);
62070    if( rc2!=SQLITE_OK ){
62071      rc = rc2;
62072    }
62073
62074    /* The rollback may have destroyed the pPage1->aData value.  So
62075    ** call btreeGetPage() on page 1 again to make
62076    ** sure pPage1->aData is set correctly. */
62077    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
62078      int nPage = get4byte(28+(u8*)pPage1->aData);
62079      testcase( nPage==0 );
62080      if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
62081      testcase( pBt->nPage!=nPage );
62082      pBt->nPage = nPage;
62083      releasePage(pPage1);
62084    }
62085    assert( countValidCursors(pBt, 1)==0 );
62086    pBt->inTransaction = TRANS_READ;
62087    btreeClearHasContent(pBt);
62088  }
62089
62090  btreeEndTransaction(p);
62091  sqlite3BtreeLeave(p);
62092  return rc;
62093}
62094
62095/*
62096** Start a statement subtransaction. The subtransaction can be rolled
62097** back independently of the main transaction. You must start a transaction
62098** before starting a subtransaction. The subtransaction is ended automatically
62099** if the main transaction commits or rolls back.
62100**
62101** Statement subtransactions are used around individual SQL statements
62102** that are contained within a BEGIN...COMMIT block.  If a constraint
62103** error occurs within the statement, the effect of that one statement
62104** can be rolled back without having to rollback the entire transaction.
62105**
62106** A statement sub-transaction is implemented as an anonymous savepoint. The
62107** value passed as the second parameter is the total number of savepoints,
62108** including the new anonymous savepoint, open on the B-Tree. i.e. if there
62109** are no active savepoints and no other statement-transactions open,
62110** iStatement is 1. This anonymous savepoint can be released or rolled back
62111** using the sqlite3BtreeSavepoint() function.
62112*/
62113SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
62114  int rc;
62115  BtShared *pBt = p->pBt;
62116  sqlite3BtreeEnter(p);
62117  assert( p->inTrans==TRANS_WRITE );
62118  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
62119  assert( iStatement>0 );
62120  assert( iStatement>p->db->nSavepoint );
62121  assert( pBt->inTransaction==TRANS_WRITE );
62122  /* At the pager level, a statement transaction is a savepoint with
62123  ** an index greater than all savepoints created explicitly using
62124  ** SQL statements. It is illegal to open, release or rollback any
62125  ** such savepoints while the statement transaction savepoint is active.
62126  */
62127  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
62128  sqlite3BtreeLeave(p);
62129  return rc;
62130}
62131
62132/*
62133** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
62134** or SAVEPOINT_RELEASE. This function either releases or rolls back the
62135** savepoint identified by parameter iSavepoint, depending on the value
62136** of op.
62137**
62138** Normally, iSavepoint is greater than or equal to zero. However, if op is
62139** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
62140** contents of the entire transaction are rolled back. This is different
62141** from a normal transaction rollback, as no locks are released and the
62142** transaction remains open.
62143*/
62144SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
62145  int rc = SQLITE_OK;
62146  if( p && p->inTrans==TRANS_WRITE ){
62147    BtShared *pBt = p->pBt;
62148    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
62149    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
62150    sqlite3BtreeEnter(p);
62151    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
62152    if( rc==SQLITE_OK ){
62153      if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
62154        pBt->nPage = 0;
62155      }
62156      rc = newDatabase(pBt);
62157      pBt->nPage = get4byte(28 + pBt->pPage1->aData);
62158
62159      /* The database size was written into the offset 28 of the header
62160      ** when the transaction started, so we know that the value at offset
62161      ** 28 is nonzero. */
62162      assert( pBt->nPage>0 );
62163    }
62164    sqlite3BtreeLeave(p);
62165  }
62166  return rc;
62167}
62168
62169/*
62170** Create a new cursor for the BTree whose root is on the page
62171** iTable. If a read-only cursor is requested, it is assumed that
62172** the caller already has at least a read-only transaction open
62173** on the database already. If a write-cursor is requested, then
62174** the caller is assumed to have an open write transaction.
62175**
62176** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
62177** be used for reading.  If the BTREE_WRCSR bit is set, then the cursor
62178** can be used for reading or for writing if other conditions for writing
62179** are also met.  These are the conditions that must be met in order
62180** for writing to be allowed:
62181**
62182** 1:  The cursor must have been opened with wrFlag containing BTREE_WRCSR
62183**
62184** 2:  Other database connections that share the same pager cache
62185**     but which are not in the READ_UNCOMMITTED state may not have
62186**     cursors open with wrFlag==0 on the same table.  Otherwise
62187**     the changes made by this write cursor would be visible to
62188**     the read cursors in the other database connection.
62189**
62190** 3:  The database must be writable (not on read-only media)
62191**
62192** 4:  There must be an active transaction.
62193**
62194** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
62195** is set.  If FORDELETE is set, that is a hint to the implementation that
62196** this cursor will only be used to seek to and delete entries of an index
62197** as part of a larger DELETE statement.  The FORDELETE hint is not used by
62198** this implementation.  But in a hypothetical alternative storage engine
62199** in which index entries are automatically deleted when corresponding table
62200** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
62201** operations on this cursor can be no-ops and all READ operations can
62202** return a null row (2-bytes: 0x01 0x00).
62203**
62204** No checking is done to make sure that page iTable really is the
62205** root page of a b-tree.  If it is not, then the cursor acquired
62206** will not work correctly.
62207**
62208** It is assumed that the sqlite3BtreeCursorZero() has been called
62209** on pCur to initialize the memory space prior to invoking this routine.
62210*/
62211static int btreeCursor(
62212  Btree *p,                              /* The btree */
62213  int iTable,                            /* Root page of table to open */
62214  int wrFlag,                            /* 1 to write. 0 read-only */
62215  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
62216  BtCursor *pCur                         /* Space for new cursor */
62217){
62218  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
62219  BtCursor *pX;                          /* Looping over other all cursors */
62220
62221  assert( sqlite3BtreeHoldsMutex(p) );
62222  assert( wrFlag==0
62223       || wrFlag==BTREE_WRCSR
62224       || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
62225  );
62226
62227  /* The following assert statements verify that if this is a sharable
62228  ** b-tree database, the connection is holding the required table locks,
62229  ** and that no other connection has any open cursor that conflicts with
62230  ** this lock.  */
62231  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
62232  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
62233
62234  /* Assert that the caller has opened the required transaction. */
62235  assert( p->inTrans>TRANS_NONE );
62236  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
62237  assert( pBt->pPage1 && pBt->pPage1->aData );
62238  assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
62239
62240  if( wrFlag ){
62241    allocateTempSpace(pBt);
62242    if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
62243  }
62244  if( iTable==1 && btreePagecount(pBt)==0 ){
62245    assert( wrFlag==0 );
62246    iTable = 0;
62247  }
62248
62249  /* Now that no other errors can occur, finish filling in the BtCursor
62250  ** variables and link the cursor into the BtShared list.  */
62251  pCur->pgnoRoot = (Pgno)iTable;
62252  pCur->iPage = -1;
62253  pCur->pKeyInfo = pKeyInfo;
62254  pCur->pBtree = p;
62255  pCur->pBt = pBt;
62256  pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
62257  pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
62258  /* If there are two or more cursors on the same btree, then all such
62259  ** cursors *must* have the BTCF_Multiple flag set. */
62260  for(pX=pBt->pCursor; pX; pX=pX->pNext){
62261    if( pX->pgnoRoot==(Pgno)iTable ){
62262      pX->curFlags |= BTCF_Multiple;
62263      pCur->curFlags |= BTCF_Multiple;
62264    }
62265  }
62266  pCur->pNext = pBt->pCursor;
62267  pBt->pCursor = pCur;
62268  pCur->eState = CURSOR_INVALID;
62269  return SQLITE_OK;
62270}
62271SQLITE_PRIVATE int sqlite3BtreeCursor(
62272  Btree *p,                                   /* The btree */
62273  int iTable,                                 /* Root page of table to open */
62274  int wrFlag,                                 /* 1 to write. 0 read-only */
62275  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
62276  BtCursor *pCur                              /* Write new cursor here */
62277){
62278  int rc;
62279  if( iTable<1 ){
62280    rc = SQLITE_CORRUPT_BKPT;
62281  }else{
62282    sqlite3BtreeEnter(p);
62283    rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
62284    sqlite3BtreeLeave(p);
62285  }
62286  return rc;
62287}
62288
62289/*
62290** Return the size of a BtCursor object in bytes.
62291**
62292** This interfaces is needed so that users of cursors can preallocate
62293** sufficient storage to hold a cursor.  The BtCursor object is opaque
62294** to users so they cannot do the sizeof() themselves - they must call
62295** this routine.
62296*/
62297SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
62298  return ROUND8(sizeof(BtCursor));
62299}
62300
62301/*
62302** Initialize memory that will be converted into a BtCursor object.
62303**
62304** The simple approach here would be to memset() the entire object
62305** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
62306** do not need to be zeroed and they are large, so we can save a lot
62307** of run-time by skipping the initialization of those elements.
62308*/
62309SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
62310  memset(p, 0, offsetof(BtCursor, iPage));
62311}
62312
62313/*
62314** Close a cursor.  The read lock on the database file is released
62315** when the last cursor is closed.
62316*/
62317SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
62318  Btree *pBtree = pCur->pBtree;
62319  if( pBtree ){
62320    int i;
62321    BtShared *pBt = pCur->pBt;
62322    sqlite3BtreeEnter(pBtree);
62323    sqlite3BtreeClearCursor(pCur);
62324    assert( pBt->pCursor!=0 );
62325    if( pBt->pCursor==pCur ){
62326      pBt->pCursor = pCur->pNext;
62327    }else{
62328      BtCursor *pPrev = pBt->pCursor;
62329      do{
62330        if( pPrev->pNext==pCur ){
62331          pPrev->pNext = pCur->pNext;
62332          break;
62333        }
62334        pPrev = pPrev->pNext;
62335      }while( ALWAYS(pPrev) );
62336    }
62337    for(i=0; i<=pCur->iPage; i++){
62338      releasePage(pCur->apPage[i]);
62339    }
62340    unlockBtreeIfUnused(pBt);
62341    sqlite3_free(pCur->aOverflow);
62342    /* sqlite3_free(pCur); */
62343    sqlite3BtreeLeave(pBtree);
62344  }
62345  return SQLITE_OK;
62346}
62347
62348/*
62349** Make sure the BtCursor* given in the argument has a valid
62350** BtCursor.info structure.  If it is not already valid, call
62351** btreeParseCell() to fill it in.
62352**
62353** BtCursor.info is a cache of the information in the current cell.
62354** Using this cache reduces the number of calls to btreeParseCell().
62355*/
62356#ifndef NDEBUG
62357  static void assertCellInfo(BtCursor *pCur){
62358    CellInfo info;
62359    int iPage = pCur->iPage;
62360    memset(&info, 0, sizeof(info));
62361    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
62362    assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
62363  }
62364#else
62365  #define assertCellInfo(x)
62366#endif
62367static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
62368  if( pCur->info.nSize==0 ){
62369    int iPage = pCur->iPage;
62370    pCur->curFlags |= BTCF_ValidNKey;
62371    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
62372  }else{
62373    assertCellInfo(pCur);
62374  }
62375}
62376
62377#ifndef NDEBUG  /* The next routine used only within assert() statements */
62378/*
62379** Return true if the given BtCursor is valid.  A valid cursor is one
62380** that is currently pointing to a row in a (non-empty) table.
62381** This is a verification routine is used only within assert() statements.
62382*/
62383SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
62384  return pCur && pCur->eState==CURSOR_VALID;
62385}
62386#endif /* NDEBUG */
62387
62388/*
62389** Return the value of the integer key or "rowid" for a table btree.
62390** This routine is only valid for a cursor that is pointing into a
62391** ordinary table btree.  If the cursor points to an index btree or
62392** is invalid, the result of this routine is undefined.
62393*/
62394SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
62395  assert( cursorHoldsMutex(pCur) );
62396  assert( pCur->eState==CURSOR_VALID );
62397  assert( pCur->curIntKey );
62398  getCellInfo(pCur);
62399  return pCur->info.nKey;
62400}
62401
62402/*
62403** Return the number of bytes of payload for the entry that pCur is
62404** currently pointing to.  For table btrees, this will be the amount
62405** of data.  For index btrees, this will be the size of the key.
62406**
62407** The caller must guarantee that the cursor is pointing to a non-NULL
62408** valid entry.  In other words, the calling procedure must guarantee
62409** that the cursor has Cursor.eState==CURSOR_VALID.
62410*/
62411SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
62412  assert( cursorHoldsMutex(pCur) );
62413  assert( pCur->eState==CURSOR_VALID );
62414  getCellInfo(pCur);
62415  return pCur->info.nPayload;
62416}
62417
62418/*
62419** Given the page number of an overflow page in the database (parameter
62420** ovfl), this function finds the page number of the next page in the
62421** linked list of overflow pages. If possible, it uses the auto-vacuum
62422** pointer-map data instead of reading the content of page ovfl to do so.
62423**
62424** If an error occurs an SQLite error code is returned. Otherwise:
62425**
62426** The page number of the next overflow page in the linked list is
62427** written to *pPgnoNext. If page ovfl is the last page in its linked
62428** list, *pPgnoNext is set to zero.
62429**
62430** If ppPage is not NULL, and a reference to the MemPage object corresponding
62431** to page number pOvfl was obtained, then *ppPage is set to point to that
62432** reference. It is the responsibility of the caller to call releasePage()
62433** on *ppPage to free the reference. In no reference was obtained (because
62434** the pointer-map was used to obtain the value for *pPgnoNext), then
62435** *ppPage is set to zero.
62436*/
62437static int getOverflowPage(
62438  BtShared *pBt,               /* The database file */
62439  Pgno ovfl,                   /* Current overflow page number */
62440  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
62441  Pgno *pPgnoNext              /* OUT: Next overflow page number */
62442){
62443  Pgno next = 0;
62444  MemPage *pPage = 0;
62445  int rc = SQLITE_OK;
62446
62447  assert( sqlite3_mutex_held(pBt->mutex) );
62448  assert(pPgnoNext);
62449
62450#ifndef SQLITE_OMIT_AUTOVACUUM
62451  /* Try to find the next page in the overflow list using the
62452  ** autovacuum pointer-map pages. Guess that the next page in
62453  ** the overflow list is page number (ovfl+1). If that guess turns
62454  ** out to be wrong, fall back to loading the data of page
62455  ** number ovfl to determine the next page number.
62456  */
62457  if( pBt->autoVacuum ){
62458    Pgno pgno;
62459    Pgno iGuess = ovfl+1;
62460    u8 eType;
62461
62462    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
62463      iGuess++;
62464    }
62465
62466    if( iGuess<=btreePagecount(pBt) ){
62467      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
62468      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
62469        next = iGuess;
62470        rc = SQLITE_DONE;
62471      }
62472    }
62473  }
62474#endif
62475
62476  assert( next==0 || rc==SQLITE_DONE );
62477  if( rc==SQLITE_OK ){
62478    rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
62479    assert( rc==SQLITE_OK || pPage==0 );
62480    if( rc==SQLITE_OK ){
62481      next = get4byte(pPage->aData);
62482    }
62483  }
62484
62485  *pPgnoNext = next;
62486  if( ppPage ){
62487    *ppPage = pPage;
62488  }else{
62489    releasePage(pPage);
62490  }
62491  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
62492}
62493
62494/*
62495** Copy data from a buffer to a page, or from a page to a buffer.
62496**
62497** pPayload is a pointer to data stored on database page pDbPage.
62498** If argument eOp is false, then nByte bytes of data are copied
62499** from pPayload to the buffer pointed at by pBuf. If eOp is true,
62500** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
62501** of data are copied from the buffer pBuf to pPayload.
62502**
62503** SQLITE_OK is returned on success, otherwise an error code.
62504*/
62505static int copyPayload(
62506  void *pPayload,           /* Pointer to page data */
62507  void *pBuf,               /* Pointer to buffer */
62508  int nByte,                /* Number of bytes to copy */
62509  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
62510  DbPage *pDbPage           /* Page containing pPayload */
62511){
62512  if( eOp ){
62513    /* Copy data from buffer to page (a write operation) */
62514    int rc = sqlite3PagerWrite(pDbPage);
62515    if( rc!=SQLITE_OK ){
62516      return rc;
62517    }
62518    memcpy(pPayload, pBuf, nByte);
62519  }else{
62520    /* Copy data from page to buffer (a read operation) */
62521    memcpy(pBuf, pPayload, nByte);
62522  }
62523  return SQLITE_OK;
62524}
62525
62526/*
62527** This function is used to read or overwrite payload information
62528** for the entry that the pCur cursor is pointing to. The eOp
62529** argument is interpreted as follows:
62530**
62531**   0: The operation is a read. Populate the overflow cache.
62532**   1: The operation is a write. Populate the overflow cache.
62533**   2: The operation is a read. Do not populate the overflow cache.
62534**
62535** A total of "amt" bytes are read or written beginning at "offset".
62536** Data is read to or from the buffer pBuf.
62537**
62538** The content being read or written might appear on the main page
62539** or be scattered out on multiple overflow pages.
62540**
62541** If the current cursor entry uses one or more overflow pages and the
62542** eOp argument is not 2, this function may allocate space for and lazily
62543** populates the overflow page-list cache array (BtCursor.aOverflow).
62544** Subsequent calls use this cache to make seeking to the supplied offset
62545** more efficient.
62546**
62547** Once an overflow page-list cache has been allocated, it may be
62548** invalidated if some other cursor writes to the same table, or if
62549** the cursor is moved to a different row. Additionally, in auto-vacuum
62550** mode, the following events may invalidate an overflow page-list cache.
62551**
62552**   * An incremental vacuum,
62553**   * A commit in auto_vacuum="full" mode,
62554**   * Creating a table (may require moving an overflow page).
62555*/
62556static int accessPayload(
62557  BtCursor *pCur,      /* Cursor pointing to entry to read from */
62558  u32 offset,          /* Begin reading this far into payload */
62559  u32 amt,             /* Read this many bytes */
62560  unsigned char *pBuf, /* Write the bytes into this buffer */
62561  int eOp              /* zero to read. non-zero to write. */
62562){
62563  unsigned char *aPayload;
62564  int rc = SQLITE_OK;
62565  int iIdx = 0;
62566  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
62567  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
62568#ifdef SQLITE_DIRECT_OVERFLOW_READ
62569  unsigned char * const pBufStart = pBuf;
62570  int bEnd;                                 /* True if reading to end of data */
62571#endif
62572
62573  assert( pPage );
62574  assert( pCur->eState==CURSOR_VALID );
62575  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
62576  assert( cursorHoldsMutex(pCur) );
62577  assert( eOp!=2 || offset==0 );    /* Always start from beginning for eOp==2 */
62578
62579  getCellInfo(pCur);
62580  aPayload = pCur->info.pPayload;
62581#ifdef SQLITE_DIRECT_OVERFLOW_READ
62582  bEnd = offset+amt==pCur->info.nPayload;
62583#endif
62584  assert( offset+amt <= pCur->info.nPayload );
62585
62586  assert( aPayload > pPage->aData );
62587  if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
62588    /* Trying to read or write past the end of the data is an error.  The
62589    ** conditional above is really:
62590    **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
62591    ** but is recast into its current form to avoid integer overflow problems
62592    */
62593    return SQLITE_CORRUPT_BKPT;
62594  }
62595
62596  /* Check if data must be read/written to/from the btree page itself. */
62597  if( offset<pCur->info.nLocal ){
62598    int a = amt;
62599    if( a+offset>pCur->info.nLocal ){
62600      a = pCur->info.nLocal - offset;
62601    }
62602    rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
62603    offset = 0;
62604    pBuf += a;
62605    amt -= a;
62606  }else{
62607    offset -= pCur->info.nLocal;
62608  }
62609
62610
62611  if( rc==SQLITE_OK && amt>0 ){
62612    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
62613    Pgno nextPage;
62614
62615    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
62616
62617    /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
62618    ** Except, do not allocate aOverflow[] for eOp==2.
62619    **
62620    ** The aOverflow[] array is sized at one entry for each overflow page
62621    ** in the overflow chain. The page number of the first overflow page is
62622    ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
62623    ** means "not yet known" (the cache is lazily populated).
62624    */
62625    if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
62626      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
62627      if( nOvfl>pCur->nOvflAlloc ){
62628        Pgno *aNew = (Pgno*)sqlite3Realloc(
62629            pCur->aOverflow, nOvfl*2*sizeof(Pgno)
62630        );
62631        if( aNew==0 ){
62632          rc = SQLITE_NOMEM_BKPT;
62633        }else{
62634          pCur->nOvflAlloc = nOvfl*2;
62635          pCur->aOverflow = aNew;
62636        }
62637      }
62638      if( rc==SQLITE_OK ){
62639        memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
62640        pCur->curFlags |= BTCF_ValidOvfl;
62641      }
62642    }
62643
62644    /* If the overflow page-list cache has been allocated and the
62645    ** entry for the first required overflow page is valid, skip
62646    ** directly to it.
62647    */
62648    if( (pCur->curFlags & BTCF_ValidOvfl)!=0
62649     && pCur->aOverflow[offset/ovflSize]
62650    ){
62651      iIdx = (offset/ovflSize);
62652      nextPage = pCur->aOverflow[iIdx];
62653      offset = (offset%ovflSize);
62654    }
62655
62656    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
62657
62658      /* If required, populate the overflow page-list cache. */
62659      if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
62660        assert( pCur->aOverflow[iIdx]==0
62661                || pCur->aOverflow[iIdx]==nextPage
62662                || CORRUPT_DB );
62663        pCur->aOverflow[iIdx] = nextPage;
62664      }
62665
62666      if( offset>=ovflSize ){
62667        /* The only reason to read this page is to obtain the page
62668        ** number for the next page in the overflow chain. The page
62669        ** data is not required. So first try to lookup the overflow
62670        ** page-list cache, if any, then fall back to the getOverflowPage()
62671        ** function.
62672        **
62673        ** Note that the aOverflow[] array must be allocated because eOp!=2
62674        ** here.  If eOp==2, then offset==0 and this branch is never taken.
62675        */
62676        assert( eOp!=2 );
62677        assert( pCur->curFlags & BTCF_ValidOvfl );
62678        assert( pCur->pBtree->db==pBt->db );
62679        if( pCur->aOverflow[iIdx+1] ){
62680          nextPage = pCur->aOverflow[iIdx+1];
62681        }else{
62682          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
62683        }
62684        offset -= ovflSize;
62685      }else{
62686        /* Need to read this page properly. It contains some of the
62687        ** range of data that is being read (eOp==0) or written (eOp!=0).
62688        */
62689#ifdef SQLITE_DIRECT_OVERFLOW_READ
62690        sqlite3_file *fd;
62691#endif
62692        int a = amt;
62693        if( a + offset > ovflSize ){
62694          a = ovflSize - offset;
62695        }
62696
62697#ifdef SQLITE_DIRECT_OVERFLOW_READ
62698        /* If all the following are true:
62699        **
62700        **   1) this is a read operation, and
62701        **   2) data is required from the start of this overflow page, and
62702        **   3) the database is file-backed, and
62703        **   4) there is no open write-transaction, and
62704        **   5) the database is not a WAL database,
62705        **   6) all data from the page is being read.
62706        **   7) at least 4 bytes have already been read into the output buffer
62707        **
62708        ** then data can be read directly from the database file into the
62709        ** output buffer, bypassing the page-cache altogether. This speeds
62710        ** up loading large records that span many overflow pages.
62711        */
62712        if( (eOp&0x01)==0                                      /* (1) */
62713         && offset==0                                          /* (2) */
62714         && (bEnd || a==ovflSize)                              /* (6) */
62715         && pBt->inTransaction==TRANS_READ                     /* (4) */
62716         && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
62717         && pBt->pPage1->aData[19]==0x01                       /* (5) */
62718         && &pBuf[-4]>=pBufStart                               /* (7) */
62719        ){
62720          u8 aSave[4];
62721          u8 *aWrite = &pBuf[-4];
62722          assert( aWrite>=pBufStart );                         /* hence (7) */
62723          memcpy(aSave, aWrite, 4);
62724          rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
62725          nextPage = get4byte(aWrite);
62726          memcpy(aWrite, aSave, 4);
62727        }else
62728#endif
62729
62730        {
62731          DbPage *pDbPage;
62732          rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
62733              ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
62734          );
62735          if( rc==SQLITE_OK ){
62736            aPayload = sqlite3PagerGetData(pDbPage);
62737            nextPage = get4byte(aPayload);
62738            rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
62739            sqlite3PagerUnref(pDbPage);
62740            offset = 0;
62741          }
62742        }
62743        amt -= a;
62744        pBuf += a;
62745      }
62746    }
62747  }
62748
62749  if( rc==SQLITE_OK && amt>0 ){
62750    return SQLITE_CORRUPT_BKPT;
62751  }
62752  return rc;
62753}
62754
62755/*
62756** Read part of the key associated with cursor pCur.  Exactly
62757** "amt" bytes will be transferred into pBuf[].  The transfer
62758** begins at "offset".
62759**
62760** The caller must ensure that pCur is pointing to a valid row
62761** in the table.
62762**
62763** Return SQLITE_OK on success or an error code if anything goes
62764** wrong.  An error is returned if "offset+amt" is larger than
62765** the available payload.
62766*/
62767SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
62768  assert( cursorHoldsMutex(pCur) );
62769  assert( pCur->eState==CURSOR_VALID );
62770  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
62771  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62772  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
62773}
62774
62775/*
62776** Read part of the data associated with cursor pCur.  Exactly
62777** "amt" bytes will be transfered into pBuf[].  The transfer
62778** begins at "offset".
62779**
62780** Return SQLITE_OK on success or an error code if anything goes
62781** wrong.  An error is returned if "offset+amt" is larger than
62782** the available payload.
62783*/
62784SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
62785  int rc;
62786
62787#ifndef SQLITE_OMIT_INCRBLOB
62788  if ( pCur->eState==CURSOR_INVALID ){
62789    return SQLITE_ABORT;
62790  }
62791#endif
62792
62793  assert( cursorOwnsBtShared(pCur) );
62794  rc = restoreCursorPosition(pCur);
62795  if( rc==SQLITE_OK ){
62796    assert( pCur->eState==CURSOR_VALID );
62797    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
62798    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62799    rc = accessPayload(pCur, offset, amt, pBuf, 0);
62800  }
62801  return rc;
62802}
62803
62804/*
62805** Return a pointer to payload information from the entry that the
62806** pCur cursor is pointing to.  The pointer is to the beginning of
62807** the key if index btrees (pPage->intKey==0) and is the data for
62808** table btrees (pPage->intKey==1). The number of bytes of available
62809** key/data is written into *pAmt.  If *pAmt==0, then the value
62810** returned will not be a valid pointer.
62811**
62812** This routine is an optimization.  It is common for the entire key
62813** and data to fit on the local page and for there to be no overflow
62814** pages.  When that is so, this routine can be used to access the
62815** key and data without making a copy.  If the key and/or data spills
62816** onto overflow pages, then accessPayload() must be used to reassemble
62817** the key/data and copy it into a preallocated buffer.
62818**
62819** The pointer returned by this routine looks directly into the cached
62820** page of the database.  The data might change or move the next time
62821** any btree routine is called.
62822*/
62823static const void *fetchPayload(
62824  BtCursor *pCur,      /* Cursor pointing to entry to read from */
62825  u32 *pAmt            /* Write the number of available bytes here */
62826){
62827  u32 amt;
62828  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
62829  assert( pCur->eState==CURSOR_VALID );
62830  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
62831  assert( cursorOwnsBtShared(pCur) );
62832  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62833  assert( pCur->info.nSize>0 );
62834  assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
62835  assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
62836  amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
62837  if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
62838  *pAmt = amt;
62839  return (void*)pCur->info.pPayload;
62840}
62841
62842
62843/*
62844** For the entry that cursor pCur is point to, return as
62845** many bytes of the key or data as are available on the local
62846** b-tree page.  Write the number of available bytes into *pAmt.
62847**
62848** The pointer returned is ephemeral.  The key/data may move
62849** or be destroyed on the next call to any Btree routine,
62850** including calls from other threads against the same cache.
62851** Hence, a mutex on the BtShared should be held prior to calling
62852** this routine.
62853**
62854** These routines is used to get quick access to key and data
62855** in the common case where no overflow pages are used.
62856*/
62857SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
62858  return fetchPayload(pCur, pAmt);
62859}
62860
62861
62862/*
62863** Move the cursor down to a new child page.  The newPgno argument is the
62864** page number of the child page to move to.
62865**
62866** This function returns SQLITE_CORRUPT if the page-header flags field of
62867** the new child page does not match the flags field of the parent (i.e.
62868** if an intkey page appears to be the parent of a non-intkey page, or
62869** vice-versa).
62870*/
62871static int moveToChild(BtCursor *pCur, u32 newPgno){
62872  BtShared *pBt = pCur->pBt;
62873
62874  assert( cursorOwnsBtShared(pCur) );
62875  assert( pCur->eState==CURSOR_VALID );
62876  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
62877  assert( pCur->iPage>=0 );
62878  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
62879    return SQLITE_CORRUPT_BKPT;
62880  }
62881  pCur->info.nSize = 0;
62882  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
62883  pCur->iPage++;
62884  pCur->aiIdx[pCur->iPage] = 0;
62885  return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
62886                        pCur, pCur->curPagerFlags);
62887}
62888
62889#if SQLITE_DEBUG
62890/*
62891** Page pParent is an internal (non-leaf) tree page. This function
62892** asserts that page number iChild is the left-child if the iIdx'th
62893** cell in page pParent. Or, if iIdx is equal to the total number of
62894** cells in pParent, that page number iChild is the right-child of
62895** the page.
62896*/
62897static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
62898  if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
62899                            ** in a corrupt database */
62900  assert( iIdx<=pParent->nCell );
62901  if( iIdx==pParent->nCell ){
62902    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
62903  }else{
62904    assert( get4byte(findCell(pParent, iIdx))==iChild );
62905  }
62906}
62907#else
62908#  define assertParentIndex(x,y,z)
62909#endif
62910
62911/*
62912** Move the cursor up to the parent page.
62913**
62914** pCur->idx is set to the cell index that contains the pointer
62915** to the page we are coming from.  If we are coming from the
62916** right-most child page then pCur->idx is set to one more than
62917** the largest cell index.
62918*/
62919static void moveToParent(BtCursor *pCur){
62920  assert( cursorOwnsBtShared(pCur) );
62921  assert( pCur->eState==CURSOR_VALID );
62922  assert( pCur->iPage>0 );
62923  assert( pCur->apPage[pCur->iPage] );
62924  assertParentIndex(
62925    pCur->apPage[pCur->iPage-1],
62926    pCur->aiIdx[pCur->iPage-1],
62927    pCur->apPage[pCur->iPage]->pgno
62928  );
62929  testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
62930  pCur->info.nSize = 0;
62931  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
62932  releasePageNotNull(pCur->apPage[pCur->iPage--]);
62933}
62934
62935/*
62936** Move the cursor to point to the root page of its b-tree structure.
62937**
62938** If the table has a virtual root page, then the cursor is moved to point
62939** to the virtual root page instead of the actual root page. A table has a
62940** virtual root page when the actual root page contains no cells and a
62941** single child page. This can only happen with the table rooted at page 1.
62942**
62943** If the b-tree structure is empty, the cursor state is set to
62944** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
62945** cell located on the root (or virtual root) page and the cursor state
62946** is set to CURSOR_VALID.
62947**
62948** If this function returns successfully, it may be assumed that the
62949** page-header flags indicate that the [virtual] root-page is the expected
62950** kind of b-tree page (i.e. if when opening the cursor the caller did not
62951** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
62952** indicating a table b-tree, or if the caller did specify a KeyInfo
62953** structure the flags byte is set to 0x02 or 0x0A, indicating an index
62954** b-tree).
62955*/
62956static int moveToRoot(BtCursor *pCur){
62957  MemPage *pRoot;
62958  int rc = SQLITE_OK;
62959
62960  assert( cursorOwnsBtShared(pCur) );
62961  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
62962  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
62963  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
62964  if( pCur->eState>=CURSOR_REQUIRESEEK ){
62965    if( pCur->eState==CURSOR_FAULT ){
62966      assert( pCur->skipNext!=SQLITE_OK );
62967      return pCur->skipNext;
62968    }
62969    sqlite3BtreeClearCursor(pCur);
62970  }
62971
62972  if( pCur->iPage>=0 ){
62973    while( pCur->iPage ){
62974      assert( pCur->apPage[pCur->iPage]!=0 );
62975      releasePageNotNull(pCur->apPage[pCur->iPage--]);
62976    }
62977  }else if( pCur->pgnoRoot==0 ){
62978    pCur->eState = CURSOR_INVALID;
62979    return SQLITE_OK;
62980  }else{
62981    assert( pCur->iPage==(-1) );
62982    rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
62983                        0, pCur->curPagerFlags);
62984    if( rc!=SQLITE_OK ){
62985      pCur->eState = CURSOR_INVALID;
62986      return rc;
62987    }
62988    pCur->iPage = 0;
62989    pCur->curIntKey = pCur->apPage[0]->intKey;
62990  }
62991  pRoot = pCur->apPage[0];
62992  assert( pRoot->pgno==pCur->pgnoRoot );
62993
62994  /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
62995  ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
62996  ** NULL, the caller expects a table b-tree. If this is not the case,
62997  ** return an SQLITE_CORRUPT error.
62998  **
62999  ** Earlier versions of SQLite assumed that this test could not fail
63000  ** if the root page was already loaded when this function was called (i.e.
63001  ** if pCur->iPage>=0). But this is not so if the database is corrupted
63002  ** in such a way that page pRoot is linked into a second b-tree table
63003  ** (or the freelist).  */
63004  assert( pRoot->intKey==1 || pRoot->intKey==0 );
63005  if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
63006    return SQLITE_CORRUPT_BKPT;
63007  }
63008
63009  pCur->aiIdx[0] = 0;
63010  pCur->info.nSize = 0;
63011  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
63012
63013  if( pRoot->nCell>0 ){
63014    pCur->eState = CURSOR_VALID;
63015  }else if( !pRoot->leaf ){
63016    Pgno subpage;
63017    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
63018    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
63019    pCur->eState = CURSOR_VALID;
63020    rc = moveToChild(pCur, subpage);
63021  }else{
63022    pCur->eState = CURSOR_INVALID;
63023  }
63024  return rc;
63025}
63026
63027/*
63028** Move the cursor down to the left-most leaf entry beneath the
63029** entry to which it is currently pointing.
63030**
63031** The left-most leaf is the one with the smallest key - the first
63032** in ascending order.
63033*/
63034static int moveToLeftmost(BtCursor *pCur){
63035  Pgno pgno;
63036  int rc = SQLITE_OK;
63037  MemPage *pPage;
63038
63039  assert( cursorOwnsBtShared(pCur) );
63040  assert( pCur->eState==CURSOR_VALID );
63041  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
63042    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
63043    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
63044    rc = moveToChild(pCur, pgno);
63045  }
63046  return rc;
63047}
63048
63049/*
63050** Move the cursor down to the right-most leaf entry beneath the
63051** page to which it is currently pointing.  Notice the difference
63052** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
63053** finds the left-most entry beneath the *entry* whereas moveToRightmost()
63054** finds the right-most entry beneath the *page*.
63055**
63056** The right-most entry is the one with the largest key - the last
63057** key in ascending order.
63058*/
63059static int moveToRightmost(BtCursor *pCur){
63060  Pgno pgno;
63061  int rc = SQLITE_OK;
63062  MemPage *pPage = 0;
63063
63064  assert( cursorOwnsBtShared(pCur) );
63065  assert( pCur->eState==CURSOR_VALID );
63066  while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
63067    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
63068    pCur->aiIdx[pCur->iPage] = pPage->nCell;
63069    rc = moveToChild(pCur, pgno);
63070    if( rc ) return rc;
63071  }
63072  pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
63073  assert( pCur->info.nSize==0 );
63074  assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
63075  return SQLITE_OK;
63076}
63077
63078/* Move the cursor to the first entry in the table.  Return SQLITE_OK
63079** on success.  Set *pRes to 0 if the cursor actually points to something
63080** or set *pRes to 1 if the table is empty.
63081*/
63082SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
63083  int rc;
63084
63085  assert( cursorOwnsBtShared(pCur) );
63086  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
63087  rc = moveToRoot(pCur);
63088  if( rc==SQLITE_OK ){
63089    if( pCur->eState==CURSOR_INVALID ){
63090      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
63091      *pRes = 1;
63092    }else{
63093      assert( pCur->apPage[pCur->iPage]->nCell>0 );
63094      *pRes = 0;
63095      rc = moveToLeftmost(pCur);
63096    }
63097  }
63098  return rc;
63099}
63100
63101/* Move the cursor to the last entry in the table.  Return SQLITE_OK
63102** on success.  Set *pRes to 0 if the cursor actually points to something
63103** or set *pRes to 1 if the table is empty.
63104*/
63105SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
63106  int rc;
63107
63108  assert( cursorOwnsBtShared(pCur) );
63109  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
63110
63111  /* If the cursor already points to the last entry, this is a no-op. */
63112  if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
63113#ifdef SQLITE_DEBUG
63114    /* This block serves to assert() that the cursor really does point
63115    ** to the last entry in the b-tree. */
63116    int ii;
63117    for(ii=0; ii<pCur->iPage; ii++){
63118      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
63119    }
63120    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
63121    assert( pCur->apPage[pCur->iPage]->leaf );
63122#endif
63123    return SQLITE_OK;
63124  }
63125
63126  rc = moveToRoot(pCur);
63127  if( rc==SQLITE_OK ){
63128    if( CURSOR_INVALID==pCur->eState ){
63129      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
63130      *pRes = 1;
63131    }else{
63132      assert( pCur->eState==CURSOR_VALID );
63133      *pRes = 0;
63134      rc = moveToRightmost(pCur);
63135      if( rc==SQLITE_OK ){
63136        pCur->curFlags |= BTCF_AtLast;
63137      }else{
63138        pCur->curFlags &= ~BTCF_AtLast;
63139      }
63140
63141    }
63142  }
63143  return rc;
63144}
63145
63146/* Move the cursor so that it points to an entry near the key
63147** specified by pIdxKey or intKey.   Return a success code.
63148**
63149** For INTKEY tables, the intKey parameter is used.  pIdxKey
63150** must be NULL.  For index tables, pIdxKey is used and intKey
63151** is ignored.
63152**
63153** If an exact match is not found, then the cursor is always
63154** left pointing at a leaf page which would hold the entry if it
63155** were present.  The cursor might point to an entry that comes
63156** before or after the key.
63157**
63158** An integer is written into *pRes which is the result of
63159** comparing the key with the entry to which the cursor is
63160** pointing.  The meaning of the integer written into
63161** *pRes is as follows:
63162**
63163**     *pRes<0      The cursor is left pointing at an entry that
63164**                  is smaller than intKey/pIdxKey or if the table is empty
63165**                  and the cursor is therefore left point to nothing.
63166**
63167**     *pRes==0     The cursor is left pointing at an entry that
63168**                  exactly matches intKey/pIdxKey.
63169**
63170**     *pRes>0      The cursor is left pointing at an entry that
63171**                  is larger than intKey/pIdxKey.
63172**
63173** For index tables, the pIdxKey->eqSeen field is set to 1 if there
63174** exists an entry in the table that exactly matches pIdxKey.
63175*/
63176SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
63177  BtCursor *pCur,          /* The cursor to be moved */
63178  UnpackedRecord *pIdxKey, /* Unpacked index key */
63179  i64 intKey,              /* The table key */
63180  int biasRight,           /* If true, bias the search to the high end */
63181  int *pRes                /* Write search results here */
63182){
63183  int rc;
63184  RecordCompare xRecordCompare;
63185
63186  assert( cursorOwnsBtShared(pCur) );
63187  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
63188  assert( pRes );
63189  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
63190  assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
63191
63192  /* If the cursor is already positioned at the point we are trying
63193  ** to move to, then just return without doing any work */
63194  if( pIdxKey==0
63195   && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
63196  ){
63197    if( pCur->info.nKey==intKey ){
63198      *pRes = 0;
63199      return SQLITE_OK;
63200    }
63201    if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
63202      *pRes = -1;
63203      return SQLITE_OK;
63204    }
63205  }
63206
63207  if( pIdxKey ){
63208    xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
63209    pIdxKey->errCode = 0;
63210    assert( pIdxKey->default_rc==1
63211         || pIdxKey->default_rc==0
63212         || pIdxKey->default_rc==-1
63213    );
63214  }else{
63215    xRecordCompare = 0; /* All keys are integers */
63216  }
63217
63218  rc = moveToRoot(pCur);
63219  if( rc ){
63220    return rc;
63221  }
63222  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
63223  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
63224  assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
63225  if( pCur->eState==CURSOR_INVALID ){
63226    *pRes = -1;
63227    assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
63228    return SQLITE_OK;
63229  }
63230  assert( pCur->apPage[0]->intKey==pCur->curIntKey );
63231  assert( pCur->curIntKey || pIdxKey );
63232  for(;;){
63233    int lwr, upr, idx, c;
63234    Pgno chldPg;
63235    MemPage *pPage = pCur->apPage[pCur->iPage];
63236    u8 *pCell;                          /* Pointer to current cell in pPage */
63237
63238    /* pPage->nCell must be greater than zero. If this is the root-page
63239    ** the cursor would have been INVALID above and this for(;;) loop
63240    ** not run. If this is not the root-page, then the moveToChild() routine
63241    ** would have already detected db corruption. Similarly, pPage must
63242    ** be the right kind (index or table) of b-tree page. Otherwise
63243    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
63244    assert( pPage->nCell>0 );
63245    assert( pPage->intKey==(pIdxKey==0) );
63246    lwr = 0;
63247    upr = pPage->nCell-1;
63248    assert( biasRight==0 || biasRight==1 );
63249    idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
63250    pCur->aiIdx[pCur->iPage] = (u16)idx;
63251    if( xRecordCompare==0 ){
63252      for(;;){
63253        i64 nCellKey;
63254        pCell = findCellPastPtr(pPage, idx);
63255        if( pPage->intKeyLeaf ){
63256          while( 0x80 <= *(pCell++) ){
63257            if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
63258          }
63259        }
63260        getVarint(pCell, (u64*)&nCellKey);
63261        if( nCellKey<intKey ){
63262          lwr = idx+1;
63263          if( lwr>upr ){ c = -1; break; }
63264        }else if( nCellKey>intKey ){
63265          upr = idx-1;
63266          if( lwr>upr ){ c = +1; break; }
63267        }else{
63268          assert( nCellKey==intKey );
63269          pCur->curFlags |= BTCF_ValidNKey;
63270          pCur->info.nKey = nCellKey;
63271          pCur->aiIdx[pCur->iPage] = (u16)idx;
63272          if( !pPage->leaf ){
63273            lwr = idx;
63274            goto moveto_next_layer;
63275          }else{
63276            *pRes = 0;
63277            rc = SQLITE_OK;
63278            goto moveto_finish;
63279          }
63280        }
63281        assert( lwr+upr>=0 );
63282        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
63283      }
63284    }else{
63285      for(;;){
63286        int nCell;  /* Size of the pCell cell in bytes */
63287        pCell = findCellPastPtr(pPage, idx);
63288
63289        /* The maximum supported page-size is 65536 bytes. This means that
63290        ** the maximum number of record bytes stored on an index B-Tree
63291        ** page is less than 16384 bytes and may be stored as a 2-byte
63292        ** varint. This information is used to attempt to avoid parsing
63293        ** the entire cell by checking for the cases where the record is
63294        ** stored entirely within the b-tree page by inspecting the first
63295        ** 2 bytes of the cell.
63296        */
63297        nCell = pCell[0];
63298        if( nCell<=pPage->max1bytePayload ){
63299          /* This branch runs if the record-size field of the cell is a
63300          ** single byte varint and the record fits entirely on the main
63301          ** b-tree page.  */
63302          testcase( pCell+nCell+1==pPage->aDataEnd );
63303          c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
63304        }else if( !(pCell[1] & 0x80)
63305          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
63306        ){
63307          /* The record-size field is a 2 byte varint and the record
63308          ** fits entirely on the main b-tree page.  */
63309          testcase( pCell+nCell+2==pPage->aDataEnd );
63310          c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
63311        }else{
63312          /* The record flows over onto one or more overflow pages. In
63313          ** this case the whole cell needs to be parsed, a buffer allocated
63314          ** and accessPayload() used to retrieve the record into the
63315          ** buffer before VdbeRecordCompare() can be called.
63316          **
63317          ** If the record is corrupt, the xRecordCompare routine may read
63318          ** up to two varints past the end of the buffer. An extra 18
63319          ** bytes of padding is allocated at the end of the buffer in
63320          ** case this happens.  */
63321          void *pCellKey;
63322          u8 * const pCellBody = pCell - pPage->childPtrSize;
63323          pPage->xParseCell(pPage, pCellBody, &pCur->info);
63324          nCell = (int)pCur->info.nKey;
63325          testcase( nCell<0 );   /* True if key size is 2^32 or more */
63326          testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
63327          testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
63328          testcase( nCell==2 );  /* Minimum legal index key size */
63329          if( nCell<2 ){
63330            rc = SQLITE_CORRUPT_BKPT;
63331            goto moveto_finish;
63332          }
63333          pCellKey = sqlite3Malloc( nCell+18 );
63334          if( pCellKey==0 ){
63335            rc = SQLITE_NOMEM_BKPT;
63336            goto moveto_finish;
63337          }
63338          pCur->aiIdx[pCur->iPage] = (u16)idx;
63339          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
63340          if( rc ){
63341            sqlite3_free(pCellKey);
63342            goto moveto_finish;
63343          }
63344          c = xRecordCompare(nCell, pCellKey, pIdxKey);
63345          sqlite3_free(pCellKey);
63346        }
63347        assert(
63348            (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
63349         && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
63350        );
63351        if( c<0 ){
63352          lwr = idx+1;
63353        }else if( c>0 ){
63354          upr = idx-1;
63355        }else{
63356          assert( c==0 );
63357          *pRes = 0;
63358          rc = SQLITE_OK;
63359          pCur->aiIdx[pCur->iPage] = (u16)idx;
63360          if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
63361          goto moveto_finish;
63362        }
63363        if( lwr>upr ) break;
63364        assert( lwr+upr>=0 );
63365        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
63366      }
63367    }
63368    assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
63369    assert( pPage->isInit );
63370    if( pPage->leaf ){
63371      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
63372      pCur->aiIdx[pCur->iPage] = (u16)idx;
63373      *pRes = c;
63374      rc = SQLITE_OK;
63375      goto moveto_finish;
63376    }
63377moveto_next_layer:
63378    if( lwr>=pPage->nCell ){
63379      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
63380    }else{
63381      chldPg = get4byte(findCell(pPage, lwr));
63382    }
63383    pCur->aiIdx[pCur->iPage] = (u16)lwr;
63384    rc = moveToChild(pCur, chldPg);
63385    if( rc ) break;
63386  }
63387moveto_finish:
63388  pCur->info.nSize = 0;
63389  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
63390  return rc;
63391}
63392
63393
63394/*
63395** Return TRUE if the cursor is not pointing at an entry of the table.
63396**
63397** TRUE will be returned after a call to sqlite3BtreeNext() moves
63398** past the last entry in the table or sqlite3BtreePrev() moves past
63399** the first entry.  TRUE is also returned if the table is empty.
63400*/
63401SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
63402  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
63403  ** have been deleted? This API will need to change to return an error code
63404  ** as well as the boolean result value.
63405  */
63406  return (CURSOR_VALID!=pCur->eState);
63407}
63408
63409/*
63410** Advance the cursor to the next entry in the database.  If
63411** successful then set *pRes=0.  If the cursor
63412** was already pointing to the last entry in the database before
63413** this routine was called, then set *pRes=1.
63414**
63415** The main entry point is sqlite3BtreeNext().  That routine is optimized
63416** for the common case of merely incrementing the cell counter BtCursor.aiIdx
63417** to the next cell on the current page.  The (slower) btreeNext() helper
63418** routine is called when it is necessary to move to a different page or
63419** to restore the cursor.
63420**
63421** The calling function will set *pRes to 0 or 1.  The initial *pRes value
63422** will be 1 if the cursor being stepped corresponds to an SQL index and
63423** if this routine could have been skipped if that SQL index had been
63424** a unique index.  Otherwise the caller will have set *pRes to zero.
63425** Zero is the common case. The btree implementation is free to use the
63426** initial *pRes value as a hint to improve performance, but the current
63427** SQLite btree implementation does not. (Note that the comdb2 btree
63428** implementation does use this hint, however.)
63429*/
63430static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
63431  int rc;
63432  int idx;
63433  MemPage *pPage;
63434
63435  assert( cursorOwnsBtShared(pCur) );
63436  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63437  assert( *pRes==0 );
63438  if( pCur->eState!=CURSOR_VALID ){
63439    assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
63440    rc = restoreCursorPosition(pCur);
63441    if( rc!=SQLITE_OK ){
63442      return rc;
63443    }
63444    if( CURSOR_INVALID==pCur->eState ){
63445      *pRes = 1;
63446      return SQLITE_OK;
63447    }
63448    if( pCur->skipNext ){
63449      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
63450      pCur->eState = CURSOR_VALID;
63451      if( pCur->skipNext>0 ){
63452        pCur->skipNext = 0;
63453        return SQLITE_OK;
63454      }
63455      pCur->skipNext = 0;
63456    }
63457  }
63458
63459  pPage = pCur->apPage[pCur->iPage];
63460  idx = ++pCur->aiIdx[pCur->iPage];
63461  assert( pPage->isInit );
63462
63463  /* If the database file is corrupt, it is possible for the value of idx
63464  ** to be invalid here. This can only occur if a second cursor modifies
63465  ** the page while cursor pCur is holding a reference to it. Which can
63466  ** only happen if the database is corrupt in such a way as to link the
63467  ** page into more than one b-tree structure. */
63468  testcase( idx>pPage->nCell );
63469
63470  if( idx>=pPage->nCell ){
63471    if( !pPage->leaf ){
63472      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
63473      if( rc ) return rc;
63474      return moveToLeftmost(pCur);
63475    }
63476    do{
63477      if( pCur->iPage==0 ){
63478        *pRes = 1;
63479        pCur->eState = CURSOR_INVALID;
63480        return SQLITE_OK;
63481      }
63482      moveToParent(pCur);
63483      pPage = pCur->apPage[pCur->iPage];
63484    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
63485    if( pPage->intKey ){
63486      return sqlite3BtreeNext(pCur, pRes);
63487    }else{
63488      return SQLITE_OK;
63489    }
63490  }
63491  if( pPage->leaf ){
63492    return SQLITE_OK;
63493  }else{
63494    return moveToLeftmost(pCur);
63495  }
63496}
63497SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
63498  MemPage *pPage;
63499  assert( cursorOwnsBtShared(pCur) );
63500  assert( pRes!=0 );
63501  assert( *pRes==0 || *pRes==1 );
63502  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63503  pCur->info.nSize = 0;
63504  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
63505  *pRes = 0;
63506  if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
63507  pPage = pCur->apPage[pCur->iPage];
63508  if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
63509    pCur->aiIdx[pCur->iPage]--;
63510    return btreeNext(pCur, pRes);
63511  }
63512  if( pPage->leaf ){
63513    return SQLITE_OK;
63514  }else{
63515    return moveToLeftmost(pCur);
63516  }
63517}
63518
63519/*
63520** Step the cursor to the back to the previous entry in the database.  If
63521** successful then set *pRes=0.  If the cursor
63522** was already pointing to the first entry in the database before
63523** this routine was called, then set *pRes=1.
63524**
63525** The main entry point is sqlite3BtreePrevious().  That routine is optimized
63526** for the common case of merely decrementing the cell counter BtCursor.aiIdx
63527** to the previous cell on the current page.  The (slower) btreePrevious()
63528** helper routine is called when it is necessary to move to a different page
63529** or to restore the cursor.
63530**
63531** The calling function will set *pRes to 0 or 1.  The initial *pRes value
63532** will be 1 if the cursor being stepped corresponds to an SQL index and
63533** if this routine could have been skipped if that SQL index had been
63534** a unique index.  Otherwise the caller will have set *pRes to zero.
63535** Zero is the common case. The btree implementation is free to use the
63536** initial *pRes value as a hint to improve performance, but the current
63537** SQLite btree implementation does not. (Note that the comdb2 btree
63538** implementation does use this hint, however.)
63539*/
63540static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
63541  int rc;
63542  MemPage *pPage;
63543
63544  assert( cursorOwnsBtShared(pCur) );
63545  assert( pRes!=0 );
63546  assert( *pRes==0 );
63547  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63548  assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
63549  assert( pCur->info.nSize==0 );
63550  if( pCur->eState!=CURSOR_VALID ){
63551    rc = restoreCursorPosition(pCur);
63552    if( rc!=SQLITE_OK ){
63553      return rc;
63554    }
63555    if( CURSOR_INVALID==pCur->eState ){
63556      *pRes = 1;
63557      return SQLITE_OK;
63558    }
63559    if( pCur->skipNext ){
63560      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
63561      pCur->eState = CURSOR_VALID;
63562      if( pCur->skipNext<0 ){
63563        pCur->skipNext = 0;
63564        return SQLITE_OK;
63565      }
63566      pCur->skipNext = 0;
63567    }
63568  }
63569
63570  pPage = pCur->apPage[pCur->iPage];
63571  assert( pPage->isInit );
63572  if( !pPage->leaf ){
63573    int idx = pCur->aiIdx[pCur->iPage];
63574    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
63575    if( rc ) return rc;
63576    rc = moveToRightmost(pCur);
63577  }else{
63578    while( pCur->aiIdx[pCur->iPage]==0 ){
63579      if( pCur->iPage==0 ){
63580        pCur->eState = CURSOR_INVALID;
63581        *pRes = 1;
63582        return SQLITE_OK;
63583      }
63584      moveToParent(pCur);
63585    }
63586    assert( pCur->info.nSize==0 );
63587    assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
63588
63589    pCur->aiIdx[pCur->iPage]--;
63590    pPage = pCur->apPage[pCur->iPage];
63591    if( pPage->intKey && !pPage->leaf ){
63592      rc = sqlite3BtreePrevious(pCur, pRes);
63593    }else{
63594      rc = SQLITE_OK;
63595    }
63596  }
63597  return rc;
63598}
63599SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
63600  assert( cursorOwnsBtShared(pCur) );
63601  assert( pRes!=0 );
63602  assert( *pRes==0 || *pRes==1 );
63603  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63604  *pRes = 0;
63605  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
63606  pCur->info.nSize = 0;
63607  if( pCur->eState!=CURSOR_VALID
63608   || pCur->aiIdx[pCur->iPage]==0
63609   || pCur->apPage[pCur->iPage]->leaf==0
63610  ){
63611    return btreePrevious(pCur, pRes);
63612  }
63613  pCur->aiIdx[pCur->iPage]--;
63614  return SQLITE_OK;
63615}
63616
63617/*
63618** Allocate a new page from the database file.
63619**
63620** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
63621** has already been called on the new page.)  The new page has also
63622** been referenced and the calling routine is responsible for calling
63623** sqlite3PagerUnref() on the new page when it is done.
63624**
63625** SQLITE_OK is returned on success.  Any other return value indicates
63626** an error.  *ppPage is set to NULL in the event of an error.
63627**
63628** If the "nearby" parameter is not 0, then an effort is made to
63629** locate a page close to the page number "nearby".  This can be used in an
63630** attempt to keep related pages close to each other in the database file,
63631** which in turn can make database access faster.
63632**
63633** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
63634** anywhere on the free-list, then it is guaranteed to be returned.  If
63635** eMode is BTALLOC_LT then the page returned will be less than or equal
63636** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
63637** are no restrictions on which page is returned.
63638*/
63639static int allocateBtreePage(
63640  BtShared *pBt,         /* The btree */
63641  MemPage **ppPage,      /* Store pointer to the allocated page here */
63642  Pgno *pPgno,           /* Store the page number here */
63643  Pgno nearby,           /* Search for a page near this one */
63644  u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
63645){
63646  MemPage *pPage1;
63647  int rc;
63648  u32 n;     /* Number of pages on the freelist */
63649  u32 k;     /* Number of leaves on the trunk of the freelist */
63650  MemPage *pTrunk = 0;
63651  MemPage *pPrevTrunk = 0;
63652  Pgno mxPage;     /* Total size of the database file */
63653
63654  assert( sqlite3_mutex_held(pBt->mutex) );
63655  assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
63656  pPage1 = pBt->pPage1;
63657  mxPage = btreePagecount(pBt);
63658  /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
63659  ** stores stores the total number of pages on the freelist. */
63660  n = get4byte(&pPage1->aData[36]);
63661  testcase( n==mxPage-1 );
63662  if( n>=mxPage ){
63663    return SQLITE_CORRUPT_BKPT;
63664  }
63665  if( n>0 ){
63666    /* There are pages on the freelist.  Reuse one of those pages. */
63667    Pgno iTrunk;
63668    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
63669    u32 nSearch = 0;   /* Count of the number of search attempts */
63670
63671    /* If eMode==BTALLOC_EXACT and a query of the pointer-map
63672    ** shows that the page 'nearby' is somewhere on the free-list, then
63673    ** the entire-list will be searched for that page.
63674    */
63675#ifndef SQLITE_OMIT_AUTOVACUUM
63676    if( eMode==BTALLOC_EXACT ){
63677      if( nearby<=mxPage ){
63678        u8 eType;
63679        assert( nearby>0 );
63680        assert( pBt->autoVacuum );
63681        rc = ptrmapGet(pBt, nearby, &eType, 0);
63682        if( rc ) return rc;
63683        if( eType==PTRMAP_FREEPAGE ){
63684          searchList = 1;
63685        }
63686      }
63687    }else if( eMode==BTALLOC_LE ){
63688      searchList = 1;
63689    }
63690#endif
63691
63692    /* Decrement the free-list count by 1. Set iTrunk to the index of the
63693    ** first free-list trunk page. iPrevTrunk is initially 1.
63694    */
63695    rc = sqlite3PagerWrite(pPage1->pDbPage);
63696    if( rc ) return rc;
63697    put4byte(&pPage1->aData[36], n-1);
63698
63699    /* The code within this loop is run only once if the 'searchList' variable
63700    ** is not true. Otherwise, it runs once for each trunk-page on the
63701    ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
63702    ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
63703    */
63704    do {
63705      pPrevTrunk = pTrunk;
63706      if( pPrevTrunk ){
63707        /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
63708        ** is the page number of the next freelist trunk page in the list or
63709        ** zero if this is the last freelist trunk page. */
63710        iTrunk = get4byte(&pPrevTrunk->aData[0]);
63711      }else{
63712        /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
63713        ** stores the page number of the first page of the freelist, or zero if
63714        ** the freelist is empty. */
63715        iTrunk = get4byte(&pPage1->aData[32]);
63716      }
63717      testcase( iTrunk==mxPage );
63718      if( iTrunk>mxPage || nSearch++ > n ){
63719        rc = SQLITE_CORRUPT_BKPT;
63720      }else{
63721        rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
63722      }
63723      if( rc ){
63724        pTrunk = 0;
63725        goto end_allocate_page;
63726      }
63727      assert( pTrunk!=0 );
63728      assert( pTrunk->aData!=0 );
63729      /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
63730      ** is the number of leaf page pointers to follow. */
63731      k = get4byte(&pTrunk->aData[4]);
63732      if( k==0 && !searchList ){
63733        /* The trunk has no leaves and the list is not being searched.
63734        ** So extract the trunk page itself and use it as the newly
63735        ** allocated page */
63736        assert( pPrevTrunk==0 );
63737        rc = sqlite3PagerWrite(pTrunk->pDbPage);
63738        if( rc ){
63739          goto end_allocate_page;
63740        }
63741        *pPgno = iTrunk;
63742        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
63743        *ppPage = pTrunk;
63744        pTrunk = 0;
63745        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
63746      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
63747        /* Value of k is out of range.  Database corruption */
63748        rc = SQLITE_CORRUPT_BKPT;
63749        goto end_allocate_page;
63750#ifndef SQLITE_OMIT_AUTOVACUUM
63751      }else if( searchList
63752            && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
63753      ){
63754        /* The list is being searched and this trunk page is the page
63755        ** to allocate, regardless of whether it has leaves.
63756        */
63757        *pPgno = iTrunk;
63758        *ppPage = pTrunk;
63759        searchList = 0;
63760        rc = sqlite3PagerWrite(pTrunk->pDbPage);
63761        if( rc ){
63762          goto end_allocate_page;
63763        }
63764        if( k==0 ){
63765          if( !pPrevTrunk ){
63766            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
63767          }else{
63768            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
63769            if( rc!=SQLITE_OK ){
63770              goto end_allocate_page;
63771            }
63772            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
63773          }
63774        }else{
63775          /* The trunk page is required by the caller but it contains
63776          ** pointers to free-list leaves. The first leaf becomes a trunk
63777          ** page in this case.
63778          */
63779          MemPage *pNewTrunk;
63780          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
63781          if( iNewTrunk>mxPage ){
63782            rc = SQLITE_CORRUPT_BKPT;
63783            goto end_allocate_page;
63784          }
63785          testcase( iNewTrunk==mxPage );
63786          rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
63787          if( rc!=SQLITE_OK ){
63788            goto end_allocate_page;
63789          }
63790          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
63791          if( rc!=SQLITE_OK ){
63792            releasePage(pNewTrunk);
63793            goto end_allocate_page;
63794          }
63795          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
63796          put4byte(&pNewTrunk->aData[4], k-1);
63797          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
63798          releasePage(pNewTrunk);
63799          if( !pPrevTrunk ){
63800            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
63801            put4byte(&pPage1->aData[32], iNewTrunk);
63802          }else{
63803            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
63804            if( rc ){
63805              goto end_allocate_page;
63806            }
63807            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
63808          }
63809        }
63810        pTrunk = 0;
63811        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
63812#endif
63813      }else if( k>0 ){
63814        /* Extract a leaf from the trunk */
63815        u32 closest;
63816        Pgno iPage;
63817        unsigned char *aData = pTrunk->aData;
63818        if( nearby>0 ){
63819          u32 i;
63820          closest = 0;
63821          if( eMode==BTALLOC_LE ){
63822            for(i=0; i<k; i++){
63823              iPage = get4byte(&aData[8+i*4]);
63824              if( iPage<=nearby ){
63825                closest = i;
63826                break;
63827              }
63828            }
63829          }else{
63830            int dist;
63831            dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
63832            for(i=1; i<k; i++){
63833              int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
63834              if( d2<dist ){
63835                closest = i;
63836                dist = d2;
63837              }
63838            }
63839          }
63840        }else{
63841          closest = 0;
63842        }
63843
63844        iPage = get4byte(&aData[8+closest*4]);
63845        testcase( iPage==mxPage );
63846        if( iPage>mxPage ){
63847          rc = SQLITE_CORRUPT_BKPT;
63848          goto end_allocate_page;
63849        }
63850        testcase( iPage==mxPage );
63851        if( !searchList
63852         || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
63853        ){
63854          int noContent;
63855          *pPgno = iPage;
63856          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
63857                 ": %d more free pages\n",
63858                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
63859          rc = sqlite3PagerWrite(pTrunk->pDbPage);
63860          if( rc ) goto end_allocate_page;
63861          if( closest<k-1 ){
63862            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
63863          }
63864          put4byte(&aData[4], k-1);
63865          noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
63866          rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
63867          if( rc==SQLITE_OK ){
63868            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
63869            if( rc!=SQLITE_OK ){
63870              releasePage(*ppPage);
63871              *ppPage = 0;
63872            }
63873          }
63874          searchList = 0;
63875        }
63876      }
63877      releasePage(pPrevTrunk);
63878      pPrevTrunk = 0;
63879    }while( searchList );
63880  }else{
63881    /* There are no pages on the freelist, so append a new page to the
63882    ** database image.
63883    **
63884    ** Normally, new pages allocated by this block can be requested from the
63885    ** pager layer with the 'no-content' flag set. This prevents the pager
63886    ** from trying to read the pages content from disk. However, if the
63887    ** current transaction has already run one or more incremental-vacuum
63888    ** steps, then the page we are about to allocate may contain content
63889    ** that is required in the event of a rollback. In this case, do
63890    ** not set the no-content flag. This causes the pager to load and journal
63891    ** the current page content before overwriting it.
63892    **
63893    ** Note that the pager will not actually attempt to load or journal
63894    ** content for any page that really does lie past the end of the database
63895    ** file on disk. So the effects of disabling the no-content optimization
63896    ** here are confined to those pages that lie between the end of the
63897    ** database image and the end of the database file.
63898    */
63899    int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
63900
63901    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
63902    if( rc ) return rc;
63903    pBt->nPage++;
63904    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
63905
63906#ifndef SQLITE_OMIT_AUTOVACUUM
63907    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
63908      /* If *pPgno refers to a pointer-map page, allocate two new pages
63909      ** at the end of the file instead of one. The first allocated page
63910      ** becomes a new pointer-map page, the second is used by the caller.
63911      */
63912      MemPage *pPg = 0;
63913      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
63914      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
63915      rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
63916      if( rc==SQLITE_OK ){
63917        rc = sqlite3PagerWrite(pPg->pDbPage);
63918        releasePage(pPg);
63919      }
63920      if( rc ) return rc;
63921      pBt->nPage++;
63922      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
63923    }
63924#endif
63925    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
63926    *pPgno = pBt->nPage;
63927
63928    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
63929    rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
63930    if( rc ) return rc;
63931    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
63932    if( rc!=SQLITE_OK ){
63933      releasePage(*ppPage);
63934      *ppPage = 0;
63935    }
63936    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
63937  }
63938
63939  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
63940
63941end_allocate_page:
63942  releasePage(pTrunk);
63943  releasePage(pPrevTrunk);
63944  assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
63945  assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
63946  return rc;
63947}
63948
63949/*
63950** This function is used to add page iPage to the database file free-list.
63951** It is assumed that the page is not already a part of the free-list.
63952**
63953** The value passed as the second argument to this function is optional.
63954** If the caller happens to have a pointer to the MemPage object
63955** corresponding to page iPage handy, it may pass it as the second value.
63956** Otherwise, it may pass NULL.
63957**
63958** If a pointer to a MemPage object is passed as the second argument,
63959** its reference count is not altered by this function.
63960*/
63961static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
63962  MemPage *pTrunk = 0;                /* Free-list trunk page */
63963  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
63964  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
63965  MemPage *pPage;                     /* Page being freed. May be NULL. */
63966  int rc;                             /* Return Code */
63967  int nFree;                          /* Initial number of pages on free-list */
63968
63969  assert( sqlite3_mutex_held(pBt->mutex) );
63970  assert( CORRUPT_DB || iPage>1 );
63971  assert( !pMemPage || pMemPage->pgno==iPage );
63972
63973  if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
63974  if( pMemPage ){
63975    pPage = pMemPage;
63976    sqlite3PagerRef(pPage->pDbPage);
63977  }else{
63978    pPage = btreePageLookup(pBt, iPage);
63979  }
63980
63981  /* Increment the free page count on pPage1 */
63982  rc = sqlite3PagerWrite(pPage1->pDbPage);
63983  if( rc ) goto freepage_out;
63984  nFree = get4byte(&pPage1->aData[36]);
63985  put4byte(&pPage1->aData[36], nFree+1);
63986
63987  if( pBt->btsFlags & BTS_SECURE_DELETE ){
63988    /* If the secure_delete option is enabled, then
63989    ** always fully overwrite deleted information with zeros.
63990    */
63991    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
63992     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
63993    ){
63994      goto freepage_out;
63995    }
63996    memset(pPage->aData, 0, pPage->pBt->pageSize);
63997  }
63998
63999  /* If the database supports auto-vacuum, write an entry in the pointer-map
64000  ** to indicate that the page is free.
64001  */
64002  if( ISAUTOVACUUM ){
64003    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
64004    if( rc ) goto freepage_out;
64005  }
64006
64007  /* Now manipulate the actual database free-list structure. There are two
64008  ** possibilities. If the free-list is currently empty, or if the first
64009  ** trunk page in the free-list is full, then this page will become a
64010  ** new free-list trunk page. Otherwise, it will become a leaf of the
64011  ** first trunk page in the current free-list. This block tests if it
64012  ** is possible to add the page as a new free-list leaf.
64013  */
64014  if( nFree!=0 ){
64015    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
64016
64017    iTrunk = get4byte(&pPage1->aData[32]);
64018    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
64019    if( rc!=SQLITE_OK ){
64020      goto freepage_out;
64021    }
64022
64023    nLeaf = get4byte(&pTrunk->aData[4]);
64024    assert( pBt->usableSize>32 );
64025    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
64026      rc = SQLITE_CORRUPT_BKPT;
64027      goto freepage_out;
64028    }
64029    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
64030      /* In this case there is room on the trunk page to insert the page
64031      ** being freed as a new leaf.
64032      **
64033      ** Note that the trunk page is not really full until it contains
64034      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
64035      ** coded.  But due to a coding error in versions of SQLite prior to
64036      ** 3.6.0, databases with freelist trunk pages holding more than
64037      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
64038      ** to maintain backwards compatibility with older versions of SQLite,
64039      ** we will continue to restrict the number of entries to usableSize/4 - 8
64040      ** for now.  At some point in the future (once everyone has upgraded
64041      ** to 3.6.0 or later) we should consider fixing the conditional above
64042      ** to read "usableSize/4-2" instead of "usableSize/4-8".
64043      **
64044      ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
64045      ** avoid using the last six entries in the freelist trunk page array in
64046      ** order that database files created by newer versions of SQLite can be
64047      ** read by older versions of SQLite.
64048      */
64049      rc = sqlite3PagerWrite(pTrunk->pDbPage);
64050      if( rc==SQLITE_OK ){
64051        put4byte(&pTrunk->aData[4], nLeaf+1);
64052        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
64053        if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
64054          sqlite3PagerDontWrite(pPage->pDbPage);
64055        }
64056        rc = btreeSetHasContent(pBt, iPage);
64057      }
64058      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
64059      goto freepage_out;
64060    }
64061  }
64062
64063  /* If control flows to this point, then it was not possible to add the
64064  ** the page being freed as a leaf page of the first trunk in the free-list.
64065  ** Possibly because the free-list is empty, or possibly because the
64066  ** first trunk in the free-list is full. Either way, the page being freed
64067  ** will become the new first trunk page in the free-list.
64068  */
64069  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
64070    goto freepage_out;
64071  }
64072  rc = sqlite3PagerWrite(pPage->pDbPage);
64073  if( rc!=SQLITE_OK ){
64074    goto freepage_out;
64075  }
64076  put4byte(pPage->aData, iTrunk);
64077  put4byte(&pPage->aData[4], 0);
64078  put4byte(&pPage1->aData[32], iPage);
64079  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
64080
64081freepage_out:
64082  if( pPage ){
64083    pPage->isInit = 0;
64084  }
64085  releasePage(pPage);
64086  releasePage(pTrunk);
64087  return rc;
64088}
64089static void freePage(MemPage *pPage, int *pRC){
64090  if( (*pRC)==SQLITE_OK ){
64091    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
64092  }
64093}
64094
64095/*
64096** Free any overflow pages associated with the given Cell.  Write the
64097** local Cell size (the number of bytes on the original page, omitting
64098** overflow) into *pnSize.
64099*/
64100static int clearCell(
64101  MemPage *pPage,          /* The page that contains the Cell */
64102  unsigned char *pCell,    /* First byte of the Cell */
64103  u16 *pnSize              /* Write the size of the Cell here */
64104){
64105  BtShared *pBt = pPage->pBt;
64106  CellInfo info;
64107  Pgno ovflPgno;
64108  int rc;
64109  int nOvfl;
64110  u32 ovflPageSize;
64111
64112  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64113  pPage->xParseCell(pPage, pCell, &info);
64114  *pnSize = info.nSize;
64115  if( info.nLocal==info.nPayload ){
64116    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
64117  }
64118  if( pCell+info.nSize-1 > pPage->aData+pPage->maskPage ){
64119    return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
64120  }
64121  ovflPgno = get4byte(pCell + info.nSize - 4);
64122  assert( pBt->usableSize > 4 );
64123  ovflPageSize = pBt->usableSize - 4;
64124  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
64125  assert( nOvfl>0 ||
64126    (CORRUPT_DB && (info.nPayload + ovflPageSize)<ovflPageSize)
64127  );
64128  while( nOvfl-- ){
64129    Pgno iNext = 0;
64130    MemPage *pOvfl = 0;
64131    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
64132      /* 0 is not a legal page number and page 1 cannot be an
64133      ** overflow page. Therefore if ovflPgno<2 or past the end of the
64134      ** file the database must be corrupt. */
64135      return SQLITE_CORRUPT_BKPT;
64136    }
64137    if( nOvfl ){
64138      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
64139      if( rc ) return rc;
64140    }
64141
64142    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
64143     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
64144    ){
64145      /* There is no reason any cursor should have an outstanding reference
64146      ** to an overflow page belonging to a cell that is being deleted/updated.
64147      ** So if there exists more than one reference to this page, then it
64148      ** must not really be an overflow page and the database must be corrupt.
64149      ** It is helpful to detect this before calling freePage2(), as
64150      ** freePage2() may zero the page contents if secure-delete mode is
64151      ** enabled. If this 'overflow' page happens to be a page that the
64152      ** caller is iterating through or using in some other way, this
64153      ** can be problematic.
64154      */
64155      rc = SQLITE_CORRUPT_BKPT;
64156    }else{
64157      rc = freePage2(pBt, pOvfl, ovflPgno);
64158    }
64159
64160    if( pOvfl ){
64161      sqlite3PagerUnref(pOvfl->pDbPage);
64162    }
64163    if( rc ) return rc;
64164    ovflPgno = iNext;
64165  }
64166  return SQLITE_OK;
64167}
64168
64169/*
64170** Create the byte sequence used to represent a cell on page pPage
64171** and write that byte sequence into pCell[].  Overflow pages are
64172** allocated and filled in as necessary.  The calling procedure
64173** is responsible for making sure sufficient space has been allocated
64174** for pCell[].
64175**
64176** Note that pCell does not necessary need to point to the pPage->aData
64177** area.  pCell might point to some temporary storage.  The cell will
64178** be constructed in this temporary area then copied into pPage->aData
64179** later.
64180*/
64181static int fillInCell(
64182  MemPage *pPage,                /* The page that contains the cell */
64183  unsigned char *pCell,          /* Complete text of the cell */
64184  const BtreePayload *pX,        /* Payload with which to construct the cell */
64185  int *pnSize                    /* Write cell size here */
64186){
64187  int nPayload;
64188  const u8 *pSrc;
64189  int nSrc, n, rc;
64190  int spaceLeft;
64191  MemPage *pOvfl = 0;
64192  MemPage *pToRelease = 0;
64193  unsigned char *pPrior;
64194  unsigned char *pPayload;
64195  BtShared *pBt = pPage->pBt;
64196  Pgno pgnoOvfl = 0;
64197  int nHeader;
64198
64199  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64200
64201  /* pPage is not necessarily writeable since pCell might be auxiliary
64202  ** buffer space that is separate from the pPage buffer area */
64203  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
64204            || sqlite3PagerIswriteable(pPage->pDbPage) );
64205
64206  /* Fill in the header. */
64207  nHeader = pPage->childPtrSize;
64208  if( pPage->intKey ){
64209    nPayload = pX->nData + pX->nZero;
64210    pSrc = pX->pData;
64211    nSrc = pX->nData;
64212    assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
64213    nHeader += putVarint32(&pCell[nHeader], nPayload);
64214    nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
64215  }else{
64216    assert( pX->nData==0 );
64217    assert( pX->nZero==0 );
64218    assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
64219    nSrc = nPayload = (int)pX->nKey;
64220    pSrc = pX->pKey;
64221    nHeader += putVarint32(&pCell[nHeader], nPayload);
64222  }
64223
64224  /* Fill in the payload */
64225  if( nPayload<=pPage->maxLocal ){
64226    n = nHeader + nPayload;
64227    testcase( n==3 );
64228    testcase( n==4 );
64229    if( n<4 ) n = 4;
64230    *pnSize = n;
64231    spaceLeft = nPayload;
64232    pPrior = pCell;
64233  }else{
64234    int mn = pPage->minLocal;
64235    n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
64236    testcase( n==pPage->maxLocal );
64237    testcase( n==pPage->maxLocal+1 );
64238    if( n > pPage->maxLocal ) n = mn;
64239    spaceLeft = n;
64240    *pnSize = n + nHeader + 4;
64241    pPrior = &pCell[nHeader+n];
64242  }
64243  pPayload = &pCell[nHeader];
64244
64245  /* At this point variables should be set as follows:
64246  **
64247  **   nPayload           Total payload size in bytes
64248  **   pPayload           Begin writing payload here
64249  **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
64250  **                      that means content must spill into overflow pages.
64251  **   *pnSize            Size of the local cell (not counting overflow pages)
64252  **   pPrior             Where to write the pgno of the first overflow page
64253  **
64254  ** Use a call to btreeParseCellPtr() to verify that the values above
64255  ** were computed correctly.
64256  */
64257#if SQLITE_DEBUG
64258  {
64259    CellInfo info;
64260    pPage->xParseCell(pPage, pCell, &info);
64261    assert( nHeader==(int)(info.pPayload - pCell) );
64262    assert( info.nKey==pX->nKey );
64263    assert( *pnSize == info.nSize );
64264    assert( spaceLeft == info.nLocal );
64265  }
64266#endif
64267
64268  /* Write the payload into the local Cell and any extra into overflow pages */
64269  while( nPayload>0 ){
64270    if( spaceLeft==0 ){
64271#ifndef SQLITE_OMIT_AUTOVACUUM
64272      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
64273      if( pBt->autoVacuum ){
64274        do{
64275          pgnoOvfl++;
64276        } while(
64277          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
64278        );
64279      }
64280#endif
64281      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
64282#ifndef SQLITE_OMIT_AUTOVACUUM
64283      /* If the database supports auto-vacuum, and the second or subsequent
64284      ** overflow page is being allocated, add an entry to the pointer-map
64285      ** for that page now.
64286      **
64287      ** If this is the first overflow page, then write a partial entry
64288      ** to the pointer-map. If we write nothing to this pointer-map slot,
64289      ** then the optimistic overflow chain processing in clearCell()
64290      ** may misinterpret the uninitialized values and delete the
64291      ** wrong pages from the database.
64292      */
64293      if( pBt->autoVacuum && rc==SQLITE_OK ){
64294        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
64295        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
64296        if( rc ){
64297          releasePage(pOvfl);
64298        }
64299      }
64300#endif
64301      if( rc ){
64302        releasePage(pToRelease);
64303        return rc;
64304      }
64305
64306      /* If pToRelease is not zero than pPrior points into the data area
64307      ** of pToRelease.  Make sure pToRelease is still writeable. */
64308      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
64309
64310      /* If pPrior is part of the data area of pPage, then make sure pPage
64311      ** is still writeable */
64312      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
64313            || sqlite3PagerIswriteable(pPage->pDbPage) );
64314
64315      put4byte(pPrior, pgnoOvfl);
64316      releasePage(pToRelease);
64317      pToRelease = pOvfl;
64318      pPrior = pOvfl->aData;
64319      put4byte(pPrior, 0);
64320      pPayload = &pOvfl->aData[4];
64321      spaceLeft = pBt->usableSize - 4;
64322    }
64323    n = nPayload;
64324    if( n>spaceLeft ) n = spaceLeft;
64325
64326    /* If pToRelease is not zero than pPayload points into the data area
64327    ** of pToRelease.  Make sure pToRelease is still writeable. */
64328    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
64329
64330    /* If pPayload is part of the data area of pPage, then make sure pPage
64331    ** is still writeable */
64332    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
64333            || sqlite3PagerIswriteable(pPage->pDbPage) );
64334
64335    if( nSrc>0 ){
64336      if( n>nSrc ) n = nSrc;
64337      assert( pSrc );
64338      memcpy(pPayload, pSrc, n);
64339    }else{
64340      memset(pPayload, 0, n);
64341    }
64342    nPayload -= n;
64343    pPayload += n;
64344    pSrc += n;
64345    nSrc -= n;
64346    spaceLeft -= n;
64347  }
64348  releasePage(pToRelease);
64349  return SQLITE_OK;
64350}
64351
64352/*
64353** Remove the i-th cell from pPage.  This routine effects pPage only.
64354** The cell content is not freed or deallocated.  It is assumed that
64355** the cell content has been copied someplace else.  This routine just
64356** removes the reference to the cell from pPage.
64357**
64358** "sz" must be the number of bytes in the cell.
64359*/
64360static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
64361  u32 pc;         /* Offset to cell content of cell being deleted */
64362  u8 *data;       /* pPage->aData */
64363  u8 *ptr;        /* Used to move bytes around within data[] */
64364  int rc;         /* The return code */
64365  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
64366
64367  if( *pRC ) return;
64368
64369  assert( idx>=0 && idx<pPage->nCell );
64370  assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
64371  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
64372  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64373  data = pPage->aData;
64374  ptr = &pPage->aCellIdx[2*idx];
64375  pc = get2byte(ptr);
64376  hdr = pPage->hdrOffset;
64377  testcase( pc==get2byte(&data[hdr+5]) );
64378  testcase( pc+sz==pPage->pBt->usableSize );
64379  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
64380    *pRC = SQLITE_CORRUPT_BKPT;
64381    return;
64382  }
64383  rc = freeSpace(pPage, pc, sz);
64384  if( rc ){
64385    *pRC = rc;
64386    return;
64387  }
64388  pPage->nCell--;
64389  if( pPage->nCell==0 ){
64390    memset(&data[hdr+1], 0, 4);
64391    data[hdr+7] = 0;
64392    put2byte(&data[hdr+5], pPage->pBt->usableSize);
64393    pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
64394                       - pPage->childPtrSize - 8;
64395  }else{
64396    memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
64397    put2byte(&data[hdr+3], pPage->nCell);
64398    pPage->nFree += 2;
64399  }
64400}
64401
64402/*
64403** Insert a new cell on pPage at cell index "i".  pCell points to the
64404** content of the cell.
64405**
64406** If the cell content will fit on the page, then put it there.  If it
64407** will not fit, then make a copy of the cell content into pTemp if
64408** pTemp is not null.  Regardless of pTemp, allocate a new entry
64409** in pPage->apOvfl[] and make it point to the cell content (either
64410** in pTemp or the original pCell) and also record its index.
64411** Allocating a new entry in pPage->aCell[] implies that
64412** pPage->nOverflow is incremented.
64413**
64414** *pRC must be SQLITE_OK when this routine is called.
64415*/
64416static void insertCell(
64417  MemPage *pPage,   /* Page into which we are copying */
64418  int i,            /* New cell becomes the i-th cell of the page */
64419  u8 *pCell,        /* Content of the new cell */
64420  int sz,           /* Bytes of content in pCell */
64421  u8 *pTemp,        /* Temp storage space for pCell, if needed */
64422  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
64423  int *pRC          /* Read and write return code from here */
64424){
64425  int idx = 0;      /* Where to write new cell content in data[] */
64426  int j;            /* Loop counter */
64427  u8 *data;         /* The content of the whole page */
64428  u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
64429
64430  assert( *pRC==SQLITE_OK );
64431  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
64432  assert( MX_CELL(pPage->pBt)<=10921 );
64433  assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
64434  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
64435  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
64436  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64437  /* The cell should normally be sized correctly.  However, when moving a
64438  ** malformed cell from a leaf page to an interior page, if the cell size
64439  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
64440  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
64441  ** the term after the || in the following assert(). */
64442  assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
64443  if( pPage->nOverflow || sz+2>pPage->nFree ){
64444    if( pTemp ){
64445      memcpy(pTemp, pCell, sz);
64446      pCell = pTemp;
64447    }
64448    if( iChild ){
64449      put4byte(pCell, iChild);
64450    }
64451    j = pPage->nOverflow++;
64452    assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
64453    pPage->apOvfl[j] = pCell;
64454    pPage->aiOvfl[j] = (u16)i;
64455
64456    /* When multiple overflows occur, they are always sequential and in
64457    ** sorted order.  This invariants arise because multiple overflows can
64458    ** only occur when inserting divider cells into the parent page during
64459    ** balancing, and the dividers are adjacent and sorted.
64460    */
64461    assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
64462    assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
64463  }else{
64464    int rc = sqlite3PagerWrite(pPage->pDbPage);
64465    if( rc!=SQLITE_OK ){
64466      *pRC = rc;
64467      return;
64468    }
64469    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
64470    data = pPage->aData;
64471    assert( &data[pPage->cellOffset]==pPage->aCellIdx );
64472    rc = allocateSpace(pPage, sz, &idx);
64473    if( rc ){ *pRC = rc; return; }
64474    /* The allocateSpace() routine guarantees the following properties
64475    ** if it returns successfully */
64476    assert( idx >= 0 );
64477    assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
64478    assert( idx+sz <= (int)pPage->pBt->usableSize );
64479    pPage->nFree -= (u16)(2 + sz);
64480    memcpy(&data[idx], pCell, sz);
64481    if( iChild ){
64482      put4byte(&data[idx], iChild);
64483    }
64484    pIns = pPage->aCellIdx + i*2;
64485    memmove(pIns+2, pIns, 2*(pPage->nCell - i));
64486    put2byte(pIns, idx);
64487    pPage->nCell++;
64488    /* increment the cell count */
64489    if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
64490    assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
64491#ifndef SQLITE_OMIT_AUTOVACUUM
64492    if( pPage->pBt->autoVacuum ){
64493      /* The cell may contain a pointer to an overflow page. If so, write
64494      ** the entry for the overflow page into the pointer map.
64495      */
64496      ptrmapPutOvflPtr(pPage, pCell, pRC);
64497    }
64498#endif
64499  }
64500}
64501
64502/*
64503** A CellArray object contains a cache of pointers and sizes for a
64504** consecutive sequence of cells that might be held on multiple pages.
64505*/
64506typedef struct CellArray CellArray;
64507struct CellArray {
64508  int nCell;              /* Number of cells in apCell[] */
64509  MemPage *pRef;          /* Reference page */
64510  u8 **apCell;            /* All cells begin balanced */
64511  u16 *szCell;            /* Local size of all cells in apCell[] */
64512};
64513
64514/*
64515** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
64516** computed.
64517*/
64518static void populateCellCache(CellArray *p, int idx, int N){
64519  assert( idx>=0 && idx+N<=p->nCell );
64520  while( N>0 ){
64521    assert( p->apCell[idx]!=0 );
64522    if( p->szCell[idx]==0 ){
64523      p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
64524    }else{
64525      assert( CORRUPT_DB ||
64526              p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
64527    }
64528    idx++;
64529    N--;
64530  }
64531}
64532
64533/*
64534** Return the size of the Nth element of the cell array
64535*/
64536static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
64537  assert( N>=0 && N<p->nCell );
64538  assert( p->szCell[N]==0 );
64539  p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
64540  return p->szCell[N];
64541}
64542static u16 cachedCellSize(CellArray *p, int N){
64543  assert( N>=0 && N<p->nCell );
64544  if( p->szCell[N] ) return p->szCell[N];
64545  return computeCellSize(p, N);
64546}
64547
64548/*
64549** Array apCell[] contains pointers to nCell b-tree page cells. The
64550** szCell[] array contains the size in bytes of each cell. This function
64551** replaces the current contents of page pPg with the contents of the cell
64552** array.
64553**
64554** Some of the cells in apCell[] may currently be stored in pPg. This
64555** function works around problems caused by this by making a copy of any
64556** such cells before overwriting the page data.
64557**
64558** The MemPage.nFree field is invalidated by this function. It is the
64559** responsibility of the caller to set it correctly.
64560*/
64561static int rebuildPage(
64562  MemPage *pPg,                   /* Edit this page */
64563  int nCell,                      /* Final number of cells on page */
64564  u8 **apCell,                    /* Array of cells */
64565  u16 *szCell                     /* Array of cell sizes */
64566){
64567  const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
64568  u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
64569  const int usableSize = pPg->pBt->usableSize;
64570  u8 * const pEnd = &aData[usableSize];
64571  int i;
64572  u8 *pCellptr = pPg->aCellIdx;
64573  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
64574  u8 *pData;
64575
64576  i = get2byte(&aData[hdr+5]);
64577  memcpy(&pTmp[i], &aData[i], usableSize - i);
64578
64579  pData = pEnd;
64580  for(i=0; i<nCell; i++){
64581    u8 *pCell = apCell[i];
64582    if( SQLITE_WITHIN(pCell,aData,pEnd) ){
64583      pCell = &pTmp[pCell - aData];
64584    }
64585    pData -= szCell[i];
64586    put2byte(pCellptr, (pData - aData));
64587    pCellptr += 2;
64588    if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
64589    memcpy(pData, pCell, szCell[i]);
64590    assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
64591    testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
64592  }
64593
64594  /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
64595  pPg->nCell = nCell;
64596  pPg->nOverflow = 0;
64597
64598  put2byte(&aData[hdr+1], 0);
64599  put2byte(&aData[hdr+3], pPg->nCell);
64600  put2byte(&aData[hdr+5], pData - aData);
64601  aData[hdr+7] = 0x00;
64602  return SQLITE_OK;
64603}
64604
64605/*
64606** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
64607** contains the size in bytes of each such cell. This function attempts to
64608** add the cells stored in the array to page pPg. If it cannot (because
64609** the page needs to be defragmented before the cells will fit), non-zero
64610** is returned. Otherwise, if the cells are added successfully, zero is
64611** returned.
64612**
64613** Argument pCellptr points to the first entry in the cell-pointer array
64614** (part of page pPg) to populate. After cell apCell[0] is written to the
64615** page body, a 16-bit offset is written to pCellptr. And so on, for each
64616** cell in the array. It is the responsibility of the caller to ensure
64617** that it is safe to overwrite this part of the cell-pointer array.
64618**
64619** When this function is called, *ppData points to the start of the
64620** content area on page pPg. If the size of the content area is extended,
64621** *ppData is updated to point to the new start of the content area
64622** before returning.
64623**
64624** Finally, argument pBegin points to the byte immediately following the
64625** end of the space required by this page for the cell-pointer area (for
64626** all cells - not just those inserted by the current call). If the content
64627** area must be extended to before this point in order to accomodate all
64628** cells in apCell[], then the cells do not fit and non-zero is returned.
64629*/
64630static int pageInsertArray(
64631  MemPage *pPg,                   /* Page to add cells to */
64632  u8 *pBegin,                     /* End of cell-pointer array */
64633  u8 **ppData,                    /* IN/OUT: Page content -area pointer */
64634  u8 *pCellptr,                   /* Pointer to cell-pointer area */
64635  int iFirst,                     /* Index of first cell to add */
64636  int nCell,                      /* Number of cells to add to pPg */
64637  CellArray *pCArray              /* Array of cells */
64638){
64639  int i;
64640  u8 *aData = pPg->aData;
64641  u8 *pData = *ppData;
64642  int iEnd = iFirst + nCell;
64643  assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
64644  for(i=iFirst; i<iEnd; i++){
64645    int sz, rc;
64646    u8 *pSlot;
64647    sz = cachedCellSize(pCArray, i);
64648    if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
64649      if( (pData - pBegin)<sz ) return 1;
64650      pData -= sz;
64651      pSlot = pData;
64652    }
64653    /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
64654    ** database.  But they might for a corrupt database.  Hence use memmove()
64655    ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
64656    assert( (pSlot+sz)<=pCArray->apCell[i]
64657         || pSlot>=(pCArray->apCell[i]+sz)
64658         || CORRUPT_DB );
64659    memmove(pSlot, pCArray->apCell[i], sz);
64660    put2byte(pCellptr, (pSlot - aData));
64661    pCellptr += 2;
64662  }
64663  *ppData = pData;
64664  return 0;
64665}
64666
64667/*
64668** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
64669** contains the size in bytes of each such cell. This function adds the
64670** space associated with each cell in the array that is currently stored
64671** within the body of pPg to the pPg free-list. The cell-pointers and other
64672** fields of the page are not updated.
64673**
64674** This function returns the total number of cells added to the free-list.
64675*/
64676static int pageFreeArray(
64677  MemPage *pPg,                   /* Page to edit */
64678  int iFirst,                     /* First cell to delete */
64679  int nCell,                      /* Cells to delete */
64680  CellArray *pCArray              /* Array of cells */
64681){
64682  u8 * const aData = pPg->aData;
64683  u8 * const pEnd = &aData[pPg->pBt->usableSize];
64684  u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
64685  int nRet = 0;
64686  int i;
64687  int iEnd = iFirst + nCell;
64688  u8 *pFree = 0;
64689  int szFree = 0;
64690
64691  for(i=iFirst; i<iEnd; i++){
64692    u8 *pCell = pCArray->apCell[i];
64693    if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
64694      int sz;
64695      /* No need to use cachedCellSize() here.  The sizes of all cells that
64696      ** are to be freed have already been computing while deciding which
64697      ** cells need freeing */
64698      sz = pCArray->szCell[i];  assert( sz>0 );
64699      if( pFree!=(pCell + sz) ){
64700        if( pFree ){
64701          assert( pFree>aData && (pFree - aData)<65536 );
64702          freeSpace(pPg, (u16)(pFree - aData), szFree);
64703        }
64704        pFree = pCell;
64705        szFree = sz;
64706        if( pFree+sz>pEnd ) return 0;
64707      }else{
64708        pFree = pCell;
64709        szFree += sz;
64710      }
64711      nRet++;
64712    }
64713  }
64714  if( pFree ){
64715    assert( pFree>aData && (pFree - aData)<65536 );
64716    freeSpace(pPg, (u16)(pFree - aData), szFree);
64717  }
64718  return nRet;
64719}
64720
64721/*
64722** apCell[] and szCell[] contains pointers to and sizes of all cells in the
64723** pages being balanced.  The current page, pPg, has pPg->nCell cells starting
64724** with apCell[iOld].  After balancing, this page should hold nNew cells
64725** starting at apCell[iNew].
64726**
64727** This routine makes the necessary adjustments to pPg so that it contains
64728** the correct cells after being balanced.
64729**
64730** The pPg->nFree field is invalid when this function returns. It is the
64731** responsibility of the caller to set it correctly.
64732*/
64733static int editPage(
64734  MemPage *pPg,                   /* Edit this page */
64735  int iOld,                       /* Index of first cell currently on page */
64736  int iNew,                       /* Index of new first cell on page */
64737  int nNew,                       /* Final number of cells on page */
64738  CellArray *pCArray              /* Array of cells and sizes */
64739){
64740  u8 * const aData = pPg->aData;
64741  const int hdr = pPg->hdrOffset;
64742  u8 *pBegin = &pPg->aCellIdx[nNew * 2];
64743  int nCell = pPg->nCell;       /* Cells stored on pPg */
64744  u8 *pData;
64745  u8 *pCellptr;
64746  int i;
64747  int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
64748  int iNewEnd = iNew + nNew;
64749
64750#ifdef SQLITE_DEBUG
64751  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
64752  memcpy(pTmp, aData, pPg->pBt->usableSize);
64753#endif
64754
64755  /* Remove cells from the start and end of the page */
64756  if( iOld<iNew ){
64757    int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
64758    memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
64759    nCell -= nShift;
64760  }
64761  if( iNewEnd < iOldEnd ){
64762    nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
64763  }
64764
64765  pData = &aData[get2byteNotZero(&aData[hdr+5])];
64766  if( pData<pBegin ) goto editpage_fail;
64767
64768  /* Add cells to the start of the page */
64769  if( iNew<iOld ){
64770    int nAdd = MIN(nNew,iOld-iNew);
64771    assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
64772    pCellptr = pPg->aCellIdx;
64773    memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
64774    if( pageInsertArray(
64775          pPg, pBegin, &pData, pCellptr,
64776          iNew, nAdd, pCArray
64777    ) ) goto editpage_fail;
64778    nCell += nAdd;
64779  }
64780
64781  /* Add any overflow cells */
64782  for(i=0; i<pPg->nOverflow; i++){
64783    int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
64784    if( iCell>=0 && iCell<nNew ){
64785      pCellptr = &pPg->aCellIdx[iCell * 2];
64786      memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
64787      nCell++;
64788      if( pageInsertArray(
64789            pPg, pBegin, &pData, pCellptr,
64790            iCell+iNew, 1, pCArray
64791      ) ) goto editpage_fail;
64792    }
64793  }
64794
64795  /* Append cells to the end of the page */
64796  pCellptr = &pPg->aCellIdx[nCell*2];
64797  if( pageInsertArray(
64798        pPg, pBegin, &pData, pCellptr,
64799        iNew+nCell, nNew-nCell, pCArray
64800  ) ) goto editpage_fail;
64801
64802  pPg->nCell = nNew;
64803  pPg->nOverflow = 0;
64804
64805  put2byte(&aData[hdr+3], pPg->nCell);
64806  put2byte(&aData[hdr+5], pData - aData);
64807
64808#ifdef SQLITE_DEBUG
64809  for(i=0; i<nNew && !CORRUPT_DB; i++){
64810    u8 *pCell = pCArray->apCell[i+iNew];
64811    int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
64812    if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
64813      pCell = &pTmp[pCell - aData];
64814    }
64815    assert( 0==memcmp(pCell, &aData[iOff],
64816            pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
64817  }
64818#endif
64819
64820  return SQLITE_OK;
64821 editpage_fail:
64822  /* Unable to edit this page. Rebuild it from scratch instead. */
64823  populateCellCache(pCArray, iNew, nNew);
64824  return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
64825}
64826
64827/*
64828** The following parameters determine how many adjacent pages get involved
64829** in a balancing operation.  NN is the number of neighbors on either side
64830** of the page that participate in the balancing operation.  NB is the
64831** total number of pages that participate, including the target page and
64832** NN neighbors on either side.
64833**
64834** The minimum value of NN is 1 (of course).  Increasing NN above 1
64835** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
64836** in exchange for a larger degradation in INSERT and UPDATE performance.
64837** The value of NN appears to give the best results overall.
64838*/
64839#define NN 1             /* Number of neighbors on either side of pPage */
64840#define NB (NN*2+1)      /* Total pages involved in the balance */
64841
64842
64843#ifndef SQLITE_OMIT_QUICKBALANCE
64844/*
64845** This version of balance() handles the common special case where
64846** a new entry is being inserted on the extreme right-end of the
64847** tree, in other words, when the new entry will become the largest
64848** entry in the tree.
64849**
64850** Instead of trying to balance the 3 right-most leaf pages, just add
64851** a new page to the right-hand side and put the one new entry in
64852** that page.  This leaves the right side of the tree somewhat
64853** unbalanced.  But odds are that we will be inserting new entries
64854** at the end soon afterwards so the nearly empty page will quickly
64855** fill up.  On average.
64856**
64857** pPage is the leaf page which is the right-most page in the tree.
64858** pParent is its parent.  pPage must have a single overflow entry
64859** which is also the right-most entry on the page.
64860**
64861** The pSpace buffer is used to store a temporary copy of the divider
64862** cell that will be inserted into pParent. Such a cell consists of a 4
64863** byte page number followed by a variable length integer. In other
64864** words, at most 13 bytes. Hence the pSpace buffer must be at
64865** least 13 bytes in size.
64866*/
64867static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
64868  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
64869  MemPage *pNew;                       /* Newly allocated page */
64870  int rc;                              /* Return Code */
64871  Pgno pgnoNew;                        /* Page number of pNew */
64872
64873  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64874  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
64875  assert( pPage->nOverflow==1 );
64876
64877  /* This error condition is now caught prior to reaching this function */
64878  if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
64879
64880  /* Allocate a new page. This page will become the right-sibling of
64881  ** pPage. Make the parent page writable, so that the new divider cell
64882  ** may be inserted. If both these operations are successful, proceed.
64883  */
64884  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
64885
64886  if( rc==SQLITE_OK ){
64887
64888    u8 *pOut = &pSpace[4];
64889    u8 *pCell = pPage->apOvfl[0];
64890    u16 szCell = pPage->xCellSize(pPage, pCell);
64891    u8 *pStop;
64892
64893    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
64894    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
64895    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
64896    rc = rebuildPage(pNew, 1, &pCell, &szCell);
64897    if( NEVER(rc) ) return rc;
64898    pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
64899
64900    /* If this is an auto-vacuum database, update the pointer map
64901    ** with entries for the new page, and any pointer from the
64902    ** cell on the page to an overflow page. If either of these
64903    ** operations fails, the return code is set, but the contents
64904    ** of the parent page are still manipulated by thh code below.
64905    ** That is Ok, at this point the parent page is guaranteed to
64906    ** be marked as dirty. Returning an error code will cause a
64907    ** rollback, undoing any changes made to the parent page.
64908    */
64909    if( ISAUTOVACUUM ){
64910      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
64911      if( szCell>pNew->minLocal ){
64912        ptrmapPutOvflPtr(pNew, pCell, &rc);
64913      }
64914    }
64915
64916    /* Create a divider cell to insert into pParent. The divider cell
64917    ** consists of a 4-byte page number (the page number of pPage) and
64918    ** a variable length key value (which must be the same value as the
64919    ** largest key on pPage).
64920    **
64921    ** To find the largest key value on pPage, first find the right-most
64922    ** cell on pPage. The first two fields of this cell are the
64923    ** record-length (a variable length integer at most 32-bits in size)
64924    ** and the key value (a variable length integer, may have any value).
64925    ** The first of the while(...) loops below skips over the record-length
64926    ** field. The second while(...) loop copies the key value from the
64927    ** cell on pPage into the pSpace buffer.
64928    */
64929    pCell = findCell(pPage, pPage->nCell-1);
64930    pStop = &pCell[9];
64931    while( (*(pCell++)&0x80) && pCell<pStop );
64932    pStop = &pCell[9];
64933    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
64934
64935    /* Insert the new divider cell into pParent. */
64936    if( rc==SQLITE_OK ){
64937      insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
64938                   0, pPage->pgno, &rc);
64939    }
64940
64941    /* Set the right-child pointer of pParent to point to the new page. */
64942    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
64943
64944    /* Release the reference to the new page. */
64945    releasePage(pNew);
64946  }
64947
64948  return rc;
64949}
64950#endif /* SQLITE_OMIT_QUICKBALANCE */
64951
64952#if 0
64953/*
64954** This function does not contribute anything to the operation of SQLite.
64955** it is sometimes activated temporarily while debugging code responsible
64956** for setting pointer-map entries.
64957*/
64958static int ptrmapCheckPages(MemPage **apPage, int nPage){
64959  int i, j;
64960  for(i=0; i<nPage; i++){
64961    Pgno n;
64962    u8 e;
64963    MemPage *pPage = apPage[i];
64964    BtShared *pBt = pPage->pBt;
64965    assert( pPage->isInit );
64966
64967    for(j=0; j<pPage->nCell; j++){
64968      CellInfo info;
64969      u8 *z;
64970
64971      z = findCell(pPage, j);
64972      pPage->xParseCell(pPage, z, &info);
64973      if( info.nLocal<info.nPayload ){
64974        Pgno ovfl = get4byte(&z[info.nSize-4]);
64975        ptrmapGet(pBt, ovfl, &e, &n);
64976        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
64977      }
64978      if( !pPage->leaf ){
64979        Pgno child = get4byte(z);
64980        ptrmapGet(pBt, child, &e, &n);
64981        assert( n==pPage->pgno && e==PTRMAP_BTREE );
64982      }
64983    }
64984    if( !pPage->leaf ){
64985      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
64986      ptrmapGet(pBt, child, &e, &n);
64987      assert( n==pPage->pgno && e==PTRMAP_BTREE );
64988    }
64989  }
64990  return 1;
64991}
64992#endif
64993
64994/*
64995** This function is used to copy the contents of the b-tree node stored
64996** on page pFrom to page pTo. If page pFrom was not a leaf page, then
64997** the pointer-map entries for each child page are updated so that the
64998** parent page stored in the pointer map is page pTo. If pFrom contained
64999** any cells with overflow page pointers, then the corresponding pointer
65000** map entries are also updated so that the parent page is page pTo.
65001**
65002** If pFrom is currently carrying any overflow cells (entries in the
65003** MemPage.apOvfl[] array), they are not copied to pTo.
65004**
65005** Before returning, page pTo is reinitialized using btreeInitPage().
65006**
65007** The performance of this function is not critical. It is only used by
65008** the balance_shallower() and balance_deeper() procedures, neither of
65009** which are called often under normal circumstances.
65010*/
65011static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
65012  if( (*pRC)==SQLITE_OK ){
65013    BtShared * const pBt = pFrom->pBt;
65014    u8 * const aFrom = pFrom->aData;
65015    u8 * const aTo = pTo->aData;
65016    int const iFromHdr = pFrom->hdrOffset;
65017    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
65018    int rc;
65019    int iData;
65020
65021
65022    assert( pFrom->isInit );
65023    assert( pFrom->nFree>=iToHdr );
65024    assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
65025
65026    /* Copy the b-tree node content from page pFrom to page pTo. */
65027    iData = get2byte(&aFrom[iFromHdr+5]);
65028    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
65029    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
65030
65031    /* Reinitialize page pTo so that the contents of the MemPage structure
65032    ** match the new data. The initialization of pTo can actually fail under
65033    ** fairly obscure circumstances, even though it is a copy of initialized
65034    ** page pFrom.
65035    */
65036    pTo->isInit = 0;
65037    rc = btreeInitPage(pTo);
65038    if( rc!=SQLITE_OK ){
65039      *pRC = rc;
65040      return;
65041    }
65042
65043    /* If this is an auto-vacuum database, update the pointer-map entries
65044    ** for any b-tree or overflow pages that pTo now contains the pointers to.
65045    */
65046    if( ISAUTOVACUUM ){
65047      *pRC = setChildPtrmaps(pTo);
65048    }
65049  }
65050}
65051
65052/*
65053** This routine redistributes cells on the iParentIdx'th child of pParent
65054** (hereafter "the page") and up to 2 siblings so that all pages have about the
65055** same amount of free space. Usually a single sibling on either side of the
65056** page are used in the balancing, though both siblings might come from one
65057** side if the page is the first or last child of its parent. If the page
65058** has fewer than 2 siblings (something which can only happen if the page
65059** is a root page or a child of a root page) then all available siblings
65060** participate in the balancing.
65061**
65062** The number of siblings of the page might be increased or decreased by
65063** one or two in an effort to keep pages nearly full but not over full.
65064**
65065** Note that when this routine is called, some of the cells on the page
65066** might not actually be stored in MemPage.aData[]. This can happen
65067** if the page is overfull. This routine ensures that all cells allocated
65068** to the page and its siblings fit into MemPage.aData[] before returning.
65069**
65070** In the course of balancing the page and its siblings, cells may be
65071** inserted into or removed from the parent page (pParent). Doing so
65072** may cause the parent page to become overfull or underfull. If this
65073** happens, it is the responsibility of the caller to invoke the correct
65074** balancing routine to fix this problem (see the balance() routine).
65075**
65076** If this routine fails for any reason, it might leave the database
65077** in a corrupted state. So if this routine fails, the database should
65078** be rolled back.
65079**
65080** The third argument to this function, aOvflSpace, is a pointer to a
65081** buffer big enough to hold one page. If while inserting cells into the parent
65082** page (pParent) the parent page becomes overfull, this buffer is
65083** used to store the parent's overflow cells. Because this function inserts
65084** a maximum of four divider cells into the parent page, and the maximum
65085** size of a cell stored within an internal node is always less than 1/4
65086** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
65087** enough for all overflow cells.
65088**
65089** If aOvflSpace is set to a null pointer, this function returns
65090** SQLITE_NOMEM.
65091*/
65092static int balance_nonroot(
65093  MemPage *pParent,               /* Parent page of siblings being balanced */
65094  int iParentIdx,                 /* Index of "the page" in pParent */
65095  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
65096  int isRoot,                     /* True if pParent is a root-page */
65097  int bBulk                       /* True if this call is part of a bulk load */
65098){
65099  BtShared *pBt;               /* The whole database */
65100  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
65101  int nNew = 0;                /* Number of pages in apNew[] */
65102  int nOld;                    /* Number of pages in apOld[] */
65103  int i, j, k;                 /* Loop counters */
65104  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
65105  int rc = SQLITE_OK;          /* The return code */
65106  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
65107  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
65108  int usableSpace;             /* Bytes in pPage beyond the header */
65109  int pageFlags;               /* Value of pPage->aData[0] */
65110  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
65111  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
65112  int szScratch;               /* Size of scratch memory requested */
65113  MemPage *apOld[NB];          /* pPage and up to two siblings */
65114  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
65115  u8 *pRight;                  /* Location in parent of right-sibling pointer */
65116  u8 *apDiv[NB-1];             /* Divider cells in pParent */
65117  int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
65118  int cntOld[NB+2];            /* Old index in b.apCell[] */
65119  int szNew[NB+2];             /* Combined size of cells placed on i-th page */
65120  u8 *aSpace1;                 /* Space for copies of dividers cells */
65121  Pgno pgno;                   /* Temp var to store a page number in */
65122  u8 abDone[NB+2];             /* True after i'th new page is populated */
65123  Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
65124  Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
65125  u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
65126  CellArray b;                  /* Parsed information on cells being balanced */
65127
65128  memset(abDone, 0, sizeof(abDone));
65129  b.nCell = 0;
65130  b.apCell = 0;
65131  pBt = pParent->pBt;
65132  assert( sqlite3_mutex_held(pBt->mutex) );
65133  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65134
65135#if 0
65136  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
65137#endif
65138
65139  /* At this point pParent may have at most one overflow cell. And if
65140  ** this overflow cell is present, it must be the cell with
65141  ** index iParentIdx. This scenario comes about when this function
65142  ** is called (indirectly) from sqlite3BtreeDelete().
65143  */
65144  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
65145  assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
65146
65147  if( !aOvflSpace ){
65148    return SQLITE_NOMEM_BKPT;
65149  }
65150
65151  /* Find the sibling pages to balance. Also locate the cells in pParent
65152  ** that divide the siblings. An attempt is made to find NN siblings on
65153  ** either side of pPage. More siblings are taken from one side, however,
65154  ** if there are fewer than NN siblings on the other side. If pParent
65155  ** has NB or fewer children then all children of pParent are taken.
65156  **
65157  ** This loop also drops the divider cells from the parent page. This
65158  ** way, the remainder of the function does not have to deal with any
65159  ** overflow cells in the parent page, since if any existed they will
65160  ** have already been removed.
65161  */
65162  i = pParent->nOverflow + pParent->nCell;
65163  if( i<2 ){
65164    nxDiv = 0;
65165  }else{
65166    assert( bBulk==0 || bBulk==1 );
65167    if( iParentIdx==0 ){
65168      nxDiv = 0;
65169    }else if( iParentIdx==i ){
65170      nxDiv = i-2+bBulk;
65171    }else{
65172      nxDiv = iParentIdx-1;
65173    }
65174    i = 2-bBulk;
65175  }
65176  nOld = i+1;
65177  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
65178    pRight = &pParent->aData[pParent->hdrOffset+8];
65179  }else{
65180    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
65181  }
65182  pgno = get4byte(pRight);
65183  while( 1 ){
65184    rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
65185    if( rc ){
65186      memset(apOld, 0, (i+1)*sizeof(MemPage*));
65187      goto balance_cleanup;
65188    }
65189    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
65190    if( (i--)==0 ) break;
65191
65192    if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
65193      apDiv[i] = pParent->apOvfl[0];
65194      pgno = get4byte(apDiv[i]);
65195      szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
65196      pParent->nOverflow = 0;
65197    }else{
65198      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
65199      pgno = get4byte(apDiv[i]);
65200      szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
65201
65202      /* Drop the cell from the parent page. apDiv[i] still points to
65203      ** the cell within the parent, even though it has been dropped.
65204      ** This is safe because dropping a cell only overwrites the first
65205      ** four bytes of it, and this function does not need the first
65206      ** four bytes of the divider cell. So the pointer is safe to use
65207      ** later on.
65208      **
65209      ** But not if we are in secure-delete mode. In secure-delete mode,
65210      ** the dropCell() routine will overwrite the entire cell with zeroes.
65211      ** In this case, temporarily copy the cell into the aOvflSpace[]
65212      ** buffer. It will be copied out again as soon as the aSpace[] buffer
65213      ** is allocated.  */
65214      if( pBt->btsFlags & BTS_SECURE_DELETE ){
65215        int iOff;
65216
65217        iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
65218        if( (iOff+szNew[i])>(int)pBt->usableSize ){
65219          rc = SQLITE_CORRUPT_BKPT;
65220          memset(apOld, 0, (i+1)*sizeof(MemPage*));
65221          goto balance_cleanup;
65222        }else{
65223          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
65224          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
65225        }
65226      }
65227      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
65228    }
65229  }
65230
65231  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
65232  ** alignment */
65233  nMaxCells = (nMaxCells + 3)&~3;
65234
65235  /*
65236  ** Allocate space for memory structures
65237  */
65238  szScratch =
65239       nMaxCells*sizeof(u8*)                       /* b.apCell */
65240     + nMaxCells*sizeof(u16)                       /* b.szCell */
65241     + pBt->pageSize;                              /* aSpace1 */
65242
65243  /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
65244  ** that is more than 6 times the database page size. */
65245  assert( szScratch<=6*(int)pBt->pageSize );
65246  b.apCell = sqlite3ScratchMalloc( szScratch );
65247  if( b.apCell==0 ){
65248    rc = SQLITE_NOMEM_BKPT;
65249    goto balance_cleanup;
65250  }
65251  b.szCell = (u16*)&b.apCell[nMaxCells];
65252  aSpace1 = (u8*)&b.szCell[nMaxCells];
65253  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
65254
65255  /*
65256  ** Load pointers to all cells on sibling pages and the divider cells
65257  ** into the local b.apCell[] array.  Make copies of the divider cells
65258  ** into space obtained from aSpace1[]. The divider cells have already
65259  ** been removed from pParent.
65260  **
65261  ** If the siblings are on leaf pages, then the child pointers of the
65262  ** divider cells are stripped from the cells before they are copied
65263  ** into aSpace1[].  In this way, all cells in b.apCell[] are without
65264  ** child pointers.  If siblings are not leaves, then all cell in
65265  ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
65266  ** are alike.
65267  **
65268  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
65269  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
65270  */
65271  b.pRef = apOld[0];
65272  leafCorrection = b.pRef->leaf*4;
65273  leafData = b.pRef->intKeyLeaf;
65274  for(i=0; i<nOld; i++){
65275    MemPage *pOld = apOld[i];
65276    int limit = pOld->nCell;
65277    u8 *aData = pOld->aData;
65278    u16 maskPage = pOld->maskPage;
65279    u8 *piCell = aData + pOld->cellOffset;
65280    u8 *piEnd;
65281
65282    /* Verify that all sibling pages are of the same "type" (table-leaf,
65283    ** table-interior, index-leaf, or index-interior).
65284    */
65285    if( pOld->aData[0]!=apOld[0]->aData[0] ){
65286      rc = SQLITE_CORRUPT_BKPT;
65287      goto balance_cleanup;
65288    }
65289
65290    /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
65291    ** constains overflow cells, include them in the b.apCell[] array
65292    ** in the correct spot.
65293    **
65294    ** Note that when there are multiple overflow cells, it is always the
65295    ** case that they are sequential and adjacent.  This invariant arises
65296    ** because multiple overflows can only occurs when inserting divider
65297    ** cells into a parent on a prior balance, and divider cells are always
65298    ** adjacent and are inserted in order.  There is an assert() tagged
65299    ** with "NOTE 1" in the overflow cell insertion loop to prove this
65300    ** invariant.
65301    **
65302    ** This must be done in advance.  Once the balance starts, the cell
65303    ** offset section of the btree page will be overwritten and we will no
65304    ** long be able to find the cells if a pointer to each cell is not saved
65305    ** first.
65306    */
65307    memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
65308    if( pOld->nOverflow>0 ){
65309      limit = pOld->aiOvfl[0];
65310      for(j=0; j<limit; j++){
65311        b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
65312        piCell += 2;
65313        b.nCell++;
65314      }
65315      for(k=0; k<pOld->nOverflow; k++){
65316        assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
65317        b.apCell[b.nCell] = pOld->apOvfl[k];
65318        b.nCell++;
65319      }
65320    }
65321    piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
65322    while( piCell<piEnd ){
65323      assert( b.nCell<nMaxCells );
65324      b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
65325      piCell += 2;
65326      b.nCell++;
65327    }
65328
65329    cntOld[i] = b.nCell;
65330    if( i<nOld-1 && !leafData){
65331      u16 sz = (u16)szNew[i];
65332      u8 *pTemp;
65333      assert( b.nCell<nMaxCells );
65334      b.szCell[b.nCell] = sz;
65335      pTemp = &aSpace1[iSpace1];
65336      iSpace1 += sz;
65337      assert( sz<=pBt->maxLocal+23 );
65338      assert( iSpace1 <= (int)pBt->pageSize );
65339      memcpy(pTemp, apDiv[i], sz);
65340      b.apCell[b.nCell] = pTemp+leafCorrection;
65341      assert( leafCorrection==0 || leafCorrection==4 );
65342      b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
65343      if( !pOld->leaf ){
65344        assert( leafCorrection==0 );
65345        assert( pOld->hdrOffset==0 );
65346        /* The right pointer of the child page pOld becomes the left
65347        ** pointer of the divider cell */
65348        memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
65349      }else{
65350        assert( leafCorrection==4 );
65351        while( b.szCell[b.nCell]<4 ){
65352          /* Do not allow any cells smaller than 4 bytes. If a smaller cell
65353          ** does exist, pad it with 0x00 bytes. */
65354          assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
65355          assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
65356          aSpace1[iSpace1++] = 0x00;
65357          b.szCell[b.nCell]++;
65358        }
65359      }
65360      b.nCell++;
65361    }
65362  }
65363
65364  /*
65365  ** Figure out the number of pages needed to hold all b.nCell cells.
65366  ** Store this number in "k".  Also compute szNew[] which is the total
65367  ** size of all cells on the i-th page and cntNew[] which is the index
65368  ** in b.apCell[] of the cell that divides page i from page i+1.
65369  ** cntNew[k] should equal b.nCell.
65370  **
65371  ** Values computed by this block:
65372  **
65373  **           k: The total number of sibling pages
65374  **    szNew[i]: Spaced used on the i-th sibling page.
65375  **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
65376  **              the right of the i-th sibling page.
65377  ** usableSpace: Number of bytes of space available on each sibling.
65378  **
65379  */
65380  usableSpace = pBt->usableSize - 12 + leafCorrection;
65381  for(i=0; i<nOld; i++){
65382    MemPage *p = apOld[i];
65383    szNew[i] = usableSpace - p->nFree;
65384    if( szNew[i]<0 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
65385    for(j=0; j<p->nOverflow; j++){
65386      szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
65387    }
65388    cntNew[i] = cntOld[i];
65389  }
65390  k = nOld;
65391  for(i=0; i<k; i++){
65392    int sz;
65393    while( szNew[i]>usableSpace ){
65394      if( i+1>=k ){
65395        k = i+2;
65396        if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
65397        szNew[k-1] = 0;
65398        cntNew[k-1] = b.nCell;
65399      }
65400      sz = 2 + cachedCellSize(&b, cntNew[i]-1);
65401      szNew[i] -= sz;
65402      if( !leafData ){
65403        if( cntNew[i]<b.nCell ){
65404          sz = 2 + cachedCellSize(&b, cntNew[i]);
65405        }else{
65406          sz = 0;
65407        }
65408      }
65409      szNew[i+1] += sz;
65410      cntNew[i]--;
65411    }
65412    while( cntNew[i]<b.nCell ){
65413      sz = 2 + cachedCellSize(&b, cntNew[i]);
65414      if( szNew[i]+sz>usableSpace ) break;
65415      szNew[i] += sz;
65416      cntNew[i]++;
65417      if( !leafData ){
65418        if( cntNew[i]<b.nCell ){
65419          sz = 2 + cachedCellSize(&b, cntNew[i]);
65420        }else{
65421          sz = 0;
65422        }
65423      }
65424      szNew[i+1] -= sz;
65425    }
65426    if( cntNew[i]>=b.nCell ){
65427      k = i+1;
65428    }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
65429      rc = SQLITE_CORRUPT_BKPT;
65430      goto balance_cleanup;
65431    }
65432  }
65433
65434  /*
65435  ** The packing computed by the previous block is biased toward the siblings
65436  ** on the left side (siblings with smaller keys). The left siblings are
65437  ** always nearly full, while the right-most sibling might be nearly empty.
65438  ** The next block of code attempts to adjust the packing of siblings to
65439  ** get a better balance.
65440  **
65441  ** This adjustment is more than an optimization.  The packing above might
65442  ** be so out of balance as to be illegal.  For example, the right-most
65443  ** sibling might be completely empty.  This adjustment is not optional.
65444  */
65445  for(i=k-1; i>0; i--){
65446    int szRight = szNew[i];  /* Size of sibling on the right */
65447    int szLeft = szNew[i-1]; /* Size of sibling on the left */
65448    int r;              /* Index of right-most cell in left sibling */
65449    int d;              /* Index of first cell to the left of right sibling */
65450
65451    r = cntNew[i-1] - 1;
65452    d = r + 1 - leafData;
65453    (void)cachedCellSize(&b, d);
65454    do{
65455      assert( d<nMaxCells );
65456      assert( r<nMaxCells );
65457      (void)cachedCellSize(&b, r);
65458      if( szRight!=0
65459       && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
65460        break;
65461      }
65462      szRight += b.szCell[d] + 2;
65463      szLeft -= b.szCell[r] + 2;
65464      cntNew[i-1] = r;
65465      r--;
65466      d--;
65467    }while( r>=0 );
65468    szNew[i] = szRight;
65469    szNew[i-1] = szLeft;
65470    if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
65471      rc = SQLITE_CORRUPT_BKPT;
65472      goto balance_cleanup;
65473    }
65474  }
65475
65476  /* Sanity check:  For a non-corrupt database file one of the follwing
65477  ** must be true:
65478  **    (1) We found one or more cells (cntNew[0])>0), or
65479  **    (2) pPage is a virtual root page.  A virtual root page is when
65480  **        the real root page is page 1 and we are the only child of
65481  **        that page.
65482  */
65483  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
65484  TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
65485    apOld[0]->pgno, apOld[0]->nCell,
65486    nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
65487    nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
65488  ));
65489
65490  /*
65491  ** Allocate k new pages.  Reuse old pages where possible.
65492  */
65493  pageFlags = apOld[0]->aData[0];
65494  for(i=0; i<k; i++){
65495    MemPage *pNew;
65496    if( i<nOld ){
65497      pNew = apNew[i] = apOld[i];
65498      apOld[i] = 0;
65499      rc = sqlite3PagerWrite(pNew->pDbPage);
65500      nNew++;
65501      if( rc ) goto balance_cleanup;
65502    }else{
65503      assert( i>0 );
65504      rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
65505      if( rc ) goto balance_cleanup;
65506      zeroPage(pNew, pageFlags);
65507      apNew[i] = pNew;
65508      nNew++;
65509      cntOld[i] = b.nCell;
65510
65511      /* Set the pointer-map entry for the new sibling page. */
65512      if( ISAUTOVACUUM ){
65513        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
65514        if( rc!=SQLITE_OK ){
65515          goto balance_cleanup;
65516        }
65517      }
65518    }
65519  }
65520
65521  /*
65522  ** Reassign page numbers so that the new pages are in ascending order.
65523  ** This helps to keep entries in the disk file in order so that a scan
65524  ** of the table is closer to a linear scan through the file. That in turn
65525  ** helps the operating system to deliver pages from the disk more rapidly.
65526  **
65527  ** An O(n^2) insertion sort algorithm is used, but since n is never more
65528  ** than (NB+2) (a small constant), that should not be a problem.
65529  **
65530  ** When NB==3, this one optimization makes the database about 25% faster
65531  ** for large insertions and deletions.
65532  */
65533  for(i=0; i<nNew; i++){
65534    aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
65535    aPgFlags[i] = apNew[i]->pDbPage->flags;
65536    for(j=0; j<i; j++){
65537      if( aPgno[j]==aPgno[i] ){
65538        /* This branch is taken if the set of sibling pages somehow contains
65539        ** duplicate entries. This can happen if the database is corrupt.
65540        ** It would be simpler to detect this as part of the loop below, but
65541        ** we do the detection here in order to avoid populating the pager
65542        ** cache with two separate objects associated with the same
65543        ** page number.  */
65544        assert( CORRUPT_DB );
65545        rc = SQLITE_CORRUPT_BKPT;
65546        goto balance_cleanup;
65547      }
65548    }
65549  }
65550  for(i=0; i<nNew; i++){
65551    int iBest = 0;                /* aPgno[] index of page number to use */
65552    for(j=1; j<nNew; j++){
65553      if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
65554    }
65555    pgno = aPgOrder[iBest];
65556    aPgOrder[iBest] = 0xffffffff;
65557    if( iBest!=i ){
65558      if( iBest>i ){
65559        sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
65560      }
65561      sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
65562      apNew[i]->pgno = pgno;
65563    }
65564  }
65565
65566  TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
65567         "%d(%d nc=%d) %d(%d nc=%d)\n",
65568    apNew[0]->pgno, szNew[0], cntNew[0],
65569    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
65570    nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
65571    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
65572    nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
65573    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
65574    nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
65575    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
65576    nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
65577  ));
65578
65579  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65580  put4byte(pRight, apNew[nNew-1]->pgno);
65581
65582  /* If the sibling pages are not leaves, ensure that the right-child pointer
65583  ** of the right-most new sibling page is set to the value that was
65584  ** originally in the same field of the right-most old sibling page. */
65585  if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
65586    MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
65587    memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
65588  }
65589
65590  /* Make any required updates to pointer map entries associated with
65591  ** cells stored on sibling pages following the balance operation. Pointer
65592  ** map entries associated with divider cells are set by the insertCell()
65593  ** routine. The associated pointer map entries are:
65594  **
65595  **   a) if the cell contains a reference to an overflow chain, the
65596  **      entry associated with the first page in the overflow chain, and
65597  **
65598  **   b) if the sibling pages are not leaves, the child page associated
65599  **      with the cell.
65600  **
65601  ** If the sibling pages are not leaves, then the pointer map entry
65602  ** associated with the right-child of each sibling may also need to be
65603  ** updated. This happens below, after the sibling pages have been
65604  ** populated, not here.
65605  */
65606  if( ISAUTOVACUUM ){
65607    MemPage *pNew = apNew[0];
65608    u8 *aOld = pNew->aData;
65609    int cntOldNext = pNew->nCell + pNew->nOverflow;
65610    int usableSize = pBt->usableSize;
65611    int iNew = 0;
65612    int iOld = 0;
65613
65614    for(i=0; i<b.nCell; i++){
65615      u8 *pCell = b.apCell[i];
65616      if( i==cntOldNext ){
65617        MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
65618        cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
65619        aOld = pOld->aData;
65620      }
65621      if( i==cntNew[iNew] ){
65622        pNew = apNew[++iNew];
65623        if( !leafData ) continue;
65624      }
65625
65626      /* Cell pCell is destined for new sibling page pNew. Originally, it
65627      ** was either part of sibling page iOld (possibly an overflow cell),
65628      ** or else the divider cell to the left of sibling page iOld. So,
65629      ** if sibling page iOld had the same page number as pNew, and if
65630      ** pCell really was a part of sibling page iOld (not a divider or
65631      ** overflow cell), we can skip updating the pointer map entries.  */
65632      if( iOld>=nNew
65633       || pNew->pgno!=aPgno[iOld]
65634       || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
65635      ){
65636        if( !leafCorrection ){
65637          ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
65638        }
65639        if( cachedCellSize(&b,i)>pNew->minLocal ){
65640          ptrmapPutOvflPtr(pNew, pCell, &rc);
65641        }
65642        if( rc ) goto balance_cleanup;
65643      }
65644    }
65645  }
65646
65647  /* Insert new divider cells into pParent. */
65648  for(i=0; i<nNew-1; i++){
65649    u8 *pCell;
65650    u8 *pTemp;
65651    int sz;
65652    MemPage *pNew = apNew[i];
65653    j = cntNew[i];
65654
65655    assert( j<nMaxCells );
65656    assert( b.apCell[j]!=0 );
65657    pCell = b.apCell[j];
65658    sz = b.szCell[j] + leafCorrection;
65659    pTemp = &aOvflSpace[iOvflSpace];
65660    if( !pNew->leaf ){
65661      memcpy(&pNew->aData[8], pCell, 4);
65662    }else if( leafData ){
65663      /* If the tree is a leaf-data tree, and the siblings are leaves,
65664      ** then there is no divider cell in b.apCell[]. Instead, the divider
65665      ** cell consists of the integer key for the right-most cell of
65666      ** the sibling-page assembled above only.
65667      */
65668      CellInfo info;
65669      j--;
65670      pNew->xParseCell(pNew, b.apCell[j], &info);
65671      pCell = pTemp;
65672      sz = 4 + putVarint(&pCell[4], info.nKey);
65673      pTemp = 0;
65674    }else{
65675      pCell -= 4;
65676      /* Obscure case for non-leaf-data trees: If the cell at pCell was
65677      ** previously stored on a leaf node, and its reported size was 4
65678      ** bytes, then it may actually be smaller than this
65679      ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
65680      ** any cell). But it is important to pass the correct size to
65681      ** insertCell(), so reparse the cell now.
65682      **
65683      ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
65684      ** and WITHOUT ROWID tables with exactly one column which is the
65685      ** primary key.
65686      */
65687      if( b.szCell[j]==4 ){
65688        assert(leafCorrection==4);
65689        sz = pParent->xCellSize(pParent, pCell);
65690      }
65691    }
65692    iOvflSpace += sz;
65693    assert( sz<=pBt->maxLocal+23 );
65694    assert( iOvflSpace <= (int)pBt->pageSize );
65695    insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
65696    if( rc!=SQLITE_OK ) goto balance_cleanup;
65697    assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65698  }
65699
65700  /* Now update the actual sibling pages. The order in which they are updated
65701  ** is important, as this code needs to avoid disrupting any page from which
65702  ** cells may still to be read. In practice, this means:
65703  **
65704  **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
65705  **      then it is not safe to update page apNew[iPg] until after
65706  **      the left-hand sibling apNew[iPg-1] has been updated.
65707  **
65708  **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
65709  **      then it is not safe to update page apNew[iPg] until after
65710  **      the right-hand sibling apNew[iPg+1] has been updated.
65711  **
65712  ** If neither of the above apply, the page is safe to update.
65713  **
65714  ** The iPg value in the following loop starts at nNew-1 goes down
65715  ** to 0, then back up to nNew-1 again, thus making two passes over
65716  ** the pages.  On the initial downward pass, only condition (1) above
65717  ** needs to be tested because (2) will always be true from the previous
65718  ** step.  On the upward pass, both conditions are always true, so the
65719  ** upwards pass simply processes pages that were missed on the downward
65720  ** pass.
65721  */
65722  for(i=1-nNew; i<nNew; i++){
65723    int iPg = i<0 ? -i : i;
65724    assert( iPg>=0 && iPg<nNew );
65725    if( abDone[iPg] ) continue;         /* Skip pages already processed */
65726    if( i>=0                            /* On the upwards pass, or... */
65727     || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
65728    ){
65729      int iNew;
65730      int iOld;
65731      int nNewCell;
65732
65733      /* Verify condition (1):  If cells are moving left, update iPg
65734      ** only after iPg-1 has already been updated. */
65735      assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
65736
65737      /* Verify condition (2):  If cells are moving right, update iPg
65738      ** only after iPg+1 has already been updated. */
65739      assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
65740
65741      if( iPg==0 ){
65742        iNew = iOld = 0;
65743        nNewCell = cntNew[0];
65744      }else{
65745        iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
65746        iNew = cntNew[iPg-1] + !leafData;
65747        nNewCell = cntNew[iPg] - iNew;
65748      }
65749
65750      rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
65751      if( rc ) goto balance_cleanup;
65752      abDone[iPg]++;
65753      apNew[iPg]->nFree = usableSpace-szNew[iPg];
65754      assert( apNew[iPg]->nOverflow==0 );
65755      assert( apNew[iPg]->nCell==nNewCell );
65756    }
65757  }
65758
65759  /* All pages have been processed exactly once */
65760  assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
65761
65762  assert( nOld>0 );
65763  assert( nNew>0 );
65764
65765  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
65766    /* The root page of the b-tree now contains no cells. The only sibling
65767    ** page is the right-child of the parent. Copy the contents of the
65768    ** child page into the parent, decreasing the overall height of the
65769    ** b-tree structure by one. This is described as the "balance-shallower"
65770    ** sub-algorithm in some documentation.
65771    **
65772    ** If this is an auto-vacuum database, the call to copyNodeContent()
65773    ** sets all pointer-map entries corresponding to database image pages
65774    ** for which the pointer is stored within the content being copied.
65775    **
65776    ** It is critical that the child page be defragmented before being
65777    ** copied into the parent, because if the parent is page 1 then it will
65778    ** by smaller than the child due to the database header, and so all the
65779    ** free space needs to be up front.
65780    */
65781    assert( nNew==1 || CORRUPT_DB );
65782    rc = defragmentPage(apNew[0]);
65783    testcase( rc!=SQLITE_OK );
65784    assert( apNew[0]->nFree ==
65785        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
65786      || rc!=SQLITE_OK
65787    );
65788    copyNodeContent(apNew[0], pParent, &rc);
65789    freePage(apNew[0], &rc);
65790  }else if( ISAUTOVACUUM && !leafCorrection ){
65791    /* Fix the pointer map entries associated with the right-child of each
65792    ** sibling page. All other pointer map entries have already been taken
65793    ** care of.  */
65794    for(i=0; i<nNew; i++){
65795      u32 key = get4byte(&apNew[i]->aData[8]);
65796      ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
65797    }
65798  }
65799
65800  assert( pParent->isInit );
65801  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
65802          nOld, nNew, b.nCell));
65803
65804  /* Free any old pages that were not reused as new pages.
65805  */
65806  for(i=nNew; i<nOld; i++){
65807    freePage(apOld[i], &rc);
65808  }
65809
65810#if 0
65811  if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
65812    /* The ptrmapCheckPages() contains assert() statements that verify that
65813    ** all pointer map pages are set correctly. This is helpful while
65814    ** debugging. This is usually disabled because a corrupt database may
65815    ** cause an assert() statement to fail.  */
65816    ptrmapCheckPages(apNew, nNew);
65817    ptrmapCheckPages(&pParent, 1);
65818  }
65819#endif
65820
65821  /*
65822  ** Cleanup before returning.
65823  */
65824balance_cleanup:
65825  sqlite3ScratchFree(b.apCell);
65826  for(i=0; i<nOld; i++){
65827    releasePage(apOld[i]);
65828  }
65829  for(i=0; i<nNew; i++){
65830    releasePage(apNew[i]);
65831  }
65832
65833  return rc;
65834}
65835
65836
65837/*
65838** This function is called when the root page of a b-tree structure is
65839** overfull (has one or more overflow pages).
65840**
65841** A new child page is allocated and the contents of the current root
65842** page, including overflow cells, are copied into the child. The root
65843** page is then overwritten to make it an empty page with the right-child
65844** pointer pointing to the new page.
65845**
65846** Before returning, all pointer-map entries corresponding to pages
65847** that the new child-page now contains pointers to are updated. The
65848** entry corresponding to the new right-child pointer of the root
65849** page is also updated.
65850**
65851** If successful, *ppChild is set to contain a reference to the child
65852** page and SQLITE_OK is returned. In this case the caller is required
65853** to call releasePage() on *ppChild exactly once. If an error occurs,
65854** an error code is returned and *ppChild is set to 0.
65855*/
65856static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
65857  int rc;                        /* Return value from subprocedures */
65858  MemPage *pChild = 0;           /* Pointer to a new child page */
65859  Pgno pgnoChild = 0;            /* Page number of the new child page */
65860  BtShared *pBt = pRoot->pBt;    /* The BTree */
65861
65862  assert( pRoot->nOverflow>0 );
65863  assert( sqlite3_mutex_held(pBt->mutex) );
65864
65865  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
65866  ** page that will become the new right-child of pPage. Copy the contents
65867  ** of the node stored on pRoot into the new child page.
65868  */
65869  rc = sqlite3PagerWrite(pRoot->pDbPage);
65870  if( rc==SQLITE_OK ){
65871    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
65872    copyNodeContent(pRoot, pChild, &rc);
65873    if( ISAUTOVACUUM ){
65874      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
65875    }
65876  }
65877  if( rc ){
65878    *ppChild = 0;
65879    releasePage(pChild);
65880    return rc;
65881  }
65882  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
65883  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
65884  assert( pChild->nCell==pRoot->nCell );
65885
65886  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
65887
65888  /* Copy the overflow cells from pRoot to pChild */
65889  memcpy(pChild->aiOvfl, pRoot->aiOvfl,
65890         pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
65891  memcpy(pChild->apOvfl, pRoot->apOvfl,
65892         pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
65893  pChild->nOverflow = pRoot->nOverflow;
65894
65895  /* Zero the contents of pRoot. Then install pChild as the right-child. */
65896  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
65897  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
65898
65899  *ppChild = pChild;
65900  return SQLITE_OK;
65901}
65902
65903/*
65904** The page that pCur currently points to has just been modified in
65905** some way. This function figures out if this modification means the
65906** tree needs to be balanced, and if so calls the appropriate balancing
65907** routine. Balancing routines are:
65908**
65909**   balance_quick()
65910**   balance_deeper()
65911**   balance_nonroot()
65912*/
65913static int balance(BtCursor *pCur){
65914  int rc = SQLITE_OK;
65915  const int nMin = pCur->pBt->usableSize * 2 / 3;
65916  u8 aBalanceQuickSpace[13];
65917  u8 *pFree = 0;
65918
65919  VVA_ONLY( int balance_quick_called = 0 );
65920  VVA_ONLY( int balance_deeper_called = 0 );
65921
65922  do {
65923    int iPage = pCur->iPage;
65924    MemPage *pPage = pCur->apPage[iPage];
65925
65926    if( iPage==0 ){
65927      if( pPage->nOverflow ){
65928        /* The root page of the b-tree is overfull. In this case call the
65929        ** balance_deeper() function to create a new child for the root-page
65930        ** and copy the current contents of the root-page to it. The
65931        ** next iteration of the do-loop will balance the child page.
65932        */
65933        assert( balance_deeper_called==0 );
65934        VVA_ONLY( balance_deeper_called++ );
65935        rc = balance_deeper(pPage, &pCur->apPage[1]);
65936        if( rc==SQLITE_OK ){
65937          pCur->iPage = 1;
65938          pCur->aiIdx[0] = 0;
65939          pCur->aiIdx[1] = 0;
65940          assert( pCur->apPage[1]->nOverflow );
65941        }
65942      }else{
65943        break;
65944      }
65945    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
65946      break;
65947    }else{
65948      MemPage * const pParent = pCur->apPage[iPage-1];
65949      int const iIdx = pCur->aiIdx[iPage-1];
65950
65951      rc = sqlite3PagerWrite(pParent->pDbPage);
65952      if( rc==SQLITE_OK ){
65953#ifndef SQLITE_OMIT_QUICKBALANCE
65954        if( pPage->intKeyLeaf
65955         && pPage->nOverflow==1
65956         && pPage->aiOvfl[0]==pPage->nCell
65957         && pParent->pgno!=1
65958         && pParent->nCell==iIdx
65959        ){
65960          /* Call balance_quick() to create a new sibling of pPage on which
65961          ** to store the overflow cell. balance_quick() inserts a new cell
65962          ** into pParent, which may cause pParent overflow. If this
65963          ** happens, the next iteration of the do-loop will balance pParent
65964          ** use either balance_nonroot() or balance_deeper(). Until this
65965          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
65966          ** buffer.
65967          **
65968          ** The purpose of the following assert() is to check that only a
65969          ** single call to balance_quick() is made for each call to this
65970          ** function. If this were not verified, a subtle bug involving reuse
65971          ** of the aBalanceQuickSpace[] might sneak in.
65972          */
65973          assert( balance_quick_called==0 );
65974          VVA_ONLY( balance_quick_called++ );
65975          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
65976        }else
65977#endif
65978        {
65979          /* In this case, call balance_nonroot() to redistribute cells
65980          ** between pPage and up to 2 of its sibling pages. This involves
65981          ** modifying the contents of pParent, which may cause pParent to
65982          ** become overfull or underfull. The next iteration of the do-loop
65983          ** will balance the parent page to correct this.
65984          **
65985          ** If the parent page becomes overfull, the overflow cell or cells
65986          ** are stored in the pSpace buffer allocated immediately below.
65987          ** A subsequent iteration of the do-loop will deal with this by
65988          ** calling balance_nonroot() (balance_deeper() may be called first,
65989          ** but it doesn't deal with overflow cells - just moves them to a
65990          ** different page). Once this subsequent call to balance_nonroot()
65991          ** has completed, it is safe to release the pSpace buffer used by
65992          ** the previous call, as the overflow cell data will have been
65993          ** copied either into the body of a database page or into the new
65994          ** pSpace buffer passed to the latter call to balance_nonroot().
65995          */
65996          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
65997          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
65998                               pCur->hints&BTREE_BULKLOAD);
65999          if( pFree ){
66000            /* If pFree is not NULL, it points to the pSpace buffer used
66001            ** by a previous call to balance_nonroot(). Its contents are
66002            ** now stored either on real database pages or within the
66003            ** new pSpace buffer, so it may be safely freed here. */
66004            sqlite3PageFree(pFree);
66005          }
66006
66007          /* The pSpace buffer will be freed after the next call to
66008          ** balance_nonroot(), or just before this function returns, whichever
66009          ** comes first. */
66010          pFree = pSpace;
66011        }
66012      }
66013
66014      pPage->nOverflow = 0;
66015
66016      /* The next iteration of the do-loop balances the parent page. */
66017      releasePage(pPage);
66018      pCur->iPage--;
66019      assert( pCur->iPage>=0 );
66020    }
66021  }while( rc==SQLITE_OK );
66022
66023  if( pFree ){
66024    sqlite3PageFree(pFree);
66025  }
66026  return rc;
66027}
66028
66029
66030/*
66031** Insert a new record into the BTree.  The content of the new record
66032** is described by the pX object.  The pCur cursor is used only to
66033** define what table the record should be inserted into, and is left
66034** pointing at a random location.
66035**
66036** For a table btree (used for rowid tables), only the pX.nKey value of
66037** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
66038** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
66039** hold the content of the row.
66040**
66041** For an index btree (used for indexes and WITHOUT ROWID tables), the
66042** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The
66043** pX.pData,nData,nZero fields must be zero.
66044**
66045** If the seekResult parameter is non-zero, then a successful call to
66046** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
66047** been performed. seekResult is the search result returned (a negative
66048** number if pCur points at an entry that is smaller than (pKey, nKey), or
66049** a positive value if pCur points at an entry that is larger than
66050** (pKey, nKey)).
66051**
66052** If the seekResult parameter is non-zero, then the caller guarantees that
66053** cursor pCur is pointing at the existing copy of a row that is to be
66054** overwritten.  If the seekResult parameter is 0, then cursor pCur may
66055** point to any entry or to no entry at all and so this function has to seek
66056** the cursor before the new key can be inserted.
66057*/
66058SQLITE_PRIVATE int sqlite3BtreeInsert(
66059  BtCursor *pCur,                /* Insert data into the table of this cursor */
66060  const BtreePayload *pX,        /* Content of the row to be inserted */
66061  int appendBias,                /* True if this is likely an append */
66062  int seekResult                 /* Result of prior MovetoUnpacked() call */
66063){
66064  int rc;
66065  int loc = seekResult;          /* -1: before desired location  +1: after */
66066  int szNew = 0;
66067  int idx;
66068  MemPage *pPage;
66069  Btree *p = pCur->pBtree;
66070  BtShared *pBt = p->pBt;
66071  unsigned char *oldCell;
66072  unsigned char *newCell = 0;
66073
66074  if( pCur->eState==CURSOR_FAULT ){
66075    assert( pCur->skipNext!=SQLITE_OK );
66076    return pCur->skipNext;
66077  }
66078
66079  assert( cursorOwnsBtShared(pCur) );
66080  assert( (pCur->curFlags & BTCF_WriteFlag)!=0
66081              && pBt->inTransaction==TRANS_WRITE
66082              && (pBt->btsFlags & BTS_READ_ONLY)==0 );
66083  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
66084
66085  /* Assert that the caller has been consistent. If this cursor was opened
66086  ** expecting an index b-tree, then the caller should be inserting blob
66087  ** keys with no associated data. If the cursor was opened expecting an
66088  ** intkey table, the caller should be inserting integer keys with a
66089  ** blob of associated data.  */
66090  assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
66091
66092  /* Save the positions of any other cursors open on this table.
66093  **
66094  ** In some cases, the call to btreeMoveto() below is a no-op. For
66095  ** example, when inserting data into a table with auto-generated integer
66096  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
66097  ** integer key to use. It then calls this function to actually insert the
66098  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
66099  ** that the cursor is already where it needs to be and returns without
66100  ** doing any work. To avoid thwarting these optimizations, it is important
66101  ** not to clear the cursor here.
66102  */
66103  if( pCur->curFlags & BTCF_Multiple ){
66104    rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
66105    if( rc ) return rc;
66106  }
66107
66108  if( pCur->pKeyInfo==0 ){
66109    assert( pX->pKey==0 );
66110    /* If this is an insert into a table b-tree, invalidate any incrblob
66111    ** cursors open on the row being replaced */
66112    invalidateIncrblobCursors(p, pX->nKey, 0);
66113
66114    /* If the cursor is currently on the last row and we are appending a
66115    ** new row onto the end, set the "loc" to avoid an unnecessary
66116    ** btreeMoveto() call */
66117    if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey>0
66118      && pCur->info.nKey==pX->nKey-1 ){
66119       loc = -1;
66120    }else if( loc==0 ){
66121      rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, appendBias, &loc);
66122      if( rc ) return rc;
66123    }
66124  }else if( loc==0 ){
66125    rc = btreeMoveto(pCur, pX->pKey, pX->nKey, appendBias, &loc);
66126    if( rc ) return rc;
66127  }
66128  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
66129
66130  pPage = pCur->apPage[pCur->iPage];
66131  assert( pPage->intKey || pX->nKey>=0 );
66132  assert( pPage->leaf || !pPage->intKey );
66133
66134  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
66135          pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
66136          loc==0 ? "overwrite" : "new entry"));
66137  assert( pPage->isInit );
66138  newCell = pBt->pTmpSpace;
66139  assert( newCell!=0 );
66140  rc = fillInCell(pPage, newCell, pX, &szNew);
66141  if( rc ) goto end_insert;
66142  assert( szNew==pPage->xCellSize(pPage, newCell) );
66143  assert( szNew <= MX_CELL_SIZE(pBt) );
66144  idx = pCur->aiIdx[pCur->iPage];
66145  if( loc==0 ){
66146    u16 szOld;
66147    assert( idx<pPage->nCell );
66148    rc = sqlite3PagerWrite(pPage->pDbPage);
66149    if( rc ){
66150      goto end_insert;
66151    }
66152    oldCell = findCell(pPage, idx);
66153    if( !pPage->leaf ){
66154      memcpy(newCell, oldCell, 4);
66155    }
66156    rc = clearCell(pPage, oldCell, &szOld);
66157    dropCell(pPage, idx, szOld, &rc);
66158    if( rc ) goto end_insert;
66159  }else if( loc<0 && pPage->nCell>0 ){
66160    assert( pPage->leaf );
66161    idx = ++pCur->aiIdx[pCur->iPage];
66162  }else{
66163    assert( pPage->leaf );
66164  }
66165  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
66166  assert( pPage->nOverflow==0 || rc==SQLITE_OK );
66167  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
66168
66169  /* If no error has occurred and pPage has an overflow cell, call balance()
66170  ** to redistribute the cells within the tree. Since balance() may move
66171  ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
66172  ** variables.
66173  **
66174  ** Previous versions of SQLite called moveToRoot() to move the cursor
66175  ** back to the root page as balance() used to invalidate the contents
66176  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
66177  ** set the cursor state to "invalid". This makes common insert operations
66178  ** slightly faster.
66179  **
66180  ** There is a subtle but important optimization here too. When inserting
66181  ** multiple records into an intkey b-tree using a single cursor (as can
66182  ** happen while processing an "INSERT INTO ... SELECT" statement), it
66183  ** is advantageous to leave the cursor pointing to the last entry in
66184  ** the b-tree if possible. If the cursor is left pointing to the last
66185  ** entry in the table, and the next row inserted has an integer key
66186  ** larger than the largest existing key, it is possible to insert the
66187  ** row without seeking the cursor. This can be a big performance boost.
66188  */
66189  pCur->info.nSize = 0;
66190  if( pPage->nOverflow ){
66191    assert( rc==SQLITE_OK );
66192    pCur->curFlags &= ~(BTCF_ValidNKey);
66193    rc = balance(pCur);
66194
66195    /* Must make sure nOverflow is reset to zero even if the balance()
66196    ** fails. Internal data structure corruption will result otherwise.
66197    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
66198    ** from trying to save the current position of the cursor.  */
66199    pCur->apPage[pCur->iPage]->nOverflow = 0;
66200    pCur->eState = CURSOR_INVALID;
66201  }
66202  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
66203
66204end_insert:
66205  return rc;
66206}
66207
66208/*
66209** Delete the entry that the cursor is pointing to.
66210**
66211** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
66212** the cursor is left pointing at an arbitrary location after the delete.
66213** But if that bit is set, then the cursor is left in a state such that
66214** the next call to BtreeNext() or BtreePrev() moves it to the same row
66215** as it would have been on if the call to BtreeDelete() had been omitted.
66216**
66217** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
66218** associated with a single table entry and its indexes.  Only one of those
66219** deletes is considered the "primary" delete.  The primary delete occurs
66220** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete
66221** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
66222** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
66223** but which might be used by alternative storage engines.
66224*/
66225SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
66226  Btree *p = pCur->pBtree;
66227  BtShared *pBt = p->pBt;
66228  int rc;                              /* Return code */
66229  MemPage *pPage;                      /* Page to delete cell from */
66230  unsigned char *pCell;                /* Pointer to cell to delete */
66231  int iCellIdx;                        /* Index of cell to delete */
66232  int iCellDepth;                      /* Depth of node containing pCell */
66233  u16 szCell;                          /* Size of the cell being deleted */
66234  int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
66235  u8 bPreserve = flags & BTREE_SAVEPOSITION;  /* Keep cursor valid */
66236
66237  assert( cursorOwnsBtShared(pCur) );
66238  assert( pBt->inTransaction==TRANS_WRITE );
66239  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
66240  assert( pCur->curFlags & BTCF_WriteFlag );
66241  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
66242  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
66243  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
66244  assert( pCur->eState==CURSOR_VALID );
66245  assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
66246
66247  iCellDepth = pCur->iPage;
66248  iCellIdx = pCur->aiIdx[iCellDepth];
66249  pPage = pCur->apPage[iCellDepth];
66250  pCell = findCell(pPage, iCellIdx);
66251
66252  /* If the bPreserve flag is set to true, then the cursor position must
66253  ** be preserved following this delete operation. If the current delete
66254  ** will cause a b-tree rebalance, then this is done by saving the cursor
66255  ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
66256  ** returning.
66257  **
66258  ** Or, if the current delete will not cause a rebalance, then the cursor
66259  ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
66260  ** before or after the deleted entry. In this case set bSkipnext to true.  */
66261  if( bPreserve ){
66262    if( !pPage->leaf
66263     || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
66264    ){
66265      /* A b-tree rebalance will be required after deleting this entry.
66266      ** Save the cursor key.  */
66267      rc = saveCursorKey(pCur);
66268      if( rc ) return rc;
66269    }else{
66270      bSkipnext = 1;
66271    }
66272  }
66273
66274  /* If the page containing the entry to delete is not a leaf page, move
66275  ** the cursor to the largest entry in the tree that is smaller than
66276  ** the entry being deleted. This cell will replace the cell being deleted
66277  ** from the internal node. The 'previous' entry is used for this instead
66278  ** of the 'next' entry, as the previous entry is always a part of the
66279  ** sub-tree headed by the child page of the cell being deleted. This makes
66280  ** balancing the tree following the delete operation easier.  */
66281  if( !pPage->leaf ){
66282    int notUsed = 0;
66283    rc = sqlite3BtreePrevious(pCur, &notUsed);
66284    if( rc ) return rc;
66285  }
66286
66287  /* Save the positions of any other cursors open on this table before
66288  ** making any modifications.  */
66289  if( pCur->curFlags & BTCF_Multiple ){
66290    rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
66291    if( rc ) return rc;
66292  }
66293
66294  /* If this is a delete operation to remove a row from a table b-tree,
66295  ** invalidate any incrblob cursors open on the row being deleted.  */
66296  if( pCur->pKeyInfo==0 ){
66297    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
66298  }
66299
66300  /* Make the page containing the entry to be deleted writable. Then free any
66301  ** overflow pages associated with the entry and finally remove the cell
66302  ** itself from within the page.  */
66303  rc = sqlite3PagerWrite(pPage->pDbPage);
66304  if( rc ) return rc;
66305  rc = clearCell(pPage, pCell, &szCell);
66306  dropCell(pPage, iCellIdx, szCell, &rc);
66307  if( rc ) return rc;
66308
66309  /* If the cell deleted was not located on a leaf page, then the cursor
66310  ** is currently pointing to the largest entry in the sub-tree headed
66311  ** by the child-page of the cell that was just deleted from an internal
66312  ** node. The cell from the leaf node needs to be moved to the internal
66313  ** node to replace the deleted cell.  */
66314  if( !pPage->leaf ){
66315    MemPage *pLeaf = pCur->apPage[pCur->iPage];
66316    int nCell;
66317    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
66318    unsigned char *pTmp;
66319
66320    pCell = findCell(pLeaf, pLeaf->nCell-1);
66321    if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
66322    nCell = pLeaf->xCellSize(pLeaf, pCell);
66323    assert( MX_CELL_SIZE(pBt) >= nCell );
66324    pTmp = pBt->pTmpSpace;
66325    assert( pTmp!=0 );
66326    rc = sqlite3PagerWrite(pLeaf->pDbPage);
66327    if( rc==SQLITE_OK ){
66328      insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
66329    }
66330    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
66331    if( rc ) return rc;
66332  }
66333
66334  /* Balance the tree. If the entry deleted was located on a leaf page,
66335  ** then the cursor still points to that page. In this case the first
66336  ** call to balance() repairs the tree, and the if(...) condition is
66337  ** never true.
66338  **
66339  ** Otherwise, if the entry deleted was on an internal node page, then
66340  ** pCur is pointing to the leaf page from which a cell was removed to
66341  ** replace the cell deleted from the internal node. This is slightly
66342  ** tricky as the leaf node may be underfull, and the internal node may
66343  ** be either under or overfull. In this case run the balancing algorithm
66344  ** on the leaf node first. If the balance proceeds far enough up the
66345  ** tree that we can be sure that any problem in the internal node has
66346  ** been corrected, so be it. Otherwise, after balancing the leaf node,
66347  ** walk the cursor up the tree to the internal node and balance it as
66348  ** well.  */
66349  rc = balance(pCur);
66350  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
66351    while( pCur->iPage>iCellDepth ){
66352      releasePage(pCur->apPage[pCur->iPage--]);
66353    }
66354    rc = balance(pCur);
66355  }
66356
66357  if( rc==SQLITE_OK ){
66358    if( bSkipnext ){
66359      assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
66360      assert( pPage==pCur->apPage[pCur->iPage] || CORRUPT_DB );
66361      assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
66362      pCur->eState = CURSOR_SKIPNEXT;
66363      if( iCellIdx>=pPage->nCell ){
66364        pCur->skipNext = -1;
66365        pCur->aiIdx[iCellDepth] = pPage->nCell-1;
66366      }else{
66367        pCur->skipNext = 1;
66368      }
66369    }else{
66370      rc = moveToRoot(pCur);
66371      if( bPreserve ){
66372        pCur->eState = CURSOR_REQUIRESEEK;
66373      }
66374    }
66375  }
66376  return rc;
66377}
66378
66379/*
66380** Create a new BTree table.  Write into *piTable the page
66381** number for the root page of the new table.
66382**
66383** The type of type is determined by the flags parameter.  Only the
66384** following values of flags are currently in use.  Other values for
66385** flags might not work:
66386**
66387**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
66388**     BTREE_ZERODATA                  Used for SQL indices
66389*/
66390static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
66391  BtShared *pBt = p->pBt;
66392  MemPage *pRoot;
66393  Pgno pgnoRoot;
66394  int rc;
66395  int ptfFlags;          /* Page-type flage for the root page of new table */
66396
66397  assert( sqlite3BtreeHoldsMutex(p) );
66398  assert( pBt->inTransaction==TRANS_WRITE );
66399  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
66400
66401#ifdef SQLITE_OMIT_AUTOVACUUM
66402  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
66403  if( rc ){
66404    return rc;
66405  }
66406#else
66407  if( pBt->autoVacuum ){
66408    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
66409    MemPage *pPageMove; /* The page to move to. */
66410
66411    /* Creating a new table may probably require moving an existing database
66412    ** to make room for the new tables root page. In case this page turns
66413    ** out to be an overflow page, delete all overflow page-map caches
66414    ** held by open cursors.
66415    */
66416    invalidateAllOverflowCache(pBt);
66417
66418    /* Read the value of meta[3] from the database to determine where the
66419    ** root page of the new table should go. meta[3] is the largest root-page
66420    ** created so far, so the new root-page is (meta[3]+1).
66421    */
66422    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
66423    pgnoRoot++;
66424
66425    /* The new root-page may not be allocated on a pointer-map page, or the
66426    ** PENDING_BYTE page.
66427    */
66428    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
66429        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
66430      pgnoRoot++;
66431    }
66432    assert( pgnoRoot>=3 || CORRUPT_DB );
66433    testcase( pgnoRoot<3 );
66434
66435    /* Allocate a page. The page that currently resides at pgnoRoot will
66436    ** be moved to the allocated page (unless the allocated page happens
66437    ** to reside at pgnoRoot).
66438    */
66439    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
66440    if( rc!=SQLITE_OK ){
66441      return rc;
66442    }
66443
66444    if( pgnoMove!=pgnoRoot ){
66445      /* pgnoRoot is the page that will be used for the root-page of
66446      ** the new table (assuming an error did not occur). But we were
66447      ** allocated pgnoMove. If required (i.e. if it was not allocated
66448      ** by extending the file), the current page at position pgnoMove
66449      ** is already journaled.
66450      */
66451      u8 eType = 0;
66452      Pgno iPtrPage = 0;
66453
66454      /* Save the positions of any open cursors. This is required in
66455      ** case they are holding a reference to an xFetch reference
66456      ** corresponding to page pgnoRoot.  */
66457      rc = saveAllCursors(pBt, 0, 0);
66458      releasePage(pPageMove);
66459      if( rc!=SQLITE_OK ){
66460        return rc;
66461      }
66462
66463      /* Move the page currently at pgnoRoot to pgnoMove. */
66464      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
66465      if( rc!=SQLITE_OK ){
66466        return rc;
66467      }
66468      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
66469      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
66470        rc = SQLITE_CORRUPT_BKPT;
66471      }
66472      if( rc!=SQLITE_OK ){
66473        releasePage(pRoot);
66474        return rc;
66475      }
66476      assert( eType!=PTRMAP_ROOTPAGE );
66477      assert( eType!=PTRMAP_FREEPAGE );
66478      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
66479      releasePage(pRoot);
66480
66481      /* Obtain the page at pgnoRoot */
66482      if( rc!=SQLITE_OK ){
66483        return rc;
66484      }
66485      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
66486      if( rc!=SQLITE_OK ){
66487        return rc;
66488      }
66489      rc = sqlite3PagerWrite(pRoot->pDbPage);
66490      if( rc!=SQLITE_OK ){
66491        releasePage(pRoot);
66492        return rc;
66493      }
66494    }else{
66495      pRoot = pPageMove;
66496    }
66497
66498    /* Update the pointer-map and meta-data with the new root-page number. */
66499    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
66500    if( rc ){
66501      releasePage(pRoot);
66502      return rc;
66503    }
66504
66505    /* When the new root page was allocated, page 1 was made writable in
66506    ** order either to increase the database filesize, or to decrement the
66507    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
66508    */
66509    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
66510    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
66511    if( NEVER(rc) ){
66512      releasePage(pRoot);
66513      return rc;
66514    }
66515
66516  }else{
66517    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
66518    if( rc ) return rc;
66519  }
66520#endif
66521  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
66522  if( createTabFlags & BTREE_INTKEY ){
66523    ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
66524  }else{
66525    ptfFlags = PTF_ZERODATA | PTF_LEAF;
66526  }
66527  zeroPage(pRoot, ptfFlags);
66528  sqlite3PagerUnref(pRoot->pDbPage);
66529  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
66530  *piTable = (int)pgnoRoot;
66531  return SQLITE_OK;
66532}
66533SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
66534  int rc;
66535  sqlite3BtreeEnter(p);
66536  rc = btreeCreateTable(p, piTable, flags);
66537  sqlite3BtreeLeave(p);
66538  return rc;
66539}
66540
66541/*
66542** Erase the given database page and all its children.  Return
66543** the page to the freelist.
66544*/
66545static int clearDatabasePage(
66546  BtShared *pBt,           /* The BTree that contains the table */
66547  Pgno pgno,               /* Page number to clear */
66548  int freePageFlag,        /* Deallocate page if true */
66549  int *pnChange            /* Add number of Cells freed to this counter */
66550){
66551  MemPage *pPage;
66552  int rc;
66553  unsigned char *pCell;
66554  int i;
66555  int hdr;
66556  u16 szCell;
66557
66558  assert( sqlite3_mutex_held(pBt->mutex) );
66559  if( pgno>btreePagecount(pBt) ){
66560    return SQLITE_CORRUPT_BKPT;
66561  }
66562  rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
66563  if( rc ) return rc;
66564  if( pPage->bBusy ){
66565    rc = SQLITE_CORRUPT_BKPT;
66566    goto cleardatabasepage_out;
66567  }
66568  pPage->bBusy = 1;
66569  hdr = pPage->hdrOffset;
66570  for(i=0; i<pPage->nCell; i++){
66571    pCell = findCell(pPage, i);
66572    if( !pPage->leaf ){
66573      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
66574      if( rc ) goto cleardatabasepage_out;
66575    }
66576    rc = clearCell(pPage, pCell, &szCell);
66577    if( rc ) goto cleardatabasepage_out;
66578  }
66579  if( !pPage->leaf ){
66580    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
66581    if( rc ) goto cleardatabasepage_out;
66582  }else if( pnChange ){
66583    assert( pPage->intKey || CORRUPT_DB );
66584    testcase( !pPage->intKey );
66585    *pnChange += pPage->nCell;
66586  }
66587  if( freePageFlag ){
66588    freePage(pPage, &rc);
66589  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
66590    zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
66591  }
66592
66593cleardatabasepage_out:
66594  pPage->bBusy = 0;
66595  releasePage(pPage);
66596  return rc;
66597}
66598
66599/*
66600** Delete all information from a single table in the database.  iTable is
66601** the page number of the root of the table.  After this routine returns,
66602** the root page is empty, but still exists.
66603**
66604** This routine will fail with SQLITE_LOCKED if there are any open
66605** read cursors on the table.  Open write cursors are moved to the
66606** root of the table.
66607**
66608** If pnChange is not NULL, then table iTable must be an intkey table. The
66609** integer value pointed to by pnChange is incremented by the number of
66610** entries in the table.
66611*/
66612SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
66613  int rc;
66614  BtShared *pBt = p->pBt;
66615  sqlite3BtreeEnter(p);
66616  assert( p->inTrans==TRANS_WRITE );
66617
66618  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
66619
66620  if( SQLITE_OK==rc ){
66621    /* Invalidate all incrblob cursors open on table iTable (assuming iTable
66622    ** is the root of a table b-tree - if it is not, the following call is
66623    ** a no-op).  */
66624    invalidateIncrblobCursors(p, 0, 1);
66625    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
66626  }
66627  sqlite3BtreeLeave(p);
66628  return rc;
66629}
66630
66631/*
66632** Delete all information from the single table that pCur is open on.
66633**
66634** This routine only work for pCur on an ephemeral table.
66635*/
66636SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
66637  return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
66638}
66639
66640/*
66641** Erase all information in a table and add the root of the table to
66642** the freelist.  Except, the root of the principle table (the one on
66643** page 1) is never added to the freelist.
66644**
66645** This routine will fail with SQLITE_LOCKED if there are any open
66646** cursors on the table.
66647**
66648** If AUTOVACUUM is enabled and the page at iTable is not the last
66649** root page in the database file, then the last root page
66650** in the database file is moved into the slot formerly occupied by
66651** iTable and that last slot formerly occupied by the last root page
66652** is added to the freelist instead of iTable.  In this say, all
66653** root pages are kept at the beginning of the database file, which
66654** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
66655** page number that used to be the last root page in the file before
66656** the move.  If no page gets moved, *piMoved is set to 0.
66657** The last root page is recorded in meta[3] and the value of
66658** meta[3] is updated by this procedure.
66659*/
66660static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
66661  int rc;
66662  MemPage *pPage = 0;
66663  BtShared *pBt = p->pBt;
66664
66665  assert( sqlite3BtreeHoldsMutex(p) );
66666  assert( p->inTrans==TRANS_WRITE );
66667
66668  /* It is illegal to drop a table if any cursors are open on the
66669  ** database. This is because in auto-vacuum mode the backend may
66670  ** need to move another root-page to fill a gap left by the deleted
66671  ** root page. If an open cursor was using this page a problem would
66672  ** occur.
66673  **
66674  ** This error is caught long before control reaches this point.
66675  */
66676  if( NEVER(pBt->pCursor) ){
66677    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
66678    return SQLITE_LOCKED_SHAREDCACHE;
66679  }
66680
66681  /*
66682  ** It is illegal to drop the sqlite_master table on page 1.  But again,
66683  ** this error is caught long before reaching this point.
66684  */
66685  if( NEVER(iTable<2) ){
66686    return SQLITE_CORRUPT_BKPT;
66687  }
66688
66689  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
66690  if( rc ) return rc;
66691  rc = sqlite3BtreeClearTable(p, iTable, 0);
66692  if( rc ){
66693    releasePage(pPage);
66694    return rc;
66695  }
66696
66697  *piMoved = 0;
66698
66699#ifdef SQLITE_OMIT_AUTOVACUUM
66700  freePage(pPage, &rc);
66701  releasePage(pPage);
66702#else
66703  if( pBt->autoVacuum ){
66704    Pgno maxRootPgno;
66705    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
66706
66707    if( iTable==maxRootPgno ){
66708      /* If the table being dropped is the table with the largest root-page
66709      ** number in the database, put the root page on the free list.
66710      */
66711      freePage(pPage, &rc);
66712      releasePage(pPage);
66713      if( rc!=SQLITE_OK ){
66714        return rc;
66715      }
66716    }else{
66717      /* The table being dropped does not have the largest root-page
66718      ** number in the database. So move the page that does into the
66719      ** gap left by the deleted root-page.
66720      */
66721      MemPage *pMove;
66722      releasePage(pPage);
66723      rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
66724      if( rc!=SQLITE_OK ){
66725        return rc;
66726      }
66727      rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
66728      releasePage(pMove);
66729      if( rc!=SQLITE_OK ){
66730        return rc;
66731      }
66732      pMove = 0;
66733      rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
66734      freePage(pMove, &rc);
66735      releasePage(pMove);
66736      if( rc!=SQLITE_OK ){
66737        return rc;
66738      }
66739      *piMoved = maxRootPgno;
66740    }
66741
66742    /* Set the new 'max-root-page' value in the database header. This
66743    ** is the old value less one, less one more if that happens to
66744    ** be a root-page number, less one again if that is the
66745    ** PENDING_BYTE_PAGE.
66746    */
66747    maxRootPgno--;
66748    while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
66749           || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
66750      maxRootPgno--;
66751    }
66752    assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
66753
66754    rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
66755  }else{
66756    freePage(pPage, &rc);
66757    releasePage(pPage);
66758  }
66759#endif
66760  return rc;
66761}
66762SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
66763  int rc;
66764  sqlite3BtreeEnter(p);
66765  rc = btreeDropTable(p, iTable, piMoved);
66766  sqlite3BtreeLeave(p);
66767  return rc;
66768}
66769
66770
66771/*
66772** This function may only be called if the b-tree connection already
66773** has a read or write transaction open on the database.
66774**
66775** Read the meta-information out of a database file.  Meta[0]
66776** is the number of free pages currently in the database.  Meta[1]
66777** through meta[15] are available for use by higher layers.  Meta[0]
66778** is read-only, the others are read/write.
66779**
66780** The schema layer numbers meta values differently.  At the schema
66781** layer (and the SetCookie and ReadCookie opcodes) the number of
66782** free pages is not visible.  So Cookie[0] is the same as Meta[1].
66783**
66784** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
66785** of reading the value out of the header, it instead loads the "DataVersion"
66786** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
66787** database file.  It is a number computed by the pager.  But its access
66788** pattern is the same as header meta values, and so it is convenient to
66789** read it from this routine.
66790*/
66791SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
66792  BtShared *pBt = p->pBt;
66793
66794  sqlite3BtreeEnter(p);
66795  assert( p->inTrans>TRANS_NONE );
66796  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
66797  assert( pBt->pPage1 );
66798  assert( idx>=0 && idx<=15 );
66799
66800  if( idx==BTREE_DATA_VERSION ){
66801    *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
66802  }else{
66803    *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
66804  }
66805
66806  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
66807  ** database, mark the database as read-only.  */
66808#ifdef SQLITE_OMIT_AUTOVACUUM
66809  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
66810    pBt->btsFlags |= BTS_READ_ONLY;
66811  }
66812#endif
66813
66814  sqlite3BtreeLeave(p);
66815}
66816
66817/*
66818** Write meta-information back into the database.  Meta[0] is
66819** read-only and may not be written.
66820*/
66821SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
66822  BtShared *pBt = p->pBt;
66823  unsigned char *pP1;
66824  int rc;
66825  assert( idx>=1 && idx<=15 );
66826  sqlite3BtreeEnter(p);
66827  assert( p->inTrans==TRANS_WRITE );
66828  assert( pBt->pPage1!=0 );
66829  pP1 = pBt->pPage1->aData;
66830  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
66831  if( rc==SQLITE_OK ){
66832    put4byte(&pP1[36 + idx*4], iMeta);
66833#ifndef SQLITE_OMIT_AUTOVACUUM
66834    if( idx==BTREE_INCR_VACUUM ){
66835      assert( pBt->autoVacuum || iMeta==0 );
66836      assert( iMeta==0 || iMeta==1 );
66837      pBt->incrVacuum = (u8)iMeta;
66838    }
66839#endif
66840  }
66841  sqlite3BtreeLeave(p);
66842  return rc;
66843}
66844
66845#ifndef SQLITE_OMIT_BTREECOUNT
66846/*
66847** The first argument, pCur, is a cursor opened on some b-tree. Count the
66848** number of entries in the b-tree and write the result to *pnEntry.
66849**
66850** SQLITE_OK is returned if the operation is successfully executed.
66851** Otherwise, if an error is encountered (i.e. an IO error or database
66852** corruption) an SQLite error code is returned.
66853*/
66854SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
66855  i64 nEntry = 0;                      /* Value to return in *pnEntry */
66856  int rc;                              /* Return code */
66857
66858  if( pCur->pgnoRoot==0 ){
66859    *pnEntry = 0;
66860    return SQLITE_OK;
66861  }
66862  rc = moveToRoot(pCur);
66863
66864  /* Unless an error occurs, the following loop runs one iteration for each
66865  ** page in the B-Tree structure (not including overflow pages).
66866  */
66867  while( rc==SQLITE_OK ){
66868    int iIdx;                          /* Index of child node in parent */
66869    MemPage *pPage;                    /* Current page of the b-tree */
66870
66871    /* If this is a leaf page or the tree is not an int-key tree, then
66872    ** this page contains countable entries. Increment the entry counter
66873    ** accordingly.
66874    */
66875    pPage = pCur->apPage[pCur->iPage];
66876    if( pPage->leaf || !pPage->intKey ){
66877      nEntry += pPage->nCell;
66878    }
66879
66880    /* pPage is a leaf node. This loop navigates the cursor so that it
66881    ** points to the first interior cell that it points to the parent of
66882    ** the next page in the tree that has not yet been visited. The
66883    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
66884    ** of the page, or to the number of cells in the page if the next page
66885    ** to visit is the right-child of its parent.
66886    **
66887    ** If all pages in the tree have been visited, return SQLITE_OK to the
66888    ** caller.
66889    */
66890    if( pPage->leaf ){
66891      do {
66892        if( pCur->iPage==0 ){
66893          /* All pages of the b-tree have been visited. Return successfully. */
66894          *pnEntry = nEntry;
66895          return moveToRoot(pCur);
66896        }
66897        moveToParent(pCur);
66898      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
66899
66900      pCur->aiIdx[pCur->iPage]++;
66901      pPage = pCur->apPage[pCur->iPage];
66902    }
66903
66904    /* Descend to the child node of the cell that the cursor currently
66905    ** points at. This is the right-child if (iIdx==pPage->nCell).
66906    */
66907    iIdx = pCur->aiIdx[pCur->iPage];
66908    if( iIdx==pPage->nCell ){
66909      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
66910    }else{
66911      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
66912    }
66913  }
66914
66915  /* An error has occurred. Return an error code. */
66916  return rc;
66917}
66918#endif
66919
66920/*
66921** Return the pager associated with a BTree.  This routine is used for
66922** testing and debugging only.
66923*/
66924SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
66925  return p->pBt->pPager;
66926}
66927
66928#ifndef SQLITE_OMIT_INTEGRITY_CHECK
66929/*
66930** Append a message to the error message string.
66931*/
66932static void checkAppendMsg(
66933  IntegrityCk *pCheck,
66934  const char *zFormat,
66935  ...
66936){
66937  va_list ap;
66938  if( !pCheck->mxErr ) return;
66939  pCheck->mxErr--;
66940  pCheck->nErr++;
66941  va_start(ap, zFormat);
66942  if( pCheck->errMsg.nChar ){
66943    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
66944  }
66945  if( pCheck->zPfx ){
66946    sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
66947  }
66948  sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
66949  va_end(ap);
66950  if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
66951    pCheck->mallocFailed = 1;
66952  }
66953}
66954#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
66955
66956#ifndef SQLITE_OMIT_INTEGRITY_CHECK
66957
66958/*
66959** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
66960** corresponds to page iPg is already set.
66961*/
66962static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
66963  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
66964  return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
66965}
66966
66967/*
66968** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
66969*/
66970static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
66971  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
66972  pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
66973}
66974
66975
66976/*
66977** Add 1 to the reference count for page iPage.  If this is the second
66978** reference to the page, add an error message to pCheck->zErrMsg.
66979** Return 1 if there are 2 or more references to the page and 0 if
66980** if this is the first reference to the page.
66981**
66982** Also check that the page number is in bounds.
66983*/
66984static int checkRef(IntegrityCk *pCheck, Pgno iPage){
66985  if( iPage==0 ) return 1;
66986  if( iPage>pCheck->nPage ){
66987    checkAppendMsg(pCheck, "invalid page number %d", iPage);
66988    return 1;
66989  }
66990  if( getPageReferenced(pCheck, iPage) ){
66991    checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
66992    return 1;
66993  }
66994  setPageReferenced(pCheck, iPage);
66995  return 0;
66996}
66997
66998#ifndef SQLITE_OMIT_AUTOVACUUM
66999/*
67000** Check that the entry in the pointer-map for page iChild maps to
67001** page iParent, pointer type ptrType. If not, append an error message
67002** to pCheck.
67003*/
67004static void checkPtrmap(
67005  IntegrityCk *pCheck,   /* Integrity check context */
67006  Pgno iChild,           /* Child page number */
67007  u8 eType,              /* Expected pointer map type */
67008  Pgno iParent           /* Expected pointer map parent page number */
67009){
67010  int rc;
67011  u8 ePtrmapType;
67012  Pgno iPtrmapParent;
67013
67014  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
67015  if( rc!=SQLITE_OK ){
67016    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
67017    checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
67018    return;
67019  }
67020
67021  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
67022    checkAppendMsg(pCheck,
67023      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
67024      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
67025  }
67026}
67027#endif
67028
67029/*
67030** Check the integrity of the freelist or of an overflow page list.
67031** Verify that the number of pages on the list is N.
67032*/
67033static void checkList(
67034  IntegrityCk *pCheck,  /* Integrity checking context */
67035  int isFreeList,       /* True for a freelist.  False for overflow page list */
67036  int iPage,            /* Page number for first page in the list */
67037  int N                 /* Expected number of pages in the list */
67038){
67039  int i;
67040  int expected = N;
67041  int iFirst = iPage;
67042  while( N-- > 0 && pCheck->mxErr ){
67043    DbPage *pOvflPage;
67044    unsigned char *pOvflData;
67045    if( iPage<1 ){
67046      checkAppendMsg(pCheck,
67047         "%d of %d pages missing from overflow list starting at %d",
67048          N+1, expected, iFirst);
67049      break;
67050    }
67051    if( checkRef(pCheck, iPage) ) break;
67052    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
67053      checkAppendMsg(pCheck, "failed to get page %d", iPage);
67054      break;
67055    }
67056    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
67057    if( isFreeList ){
67058      int n = get4byte(&pOvflData[4]);
67059#ifndef SQLITE_OMIT_AUTOVACUUM
67060      if( pCheck->pBt->autoVacuum ){
67061        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
67062      }
67063#endif
67064      if( n>(int)pCheck->pBt->usableSize/4-2 ){
67065        checkAppendMsg(pCheck,
67066           "freelist leaf count too big on page %d", iPage);
67067        N--;
67068      }else{
67069        for(i=0; i<n; i++){
67070          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
67071#ifndef SQLITE_OMIT_AUTOVACUUM
67072          if( pCheck->pBt->autoVacuum ){
67073            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
67074          }
67075#endif
67076          checkRef(pCheck, iFreePage);
67077        }
67078        N -= n;
67079      }
67080    }
67081#ifndef SQLITE_OMIT_AUTOVACUUM
67082    else{
67083      /* If this database supports auto-vacuum and iPage is not the last
67084      ** page in this overflow list, check that the pointer-map entry for
67085      ** the following page matches iPage.
67086      */
67087      if( pCheck->pBt->autoVacuum && N>0 ){
67088        i = get4byte(pOvflData);
67089        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
67090      }
67091    }
67092#endif
67093    iPage = get4byte(pOvflData);
67094    sqlite3PagerUnref(pOvflPage);
67095
67096    if( isFreeList && N<(iPage!=0) ){
67097      checkAppendMsg(pCheck, "free-page count in header is too small");
67098    }
67099  }
67100}
67101#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67102
67103/*
67104** An implementation of a min-heap.
67105**
67106** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
67107** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
67108** and aHeap[N*2+1].
67109**
67110** The heap property is this:  Every node is less than or equal to both
67111** of its daughter nodes.  A consequence of the heap property is that the
67112** root node aHeap[1] is always the minimum value currently in the heap.
67113**
67114** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
67115** the heap, preserving the heap property.  The btreeHeapPull() routine
67116** removes the root element from the heap (the minimum value in the heap)
67117** and then moves other nodes around as necessary to preserve the heap
67118** property.
67119**
67120** This heap is used for cell overlap and coverage testing.  Each u32
67121** entry represents the span of a cell or freeblock on a btree page.
67122** The upper 16 bits are the index of the first byte of a range and the
67123** lower 16 bits are the index of the last byte of that range.
67124*/
67125static void btreeHeapInsert(u32 *aHeap, u32 x){
67126  u32 j, i = ++aHeap[0];
67127  aHeap[i] = x;
67128  while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
67129    x = aHeap[j];
67130    aHeap[j] = aHeap[i];
67131    aHeap[i] = x;
67132    i = j;
67133  }
67134}
67135static int btreeHeapPull(u32 *aHeap, u32 *pOut){
67136  u32 j, i, x;
67137  if( (x = aHeap[0])==0 ) return 0;
67138  *pOut = aHeap[1];
67139  aHeap[1] = aHeap[x];
67140  aHeap[x] = 0xffffffff;
67141  aHeap[0]--;
67142  i = 1;
67143  while( (j = i*2)<=aHeap[0] ){
67144    if( aHeap[j]>aHeap[j+1] ) j++;
67145    if( aHeap[i]<aHeap[j] ) break;
67146    x = aHeap[i];
67147    aHeap[i] = aHeap[j];
67148    aHeap[j] = x;
67149    i = j;
67150  }
67151  return 1;
67152}
67153
67154#ifndef SQLITE_OMIT_INTEGRITY_CHECK
67155/*
67156** Do various sanity checks on a single page of a tree.  Return
67157** the tree depth.  Root pages return 0.  Parents of root pages
67158** return 1, and so forth.
67159**
67160** These checks are done:
67161**
67162**      1.  Make sure that cells and freeblocks do not overlap
67163**          but combine to completely cover the page.
67164**      2.  Make sure integer cell keys are in order.
67165**      3.  Check the integrity of overflow pages.
67166**      4.  Recursively call checkTreePage on all children.
67167**      5.  Verify that the depth of all children is the same.
67168*/
67169static int checkTreePage(
67170  IntegrityCk *pCheck,  /* Context for the sanity check */
67171  int iPage,            /* Page number of the page to check */
67172  i64 *piMinKey,        /* Write minimum integer primary key here */
67173  i64 maxKey            /* Error if integer primary key greater than this */
67174){
67175  MemPage *pPage = 0;      /* The page being analyzed */
67176  int i;                   /* Loop counter */
67177  int rc;                  /* Result code from subroutine call */
67178  int depth = -1, d2;      /* Depth of a subtree */
67179  int pgno;                /* Page number */
67180  int nFrag;               /* Number of fragmented bytes on the page */
67181  int hdr;                 /* Offset to the page header */
67182  int cellStart;           /* Offset to the start of the cell pointer array */
67183  int nCell;               /* Number of cells */
67184  int doCoverageCheck = 1; /* True if cell coverage checking should be done */
67185  int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
67186                           ** False if IPK must be strictly less than maxKey */
67187  u8 *data;                /* Page content */
67188  u8 *pCell;               /* Cell content */
67189  u8 *pCellIdx;            /* Next element of the cell pointer array */
67190  BtShared *pBt;           /* The BtShared object that owns pPage */
67191  u32 pc;                  /* Address of a cell */
67192  u32 usableSize;          /* Usable size of the page */
67193  u32 contentOffset;       /* Offset to the start of the cell content area */
67194  u32 *heap = 0;           /* Min-heap used for checking cell coverage */
67195  u32 x, prev = 0;         /* Next and previous entry on the min-heap */
67196  const char *saved_zPfx = pCheck->zPfx;
67197  int saved_v1 = pCheck->v1;
67198  int saved_v2 = pCheck->v2;
67199  u8 savedIsInit = 0;
67200
67201  /* Check that the page exists
67202  */
67203  pBt = pCheck->pBt;
67204  usableSize = pBt->usableSize;
67205  if( iPage==0 ) return 0;
67206  if( checkRef(pCheck, iPage) ) return 0;
67207  pCheck->zPfx = "Page %d: ";
67208  pCheck->v1 = iPage;
67209  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
67210    checkAppendMsg(pCheck,
67211       "unable to get the page. error code=%d", rc);
67212    goto end_of_check;
67213  }
67214
67215  /* Clear MemPage.isInit to make sure the corruption detection code in
67216  ** btreeInitPage() is executed.  */
67217  savedIsInit = pPage->isInit;
67218  pPage->isInit = 0;
67219  if( (rc = btreeInitPage(pPage))!=0 ){
67220    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
67221    checkAppendMsg(pCheck,
67222                   "btreeInitPage() returns error code %d", rc);
67223    goto end_of_check;
67224  }
67225  data = pPage->aData;
67226  hdr = pPage->hdrOffset;
67227
67228  /* Set up for cell analysis */
67229  pCheck->zPfx = "On tree page %d cell %d: ";
67230  contentOffset = get2byteNotZero(&data[hdr+5]);
67231  assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
67232
67233  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
67234  ** number of cells on the page. */
67235  nCell = get2byte(&data[hdr+3]);
67236  assert( pPage->nCell==nCell );
67237
67238  /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
67239  ** immediately follows the b-tree page header. */
67240  cellStart = hdr + 12 - 4*pPage->leaf;
67241  assert( pPage->aCellIdx==&data[cellStart] );
67242  pCellIdx = &data[cellStart + 2*(nCell-1)];
67243
67244  if( !pPage->leaf ){
67245    /* Analyze the right-child page of internal pages */
67246    pgno = get4byte(&data[hdr+8]);
67247#ifndef SQLITE_OMIT_AUTOVACUUM
67248    if( pBt->autoVacuum ){
67249      pCheck->zPfx = "On page %d at right child: ";
67250      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
67251    }
67252#endif
67253    depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
67254    keyCanBeEqual = 0;
67255  }else{
67256    /* For leaf pages, the coverage check will occur in the same loop
67257    ** as the other cell checks, so initialize the heap.  */
67258    heap = pCheck->heap;
67259    heap[0] = 0;
67260  }
67261
67262  /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
67263  ** integer offsets to the cell contents. */
67264  for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
67265    CellInfo info;
67266
67267    /* Check cell size */
67268    pCheck->v2 = i;
67269    assert( pCellIdx==&data[cellStart + i*2] );
67270    pc = get2byteAligned(pCellIdx);
67271    pCellIdx -= 2;
67272    if( pc<contentOffset || pc>usableSize-4 ){
67273      checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
67274                             pc, contentOffset, usableSize-4);
67275      doCoverageCheck = 0;
67276      continue;
67277    }
67278    pCell = &data[pc];
67279    pPage->xParseCell(pPage, pCell, &info);
67280    if( pc+info.nSize>usableSize ){
67281      checkAppendMsg(pCheck, "Extends off end of page");
67282      doCoverageCheck = 0;
67283      continue;
67284    }
67285
67286    /* Check for integer primary key out of range */
67287    if( pPage->intKey ){
67288      if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
67289        checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
67290      }
67291      maxKey = info.nKey;
67292    }
67293
67294    /* Check the content overflow list */
67295    if( info.nPayload>info.nLocal ){
67296      int nPage;       /* Number of pages on the overflow chain */
67297      Pgno pgnoOvfl;   /* First page of the overflow chain */
67298      assert( pc + info.nSize - 4 <= usableSize );
67299      nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
67300      pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
67301#ifndef SQLITE_OMIT_AUTOVACUUM
67302      if( pBt->autoVacuum ){
67303        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
67304      }
67305#endif
67306      checkList(pCheck, 0, pgnoOvfl, nPage);
67307    }
67308
67309    if( !pPage->leaf ){
67310      /* Check sanity of left child page for internal pages */
67311      pgno = get4byte(pCell);
67312#ifndef SQLITE_OMIT_AUTOVACUUM
67313      if( pBt->autoVacuum ){
67314        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
67315      }
67316#endif
67317      d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
67318      keyCanBeEqual = 0;
67319      if( d2!=depth ){
67320        checkAppendMsg(pCheck, "Child page depth differs");
67321        depth = d2;
67322      }
67323    }else{
67324      /* Populate the coverage-checking heap for leaf pages */
67325      btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
67326    }
67327  }
67328  *piMinKey = maxKey;
67329
67330  /* Check for complete coverage of the page
67331  */
67332  pCheck->zPfx = 0;
67333  if( doCoverageCheck && pCheck->mxErr>0 ){
67334    /* For leaf pages, the min-heap has already been initialized and the
67335    ** cells have already been inserted.  But for internal pages, that has
67336    ** not yet been done, so do it now */
67337    if( !pPage->leaf ){
67338      heap = pCheck->heap;
67339      heap[0] = 0;
67340      for(i=nCell-1; i>=0; i--){
67341        u32 size;
67342        pc = get2byteAligned(&data[cellStart+i*2]);
67343        size = pPage->xCellSize(pPage, &data[pc]);
67344        btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
67345      }
67346    }
67347    /* Add the freeblocks to the min-heap
67348    **
67349    ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
67350    ** is the offset of the first freeblock, or zero if there are no
67351    ** freeblocks on the page.
67352    */
67353    i = get2byte(&data[hdr+1]);
67354    while( i>0 ){
67355      int size, j;
67356      assert( (u32)i<=usableSize-4 );     /* Enforced by btreeInitPage() */
67357      size = get2byte(&data[i+2]);
67358      assert( (u32)(i+size)<=usableSize );  /* Enforced by btreeInitPage() */
67359      btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
67360      /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
67361      ** big-endian integer which is the offset in the b-tree page of the next
67362      ** freeblock in the chain, or zero if the freeblock is the last on the
67363      ** chain. */
67364      j = get2byte(&data[i]);
67365      /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
67366      ** increasing offset. */
67367      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
67368      assert( (u32)j<=usableSize-4 );   /* Enforced by btreeInitPage() */
67369      i = j;
67370    }
67371    /* Analyze the min-heap looking for overlap between cells and/or
67372    ** freeblocks, and counting the number of untracked bytes in nFrag.
67373    **
67374    ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
67375    ** There is an implied first entry the covers the page header, the cell
67376    ** pointer index, and the gap between the cell pointer index and the start
67377    ** of cell content.
67378    **
67379    ** The loop below pulls entries from the min-heap in order and compares
67380    ** the start_address against the previous end_address.  If there is an
67381    ** overlap, that means bytes are used multiple times.  If there is a gap,
67382    ** that gap is added to the fragmentation count.
67383    */
67384    nFrag = 0;
67385    prev = contentOffset - 1;   /* Implied first min-heap entry */
67386    while( btreeHeapPull(heap,&x) ){
67387      if( (prev&0xffff)>=(x>>16) ){
67388        checkAppendMsg(pCheck,
67389          "Multiple uses for byte %u of page %d", x>>16, iPage);
67390        break;
67391      }else{
67392        nFrag += (x>>16) - (prev&0xffff) - 1;
67393        prev = x;
67394      }
67395    }
67396    nFrag += usableSize - (prev&0xffff) - 1;
67397    /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
67398    ** is stored in the fifth field of the b-tree page header.
67399    ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
67400    ** number of fragmented free bytes within the cell content area.
67401    */
67402    if( heap[0]==0 && nFrag!=data[hdr+7] ){
67403      checkAppendMsg(pCheck,
67404          "Fragmentation of %d bytes reported as %d on page %d",
67405          nFrag, data[hdr+7], iPage);
67406    }
67407  }
67408
67409end_of_check:
67410  if( !doCoverageCheck ) pPage->isInit = savedIsInit;
67411  releasePage(pPage);
67412  pCheck->zPfx = saved_zPfx;
67413  pCheck->v1 = saved_v1;
67414  pCheck->v2 = saved_v2;
67415  return depth+1;
67416}
67417#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67418
67419#ifndef SQLITE_OMIT_INTEGRITY_CHECK
67420/*
67421** This routine does a complete check of the given BTree file.  aRoot[] is
67422** an array of pages numbers were each page number is the root page of
67423** a table.  nRoot is the number of entries in aRoot.
67424**
67425** A read-only or read-write transaction must be opened before calling
67426** this function.
67427**
67428** Write the number of error seen in *pnErr.  Except for some memory
67429** allocation errors,  an error message held in memory obtained from
67430** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
67431** returned.  If a memory allocation error occurs, NULL is returned.
67432*/
67433SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
67434  Btree *p,     /* The btree to be checked */
67435  int *aRoot,   /* An array of root pages numbers for individual trees */
67436  int nRoot,    /* Number of entries in aRoot[] */
67437  int mxErr,    /* Stop reporting errors after this many */
67438  int *pnErr    /* Write number of errors seen to this variable */
67439){
67440  Pgno i;
67441  IntegrityCk sCheck;
67442  BtShared *pBt = p->pBt;
67443  int savedDbFlags = pBt->db->flags;
67444  char zErr[100];
67445  VVA_ONLY( int nRef );
67446
67447  sqlite3BtreeEnter(p);
67448  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
67449  VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
67450  assert( nRef>=0 );
67451  sCheck.pBt = pBt;
67452  sCheck.pPager = pBt->pPager;
67453  sCheck.nPage = btreePagecount(sCheck.pBt);
67454  sCheck.mxErr = mxErr;
67455  sCheck.nErr = 0;
67456  sCheck.mallocFailed = 0;
67457  sCheck.zPfx = 0;
67458  sCheck.v1 = 0;
67459  sCheck.v2 = 0;
67460  sCheck.aPgRef = 0;
67461  sCheck.heap = 0;
67462  sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
67463  sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
67464  if( sCheck.nPage==0 ){
67465    goto integrity_ck_cleanup;
67466  }
67467
67468  sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
67469  if( !sCheck.aPgRef ){
67470    sCheck.mallocFailed = 1;
67471    goto integrity_ck_cleanup;
67472  }
67473  sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
67474  if( sCheck.heap==0 ){
67475    sCheck.mallocFailed = 1;
67476    goto integrity_ck_cleanup;
67477  }
67478
67479  i = PENDING_BYTE_PAGE(pBt);
67480  if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
67481
67482  /* Check the integrity of the freelist
67483  */
67484  sCheck.zPfx = "Main freelist: ";
67485  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
67486            get4byte(&pBt->pPage1->aData[36]));
67487  sCheck.zPfx = 0;
67488
67489  /* Check all the tables.
67490  */
67491  testcase( pBt->db->flags & SQLITE_CellSizeCk );
67492  pBt->db->flags &= ~SQLITE_CellSizeCk;
67493  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
67494    i64 notUsed;
67495    if( aRoot[i]==0 ) continue;
67496#ifndef SQLITE_OMIT_AUTOVACUUM
67497    if( pBt->autoVacuum && aRoot[i]>1 ){
67498      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
67499    }
67500#endif
67501    checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
67502  }
67503  pBt->db->flags = savedDbFlags;
67504
67505  /* Make sure every page in the file is referenced
67506  */
67507  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
67508#ifdef SQLITE_OMIT_AUTOVACUUM
67509    if( getPageReferenced(&sCheck, i)==0 ){
67510      checkAppendMsg(&sCheck, "Page %d is never used", i);
67511    }
67512#else
67513    /* If the database supports auto-vacuum, make sure no tables contain
67514    ** references to pointer-map pages.
67515    */
67516    if( getPageReferenced(&sCheck, i)==0 &&
67517       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
67518      checkAppendMsg(&sCheck, "Page %d is never used", i);
67519    }
67520    if( getPageReferenced(&sCheck, i)!=0 &&
67521       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
67522      checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
67523    }
67524#endif
67525  }
67526
67527  /* Clean  up and report errors.
67528  */
67529integrity_ck_cleanup:
67530  sqlite3PageFree(sCheck.heap);
67531  sqlite3_free(sCheck.aPgRef);
67532  if( sCheck.mallocFailed ){
67533    sqlite3StrAccumReset(&sCheck.errMsg);
67534    sCheck.nErr++;
67535  }
67536  *pnErr = sCheck.nErr;
67537  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
67538  /* Make sure this analysis did not leave any unref() pages. */
67539  assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
67540  sqlite3BtreeLeave(p);
67541  return sqlite3StrAccumFinish(&sCheck.errMsg);
67542}
67543#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67544
67545/*
67546** Return the full pathname of the underlying database file.  Return
67547** an empty string if the database is in-memory or a TEMP database.
67548**
67549** The pager filename is invariant as long as the pager is
67550** open so it is safe to access without the BtShared mutex.
67551*/
67552SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
67553  assert( p->pBt->pPager!=0 );
67554  return sqlite3PagerFilename(p->pBt->pPager, 1);
67555}
67556
67557/*
67558** Return the pathname of the journal file for this database. The return
67559** value of this routine is the same regardless of whether the journal file
67560** has been created or not.
67561**
67562** The pager journal filename is invariant as long as the pager is
67563** open so it is safe to access without the BtShared mutex.
67564*/
67565SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
67566  assert( p->pBt->pPager!=0 );
67567  return sqlite3PagerJournalname(p->pBt->pPager);
67568}
67569
67570/*
67571** Return non-zero if a transaction is active.
67572*/
67573SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
67574  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
67575  return (p && (p->inTrans==TRANS_WRITE));
67576}
67577
67578#ifndef SQLITE_OMIT_WAL
67579/*
67580** Run a checkpoint on the Btree passed as the first argument.
67581**
67582** Return SQLITE_LOCKED if this or any other connection has an open
67583** transaction on the shared-cache the argument Btree is connected to.
67584**
67585** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
67586*/
67587SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
67588  int rc = SQLITE_OK;
67589  if( p ){
67590    BtShared *pBt = p->pBt;
67591    sqlite3BtreeEnter(p);
67592    if( pBt->inTransaction!=TRANS_NONE ){
67593      rc = SQLITE_LOCKED;
67594    }else{
67595      rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
67596    }
67597    sqlite3BtreeLeave(p);
67598  }
67599  return rc;
67600}
67601#endif
67602
67603/*
67604** Return non-zero if a read (or write) transaction is active.
67605*/
67606SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
67607  assert( p );
67608  assert( sqlite3_mutex_held(p->db->mutex) );
67609  return p->inTrans!=TRANS_NONE;
67610}
67611
67612SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
67613  assert( p );
67614  assert( sqlite3_mutex_held(p->db->mutex) );
67615  return p->nBackup!=0;
67616}
67617
67618/*
67619** This function returns a pointer to a blob of memory associated with
67620** a single shared-btree. The memory is used by client code for its own
67621** purposes (for example, to store a high-level schema associated with
67622** the shared-btree). The btree layer manages reference counting issues.
67623**
67624** The first time this is called on a shared-btree, nBytes bytes of memory
67625** are allocated, zeroed, and returned to the caller. For each subsequent
67626** call the nBytes parameter is ignored and a pointer to the same blob
67627** of memory returned.
67628**
67629** If the nBytes parameter is 0 and the blob of memory has not yet been
67630** allocated, a null pointer is returned. If the blob has already been
67631** allocated, it is returned as normal.
67632**
67633** Just before the shared-btree is closed, the function passed as the
67634** xFree argument when the memory allocation was made is invoked on the
67635** blob of allocated memory. The xFree function should not call sqlite3_free()
67636** on the memory, the btree layer does that.
67637*/
67638SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
67639  BtShared *pBt = p->pBt;
67640  sqlite3BtreeEnter(p);
67641  if( !pBt->pSchema && nBytes ){
67642    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
67643    pBt->xFreeSchema = xFree;
67644  }
67645  sqlite3BtreeLeave(p);
67646  return pBt->pSchema;
67647}
67648
67649/*
67650** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
67651** btree as the argument handle holds an exclusive lock on the
67652** sqlite_master table. Otherwise SQLITE_OK.
67653*/
67654SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
67655  int rc;
67656  assert( sqlite3_mutex_held(p->db->mutex) );
67657  sqlite3BtreeEnter(p);
67658  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
67659  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
67660  sqlite3BtreeLeave(p);
67661  return rc;
67662}
67663
67664
67665#ifndef SQLITE_OMIT_SHARED_CACHE
67666/*
67667** Obtain a lock on the table whose root page is iTab.  The
67668** lock is a write lock if isWritelock is true or a read lock
67669** if it is false.
67670*/
67671SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
67672  int rc = SQLITE_OK;
67673  assert( p->inTrans!=TRANS_NONE );
67674  if( p->sharable ){
67675    u8 lockType = READ_LOCK + isWriteLock;
67676    assert( READ_LOCK+1==WRITE_LOCK );
67677    assert( isWriteLock==0 || isWriteLock==1 );
67678
67679    sqlite3BtreeEnter(p);
67680    rc = querySharedCacheTableLock(p, iTab, lockType);
67681    if( rc==SQLITE_OK ){
67682      rc = setSharedCacheTableLock(p, iTab, lockType);
67683    }
67684    sqlite3BtreeLeave(p);
67685  }
67686  return rc;
67687}
67688#endif
67689
67690#ifndef SQLITE_OMIT_INCRBLOB
67691/*
67692** Argument pCsr must be a cursor opened for writing on an
67693** INTKEY table currently pointing at a valid table entry.
67694** This function modifies the data stored as part of that entry.
67695**
67696** Only the data content may only be modified, it is not possible to
67697** change the length of the data stored. If this function is called with
67698** parameters that attempt to write past the end of the existing data,
67699** no modifications are made and SQLITE_CORRUPT is returned.
67700*/
67701SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
67702  int rc;
67703  assert( cursorOwnsBtShared(pCsr) );
67704  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
67705  assert( pCsr->curFlags & BTCF_Incrblob );
67706
67707  rc = restoreCursorPosition(pCsr);
67708  if( rc!=SQLITE_OK ){
67709    return rc;
67710  }
67711  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
67712  if( pCsr->eState!=CURSOR_VALID ){
67713    return SQLITE_ABORT;
67714  }
67715
67716  /* Save the positions of all other cursors open on this table. This is
67717  ** required in case any of them are holding references to an xFetch
67718  ** version of the b-tree page modified by the accessPayload call below.
67719  **
67720  ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
67721  ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
67722  ** saveAllCursors can only return SQLITE_OK.
67723  */
67724  VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
67725  assert( rc==SQLITE_OK );
67726
67727  /* Check some assumptions:
67728  **   (a) the cursor is open for writing,
67729  **   (b) there is a read/write transaction open,
67730  **   (c) the connection holds a write-lock on the table (if required),
67731  **   (d) there are no conflicting read-locks, and
67732  **   (e) the cursor points at a valid row of an intKey table.
67733  */
67734  if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
67735    return SQLITE_READONLY;
67736  }
67737  assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
67738              && pCsr->pBt->inTransaction==TRANS_WRITE );
67739  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
67740  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
67741  assert( pCsr->apPage[pCsr->iPage]->intKey );
67742
67743  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
67744}
67745
67746/*
67747** Mark this cursor as an incremental blob cursor.
67748*/
67749SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
67750  pCur->curFlags |= BTCF_Incrblob;
67751  pCur->pBtree->hasIncrblobCur = 1;
67752}
67753#endif
67754
67755/*
67756** Set both the "read version" (single byte at byte offset 18) and
67757** "write version" (single byte at byte offset 19) fields in the database
67758** header to iVersion.
67759*/
67760SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
67761  BtShared *pBt = pBtree->pBt;
67762  int rc;                         /* Return code */
67763
67764  assert( iVersion==1 || iVersion==2 );
67765
67766  /* If setting the version fields to 1, do not automatically open the
67767  ** WAL connection, even if the version fields are currently set to 2.
67768  */
67769  pBt->btsFlags &= ~BTS_NO_WAL;
67770  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
67771
67772  rc = sqlite3BtreeBeginTrans(pBtree, 0);
67773  if( rc==SQLITE_OK ){
67774    u8 *aData = pBt->pPage1->aData;
67775    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
67776      rc = sqlite3BtreeBeginTrans(pBtree, 2);
67777      if( rc==SQLITE_OK ){
67778        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
67779        if( rc==SQLITE_OK ){
67780          aData[18] = (u8)iVersion;
67781          aData[19] = (u8)iVersion;
67782        }
67783      }
67784    }
67785  }
67786
67787  pBt->btsFlags &= ~BTS_NO_WAL;
67788  return rc;
67789}
67790
67791/*
67792** Return true if the cursor has a hint specified.  This routine is
67793** only used from within assert() statements
67794*/
67795SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
67796  return (pCsr->hints & mask)!=0;
67797}
67798
67799/*
67800** Return true if the given Btree is read-only.
67801*/
67802SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
67803  return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
67804}
67805
67806/*
67807** Return the size of the header added to each page by this module.
67808*/
67809SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
67810
67811#if !defined(SQLITE_OMIT_SHARED_CACHE)
67812/*
67813** Return true if the Btree passed as the only argument is sharable.
67814*/
67815SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
67816  return p->sharable;
67817}
67818
67819/*
67820** Return the number of connections to the BtShared object accessed by
67821** the Btree handle passed as the only argument. For private caches
67822** this is always 1. For shared caches it may be 1 or greater.
67823*/
67824SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
67825  testcase( p->sharable );
67826  return p->pBt->nRef;
67827}
67828#endif
67829
67830/************** End of btree.c ***********************************************/
67831/************** Begin file backup.c ******************************************/
67832/*
67833** 2009 January 28
67834**
67835** The author disclaims copyright to this source code.  In place of
67836** a legal notice, here is a blessing:
67837**
67838**    May you do good and not evil.
67839**    May you find forgiveness for yourself and forgive others.
67840**    May you share freely, never taking more than you give.
67841**
67842*************************************************************************
67843** This file contains the implementation of the sqlite3_backup_XXX()
67844** API functions and the related features.
67845*/
67846/* #include "sqliteInt.h" */
67847/* #include "btreeInt.h" */
67848
67849/*
67850** Structure allocated for each backup operation.
67851*/
67852struct sqlite3_backup {
67853  sqlite3* pDestDb;        /* Destination database handle */
67854  Btree *pDest;            /* Destination b-tree file */
67855  u32 iDestSchema;         /* Original schema cookie in destination */
67856  int bDestLocked;         /* True once a write-transaction is open on pDest */
67857
67858  Pgno iNext;              /* Page number of the next source page to copy */
67859  sqlite3* pSrcDb;         /* Source database handle */
67860  Btree *pSrc;             /* Source b-tree file */
67861
67862  int rc;                  /* Backup process error code */
67863
67864  /* These two variables are set by every call to backup_step(). They are
67865  ** read by calls to backup_remaining() and backup_pagecount().
67866  */
67867  Pgno nRemaining;         /* Number of pages left to copy */
67868  Pgno nPagecount;         /* Total number of pages to copy */
67869
67870  int isAttached;          /* True once backup has been registered with pager */
67871  sqlite3_backup *pNext;   /* Next backup associated with source pager */
67872};
67873
67874/*
67875** THREAD SAFETY NOTES:
67876**
67877**   Once it has been created using backup_init(), a single sqlite3_backup
67878**   structure may be accessed via two groups of thread-safe entry points:
67879**
67880**     * Via the sqlite3_backup_XXX() API function backup_step() and
67881**       backup_finish(). Both these functions obtain the source database
67882**       handle mutex and the mutex associated with the source BtShared
67883**       structure, in that order.
67884**
67885**     * Via the BackupUpdate() and BackupRestart() functions, which are
67886**       invoked by the pager layer to report various state changes in
67887**       the page cache associated with the source database. The mutex
67888**       associated with the source database BtShared structure will always
67889**       be held when either of these functions are invoked.
67890**
67891**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
67892**   backup_pagecount() are not thread-safe functions. If they are called
67893**   while some other thread is calling backup_step() or backup_finish(),
67894**   the values returned may be invalid. There is no way for a call to
67895**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
67896**   or backup_pagecount().
67897**
67898**   Depending on the SQLite configuration, the database handles and/or
67899**   the Btree objects may have their own mutexes that require locking.
67900**   Non-sharable Btrees (in-memory databases for example), do not have
67901**   associated mutexes.
67902*/
67903
67904/*
67905** Return a pointer corresponding to database zDb (i.e. "main", "temp")
67906** in connection handle pDb. If such a database cannot be found, return
67907** a NULL pointer and write an error message to pErrorDb.
67908**
67909** If the "temp" database is requested, it may need to be opened by this
67910** function. If an error occurs while doing so, return 0 and write an
67911** error message to pErrorDb.
67912*/
67913static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
67914  int i = sqlite3FindDbName(pDb, zDb);
67915
67916  if( i==1 ){
67917    Parse *pParse;
67918    int rc = 0;
67919    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
67920    if( pParse==0 ){
67921      sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
67922      rc = SQLITE_NOMEM_BKPT;
67923    }else{
67924      pParse->db = pDb;
67925      if( sqlite3OpenTempDatabase(pParse) ){
67926        sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
67927        rc = SQLITE_ERROR;
67928      }
67929      sqlite3DbFree(pErrorDb, pParse->zErrMsg);
67930      sqlite3ParserReset(pParse);
67931      sqlite3StackFree(pErrorDb, pParse);
67932    }
67933    if( rc ){
67934      return 0;
67935    }
67936  }
67937
67938  if( i<0 ){
67939    sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
67940    return 0;
67941  }
67942
67943  return pDb->aDb[i].pBt;
67944}
67945
67946/*
67947** Attempt to set the page size of the destination to match the page size
67948** of the source.
67949*/
67950static int setDestPgsz(sqlite3_backup *p){
67951  int rc;
67952  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
67953  return rc;
67954}
67955
67956/*
67957** Check that there is no open read-transaction on the b-tree passed as the
67958** second argument. If there is not, return SQLITE_OK. Otherwise, if there
67959** is an open read-transaction, return SQLITE_ERROR and leave an error
67960** message in database handle db.
67961*/
67962static int checkReadTransaction(sqlite3 *db, Btree *p){
67963  if( sqlite3BtreeIsInReadTrans(p) ){
67964    sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
67965    return SQLITE_ERROR;
67966  }
67967  return SQLITE_OK;
67968}
67969
67970/*
67971** Create an sqlite3_backup process to copy the contents of zSrcDb from
67972** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
67973** a pointer to the new sqlite3_backup object.
67974**
67975** If an error occurs, NULL is returned and an error code and error message
67976** stored in database handle pDestDb.
67977*/
67978SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
67979  sqlite3* pDestDb,                     /* Database to write to */
67980  const char *zDestDb,                  /* Name of database within pDestDb */
67981  sqlite3* pSrcDb,                      /* Database connection to read from */
67982  const char *zSrcDb                    /* Name of database within pSrcDb */
67983){
67984  sqlite3_backup *p;                    /* Value to return */
67985
67986#ifdef SQLITE_ENABLE_API_ARMOR
67987  if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
67988    (void)SQLITE_MISUSE_BKPT;
67989    return 0;
67990  }
67991#endif
67992
67993  /* Lock the source database handle. The destination database
67994  ** handle is not locked in this routine, but it is locked in
67995  ** sqlite3_backup_step(). The user is required to ensure that no
67996  ** other thread accesses the destination handle for the duration
67997  ** of the backup operation.  Any attempt to use the destination
67998  ** database connection while a backup is in progress may cause
67999  ** a malfunction or a deadlock.
68000  */
68001  sqlite3_mutex_enter(pSrcDb->mutex);
68002  sqlite3_mutex_enter(pDestDb->mutex);
68003
68004  if( pSrcDb==pDestDb ){
68005    sqlite3ErrorWithMsg(
68006        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
68007    );
68008    p = 0;
68009  }else {
68010    /* Allocate space for a new sqlite3_backup object...
68011    ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
68012    ** call to sqlite3_backup_init() and is destroyed by a call to
68013    ** sqlite3_backup_finish(). */
68014    p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
68015    if( !p ){
68016      sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
68017    }
68018  }
68019
68020  /* If the allocation succeeded, populate the new object. */
68021  if( p ){
68022    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
68023    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
68024    p->pDestDb = pDestDb;
68025    p->pSrcDb = pSrcDb;
68026    p->iNext = 1;
68027    p->isAttached = 0;
68028
68029    if( 0==p->pSrc || 0==p->pDest
68030     || setDestPgsz(p)==SQLITE_NOMEM
68031     || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
68032     ){
68033      /* One (or both) of the named databases did not exist or an OOM
68034      ** error was hit. Or there is a transaction open on the destination
68035      ** database. The error has already been written into the pDestDb
68036      ** handle. All that is left to do here is free the sqlite3_backup
68037      ** structure.  */
68038      sqlite3_free(p);
68039      p = 0;
68040    }
68041  }
68042  if( p ){
68043    p->pSrc->nBackup++;
68044  }
68045
68046  sqlite3_mutex_leave(pDestDb->mutex);
68047  sqlite3_mutex_leave(pSrcDb->mutex);
68048  return p;
68049}
68050
68051/*
68052** Argument rc is an SQLite error code. Return true if this error is
68053** considered fatal if encountered during a backup operation. All errors
68054** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
68055*/
68056static int isFatalError(int rc){
68057  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
68058}
68059
68060/*
68061** Parameter zSrcData points to a buffer containing the data for
68062** page iSrcPg from the source database. Copy this data into the
68063** destination database.
68064*/
68065static int backupOnePage(
68066  sqlite3_backup *p,              /* Backup handle */
68067  Pgno iSrcPg,                    /* Source database page to backup */
68068  const u8 *zSrcData,             /* Source database page data */
68069  int bUpdate                     /* True for an update, false otherwise */
68070){
68071  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
68072  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
68073  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
68074  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
68075  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
68076#ifdef SQLITE_HAS_CODEC
68077  /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
68078  ** guaranteed that the shared-mutex is held by this thread, handle
68079  ** p->pSrc may not actually be the owner.  */
68080  int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
68081  int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
68082#endif
68083  int rc = SQLITE_OK;
68084  i64 iOff;
68085
68086  assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
68087  assert( p->bDestLocked );
68088  assert( !isFatalError(p->rc) );
68089  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
68090  assert( zSrcData );
68091
68092  /* Catch the case where the destination is an in-memory database and the
68093  ** page sizes of the source and destination differ.
68094  */
68095  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
68096    rc = SQLITE_READONLY;
68097  }
68098
68099#ifdef SQLITE_HAS_CODEC
68100  /* Backup is not possible if the page size of the destination is changing
68101  ** and a codec is in use.
68102  */
68103  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
68104    rc = SQLITE_READONLY;
68105  }
68106
68107  /* Backup is not possible if the number of bytes of reserve space differ
68108  ** between source and destination.  If there is a difference, try to
68109  ** fix the destination to agree with the source.  If that is not possible,
68110  ** then the backup cannot proceed.
68111  */
68112  if( nSrcReserve!=nDestReserve ){
68113    u32 newPgsz = nSrcPgsz;
68114    rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
68115    if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
68116  }
68117#endif
68118
68119  /* This loop runs once for each destination page spanned by the source
68120  ** page. For each iteration, variable iOff is set to the byte offset
68121  ** of the destination page.
68122  */
68123  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
68124    DbPage *pDestPg = 0;
68125    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
68126    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
68127    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
68128     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
68129    ){
68130      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
68131      u8 *zDestData = sqlite3PagerGetData(pDestPg);
68132      u8 *zOut = &zDestData[iOff%nDestPgsz];
68133
68134      /* Copy the data from the source page into the destination page.
68135      ** Then clear the Btree layer MemPage.isInit flag. Both this module
68136      ** and the pager code use this trick (clearing the first byte
68137      ** of the page 'extra' space to invalidate the Btree layers
68138      ** cached parse of the page). MemPage.isInit is marked
68139      ** "MUST BE FIRST" for this purpose.
68140      */
68141      memcpy(zOut, zIn, nCopy);
68142      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
68143      if( iOff==0 && bUpdate==0 ){
68144        sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
68145      }
68146    }
68147    sqlite3PagerUnref(pDestPg);
68148  }
68149
68150  return rc;
68151}
68152
68153/*
68154** If pFile is currently larger than iSize bytes, then truncate it to
68155** exactly iSize bytes. If pFile is not larger than iSize bytes, then
68156** this function is a no-op.
68157**
68158** Return SQLITE_OK if everything is successful, or an SQLite error
68159** code if an error occurs.
68160*/
68161static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
68162  i64 iCurrent;
68163  int rc = sqlite3OsFileSize(pFile, &iCurrent);
68164  if( rc==SQLITE_OK && iCurrent>iSize ){
68165    rc = sqlite3OsTruncate(pFile, iSize);
68166  }
68167  return rc;
68168}
68169
68170/*
68171** Register this backup object with the associated source pager for
68172** callbacks when pages are changed or the cache invalidated.
68173*/
68174static void attachBackupObject(sqlite3_backup *p){
68175  sqlite3_backup **pp;
68176  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
68177  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
68178  p->pNext = *pp;
68179  *pp = p;
68180  p->isAttached = 1;
68181}
68182
68183/*
68184** Copy nPage pages from the source b-tree to the destination.
68185*/
68186SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage){
68187  int rc;
68188  int destMode;       /* Destination journal mode */
68189  int pgszSrc = 0;    /* Source page size */
68190  int pgszDest = 0;   /* Destination page size */
68191
68192#ifdef SQLITE_ENABLE_API_ARMOR
68193  if( p==0 ) return SQLITE_MISUSE_BKPT;
68194#endif
68195  sqlite3_mutex_enter(p->pSrcDb->mutex);
68196  sqlite3BtreeEnter(p->pSrc);
68197  if( p->pDestDb ){
68198    sqlite3_mutex_enter(p->pDestDb->mutex);
68199  }
68200
68201  rc = p->rc;
68202  if( !isFatalError(rc) ){
68203    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
68204    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
68205    int ii;                            /* Iterator variable */
68206    int nSrcPage = -1;                 /* Size of source db in pages */
68207    int bCloseTrans = 0;               /* True if src db requires unlocking */
68208
68209    /* If the source pager is currently in a write-transaction, return
68210    ** SQLITE_BUSY immediately.
68211    */
68212    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
68213      rc = SQLITE_BUSY;
68214    }else{
68215      rc = SQLITE_OK;
68216    }
68217
68218    /* Lock the destination database, if it is not locked already. */
68219    if( SQLITE_OK==rc && p->bDestLocked==0
68220     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
68221    ){
68222      p->bDestLocked = 1;
68223      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
68224    }
68225
68226    /* If there is no open read-transaction on the source database, open
68227    ** one now. If a transaction is opened here, then it will be closed
68228    ** before this function exits.
68229    */
68230    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
68231      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
68232      bCloseTrans = 1;
68233    }
68234
68235    /* Do not allow backup if the destination database is in WAL mode
68236    ** and the page sizes are different between source and destination */
68237    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
68238    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
68239    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
68240    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
68241      rc = SQLITE_READONLY;
68242    }
68243
68244    /* Now that there is a read-lock on the source database, query the
68245    ** source pager for the number of pages in the database.
68246    */
68247    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
68248    assert( nSrcPage>=0 );
68249    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
68250      const Pgno iSrcPg = p->iNext;                 /* Source page number */
68251      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
68252        DbPage *pSrcPg;                             /* Source page object */
68253        rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
68254        if( rc==SQLITE_OK ){
68255          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
68256          sqlite3PagerUnref(pSrcPg);
68257        }
68258      }
68259      p->iNext++;
68260    }
68261    if( rc==SQLITE_OK ){
68262      p->nPagecount = nSrcPage;
68263      p->nRemaining = nSrcPage+1-p->iNext;
68264      if( p->iNext>(Pgno)nSrcPage ){
68265        rc = SQLITE_DONE;
68266      }else if( !p->isAttached ){
68267        attachBackupObject(p);
68268      }
68269    }
68270
68271    /* Update the schema version field in the destination database. This
68272    ** is to make sure that the schema-version really does change in
68273    ** the case where the source and destination databases have the
68274    ** same schema version.
68275    */
68276    if( rc==SQLITE_DONE ){
68277      if( nSrcPage==0 ){
68278        rc = sqlite3BtreeNewDb(p->pDest);
68279        nSrcPage = 1;
68280      }
68281      if( rc==SQLITE_OK || rc==SQLITE_DONE ){
68282        rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
68283      }
68284      if( rc==SQLITE_OK ){
68285        if( p->pDestDb ){
68286          sqlite3ResetAllSchemasOfConnection(p->pDestDb);
68287        }
68288        if( destMode==PAGER_JOURNALMODE_WAL ){
68289          rc = sqlite3BtreeSetVersion(p->pDest, 2);
68290        }
68291      }
68292      if( rc==SQLITE_OK ){
68293        int nDestTruncate;
68294        /* Set nDestTruncate to the final number of pages in the destination
68295        ** database. The complication here is that the destination page
68296        ** size may be different to the source page size.
68297        **
68298        ** If the source page size is smaller than the destination page size,
68299        ** round up. In this case the call to sqlite3OsTruncate() below will
68300        ** fix the size of the file. However it is important to call
68301        ** sqlite3PagerTruncateImage() here so that any pages in the
68302        ** destination file that lie beyond the nDestTruncate page mark are
68303        ** journalled by PagerCommitPhaseOne() before they are destroyed
68304        ** by the file truncation.
68305        */
68306        assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
68307        assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
68308        if( pgszSrc<pgszDest ){
68309          int ratio = pgszDest/pgszSrc;
68310          nDestTruncate = (nSrcPage+ratio-1)/ratio;
68311          if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
68312            nDestTruncate--;
68313          }
68314        }else{
68315          nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
68316        }
68317        assert( nDestTruncate>0 );
68318
68319        if( pgszSrc<pgszDest ){
68320          /* If the source page-size is smaller than the destination page-size,
68321          ** two extra things may need to happen:
68322          **
68323          **   * The destination may need to be truncated, and
68324          **
68325          **   * Data stored on the pages immediately following the
68326          **     pending-byte page in the source database may need to be
68327          **     copied into the destination database.
68328          */
68329          const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
68330          sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
68331          Pgno iPg;
68332          int nDstPage;
68333          i64 iOff;
68334          i64 iEnd;
68335
68336          assert( pFile );
68337          assert( nDestTruncate==0
68338              || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
68339                nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
68340             && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
68341          ));
68342
68343          /* This block ensures that all data required to recreate the original
68344          ** database has been stored in the journal for pDestPager and the
68345          ** journal synced to disk. So at this point we may safely modify
68346          ** the database file in any way, knowing that if a power failure
68347          ** occurs, the original database will be reconstructed from the
68348          ** journal file.  */
68349          sqlite3PagerPagecount(pDestPager, &nDstPage);
68350          for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
68351            if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
68352              DbPage *pPg;
68353              rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
68354              if( rc==SQLITE_OK ){
68355                rc = sqlite3PagerWrite(pPg);
68356                sqlite3PagerUnref(pPg);
68357              }
68358            }
68359          }
68360          if( rc==SQLITE_OK ){
68361            rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
68362          }
68363
68364          /* Write the extra pages and truncate the database file as required */
68365          iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
68366          for(
68367            iOff=PENDING_BYTE+pgszSrc;
68368            rc==SQLITE_OK && iOff<iEnd;
68369            iOff+=pgszSrc
68370          ){
68371            PgHdr *pSrcPg = 0;
68372            const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
68373            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
68374            if( rc==SQLITE_OK ){
68375              u8 *zData = sqlite3PagerGetData(pSrcPg);
68376              rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
68377            }
68378            sqlite3PagerUnref(pSrcPg);
68379          }
68380          if( rc==SQLITE_OK ){
68381            rc = backupTruncateFile(pFile, iSize);
68382          }
68383
68384          /* Sync the database file to disk. */
68385          if( rc==SQLITE_OK ){
68386            rc = sqlite3PagerSync(pDestPager, 0);
68387          }
68388        }else{
68389          sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
68390          rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
68391        }
68392
68393        /* Finish committing the transaction to the destination database. */
68394        if( SQLITE_OK==rc
68395         && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
68396        ){
68397          rc = SQLITE_DONE;
68398        }
68399      }
68400    }
68401
68402    /* If bCloseTrans is true, then this function opened a read transaction
68403    ** on the source database. Close the read transaction here. There is
68404    ** no need to check the return values of the btree methods here, as
68405    ** "committing" a read-only transaction cannot fail.
68406    */
68407    if( bCloseTrans ){
68408      TESTONLY( int rc2 );
68409      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
68410      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
68411      assert( rc2==SQLITE_OK );
68412    }
68413
68414    if( rc==SQLITE_IOERR_NOMEM ){
68415      rc = SQLITE_NOMEM_BKPT;
68416    }
68417    p->rc = rc;
68418  }
68419  if( p->pDestDb ){
68420    sqlite3_mutex_leave(p->pDestDb->mutex);
68421  }
68422  sqlite3BtreeLeave(p->pSrc);
68423  sqlite3_mutex_leave(p->pSrcDb->mutex);
68424  return rc;
68425}
68426
68427/*
68428** Release all resources associated with an sqlite3_backup* handle.
68429*/
68430SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p){
68431  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
68432  sqlite3 *pSrcDb;                     /* Source database connection */
68433  int rc;                              /* Value to return */
68434
68435  /* Enter the mutexes */
68436  if( p==0 ) return SQLITE_OK;
68437  pSrcDb = p->pSrcDb;
68438  sqlite3_mutex_enter(pSrcDb->mutex);
68439  sqlite3BtreeEnter(p->pSrc);
68440  if( p->pDestDb ){
68441    sqlite3_mutex_enter(p->pDestDb->mutex);
68442  }
68443
68444  /* Detach this backup from the source pager. */
68445  if( p->pDestDb ){
68446    p->pSrc->nBackup--;
68447  }
68448  if( p->isAttached ){
68449    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
68450    while( *pp!=p ){
68451      pp = &(*pp)->pNext;
68452    }
68453    *pp = p->pNext;
68454  }
68455
68456  /* If a transaction is still open on the Btree, roll it back. */
68457  sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
68458
68459  /* Set the error code of the destination database handle. */
68460  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
68461  if( p->pDestDb ){
68462    sqlite3Error(p->pDestDb, rc);
68463
68464    /* Exit the mutexes and free the backup context structure. */
68465    sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
68466  }
68467  sqlite3BtreeLeave(p->pSrc);
68468  if( p->pDestDb ){
68469    /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
68470    ** call to sqlite3_backup_init() and is destroyed by a call to
68471    ** sqlite3_backup_finish(). */
68472    sqlite3_free(p);
68473  }
68474  sqlite3LeaveMutexAndCloseZombie(pSrcDb);
68475  return rc;
68476}
68477
68478/*
68479** Return the number of pages still to be backed up as of the most recent
68480** call to sqlite3_backup_step().
68481*/
68482SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p){
68483#ifdef SQLITE_ENABLE_API_ARMOR
68484  if( p==0 ){
68485    (void)SQLITE_MISUSE_BKPT;
68486    return 0;
68487  }
68488#endif
68489  return p->nRemaining;
68490}
68491
68492/*
68493** Return the total number of pages in the source database as of the most
68494** recent call to sqlite3_backup_step().
68495*/
68496SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p){
68497#ifdef SQLITE_ENABLE_API_ARMOR
68498  if( p==0 ){
68499    (void)SQLITE_MISUSE_BKPT;
68500    return 0;
68501  }
68502#endif
68503  return p->nPagecount;
68504}
68505
68506/*
68507** This function is called after the contents of page iPage of the
68508** source database have been modified. If page iPage has already been
68509** copied into the destination database, then the data written to the
68510** destination is now invalidated. The destination copy of iPage needs
68511** to be updated with the new data before the backup operation is
68512** complete.
68513**
68514** It is assumed that the mutex associated with the BtShared object
68515** corresponding to the source database is held when this function is
68516** called.
68517*/
68518static SQLITE_NOINLINE void backupUpdate(
68519  sqlite3_backup *p,
68520  Pgno iPage,
68521  const u8 *aData
68522){
68523  assert( p!=0 );
68524  do{
68525    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
68526    if( !isFatalError(p->rc) && iPage<p->iNext ){
68527      /* The backup process p has already copied page iPage. But now it
68528      ** has been modified by a transaction on the source pager. Copy
68529      ** the new data into the backup.
68530      */
68531      int rc;
68532      assert( p->pDestDb );
68533      sqlite3_mutex_enter(p->pDestDb->mutex);
68534      rc = backupOnePage(p, iPage, aData, 1);
68535      sqlite3_mutex_leave(p->pDestDb->mutex);
68536      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
68537      if( rc!=SQLITE_OK ){
68538        p->rc = rc;
68539      }
68540    }
68541  }while( (p = p->pNext)!=0 );
68542}
68543SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
68544  if( pBackup ) backupUpdate(pBackup, iPage, aData);
68545}
68546
68547/*
68548** Restart the backup process. This is called when the pager layer
68549** detects that the database has been modified by an external database
68550** connection. In this case there is no way of knowing which of the
68551** pages that have been copied into the destination database are still
68552** valid and which are not, so the entire process needs to be restarted.
68553**
68554** It is assumed that the mutex associated with the BtShared object
68555** corresponding to the source database is held when this function is
68556** called.
68557*/
68558SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
68559  sqlite3_backup *p;                   /* Iterator variable */
68560  for(p=pBackup; p; p=p->pNext){
68561    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
68562    p->iNext = 1;
68563  }
68564}
68565
68566#ifndef SQLITE_OMIT_VACUUM
68567/*
68568** Copy the complete content of pBtFrom into pBtTo.  A transaction
68569** must be active for both files.
68570**
68571** The size of file pTo may be reduced by this operation. If anything
68572** goes wrong, the transaction on pTo is rolled back. If successful, the
68573** transaction is committed before returning.
68574*/
68575SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
68576  int rc;
68577  sqlite3_file *pFd;              /* File descriptor for database pTo */
68578  sqlite3_backup b;
68579  sqlite3BtreeEnter(pTo);
68580  sqlite3BtreeEnter(pFrom);
68581
68582  assert( sqlite3BtreeIsInTrans(pTo) );
68583  pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
68584  if( pFd->pMethods ){
68585    i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
68586    rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
68587    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
68588    if( rc ) goto copy_finished;
68589  }
68590
68591  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
68592  ** to 0. This is used by the implementations of sqlite3_backup_step()
68593  ** and sqlite3_backup_finish() to detect that they are being called
68594  ** from this function, not directly by the user.
68595  */
68596  memset(&b, 0, sizeof(b));
68597  b.pSrcDb = pFrom->db;
68598  b.pSrc = pFrom;
68599  b.pDest = pTo;
68600  b.iNext = 1;
68601
68602#ifdef SQLITE_HAS_CODEC
68603  sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
68604#endif
68605
68606  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
68607  ** file. By passing this as the number of pages to copy to
68608  ** sqlite3_backup_step(), we can guarantee that the copy finishes
68609  ** within a single call (unless an error occurs). The assert() statement
68610  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
68611  ** or an error code.  */
68612  sqlite3_backup_step(&b, 0x7FFFFFFF);
68613  assert( b.rc!=SQLITE_OK );
68614
68615  rc = sqlite3_backup_finish(&b);
68616  if( rc==SQLITE_OK ){
68617    pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
68618  }else{
68619    sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
68620  }
68621
68622  assert( sqlite3BtreeIsInTrans(pTo)==0 );
68623copy_finished:
68624  sqlite3BtreeLeave(pFrom);
68625  sqlite3BtreeLeave(pTo);
68626  return rc;
68627}
68628#endif /* SQLITE_OMIT_VACUUM */
68629
68630/************** End of backup.c **********************************************/
68631/************** Begin file vdbemem.c *****************************************/
68632/*
68633** 2004 May 26
68634**
68635** The author disclaims copyright to this source code.  In place of
68636** a legal notice, here is a blessing:
68637**
68638**    May you do good and not evil.
68639**    May you find forgiveness for yourself and forgive others.
68640**    May you share freely, never taking more than you give.
68641**
68642*************************************************************************
68643**
68644** This file contains code use to manipulate "Mem" structure.  A "Mem"
68645** stores a single value in the VDBE.  Mem is an opaque structure visible
68646** only within the VDBE.  Interface routines refer to a Mem using the
68647** name sqlite_value
68648*/
68649/* #include "sqliteInt.h" */
68650/* #include "vdbeInt.h" */
68651
68652#ifdef SQLITE_DEBUG
68653/*
68654** Check invariants on a Mem object.
68655**
68656** This routine is intended for use inside of assert() statements, like
68657** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
68658*/
68659SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
68660  /* If MEM_Dyn is set then Mem.xDel!=0.
68661  ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
68662  */
68663  assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
68664
68665  /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we
68666  ** ensure that if Mem.szMalloc>0 then it is safe to do
68667  ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
68668  ** That saves a few cycles in inner loops. */
68669  assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
68670
68671  /* Cannot be both MEM_Int and MEM_Real at the same time */
68672  assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
68673
68674  /* The szMalloc field holds the correct memory allocation size */
68675  assert( p->szMalloc==0
68676       || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
68677
68678  /* If p holds a string or blob, the Mem.z must point to exactly
68679  ** one of the following:
68680  **
68681  **   (1) Memory in Mem.zMalloc and managed by the Mem object
68682  **   (2) Memory to be freed using Mem.xDel
68683  **   (3) An ephemeral string or blob
68684  **   (4) A static string or blob
68685  */
68686  if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
68687    assert(
68688      ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
68689      ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
68690      ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
68691      ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
68692    );
68693  }
68694  return 1;
68695}
68696#endif
68697
68698
68699/*
68700** If pMem is an object with a valid string representation, this routine
68701** ensures the internal encoding for the string representation is
68702** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
68703**
68704** If pMem is not a string object, or the encoding of the string
68705** representation is already stored using the requested encoding, then this
68706** routine is a no-op.
68707**
68708** SQLITE_OK is returned if the conversion is successful (or not required).
68709** SQLITE_NOMEM may be returned if a malloc() fails during conversion
68710** between formats.
68711*/
68712SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
68713#ifndef SQLITE_OMIT_UTF16
68714  int rc;
68715#endif
68716  assert( (pMem->flags&MEM_RowSet)==0 );
68717  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
68718           || desiredEnc==SQLITE_UTF16BE );
68719  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
68720    return SQLITE_OK;
68721  }
68722  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68723#ifdef SQLITE_OMIT_UTF16
68724  return SQLITE_ERROR;
68725#else
68726
68727  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
68728  ** then the encoding of the value may not have changed.
68729  */
68730  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
68731  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
68732  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
68733  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
68734  return rc;
68735#endif
68736}
68737
68738/*
68739** Make sure pMem->z points to a writable allocation of at least
68740** min(n,32) bytes.
68741**
68742** If the bPreserve argument is true, then copy of the content of
68743** pMem->z into the new allocation.  pMem must be either a string or
68744** blob if bPreserve is true.  If bPreserve is false, any prior content
68745** in pMem->z is discarded.
68746*/
68747SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
68748  assert( sqlite3VdbeCheckMemInvariants(pMem) );
68749  assert( (pMem->flags&MEM_RowSet)==0 );
68750  testcase( pMem->db==0 );
68751
68752  /* If the bPreserve flag is set to true, then the memory cell must already
68753  ** contain a valid string or blob value.  */
68754  assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
68755  testcase( bPreserve && pMem->z==0 );
68756
68757  assert( pMem->szMalloc==0
68758       || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
68759  if( pMem->szMalloc<n ){
68760    if( n<32 ) n = 32;
68761    if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
68762      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
68763      bPreserve = 0;
68764    }else{
68765      if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
68766      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
68767    }
68768    if( pMem->zMalloc==0 ){
68769      sqlite3VdbeMemSetNull(pMem);
68770      pMem->z = 0;
68771      pMem->szMalloc = 0;
68772      return SQLITE_NOMEM_BKPT;
68773    }else{
68774      pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
68775    }
68776  }
68777
68778  if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
68779    memcpy(pMem->zMalloc, pMem->z, pMem->n);
68780  }
68781  if( (pMem->flags&MEM_Dyn)!=0 ){
68782    assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
68783    pMem->xDel((void *)(pMem->z));
68784  }
68785
68786  pMem->z = pMem->zMalloc;
68787  pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
68788  return SQLITE_OK;
68789}
68790
68791/*
68792** Change the pMem->zMalloc allocation to be at least szNew bytes.
68793** If pMem->zMalloc already meets or exceeds the requested size, this
68794** routine is a no-op.
68795**
68796** Any prior string or blob content in the pMem object may be discarded.
68797** The pMem->xDel destructor is called, if it exists.  Though MEM_Str
68798** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
68799** values are preserved.
68800**
68801** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
68802** if unable to complete the resizing.
68803*/
68804SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
68805  assert( szNew>0 );
68806  assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
68807  if( pMem->szMalloc<szNew ){
68808    return sqlite3VdbeMemGrow(pMem, szNew, 0);
68809  }
68810  assert( (pMem->flags & MEM_Dyn)==0 );
68811  pMem->z = pMem->zMalloc;
68812  pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
68813  return SQLITE_OK;
68814}
68815
68816/*
68817** Change pMem so that its MEM_Str or MEM_Blob value is stored in
68818** MEM.zMalloc, where it can be safely written.
68819**
68820** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
68821*/
68822SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
68823  int f;
68824  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68825  assert( (pMem->flags&MEM_RowSet)==0 );
68826  ExpandBlob(pMem);
68827  f = pMem->flags;
68828  if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
68829    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
68830      return SQLITE_NOMEM_BKPT;
68831    }
68832    pMem->z[pMem->n] = 0;
68833    pMem->z[pMem->n+1] = 0;
68834    pMem->flags |= MEM_Term;
68835  }
68836  pMem->flags &= ~MEM_Ephem;
68837#ifdef SQLITE_DEBUG
68838  pMem->pScopyFrom = 0;
68839#endif
68840
68841  return SQLITE_OK;
68842}
68843
68844/*
68845** If the given Mem* has a zero-filled tail, turn it into an ordinary
68846** blob stored in dynamically allocated space.
68847*/
68848#ifndef SQLITE_OMIT_INCRBLOB
68849SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
68850  if( pMem->flags & MEM_Zero ){
68851    int nByte;
68852    assert( pMem->flags&MEM_Blob );
68853    assert( (pMem->flags&MEM_RowSet)==0 );
68854    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68855
68856    /* Set nByte to the number of bytes required to store the expanded blob. */
68857    nByte = pMem->n + pMem->u.nZero;
68858    if( nByte<=0 ){
68859      nByte = 1;
68860    }
68861    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
68862      return SQLITE_NOMEM_BKPT;
68863    }
68864
68865    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
68866    pMem->n += pMem->u.nZero;
68867    pMem->flags &= ~(MEM_Zero|MEM_Term);
68868  }
68869  return SQLITE_OK;
68870}
68871#endif
68872
68873/*
68874** It is already known that pMem contains an unterminated string.
68875** Add the zero terminator.
68876*/
68877static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
68878  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
68879    return SQLITE_NOMEM_BKPT;
68880  }
68881  pMem->z[pMem->n] = 0;
68882  pMem->z[pMem->n+1] = 0;
68883  pMem->flags |= MEM_Term;
68884  return SQLITE_OK;
68885}
68886
68887/*
68888** Make sure the given Mem is \u0000 terminated.
68889*/
68890SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
68891  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68892  testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
68893  testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
68894  if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
68895    return SQLITE_OK;   /* Nothing to do */
68896  }else{
68897    return vdbeMemAddTerminator(pMem);
68898  }
68899}
68900
68901/*
68902** Add MEM_Str to the set of representations for the given Mem.  Numbers
68903** are converted using sqlite3_snprintf().  Converting a BLOB to a string
68904** is a no-op.
68905**
68906** Existing representations MEM_Int and MEM_Real are invalidated if
68907** bForce is true but are retained if bForce is false.
68908**
68909** A MEM_Null value will never be passed to this function. This function is
68910** used for converting values to text for returning to the user (i.e. via
68911** sqlite3_value_text()), or for ensuring that values to be used as btree
68912** keys are strings. In the former case a NULL pointer is returned the
68913** user and the latter is an internal programming error.
68914*/
68915SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
68916  int fg = pMem->flags;
68917  const int nByte = 32;
68918
68919  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68920  assert( !(fg&MEM_Zero) );
68921  assert( !(fg&(MEM_Str|MEM_Blob)) );
68922  assert( fg&(MEM_Int|MEM_Real) );
68923  assert( (pMem->flags&MEM_RowSet)==0 );
68924  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
68925
68926
68927  if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
68928    return SQLITE_NOMEM_BKPT;
68929  }
68930
68931  /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
68932  ** string representation of the value. Then, if the required encoding
68933  ** is UTF-16le or UTF-16be do a translation.
68934  **
68935  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
68936  */
68937  if( fg & MEM_Int ){
68938    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
68939  }else{
68940    assert( fg & MEM_Real );
68941    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
68942  }
68943  pMem->n = sqlite3Strlen30(pMem->z);
68944  pMem->enc = SQLITE_UTF8;
68945  pMem->flags |= MEM_Str|MEM_Term;
68946  if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
68947  sqlite3VdbeChangeEncoding(pMem, enc);
68948  return SQLITE_OK;
68949}
68950
68951/*
68952** Memory cell pMem contains the context of an aggregate function.
68953** This routine calls the finalize method for that function.  The
68954** result of the aggregate is stored back into pMem.
68955**
68956** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
68957** otherwise.
68958*/
68959SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
68960  int rc = SQLITE_OK;
68961  if( ALWAYS(pFunc && pFunc->xFinalize) ){
68962    sqlite3_context ctx;
68963    Mem t;
68964    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
68965    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68966    memset(&ctx, 0, sizeof(ctx));
68967    memset(&t, 0, sizeof(t));
68968    t.flags = MEM_Null;
68969    t.db = pMem->db;
68970    ctx.pOut = &t;
68971    ctx.pMem = pMem;
68972    ctx.pFunc = pFunc;
68973    pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
68974    assert( (pMem->flags & MEM_Dyn)==0 );
68975    if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
68976    memcpy(pMem, &t, sizeof(t));
68977    rc = ctx.isError;
68978  }
68979  return rc;
68980}
68981
68982/*
68983** If the memory cell contains a value that must be freed by
68984** invoking the external callback in Mem.xDel, then this routine
68985** will free that value.  It also sets Mem.flags to MEM_Null.
68986**
68987** This is a helper routine for sqlite3VdbeMemSetNull() and
68988** for sqlite3VdbeMemRelease().  Use those other routines as the
68989** entry point for releasing Mem resources.
68990*/
68991static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
68992  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
68993  assert( VdbeMemDynamic(p) );
68994  if( p->flags&MEM_Agg ){
68995    sqlite3VdbeMemFinalize(p, p->u.pDef);
68996    assert( (p->flags & MEM_Agg)==0 );
68997    testcase( p->flags & MEM_Dyn );
68998  }
68999  if( p->flags&MEM_Dyn ){
69000    assert( (p->flags&MEM_RowSet)==0 );
69001    assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
69002    p->xDel((void *)p->z);
69003  }else if( p->flags&MEM_RowSet ){
69004    sqlite3RowSetClear(p->u.pRowSet);
69005  }else if( p->flags&MEM_Frame ){
69006    VdbeFrame *pFrame = p->u.pFrame;
69007    pFrame->pParent = pFrame->v->pDelFrame;
69008    pFrame->v->pDelFrame = pFrame;
69009  }
69010  p->flags = MEM_Null;
69011}
69012
69013/*
69014** Release memory held by the Mem p, both external memory cleared
69015** by p->xDel and memory in p->zMalloc.
69016**
69017** This is a helper routine invoked by sqlite3VdbeMemRelease() in
69018** the unusual case where there really is memory in p that needs
69019** to be freed.
69020*/
69021static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
69022  if( VdbeMemDynamic(p) ){
69023    vdbeMemClearExternAndSetNull(p);
69024  }
69025  if( p->szMalloc ){
69026    sqlite3DbFree(p->db, p->zMalloc);
69027    p->szMalloc = 0;
69028  }
69029  p->z = 0;
69030}
69031
69032/*
69033** Release any memory resources held by the Mem.  Both the memory that is
69034** free by Mem.xDel and the Mem.zMalloc allocation are freed.
69035**
69036** Use this routine prior to clean up prior to abandoning a Mem, or to
69037** reset a Mem back to its minimum memory utilization.
69038**
69039** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
69040** prior to inserting new content into the Mem.
69041*/
69042SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
69043  assert( sqlite3VdbeCheckMemInvariants(p) );
69044  if( VdbeMemDynamic(p) || p->szMalloc ){
69045    vdbeMemClear(p);
69046  }
69047}
69048
69049/*
69050** Convert a 64-bit IEEE double into a 64-bit signed integer.
69051** If the double is out of range of a 64-bit signed integer then
69052** return the closest available 64-bit signed integer.
69053*/
69054static i64 doubleToInt64(double r){
69055#ifdef SQLITE_OMIT_FLOATING_POINT
69056  /* When floating-point is omitted, double and int64 are the same thing */
69057  return r;
69058#else
69059  /*
69060  ** Many compilers we encounter do not define constants for the
69061  ** minimum and maximum 64-bit integers, or they define them
69062  ** inconsistently.  And many do not understand the "LL" notation.
69063  ** So we define our own static constants here using nothing
69064  ** larger than a 32-bit integer constant.
69065  */
69066  static const i64 maxInt = LARGEST_INT64;
69067  static const i64 minInt = SMALLEST_INT64;
69068
69069  if( r<=(double)minInt ){
69070    return minInt;
69071  }else if( r>=(double)maxInt ){
69072    return maxInt;
69073  }else{
69074    return (i64)r;
69075  }
69076#endif
69077}
69078
69079/*
69080** Return some kind of integer value which is the best we can do
69081** at representing the value that *pMem describes as an integer.
69082** If pMem is an integer, then the value is exact.  If pMem is
69083** a floating-point then the value returned is the integer part.
69084** If pMem is a string or blob, then we make an attempt to convert
69085** it into an integer and return that.  If pMem represents an
69086** an SQL-NULL value, return 0.
69087**
69088** If pMem represents a string value, its encoding might be changed.
69089*/
69090SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
69091  int flags;
69092  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69093  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69094  flags = pMem->flags;
69095  if( flags & MEM_Int ){
69096    return pMem->u.i;
69097  }else if( flags & MEM_Real ){
69098    return doubleToInt64(pMem->u.r);
69099  }else if( flags & (MEM_Str|MEM_Blob) ){
69100    i64 value = 0;
69101    assert( pMem->z || pMem->n==0 );
69102    sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
69103    return value;
69104  }else{
69105    return 0;
69106  }
69107}
69108
69109/*
69110** Return the best representation of pMem that we can get into a
69111** double.  If pMem is already a double or an integer, return its
69112** value.  If it is a string or blob, try to convert it to a double.
69113** If it is a NULL, return 0.0.
69114*/
69115SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
69116  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69117  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69118  if( pMem->flags & MEM_Real ){
69119    return pMem->u.r;
69120  }else if( pMem->flags & MEM_Int ){
69121    return (double)pMem->u.i;
69122  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
69123    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
69124    double val = (double)0;
69125    sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
69126    return val;
69127  }else{
69128    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
69129    return (double)0;
69130  }
69131}
69132
69133/*
69134** The MEM structure is already a MEM_Real.  Try to also make it a
69135** MEM_Int if we can.
69136*/
69137SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
69138  i64 ix;
69139  assert( pMem->flags & MEM_Real );
69140  assert( (pMem->flags & MEM_RowSet)==0 );
69141  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69142  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69143
69144  ix = doubleToInt64(pMem->u.r);
69145
69146  /* Only mark the value as an integer if
69147  **
69148  **    (1) the round-trip conversion real->int->real is a no-op, and
69149  **    (2) The integer is neither the largest nor the smallest
69150  **        possible integer (ticket #3922)
69151  **
69152  ** The second and third terms in the following conditional enforces
69153  ** the second condition under the assumption that addition overflow causes
69154  ** values to wrap around.
69155  */
69156  if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
69157    pMem->u.i = ix;
69158    MemSetTypeFlag(pMem, MEM_Int);
69159  }
69160}
69161
69162/*
69163** Convert pMem to type integer.  Invalidate any prior representations.
69164*/
69165SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
69166  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69167  assert( (pMem->flags & MEM_RowSet)==0 );
69168  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69169
69170  pMem->u.i = sqlite3VdbeIntValue(pMem);
69171  MemSetTypeFlag(pMem, MEM_Int);
69172  return SQLITE_OK;
69173}
69174
69175/*
69176** Convert pMem so that it is of type MEM_Real.
69177** Invalidate any prior representations.
69178*/
69179SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
69180  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69181  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69182
69183  pMem->u.r = sqlite3VdbeRealValue(pMem);
69184  MemSetTypeFlag(pMem, MEM_Real);
69185  return SQLITE_OK;
69186}
69187
69188/*
69189** Convert pMem so that it has types MEM_Real or MEM_Int or both.
69190** Invalidate any prior representations.
69191**
69192** Every effort is made to force the conversion, even if the input
69193** is a string that does not look completely like a number.  Convert
69194** as much of the string as we can and ignore the rest.
69195*/
69196SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
69197  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
69198    assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
69199    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69200    if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
69201      MemSetTypeFlag(pMem, MEM_Int);
69202    }else{
69203      pMem->u.r = sqlite3VdbeRealValue(pMem);
69204      MemSetTypeFlag(pMem, MEM_Real);
69205      sqlite3VdbeIntegerAffinity(pMem);
69206    }
69207  }
69208  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
69209  pMem->flags &= ~(MEM_Str|MEM_Blob);
69210  return SQLITE_OK;
69211}
69212
69213/*
69214** Cast the datatype of the value in pMem according to the affinity
69215** "aff".  Casting is different from applying affinity in that a cast
69216** is forced.  In other words, the value is converted into the desired
69217** affinity even if that results in loss of data.  This routine is
69218** used (for example) to implement the SQL "cast()" operator.
69219*/
69220SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
69221  if( pMem->flags & MEM_Null ) return;
69222  switch( aff ){
69223    case SQLITE_AFF_BLOB: {   /* Really a cast to BLOB */
69224      if( (pMem->flags & MEM_Blob)==0 ){
69225        sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
69226        assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
69227        MemSetTypeFlag(pMem, MEM_Blob);
69228      }else{
69229        pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
69230      }
69231      break;
69232    }
69233    case SQLITE_AFF_NUMERIC: {
69234      sqlite3VdbeMemNumerify(pMem);
69235      break;
69236    }
69237    case SQLITE_AFF_INTEGER: {
69238      sqlite3VdbeMemIntegerify(pMem);
69239      break;
69240    }
69241    case SQLITE_AFF_REAL: {
69242      sqlite3VdbeMemRealify(pMem);
69243      break;
69244    }
69245    default: {
69246      assert( aff==SQLITE_AFF_TEXT );
69247      assert( MEM_Str==(MEM_Blob>>3) );
69248      pMem->flags |= (pMem->flags&MEM_Blob)>>3;
69249      sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
69250      assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
69251      pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
69252      break;
69253    }
69254  }
69255}
69256
69257/*
69258** Initialize bulk memory to be a consistent Mem object.
69259**
69260** The minimum amount of initialization feasible is performed.
69261*/
69262SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
69263  assert( (flags & ~MEM_TypeMask)==0 );
69264  pMem->flags = flags;
69265  pMem->db = db;
69266  pMem->szMalloc = 0;
69267}
69268
69269
69270/*
69271** Delete any previous value and set the value stored in *pMem to NULL.
69272**
69273** This routine calls the Mem.xDel destructor to dispose of values that
69274** require the destructor.  But it preserves the Mem.zMalloc memory allocation.
69275** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
69276** routine to invoke the destructor and deallocates Mem.zMalloc.
69277**
69278** Use this routine to reset the Mem prior to insert a new value.
69279**
69280** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
69281*/
69282SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
69283  if( VdbeMemDynamic(pMem) ){
69284    vdbeMemClearExternAndSetNull(pMem);
69285  }else{
69286    pMem->flags = MEM_Null;
69287  }
69288}
69289SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
69290  sqlite3VdbeMemSetNull((Mem*)p);
69291}
69292
69293/*
69294** Delete any previous value and set the value to be a BLOB of length
69295** n containing all zeros.
69296*/
69297SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
69298  sqlite3VdbeMemRelease(pMem);
69299  pMem->flags = MEM_Blob|MEM_Zero;
69300  pMem->n = 0;
69301  if( n<0 ) n = 0;
69302  pMem->u.nZero = n;
69303  pMem->enc = SQLITE_UTF8;
69304  pMem->z = 0;
69305}
69306
69307/*
69308** The pMem is known to contain content that needs to be destroyed prior
69309** to a value change.  So invoke the destructor, then set the value to
69310** a 64-bit integer.
69311*/
69312static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
69313  sqlite3VdbeMemSetNull(pMem);
69314  pMem->u.i = val;
69315  pMem->flags = MEM_Int;
69316}
69317
69318/*
69319** Delete any previous value and set the value stored in *pMem to val,
69320** manifest type INTEGER.
69321*/
69322SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
69323  if( VdbeMemDynamic(pMem) ){
69324    vdbeReleaseAndSetInt64(pMem, val);
69325  }else{
69326    pMem->u.i = val;
69327    pMem->flags = MEM_Int;
69328  }
69329}
69330
69331#ifndef SQLITE_OMIT_FLOATING_POINT
69332/*
69333** Delete any previous value and set the value stored in *pMem to val,
69334** manifest type REAL.
69335*/
69336SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
69337  sqlite3VdbeMemSetNull(pMem);
69338  if( !sqlite3IsNaN(val) ){
69339    pMem->u.r = val;
69340    pMem->flags = MEM_Real;
69341  }
69342}
69343#endif
69344
69345/*
69346** Delete any previous value and set the value of pMem to be an
69347** empty boolean index.
69348*/
69349SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
69350  sqlite3 *db = pMem->db;
69351  assert( db!=0 );
69352  assert( (pMem->flags & MEM_RowSet)==0 );
69353  sqlite3VdbeMemRelease(pMem);
69354  pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
69355  if( db->mallocFailed ){
69356    pMem->flags = MEM_Null;
69357    pMem->szMalloc = 0;
69358  }else{
69359    assert( pMem->zMalloc );
69360    pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
69361    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
69362    assert( pMem->u.pRowSet!=0 );
69363    pMem->flags = MEM_RowSet;
69364  }
69365}
69366
69367/*
69368** Return true if the Mem object contains a TEXT or BLOB that is
69369** too large - whose size exceeds SQLITE_MAX_LENGTH.
69370*/
69371SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
69372  assert( p->db!=0 );
69373  if( p->flags & (MEM_Str|MEM_Blob) ){
69374    int n = p->n;
69375    if( p->flags & MEM_Zero ){
69376      n += p->u.nZero;
69377    }
69378    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
69379  }
69380  return 0;
69381}
69382
69383#ifdef SQLITE_DEBUG
69384/*
69385** This routine prepares a memory cell for modification by breaking
69386** its link to a shallow copy and by marking any current shallow
69387** copies of this cell as invalid.
69388**
69389** This is used for testing and debugging only - to make sure shallow
69390** copies are not misused.
69391*/
69392SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
69393  int i;
69394  Mem *pX;
69395  for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
69396    if( pX->pScopyFrom==pMem ){
69397      pX->flags |= MEM_Undefined;
69398      pX->pScopyFrom = 0;
69399    }
69400  }
69401  pMem->pScopyFrom = 0;
69402}
69403#endif /* SQLITE_DEBUG */
69404
69405
69406/*
69407** Make an shallow copy of pFrom into pTo.  Prior contents of
69408** pTo are freed.  The pFrom->z field is not duplicated.  If
69409** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
69410** and flags gets srcType (either MEM_Ephem or MEM_Static).
69411*/
69412static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
69413  vdbeMemClearExternAndSetNull(pTo);
69414  assert( !VdbeMemDynamic(pTo) );
69415  sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
69416}
69417SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
69418  assert( (pFrom->flags & MEM_RowSet)==0 );
69419  assert( pTo->db==pFrom->db );
69420  if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
69421  memcpy(pTo, pFrom, MEMCELLSIZE);
69422  if( (pFrom->flags&MEM_Static)==0 ){
69423    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
69424    assert( srcType==MEM_Ephem || srcType==MEM_Static );
69425    pTo->flags |= srcType;
69426  }
69427}
69428
69429/*
69430** Make a full copy of pFrom into pTo.  Prior contents of pTo are
69431** freed before the copy is made.
69432*/
69433SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
69434  int rc = SQLITE_OK;
69435
69436  assert( (pFrom->flags & MEM_RowSet)==0 );
69437  if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
69438  memcpy(pTo, pFrom, MEMCELLSIZE);
69439  pTo->flags &= ~MEM_Dyn;
69440  if( pTo->flags&(MEM_Str|MEM_Blob) ){
69441    if( 0==(pFrom->flags&MEM_Static) ){
69442      pTo->flags |= MEM_Ephem;
69443      rc = sqlite3VdbeMemMakeWriteable(pTo);
69444    }
69445  }
69446
69447  return rc;
69448}
69449
69450/*
69451** Transfer the contents of pFrom to pTo. Any existing value in pTo is
69452** freed. If pFrom contains ephemeral data, a copy is made.
69453**
69454** pFrom contains an SQL NULL when this routine returns.
69455*/
69456SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
69457  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
69458  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
69459  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
69460
69461  sqlite3VdbeMemRelease(pTo);
69462  memcpy(pTo, pFrom, sizeof(Mem));
69463  pFrom->flags = MEM_Null;
69464  pFrom->szMalloc = 0;
69465}
69466
69467/*
69468** Change the value of a Mem to be a string or a BLOB.
69469**
69470** The memory management strategy depends on the value of the xDel
69471** parameter. If the value passed is SQLITE_TRANSIENT, then the
69472** string is copied into a (possibly existing) buffer managed by the
69473** Mem structure. Otherwise, any existing buffer is freed and the
69474** pointer copied.
69475**
69476** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
69477** size limit) then no memory allocation occurs.  If the string can be
69478** stored without allocating memory, then it is.  If a memory allocation
69479** is required to store the string, then value of pMem is unchanged.  In
69480** either case, SQLITE_TOOBIG is returned.
69481*/
69482SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
69483  Mem *pMem,          /* Memory cell to set to string value */
69484  const char *z,      /* String pointer */
69485  int n,              /* Bytes in string, or negative */
69486  u8 enc,             /* Encoding of z.  0 for BLOBs */
69487  void (*xDel)(void*) /* Destructor function */
69488){
69489  int nByte = n;      /* New value for pMem->n */
69490  int iLimit;         /* Maximum allowed string or blob size */
69491  u16 flags = 0;      /* New value for pMem->flags */
69492
69493  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69494  assert( (pMem->flags & MEM_RowSet)==0 );
69495
69496  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
69497  if( !z ){
69498    sqlite3VdbeMemSetNull(pMem);
69499    return SQLITE_OK;
69500  }
69501
69502  if( pMem->db ){
69503    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
69504  }else{
69505    iLimit = SQLITE_MAX_LENGTH;
69506  }
69507  flags = (enc==0?MEM_Blob:MEM_Str);
69508  if( nByte<0 ){
69509    assert( enc!=0 );
69510    if( enc==SQLITE_UTF8 ){
69511      nByte = sqlite3Strlen30(z);
69512      if( nByte>iLimit ) nByte = iLimit+1;
69513    }else{
69514      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
69515    }
69516    flags |= MEM_Term;
69517  }
69518
69519  /* The following block sets the new values of Mem.z and Mem.xDel. It
69520  ** also sets a flag in local variable "flags" to indicate the memory
69521  ** management (one of MEM_Dyn or MEM_Static).
69522  */
69523  if( xDel==SQLITE_TRANSIENT ){
69524    int nAlloc = nByte;
69525    if( flags&MEM_Term ){
69526      nAlloc += (enc==SQLITE_UTF8?1:2);
69527    }
69528    if( nByte>iLimit ){
69529      return SQLITE_TOOBIG;
69530    }
69531    testcase( nAlloc==0 );
69532    testcase( nAlloc==31 );
69533    testcase( nAlloc==32 );
69534    if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
69535      return SQLITE_NOMEM_BKPT;
69536    }
69537    memcpy(pMem->z, z, nAlloc);
69538  }else if( xDel==SQLITE_DYNAMIC ){
69539    sqlite3VdbeMemRelease(pMem);
69540    pMem->zMalloc = pMem->z = (char *)z;
69541    pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
69542  }else{
69543    sqlite3VdbeMemRelease(pMem);
69544    pMem->z = (char *)z;
69545    pMem->xDel = xDel;
69546    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
69547  }
69548
69549  pMem->n = nByte;
69550  pMem->flags = flags;
69551  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
69552
69553#ifndef SQLITE_OMIT_UTF16
69554  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
69555    return SQLITE_NOMEM_BKPT;
69556  }
69557#endif
69558
69559  if( nByte>iLimit ){
69560    return SQLITE_TOOBIG;
69561  }
69562
69563  return SQLITE_OK;
69564}
69565
69566/*
69567** Move data out of a btree key or data field and into a Mem structure.
69568** The data or key is taken from the entry that pCur is currently pointing
69569** to.  offset and amt determine what portion of the data or key to retrieve.
69570** key is true to get the key or false to get data.  The result is written
69571** into the pMem element.
69572**
69573** The pMem object must have been initialized.  This routine will use
69574** pMem->zMalloc to hold the content from the btree, if possible.  New
69575** pMem->zMalloc space will be allocated if necessary.  The calling routine
69576** is responsible for making sure that the pMem object is eventually
69577** destroyed.
69578**
69579** If this routine fails for any reason (malloc returns NULL or unable
69580** to read from the disk) then the pMem is left in an inconsistent state.
69581*/
69582static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
69583  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
69584  u32 offset,       /* Offset from the start of data to return bytes from. */
69585  u32 amt,          /* Number of bytes to return. */
69586  int key,          /* If true, retrieve from the btree key, not data. */
69587  Mem *pMem         /* OUT: Return data in this Mem structure. */
69588){
69589  int rc;
69590  pMem->flags = MEM_Null;
69591  if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
69592    if( key ){
69593      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
69594    }else{
69595      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
69596    }
69597    if( rc==SQLITE_OK ){
69598      pMem->z[amt] = 0;
69599      pMem->z[amt+1] = 0;
69600      pMem->flags = MEM_Blob|MEM_Term;
69601      pMem->n = (int)amt;
69602    }else{
69603      sqlite3VdbeMemRelease(pMem);
69604    }
69605  }
69606  return rc;
69607}
69608SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
69609  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
69610  u32 offset,       /* Offset from the start of data to return bytes from. */
69611  u32 amt,          /* Number of bytes to return. */
69612  int key,          /* If true, retrieve from the btree key, not data. */
69613  Mem *pMem         /* OUT: Return data in this Mem structure. */
69614){
69615  char *zData;        /* Data from the btree layer */
69616  u32 available = 0;  /* Number of bytes available on the local btree page */
69617  int rc = SQLITE_OK; /* Return code */
69618
69619  assert( sqlite3BtreeCursorIsValid(pCur) );
69620  assert( !VdbeMemDynamic(pMem) );
69621
69622  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
69623  ** that both the BtShared and database handle mutexes are held. */
69624  assert( (pMem->flags & MEM_RowSet)==0 );
69625  zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
69626  assert( zData!=0 );
69627
69628  if( offset+amt<=available ){
69629    pMem->z = &zData[offset];
69630    pMem->flags = MEM_Blob|MEM_Ephem;
69631    pMem->n = (int)amt;
69632  }else{
69633    rc = vdbeMemFromBtreeResize(pCur, offset, amt, key, pMem);
69634  }
69635
69636  return rc;
69637}
69638
69639/*
69640** The pVal argument is known to be a value other than NULL.
69641** Convert it into a string with encoding enc and return a pointer
69642** to a zero-terminated version of that string.
69643*/
69644static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
69645  assert( pVal!=0 );
69646  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
69647  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
69648  assert( (pVal->flags & MEM_RowSet)==0 );
69649  assert( (pVal->flags & (MEM_Null))==0 );
69650  if( pVal->flags & (MEM_Blob|MEM_Str) ){
69651    pVal->flags |= MEM_Str;
69652    if( pVal->flags & MEM_Zero ){
69653      sqlite3VdbeMemExpandBlob(pVal);
69654    }
69655    if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
69656      sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
69657    }
69658    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
69659      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
69660      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
69661        return 0;
69662      }
69663    }
69664    sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
69665  }else{
69666    sqlite3VdbeMemStringify(pVal, enc, 0);
69667    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
69668  }
69669  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
69670              || pVal->db->mallocFailed );
69671  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
69672    return pVal->z;
69673  }else{
69674    return 0;
69675  }
69676}
69677
69678/* This function is only available internally, it is not part of the
69679** external API. It works in a similar way to sqlite3_value_text(),
69680** except the data returned is in the encoding specified by the second
69681** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
69682** SQLITE_UTF8.
69683**
69684** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
69685** If that is the case, then the result must be aligned on an even byte
69686** boundary.
69687*/
69688SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
69689  if( !pVal ) return 0;
69690  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
69691  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
69692  assert( (pVal->flags & MEM_RowSet)==0 );
69693  if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
69694    return pVal->z;
69695  }
69696  if( pVal->flags&MEM_Null ){
69697    return 0;
69698  }
69699  return valueToText(pVal, enc);
69700}
69701
69702/*
69703** Create a new sqlite3_value object.
69704*/
69705SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
69706  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
69707  if( p ){
69708    p->flags = MEM_Null;
69709    p->db = db;
69710  }
69711  return p;
69712}
69713
69714/*
69715** Context object passed by sqlite3Stat4ProbeSetValue() through to
69716** valueNew(). See comments above valueNew() for details.
69717*/
69718struct ValueNewStat4Ctx {
69719  Parse *pParse;
69720  Index *pIdx;
69721  UnpackedRecord **ppRec;
69722  int iVal;
69723};
69724
69725/*
69726** Allocate and return a pointer to a new sqlite3_value object. If
69727** the second argument to this function is NULL, the object is allocated
69728** by calling sqlite3ValueNew().
69729**
69730** Otherwise, if the second argument is non-zero, then this function is
69731** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
69732** already been allocated, allocate the UnpackedRecord structure that
69733** that function will return to its caller here. Then return a pointer to
69734** an sqlite3_value within the UnpackedRecord.a[] array.
69735*/
69736static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
69737#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69738  if( p ){
69739    UnpackedRecord *pRec = p->ppRec[0];
69740
69741    if( pRec==0 ){
69742      Index *pIdx = p->pIdx;      /* Index being probed */
69743      int nByte;                  /* Bytes of space to allocate */
69744      int i;                      /* Counter variable */
69745      int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
69746
69747      nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
69748      pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
69749      if( pRec ){
69750        pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
69751        if( pRec->pKeyInfo ){
69752          assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
69753          assert( pRec->pKeyInfo->enc==ENC(db) );
69754          pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
69755          for(i=0; i<nCol; i++){
69756            pRec->aMem[i].flags = MEM_Null;
69757            pRec->aMem[i].db = db;
69758          }
69759        }else{
69760          sqlite3DbFree(db, pRec);
69761          pRec = 0;
69762        }
69763      }
69764      if( pRec==0 ) return 0;
69765      p->ppRec[0] = pRec;
69766    }
69767
69768    pRec->nField = p->iVal+1;
69769    return &pRec->aMem[p->iVal];
69770  }
69771#else
69772  UNUSED_PARAMETER(p);
69773#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
69774  return sqlite3ValueNew(db);
69775}
69776
69777/*
69778** The expression object indicated by the second argument is guaranteed
69779** to be a scalar SQL function. If
69780**
69781**   * all function arguments are SQL literals,
69782**   * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
69783**   * the SQLITE_FUNC_NEEDCOLL function flag is not set,
69784**
69785** then this routine attempts to invoke the SQL function. Assuming no
69786** error occurs, output parameter (*ppVal) is set to point to a value
69787** object containing the result before returning SQLITE_OK.
69788**
69789** Affinity aff is applied to the result of the function before returning.
69790** If the result is a text value, the sqlite3_value object uses encoding
69791** enc.
69792**
69793** If the conditions above are not met, this function returns SQLITE_OK
69794** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
69795** NULL and an SQLite error code returned.
69796*/
69797#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69798static int valueFromFunction(
69799  sqlite3 *db,                    /* The database connection */
69800  Expr *p,                        /* The expression to evaluate */
69801  u8 enc,                         /* Encoding to use */
69802  u8 aff,                         /* Affinity to use */
69803  sqlite3_value **ppVal,          /* Write the new value here */
69804  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
69805){
69806  sqlite3_context ctx;            /* Context object for function invocation */
69807  sqlite3_value **apVal = 0;      /* Function arguments */
69808  int nVal = 0;                   /* Size of apVal[] array */
69809  FuncDef *pFunc = 0;             /* Function definition */
69810  sqlite3_value *pVal = 0;        /* New value */
69811  int rc = SQLITE_OK;             /* Return code */
69812  ExprList *pList = 0;            /* Function arguments */
69813  int i;                          /* Iterator variable */
69814
69815  assert( pCtx!=0 );
69816  assert( (p->flags & EP_TokenOnly)==0 );
69817  pList = p->x.pList;
69818  if( pList ) nVal = pList->nExpr;
69819  pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
69820  assert( pFunc );
69821  if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
69822   || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
69823  ){
69824    return SQLITE_OK;
69825  }
69826
69827  if( pList ){
69828    apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
69829    if( apVal==0 ){
69830      rc = SQLITE_NOMEM_BKPT;
69831      goto value_from_function_out;
69832    }
69833    for(i=0; i<nVal; i++){
69834      rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
69835      if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
69836    }
69837  }
69838
69839  pVal = valueNew(db, pCtx);
69840  if( pVal==0 ){
69841    rc = SQLITE_NOMEM_BKPT;
69842    goto value_from_function_out;
69843  }
69844
69845  assert( pCtx->pParse->rc==SQLITE_OK );
69846  memset(&ctx, 0, sizeof(ctx));
69847  ctx.pOut = pVal;
69848  ctx.pFunc = pFunc;
69849  pFunc->xSFunc(&ctx, nVal, apVal);
69850  if( ctx.isError ){
69851    rc = ctx.isError;
69852    sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
69853  }else{
69854    sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
69855    assert( rc==SQLITE_OK );
69856    rc = sqlite3VdbeChangeEncoding(pVal, enc);
69857    if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
69858      rc = SQLITE_TOOBIG;
69859      pCtx->pParse->nErr++;
69860    }
69861  }
69862  pCtx->pParse->rc = rc;
69863
69864 value_from_function_out:
69865  if( rc!=SQLITE_OK ){
69866    pVal = 0;
69867  }
69868  if( apVal ){
69869    for(i=0; i<nVal; i++){
69870      sqlite3ValueFree(apVal[i]);
69871    }
69872    sqlite3DbFree(db, apVal);
69873  }
69874
69875  *ppVal = pVal;
69876  return rc;
69877}
69878#else
69879# define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
69880#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
69881
69882/*
69883** Extract a value from the supplied expression in the manner described
69884** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
69885** using valueNew().
69886**
69887** If pCtx is NULL and an error occurs after the sqlite3_value object
69888** has been allocated, it is freed before returning. Or, if pCtx is not
69889** NULL, it is assumed that the caller will free any allocated object
69890** in all cases.
69891*/
69892static int valueFromExpr(
69893  sqlite3 *db,                    /* The database connection */
69894  Expr *pExpr,                    /* The expression to evaluate */
69895  u8 enc,                         /* Encoding to use */
69896  u8 affinity,                    /* Affinity to use */
69897  sqlite3_value **ppVal,          /* Write the new value here */
69898  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
69899){
69900  int op;
69901  char *zVal = 0;
69902  sqlite3_value *pVal = 0;
69903  int negInt = 1;
69904  const char *zNeg = "";
69905  int rc = SQLITE_OK;
69906
69907  if( !pExpr ){
69908    *ppVal = 0;
69909    return SQLITE_OK;
69910  }
69911  while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
69912  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
69913
69914  /* Compressed expressions only appear when parsing the DEFAULT clause
69915  ** on a table column definition, and hence only when pCtx==0.  This
69916  ** check ensures that an EP_TokenOnly expression is never passed down
69917  ** into valueFromFunction(). */
69918  assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
69919
69920  if( op==TK_CAST ){
69921    u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
69922    rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
69923    testcase( rc!=SQLITE_OK );
69924    if( *ppVal ){
69925      sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
69926      sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
69927    }
69928    return rc;
69929  }
69930
69931  /* Handle negative integers in a single step.  This is needed in the
69932  ** case when the value is -9223372036854775808.
69933  */
69934  if( op==TK_UMINUS
69935   && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
69936    pExpr = pExpr->pLeft;
69937    op = pExpr->op;
69938    negInt = -1;
69939    zNeg = "-";
69940  }
69941
69942  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
69943    pVal = valueNew(db, pCtx);
69944    if( pVal==0 ) goto no_mem;
69945    if( ExprHasProperty(pExpr, EP_IntValue) ){
69946      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
69947    }else{
69948      zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
69949      if( zVal==0 ) goto no_mem;
69950      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
69951    }
69952    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
69953      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
69954    }else{
69955      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
69956    }
69957    if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
69958    if( enc!=SQLITE_UTF8 ){
69959      rc = sqlite3VdbeChangeEncoding(pVal, enc);
69960    }
69961  }else if( op==TK_UMINUS ) {
69962    /* This branch happens for multiple negative signs.  Ex: -(-5) */
69963    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
69964     && pVal!=0
69965    ){
69966      sqlite3VdbeMemNumerify(pVal);
69967      if( pVal->flags & MEM_Real ){
69968        pVal->u.r = -pVal->u.r;
69969      }else if( pVal->u.i==SMALLEST_INT64 ){
69970        pVal->u.r = -(double)SMALLEST_INT64;
69971        MemSetTypeFlag(pVal, MEM_Real);
69972      }else{
69973        pVal->u.i = -pVal->u.i;
69974      }
69975      sqlite3ValueApplyAffinity(pVal, affinity, enc);
69976    }
69977  }else if( op==TK_NULL ){
69978    pVal = valueNew(db, pCtx);
69979    if( pVal==0 ) goto no_mem;
69980  }
69981#ifndef SQLITE_OMIT_BLOB_LITERAL
69982  else if( op==TK_BLOB ){
69983    int nVal;
69984    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
69985    assert( pExpr->u.zToken[1]=='\'' );
69986    pVal = valueNew(db, pCtx);
69987    if( !pVal ) goto no_mem;
69988    zVal = &pExpr->u.zToken[2];
69989    nVal = sqlite3Strlen30(zVal)-1;
69990    assert( zVal[nVal]=='\'' );
69991    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
69992                         0, SQLITE_DYNAMIC);
69993  }
69994#endif
69995
69996#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69997  else if( op==TK_FUNCTION && pCtx!=0 ){
69998    rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
69999  }
70000#endif
70001
70002  *ppVal = pVal;
70003  return rc;
70004
70005no_mem:
70006  sqlite3OomFault(db);
70007  sqlite3DbFree(db, zVal);
70008  assert( *ppVal==0 );
70009#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70010  if( pCtx==0 ) sqlite3ValueFree(pVal);
70011#else
70012  assert( pCtx==0 ); sqlite3ValueFree(pVal);
70013#endif
70014  return SQLITE_NOMEM_BKPT;
70015}
70016
70017/*
70018** Create a new sqlite3_value object, containing the value of pExpr.
70019**
70020** This only works for very simple expressions that consist of one constant
70021** token (i.e. "5", "5.1", "'a string'"). If the expression can
70022** be converted directly into a value, then the value is allocated and
70023** a pointer written to *ppVal. The caller is responsible for deallocating
70024** the value by passing it to sqlite3ValueFree() later on. If the expression
70025** cannot be converted to a value, then *ppVal is set to NULL.
70026*/
70027SQLITE_PRIVATE int sqlite3ValueFromExpr(
70028  sqlite3 *db,              /* The database connection */
70029  Expr *pExpr,              /* The expression to evaluate */
70030  u8 enc,                   /* Encoding to use */
70031  u8 affinity,              /* Affinity to use */
70032  sqlite3_value **ppVal     /* Write the new value here */
70033){
70034  return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
70035}
70036
70037#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70038/*
70039** The implementation of the sqlite_record() function. This function accepts
70040** a single argument of any type. The return value is a formatted database
70041** record (a blob) containing the argument value.
70042**
70043** This is used to convert the value stored in the 'sample' column of the
70044** sqlite_stat3 table to the record format SQLite uses internally.
70045*/
70046static void recordFunc(
70047  sqlite3_context *context,
70048  int argc,
70049  sqlite3_value **argv
70050){
70051  const int file_format = 1;
70052  u32 iSerial;                    /* Serial type */
70053  int nSerial;                    /* Bytes of space for iSerial as varint */
70054  u32 nVal;                       /* Bytes of space required for argv[0] */
70055  int nRet;
70056  sqlite3 *db;
70057  u8 *aRet;
70058
70059  UNUSED_PARAMETER( argc );
70060  iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
70061  nSerial = sqlite3VarintLen(iSerial);
70062  db = sqlite3_context_db_handle(context);
70063
70064  nRet = 1 + nSerial + nVal;
70065  aRet = sqlite3DbMallocRawNN(db, nRet);
70066  if( aRet==0 ){
70067    sqlite3_result_error_nomem(context);
70068  }else{
70069    aRet[0] = nSerial+1;
70070    putVarint32(&aRet[1], iSerial);
70071    sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
70072    sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
70073    sqlite3DbFree(db, aRet);
70074  }
70075}
70076
70077/*
70078** Register built-in functions used to help read ANALYZE data.
70079*/
70080SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
70081  static FuncDef aAnalyzeTableFuncs[] = {
70082    FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
70083  };
70084  sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
70085}
70086
70087/*
70088** Attempt to extract a value from pExpr and use it to construct *ppVal.
70089**
70090** If pAlloc is not NULL, then an UnpackedRecord object is created for
70091** pAlloc if one does not exist and the new value is added to the
70092** UnpackedRecord object.
70093**
70094** A value is extracted in the following cases:
70095**
70096**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
70097**
70098**  * The expression is a bound variable, and this is a reprepare, or
70099**
70100**  * The expression is a literal value.
70101**
70102** On success, *ppVal is made to point to the extracted value.  The caller
70103** is responsible for ensuring that the value is eventually freed.
70104*/
70105static int stat4ValueFromExpr(
70106  Parse *pParse,                  /* Parse context */
70107  Expr *pExpr,                    /* The expression to extract a value from */
70108  u8 affinity,                    /* Affinity to use */
70109  struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
70110  sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
70111){
70112  int rc = SQLITE_OK;
70113  sqlite3_value *pVal = 0;
70114  sqlite3 *db = pParse->db;
70115
70116  /* Skip over any TK_COLLATE nodes */
70117  pExpr = sqlite3ExprSkipCollate(pExpr);
70118
70119  if( !pExpr ){
70120    pVal = valueNew(db, pAlloc);
70121    if( pVal ){
70122      sqlite3VdbeMemSetNull((Mem*)pVal);
70123    }
70124  }else if( pExpr->op==TK_VARIABLE
70125        || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
70126  ){
70127    Vdbe *v;
70128    int iBindVar = pExpr->iColumn;
70129    sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
70130    if( (v = pParse->pReprepare)!=0 ){
70131      pVal = valueNew(db, pAlloc);
70132      if( pVal ){
70133        rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
70134        if( rc==SQLITE_OK ){
70135          sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
70136        }
70137        pVal->db = pParse->db;
70138      }
70139    }
70140  }else{
70141    rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
70142  }
70143
70144  assert( pVal==0 || pVal->db==db );
70145  *ppVal = pVal;
70146  return rc;
70147}
70148
70149/*
70150** This function is used to allocate and populate UnpackedRecord
70151** structures intended to be compared against sample index keys stored
70152** in the sqlite_stat4 table.
70153**
70154** A single call to this function attempts to populates field iVal (leftmost
70155** is 0 etc.) of the unpacked record with a value extracted from expression
70156** pExpr. Extraction of values is possible if:
70157**
70158**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
70159**
70160**  * The expression is a bound variable, and this is a reprepare, or
70161**
70162**  * The sqlite3ValueFromExpr() function is able to extract a value
70163**    from the expression (i.e. the expression is a literal value).
70164**
70165** If a value can be extracted, the affinity passed as the 5th argument
70166** is applied to it before it is copied into the UnpackedRecord. Output
70167** parameter *pbOk is set to true if a value is extracted, or false
70168** otherwise.
70169**
70170** When this function is called, *ppRec must either point to an object
70171** allocated by an earlier call to this function, or must be NULL. If it
70172** is NULL and a value can be successfully extracted, a new UnpackedRecord
70173** is allocated (and *ppRec set to point to it) before returning.
70174**
70175** Unless an error is encountered, SQLITE_OK is returned. It is not an
70176** error if a value cannot be extracted from pExpr. If an error does
70177** occur, an SQLite error code is returned.
70178*/
70179SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
70180  Parse *pParse,                  /* Parse context */
70181  Index *pIdx,                    /* Index being probed */
70182  UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
70183  Expr *pExpr,                    /* The expression to extract a value from */
70184  u8 affinity,                    /* Affinity to use */
70185  int iVal,                       /* Array element to populate */
70186  int *pbOk                       /* OUT: True if value was extracted */
70187){
70188  int rc;
70189  sqlite3_value *pVal = 0;
70190  struct ValueNewStat4Ctx alloc;
70191
70192  alloc.pParse = pParse;
70193  alloc.pIdx = pIdx;
70194  alloc.ppRec = ppRec;
70195  alloc.iVal = iVal;
70196
70197  rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
70198  assert( pVal==0 || pVal->db==pParse->db );
70199  *pbOk = (pVal!=0);
70200  return rc;
70201}
70202
70203/*
70204** Attempt to extract a value from expression pExpr using the methods
70205** as described for sqlite3Stat4ProbeSetValue() above.
70206**
70207** If successful, set *ppVal to point to a new value object and return
70208** SQLITE_OK. If no value can be extracted, but no other error occurs
70209** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
70210** does occur, return an SQLite error code. The final value of *ppVal
70211** is undefined in this case.
70212*/
70213SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
70214  Parse *pParse,                  /* Parse context */
70215  Expr *pExpr,                    /* The expression to extract a value from */
70216  u8 affinity,                    /* Affinity to use */
70217  sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
70218){
70219  return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
70220}
70221
70222/*
70223** Extract the iCol-th column from the nRec-byte record in pRec.  Write
70224** the column value into *ppVal.  If *ppVal is initially NULL then a new
70225** sqlite3_value object is allocated.
70226**
70227** If *ppVal is initially NULL then the caller is responsible for
70228** ensuring that the value written into *ppVal is eventually freed.
70229*/
70230SQLITE_PRIVATE int sqlite3Stat4Column(
70231  sqlite3 *db,                    /* Database handle */
70232  const void *pRec,               /* Pointer to buffer containing record */
70233  int nRec,                       /* Size of buffer pRec in bytes */
70234  int iCol,                       /* Column to extract */
70235  sqlite3_value **ppVal           /* OUT: Extracted value */
70236){
70237  u32 t;                          /* a column type code */
70238  int nHdr;                       /* Size of the header in the record */
70239  int iHdr;                       /* Next unread header byte */
70240  int iField;                     /* Next unread data byte */
70241  int szField;                    /* Size of the current data field */
70242  int i;                          /* Column index */
70243  u8 *a = (u8*)pRec;              /* Typecast byte array */
70244  Mem *pMem = *ppVal;             /* Write result into this Mem object */
70245
70246  assert( iCol>0 );
70247  iHdr = getVarint32(a, nHdr);
70248  if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
70249  iField = nHdr;
70250  for(i=0; i<=iCol; i++){
70251    iHdr += getVarint32(&a[iHdr], t);
70252    testcase( iHdr==nHdr );
70253    testcase( iHdr==nHdr+1 );
70254    if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
70255    szField = sqlite3VdbeSerialTypeLen(t);
70256    iField += szField;
70257  }
70258  testcase( iField==nRec );
70259  testcase( iField==nRec+1 );
70260  if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
70261  if( pMem==0 ){
70262    pMem = *ppVal = sqlite3ValueNew(db);
70263    if( pMem==0 ) return SQLITE_NOMEM_BKPT;
70264  }
70265  sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
70266  pMem->enc = ENC(db);
70267  return SQLITE_OK;
70268}
70269
70270/*
70271** Unless it is NULL, the argument must be an UnpackedRecord object returned
70272** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
70273** the object.
70274*/
70275SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
70276  if( pRec ){
70277    int i;
70278    int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
70279    Mem *aMem = pRec->aMem;
70280    sqlite3 *db = aMem[0].db;
70281    for(i=0; i<nCol; i++){
70282      sqlite3VdbeMemRelease(&aMem[i]);
70283    }
70284    sqlite3KeyInfoUnref(pRec->pKeyInfo);
70285    sqlite3DbFree(db, pRec);
70286  }
70287}
70288#endif /* ifdef SQLITE_ENABLE_STAT4 */
70289
70290/*
70291** Change the string value of an sqlite3_value object
70292*/
70293SQLITE_PRIVATE void sqlite3ValueSetStr(
70294  sqlite3_value *v,     /* Value to be set */
70295  int n,                /* Length of string z */
70296  const void *z,        /* Text of the new string */
70297  u8 enc,               /* Encoding to use */
70298  void (*xDel)(void*)   /* Destructor for the string */
70299){
70300  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
70301}
70302
70303/*
70304** Free an sqlite3_value object
70305*/
70306SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
70307  if( !v ) return;
70308  sqlite3VdbeMemRelease((Mem *)v);
70309  sqlite3DbFree(((Mem*)v)->db, v);
70310}
70311
70312/*
70313** The sqlite3ValueBytes() routine returns the number of bytes in the
70314** sqlite3_value object assuming that it uses the encoding "enc".
70315** The valueBytes() routine is a helper function.
70316*/
70317static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
70318  return valueToText(pVal, enc)!=0 ? pVal->n : 0;
70319}
70320SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
70321  Mem *p = (Mem*)pVal;
70322  assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
70323  if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
70324    return p->n;
70325  }
70326  if( (p->flags & MEM_Blob)!=0 ){
70327    if( p->flags & MEM_Zero ){
70328      return p->n + p->u.nZero;
70329    }else{
70330      return p->n;
70331    }
70332  }
70333  if( p->flags & MEM_Null ) return 0;
70334  return valueBytes(pVal, enc);
70335}
70336
70337/************** End of vdbemem.c *********************************************/
70338/************** Begin file vdbeaux.c *****************************************/
70339/*
70340** 2003 September 6
70341**
70342** The author disclaims copyright to this source code.  In place of
70343** a legal notice, here is a blessing:
70344**
70345**    May you do good and not evil.
70346**    May you find forgiveness for yourself and forgive others.
70347**    May you share freely, never taking more than you give.
70348**
70349*************************************************************************
70350** This file contains code used for creating, destroying, and populating
70351** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
70352*/
70353/* #include "sqliteInt.h" */
70354/* #include "vdbeInt.h" */
70355
70356/*
70357** Create a new virtual database engine.
70358*/
70359SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
70360  sqlite3 *db = pParse->db;
70361  Vdbe *p;
70362  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
70363  if( p==0 ) return 0;
70364  p->db = db;
70365  if( db->pVdbe ){
70366    db->pVdbe->pPrev = p;
70367  }
70368  p->pNext = db->pVdbe;
70369  p->pPrev = 0;
70370  db->pVdbe = p;
70371  p->magic = VDBE_MAGIC_INIT;
70372  p->pParse = pParse;
70373  assert( pParse->aLabel==0 );
70374  assert( pParse->nLabel==0 );
70375  assert( pParse->nOpAlloc==0 );
70376  assert( pParse->szOpAlloc==0 );
70377  return p;
70378}
70379
70380/*
70381** Change the error string stored in Vdbe.zErrMsg
70382*/
70383SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
70384  va_list ap;
70385  sqlite3DbFree(p->db, p->zErrMsg);
70386  va_start(ap, zFormat);
70387  p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
70388  va_end(ap);
70389}
70390
70391/*
70392** Remember the SQL string for a prepared statement.
70393*/
70394SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
70395  assert( isPrepareV2==1 || isPrepareV2==0 );
70396  if( p==0 ) return;
70397#if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
70398  if( !isPrepareV2 ) return;
70399#endif
70400  assert( p->zSql==0 );
70401  p->zSql = sqlite3DbStrNDup(p->db, z, n);
70402  p->isPrepareV2 = (u8)isPrepareV2;
70403}
70404
70405/*
70406** Swap all content between two VDBE structures.
70407*/
70408SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
70409  Vdbe tmp, *pTmp;
70410  char *zTmp;
70411  assert( pA->db==pB->db );
70412  tmp = *pA;
70413  *pA = *pB;
70414  *pB = tmp;
70415  pTmp = pA->pNext;
70416  pA->pNext = pB->pNext;
70417  pB->pNext = pTmp;
70418  pTmp = pA->pPrev;
70419  pA->pPrev = pB->pPrev;
70420  pB->pPrev = pTmp;
70421  zTmp = pA->zSql;
70422  pA->zSql = pB->zSql;
70423  pB->zSql = zTmp;
70424  pB->isPrepareV2 = pA->isPrepareV2;
70425}
70426
70427/*
70428** Resize the Vdbe.aOp array so that it is at least nOp elements larger
70429** than its current size. nOp is guaranteed to be less than or equal
70430** to 1024/sizeof(Op).
70431**
70432** If an out-of-memory error occurs while resizing the array, return
70433** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
70434** unchanged (this is so that any opcodes already allocated can be
70435** correctly deallocated along with the rest of the Vdbe).
70436*/
70437static int growOpArray(Vdbe *v, int nOp){
70438  VdbeOp *pNew;
70439  Parse *p = v->pParse;
70440
70441  /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
70442  ** more frequent reallocs and hence provide more opportunities for
70443  ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
70444  ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
70445  ** by the minimum* amount required until the size reaches 512.  Normal
70446  ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
70447  ** size of the op array or add 1KB of space, whichever is smaller. */
70448#ifdef SQLITE_TEST_REALLOC_STRESS
70449  int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
70450#else
70451  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
70452  UNUSED_PARAMETER(nOp);
70453#endif
70454
70455  assert( nOp<=(1024/sizeof(Op)) );
70456  assert( nNew>=(p->nOpAlloc+nOp) );
70457  pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
70458  if( pNew ){
70459    p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
70460    p->nOpAlloc = p->szOpAlloc/sizeof(Op);
70461    v->aOp = pNew;
70462  }
70463  return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
70464}
70465
70466#ifdef SQLITE_DEBUG
70467/* This routine is just a convenient place to set a breakpoint that will
70468** fire after each opcode is inserted and displayed using
70469** "PRAGMA vdbe_addoptrace=on".
70470*/
70471static void test_addop_breakpoint(void){
70472  static int n = 0;
70473  n++;
70474}
70475#endif
70476
70477/*
70478** Add a new instruction to the list of instructions current in the
70479** VDBE.  Return the address of the new instruction.
70480**
70481** Parameters:
70482**
70483**    p               Pointer to the VDBE
70484**
70485**    op              The opcode for this instruction
70486**
70487**    p1, p2, p3      Operands
70488**
70489** Use the sqlite3VdbeResolveLabel() function to fix an address and
70490** the sqlite3VdbeChangeP4() function to change the value of the P4
70491** operand.
70492*/
70493static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
70494  assert( p->pParse->nOpAlloc<=p->nOp );
70495  if( growOpArray(p, 1) ) return 1;
70496  assert( p->pParse->nOpAlloc>p->nOp );
70497  return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70498}
70499SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
70500  int i;
70501  VdbeOp *pOp;
70502
70503  i = p->nOp;
70504  assert( p->magic==VDBE_MAGIC_INIT );
70505  assert( op>=0 && op<0xff );
70506  if( p->pParse->nOpAlloc<=i ){
70507    return growOp3(p, op, p1, p2, p3);
70508  }
70509  p->nOp++;
70510  pOp = &p->aOp[i];
70511  pOp->opcode = (u8)op;
70512  pOp->p5 = 0;
70513  pOp->p1 = p1;
70514  pOp->p2 = p2;
70515  pOp->p3 = p3;
70516  pOp->p4.p = 0;
70517  pOp->p4type = P4_NOTUSED;
70518#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
70519  pOp->zComment = 0;
70520#endif
70521#ifdef SQLITE_DEBUG
70522  if( p->db->flags & SQLITE_VdbeAddopTrace ){
70523    int jj, kk;
70524    Parse *pParse = p->pParse;
70525    for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
70526      struct yColCache *x = pParse->aColCache + jj;
70527      if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
70528      printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
70529      kk++;
70530    }
70531    if( kk ) printf("\n");
70532    sqlite3VdbePrintOp(0, i, &p->aOp[i]);
70533    test_addop_breakpoint();
70534  }
70535#endif
70536#ifdef VDBE_PROFILE
70537  pOp->cycles = 0;
70538  pOp->cnt = 0;
70539#endif
70540#ifdef SQLITE_VDBE_COVERAGE
70541  pOp->iSrcLine = 0;
70542#endif
70543  return i;
70544}
70545SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
70546  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
70547}
70548SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
70549  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
70550}
70551SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
70552  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
70553}
70554
70555/* Generate code for an unconditional jump to instruction iDest
70556*/
70557SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
70558  return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
70559}
70560
70561/* Generate code to cause the string zStr to be loaded into
70562** register iDest
70563*/
70564SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
70565  return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
70566}
70567
70568/*
70569** Generate code that initializes multiple registers to string or integer
70570** constants.  The registers begin with iDest and increase consecutively.
70571** One register is initialized for each characgter in zTypes[].  For each
70572** "s" character in zTypes[], the register is a string if the argument is
70573** not NULL, or OP_Null if the value is a null pointer.  For each "i" character
70574** in zTypes[], the register is initialized to an integer.
70575*/
70576SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
70577  va_list ap;
70578  int i;
70579  char c;
70580  va_start(ap, zTypes);
70581  for(i=0; (c = zTypes[i])!=0; i++){
70582    if( c=='s' ){
70583      const char *z = va_arg(ap, const char*);
70584      sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest++, 0, z, 0);
70585    }else{
70586      assert( c=='i' );
70587      sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++);
70588    }
70589  }
70590  va_end(ap);
70591}
70592
70593/*
70594** Add an opcode that includes the p4 value as a pointer.
70595*/
70596SQLITE_PRIVATE int sqlite3VdbeAddOp4(
70597  Vdbe *p,            /* Add the opcode to this VM */
70598  int op,             /* The new opcode */
70599  int p1,             /* The P1 operand */
70600  int p2,             /* The P2 operand */
70601  int p3,             /* The P3 operand */
70602  const char *zP4,    /* The P4 operand */
70603  int p4type          /* P4 operand type */
70604){
70605  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70606  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
70607  return addr;
70608}
70609
70610/*
70611** Add an opcode that includes the p4 value with a P4_INT64 or
70612** P4_REAL type.
70613*/
70614SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
70615  Vdbe *p,            /* Add the opcode to this VM */
70616  int op,             /* The new opcode */
70617  int p1,             /* The P1 operand */
70618  int p2,             /* The P2 operand */
70619  int p3,             /* The P3 operand */
70620  const u8 *zP4,      /* The P4 operand */
70621  int p4type          /* P4 operand type */
70622){
70623  char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
70624  if( p4copy ) memcpy(p4copy, zP4, 8);
70625  return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
70626}
70627
70628/*
70629** Add an OP_ParseSchema opcode.  This routine is broken out from
70630** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
70631** as having been used.
70632**
70633** The zWhere string must have been obtained from sqlite3_malloc().
70634** This routine will take ownership of the allocated memory.
70635*/
70636SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
70637  int j;
70638  sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
70639  for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
70640}
70641
70642/*
70643** Add an opcode that includes the p4 value as an integer.
70644*/
70645SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
70646  Vdbe *p,            /* Add the opcode to this VM */
70647  int op,             /* The new opcode */
70648  int p1,             /* The P1 operand */
70649  int p2,             /* The P2 operand */
70650  int p3,             /* The P3 operand */
70651  int p4              /* The P4 operand as an integer */
70652){
70653  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70654  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
70655  return addr;
70656}
70657
70658/* Insert the end of a co-routine
70659*/
70660SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
70661  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
70662
70663  /* Clear the temporary register cache, thereby ensuring that each
70664  ** co-routine has its own independent set of registers, because co-routines
70665  ** might expect their registers to be preserved across an OP_Yield, and
70666  ** that could cause problems if two or more co-routines are using the same
70667  ** temporary register.
70668  */
70669  v->pParse->nTempReg = 0;
70670  v->pParse->nRangeReg = 0;
70671}
70672
70673/*
70674** Create a new symbolic label for an instruction that has yet to be
70675** coded.  The symbolic label is really just a negative number.  The
70676** label can be used as the P2 value of an operation.  Later, when
70677** the label is resolved to a specific address, the VDBE will scan
70678** through its operation list and change all values of P2 which match
70679** the label into the resolved address.
70680**
70681** The VDBE knows that a P2 value is a label because labels are
70682** always negative and P2 values are suppose to be non-negative.
70683** Hence, a negative P2 value is a label that has yet to be resolved.
70684**
70685** Zero is returned if a malloc() fails.
70686*/
70687SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
70688  Parse *p = v->pParse;
70689  int i = p->nLabel++;
70690  assert( v->magic==VDBE_MAGIC_INIT );
70691  if( (i & (i-1))==0 ){
70692    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
70693                                       (i*2+1)*sizeof(p->aLabel[0]));
70694  }
70695  if( p->aLabel ){
70696    p->aLabel[i] = -1;
70697  }
70698  return ADDR(i);
70699}
70700
70701/*
70702** Resolve label "x" to be the address of the next instruction to
70703** be inserted.  The parameter "x" must have been obtained from
70704** a prior call to sqlite3VdbeMakeLabel().
70705*/
70706SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
70707  Parse *p = v->pParse;
70708  int j = ADDR(x);
70709  assert( v->magic==VDBE_MAGIC_INIT );
70710  assert( j<p->nLabel );
70711  assert( j>=0 );
70712  if( p->aLabel ){
70713    p->aLabel[j] = v->nOp;
70714  }
70715  p->iFixedOp = v->nOp - 1;
70716}
70717
70718/*
70719** Mark the VDBE as one that can only be run one time.
70720*/
70721SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
70722  p->runOnlyOnce = 1;
70723}
70724
70725/*
70726** Mark the VDBE as one that can only be run multiple times.
70727*/
70728SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
70729  p->runOnlyOnce = 0;
70730}
70731
70732#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
70733
70734/*
70735** The following type and function are used to iterate through all opcodes
70736** in a Vdbe main program and each of the sub-programs (triggers) it may
70737** invoke directly or indirectly. It should be used as follows:
70738**
70739**   Op *pOp;
70740**   VdbeOpIter sIter;
70741**
70742**   memset(&sIter, 0, sizeof(sIter));
70743**   sIter.v = v;                            // v is of type Vdbe*
70744**   while( (pOp = opIterNext(&sIter)) ){
70745**     // Do something with pOp
70746**   }
70747**   sqlite3DbFree(v->db, sIter.apSub);
70748**
70749*/
70750typedef struct VdbeOpIter VdbeOpIter;
70751struct VdbeOpIter {
70752  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
70753  SubProgram **apSub;        /* Array of subprograms */
70754  int nSub;                  /* Number of entries in apSub */
70755  int iAddr;                 /* Address of next instruction to return */
70756  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
70757};
70758static Op *opIterNext(VdbeOpIter *p){
70759  Vdbe *v = p->v;
70760  Op *pRet = 0;
70761  Op *aOp;
70762  int nOp;
70763
70764  if( p->iSub<=p->nSub ){
70765
70766    if( p->iSub==0 ){
70767      aOp = v->aOp;
70768      nOp = v->nOp;
70769    }else{
70770      aOp = p->apSub[p->iSub-1]->aOp;
70771      nOp = p->apSub[p->iSub-1]->nOp;
70772    }
70773    assert( p->iAddr<nOp );
70774
70775    pRet = &aOp[p->iAddr];
70776    p->iAddr++;
70777    if( p->iAddr==nOp ){
70778      p->iSub++;
70779      p->iAddr = 0;
70780    }
70781
70782    if( pRet->p4type==P4_SUBPROGRAM ){
70783      int nByte = (p->nSub+1)*sizeof(SubProgram*);
70784      int j;
70785      for(j=0; j<p->nSub; j++){
70786        if( p->apSub[j]==pRet->p4.pProgram ) break;
70787      }
70788      if( j==p->nSub ){
70789        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
70790        if( !p->apSub ){
70791          pRet = 0;
70792        }else{
70793          p->apSub[p->nSub++] = pRet->p4.pProgram;
70794        }
70795      }
70796    }
70797  }
70798
70799  return pRet;
70800}
70801
70802/*
70803** Check if the program stored in the VM associated with pParse may
70804** throw an ABORT exception (causing the statement, but not entire transaction
70805** to be rolled back). This condition is true if the main program or any
70806** sub-programs contains any of the following:
70807**
70808**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
70809**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
70810**   *  OP_Destroy
70811**   *  OP_VUpdate
70812**   *  OP_VRename
70813**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
70814**   *  OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
70815**
70816** Then check that the value of Parse.mayAbort is true if an
70817** ABORT may be thrown, or false otherwise. Return true if it does
70818** match, or false otherwise. This function is intended to be used as
70819** part of an assert statement in the compiler. Similar to:
70820**
70821**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
70822*/
70823SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
70824  int hasAbort = 0;
70825  int hasFkCounter = 0;
70826  int hasCreateTable = 0;
70827  int hasInitCoroutine = 0;
70828  Op *pOp;
70829  VdbeOpIter sIter;
70830  memset(&sIter, 0, sizeof(sIter));
70831  sIter.v = v;
70832
70833  while( (pOp = opIterNext(&sIter))!=0 ){
70834    int opcode = pOp->opcode;
70835    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
70836     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
70837      && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
70838    ){
70839      hasAbort = 1;
70840      break;
70841    }
70842    if( opcode==OP_CreateTable ) hasCreateTable = 1;
70843    if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
70844#ifndef SQLITE_OMIT_FOREIGN_KEY
70845    if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
70846      hasFkCounter = 1;
70847    }
70848#endif
70849  }
70850  sqlite3DbFree(v->db, sIter.apSub);
70851
70852  /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
70853  ** If malloc failed, then the while() loop above may not have iterated
70854  ** through all opcodes and hasAbort may be set incorrectly. Return
70855  ** true for this case to prevent the assert() in the callers frame
70856  ** from failing.  */
70857  return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
70858              || (hasCreateTable && hasInitCoroutine) );
70859}
70860#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
70861
70862/*
70863** This routine is called after all opcodes have been inserted.  It loops
70864** through all the opcodes and fixes up some details.
70865**
70866** (1) For each jump instruction with a negative P2 value (a label)
70867**     resolve the P2 value to an actual address.
70868**
70869** (2) Compute the maximum number of arguments used by any SQL function
70870**     and store that value in *pMaxFuncArgs.
70871**
70872** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
70873**     indicate what the prepared statement actually does.
70874**
70875** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
70876**
70877** (5) Reclaim the memory allocated for storing labels.
70878**
70879** This routine will only function correctly if the mkopcodeh.tcl generator
70880** script numbers the opcodes correctly.  Changes to this routine must be
70881** coordinated with changes to mkopcodeh.tcl.
70882*/
70883static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
70884  int nMaxArgs = *pMaxFuncArgs;
70885  Op *pOp;
70886  Parse *pParse = p->pParse;
70887  int *aLabel = pParse->aLabel;
70888  p->readOnly = 1;
70889  p->bIsReader = 0;
70890  pOp = &p->aOp[p->nOp-1];
70891  while(1){
70892
70893    /* Only JUMP opcodes and the short list of special opcodes in the switch
70894    ** below need to be considered.  The mkopcodeh.tcl generator script groups
70895    ** all these opcodes together near the front of the opcode list.  Skip
70896    ** any opcode that does not need processing by virtual of the fact that
70897    ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
70898    */
70899    if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
70900      /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
70901      ** cases from this switch! */
70902      switch( pOp->opcode ){
70903        case OP_Transaction: {
70904          if( pOp->p2!=0 ) p->readOnly = 0;
70905          /* fall thru */
70906        }
70907        case OP_AutoCommit:
70908        case OP_Savepoint: {
70909          p->bIsReader = 1;
70910          break;
70911        }
70912#ifndef SQLITE_OMIT_WAL
70913        case OP_Checkpoint:
70914#endif
70915        case OP_Vacuum:
70916        case OP_JournalMode: {
70917          p->readOnly = 0;
70918          p->bIsReader = 1;
70919          break;
70920        }
70921#ifndef SQLITE_OMIT_VIRTUALTABLE
70922        case OP_VUpdate: {
70923          if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
70924          break;
70925        }
70926        case OP_VFilter: {
70927          int n;
70928          assert( (pOp - p->aOp) >= 3 );
70929          assert( pOp[-1].opcode==OP_Integer );
70930          n = pOp[-1].p1;
70931          if( n>nMaxArgs ) nMaxArgs = n;
70932          break;
70933        }
70934#endif
70935        case OP_Next:
70936        case OP_NextIfOpen:
70937        case OP_SorterNext: {
70938          pOp->p4.xAdvance = sqlite3BtreeNext;
70939          pOp->p4type = P4_ADVANCE;
70940          break;
70941        }
70942        case OP_Prev:
70943        case OP_PrevIfOpen: {
70944          pOp->p4.xAdvance = sqlite3BtreePrevious;
70945          pOp->p4type = P4_ADVANCE;
70946          break;
70947        }
70948      }
70949      if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 && pOp->p2<0 ){
70950        assert( ADDR(pOp->p2)<pParse->nLabel );
70951        pOp->p2 = aLabel[ADDR(pOp->p2)];
70952      }
70953    }
70954    if( pOp==p->aOp ) break;
70955    pOp--;
70956  }
70957  sqlite3DbFree(p->db, pParse->aLabel);
70958  pParse->aLabel = 0;
70959  pParse->nLabel = 0;
70960  *pMaxFuncArgs = nMaxArgs;
70961  assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
70962}
70963
70964/*
70965** Return the address of the next instruction to be inserted.
70966*/
70967SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
70968  assert( p->magic==VDBE_MAGIC_INIT );
70969  return p->nOp;
70970}
70971
70972/*
70973** Verify that at least N opcode slots are available in p without
70974** having to malloc for more space (except when compiled using
70975** SQLITE_TEST_REALLOC_STRESS).  This interface is used during testing
70976** to verify that certain calls to sqlite3VdbeAddOpList() can never
70977** fail due to a OOM fault and hence that the return value from
70978** sqlite3VdbeAddOpList() will always be non-NULL.
70979*/
70980#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
70981SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
70982  assert( p->nOp + N <= p->pParse->nOpAlloc );
70983}
70984#endif
70985
70986/*
70987** This function returns a pointer to the array of opcodes associated with
70988** the Vdbe passed as the first argument. It is the callers responsibility
70989** to arrange for the returned array to be eventually freed using the
70990** vdbeFreeOpArray() function.
70991**
70992** Before returning, *pnOp is set to the number of entries in the returned
70993** array. Also, *pnMaxArg is set to the larger of its current value and
70994** the number of entries in the Vdbe.apArg[] array required to execute the
70995** returned program.
70996*/
70997SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
70998  VdbeOp *aOp = p->aOp;
70999  assert( aOp && !p->db->mallocFailed );
71000
71001  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
71002  assert( DbMaskAllZero(p->btreeMask) );
71003
71004  resolveP2Values(p, pnMaxArg);
71005  *pnOp = p->nOp;
71006  p->aOp = 0;
71007  return aOp;
71008}
71009
71010/*
71011** Add a whole list of operations to the operation stack.  Return a
71012** pointer to the first operation inserted.
71013**
71014** Non-zero P2 arguments to jump instructions are automatically adjusted
71015** so that the jump target is relative to the first operation inserted.
71016*/
71017SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
71018  Vdbe *p,                     /* Add opcodes to the prepared statement */
71019  int nOp,                     /* Number of opcodes to add */
71020  VdbeOpList const *aOp,       /* The opcodes to be added */
71021  int iLineno                  /* Source-file line number of first opcode */
71022){
71023  int i;
71024  VdbeOp *pOut, *pFirst;
71025  assert( nOp>0 );
71026  assert( p->magic==VDBE_MAGIC_INIT );
71027  if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
71028    return 0;
71029  }
71030  pFirst = pOut = &p->aOp[p->nOp];
71031  for(i=0; i<nOp; i++, aOp++, pOut++){
71032    pOut->opcode = aOp->opcode;
71033    pOut->p1 = aOp->p1;
71034    pOut->p2 = aOp->p2;
71035    assert( aOp->p2>=0 );
71036    if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
71037      pOut->p2 += p->nOp;
71038    }
71039    pOut->p3 = aOp->p3;
71040    pOut->p4type = P4_NOTUSED;
71041    pOut->p4.p = 0;
71042    pOut->p5 = 0;
71043#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71044    pOut->zComment = 0;
71045#endif
71046#ifdef SQLITE_VDBE_COVERAGE
71047    pOut->iSrcLine = iLineno+i;
71048#else
71049    (void)iLineno;
71050#endif
71051#ifdef SQLITE_DEBUG
71052    if( p->db->flags & SQLITE_VdbeAddopTrace ){
71053      sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
71054    }
71055#endif
71056  }
71057  p->nOp += nOp;
71058  return pFirst;
71059}
71060
71061#if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
71062/*
71063** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
71064*/
71065SQLITE_PRIVATE void sqlite3VdbeScanStatus(
71066  Vdbe *p,                        /* VM to add scanstatus() to */
71067  int addrExplain,                /* Address of OP_Explain (or 0) */
71068  int addrLoop,                   /* Address of loop counter */
71069  int addrVisit,                  /* Address of rows visited counter */
71070  LogEst nEst,                    /* Estimated number of output rows */
71071  const char *zName               /* Name of table or index being scanned */
71072){
71073  int nByte = (p->nScan+1) * sizeof(ScanStatus);
71074  ScanStatus *aNew;
71075  aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
71076  if( aNew ){
71077    ScanStatus *pNew = &aNew[p->nScan++];
71078    pNew->addrExplain = addrExplain;
71079    pNew->addrLoop = addrLoop;
71080    pNew->addrVisit = addrVisit;
71081    pNew->nEst = nEst;
71082    pNew->zName = sqlite3DbStrDup(p->db, zName);
71083    p->aScan = aNew;
71084  }
71085}
71086#endif
71087
71088
71089/*
71090** Change the value of the opcode, or P1, P2, P3, or P5 operands
71091** for a specific instruction.
71092*/
71093SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
71094  sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
71095}
71096SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
71097  sqlite3VdbeGetOp(p,addr)->p1 = val;
71098}
71099SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
71100  sqlite3VdbeGetOp(p,addr)->p2 = val;
71101}
71102SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
71103  sqlite3VdbeGetOp(p,addr)->p3 = val;
71104}
71105SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 p5){
71106  if( !p->db->mallocFailed ) p->aOp[p->nOp-1].p5 = p5;
71107}
71108
71109/*
71110** Change the P2 operand of instruction addr so that it points to
71111** the address of the next instruction to be coded.
71112*/
71113SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
71114  p->pParse->iFixedOp = p->nOp - 1;
71115  sqlite3VdbeChangeP2(p, addr, p->nOp);
71116}
71117
71118
71119/*
71120** If the input FuncDef structure is ephemeral, then free it.  If
71121** the FuncDef is not ephermal, then do nothing.
71122*/
71123static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
71124  if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
71125    sqlite3DbFree(db, pDef);
71126  }
71127}
71128
71129static void vdbeFreeOpArray(sqlite3 *, Op *, int);
71130
71131/*
71132** Delete a P4 value if necessary.
71133*/
71134static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
71135  if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
71136  sqlite3DbFree(db, p);
71137}
71138static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
71139  freeEphemeralFunction(db, p->pFunc);
71140  sqlite3DbFree(db, p);
71141}
71142static void freeP4(sqlite3 *db, int p4type, void *p4){
71143  assert( db );
71144  switch( p4type ){
71145    case P4_FUNCCTX: {
71146      freeP4FuncCtx(db, (sqlite3_context*)p4);
71147      break;
71148    }
71149    case P4_REAL:
71150    case P4_INT64:
71151    case P4_DYNAMIC:
71152    case P4_INTARRAY: {
71153      sqlite3DbFree(db, p4);
71154      break;
71155    }
71156    case P4_KEYINFO: {
71157      if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
71158      break;
71159    }
71160#ifdef SQLITE_ENABLE_CURSOR_HINTS
71161    case P4_EXPR: {
71162      sqlite3ExprDelete(db, (Expr*)p4);
71163      break;
71164    }
71165#endif
71166    case P4_MPRINTF: {
71167      if( db->pnBytesFreed==0 ) sqlite3_free(p4);
71168      break;
71169    }
71170    case P4_FUNCDEF: {
71171      freeEphemeralFunction(db, (FuncDef*)p4);
71172      break;
71173    }
71174    case P4_MEM: {
71175      if( db->pnBytesFreed==0 ){
71176        sqlite3ValueFree((sqlite3_value*)p4);
71177      }else{
71178        freeP4Mem(db, (Mem*)p4);
71179      }
71180      break;
71181    }
71182    case P4_VTAB : {
71183      if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
71184      break;
71185    }
71186  }
71187}
71188
71189/*
71190** Free the space allocated for aOp and any p4 values allocated for the
71191** opcodes contained within. If aOp is not NULL it is assumed to contain
71192** nOp entries.
71193*/
71194static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
71195  if( aOp ){
71196    Op *pOp;
71197    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
71198      if( pOp->p4type ) freeP4(db, pOp->p4type, pOp->p4.p);
71199#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71200      sqlite3DbFree(db, pOp->zComment);
71201#endif
71202    }
71203  }
71204  sqlite3DbFree(db, aOp);
71205}
71206
71207/*
71208** Link the SubProgram object passed as the second argument into the linked
71209** list at Vdbe.pSubProgram. This list is used to delete all sub-program
71210** objects when the VM is no longer required.
71211*/
71212SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
71213  p->pNext = pVdbe->pProgram;
71214  pVdbe->pProgram = p;
71215}
71216
71217/*
71218** Change the opcode at addr into OP_Noop
71219*/
71220SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
71221  VdbeOp *pOp;
71222  if( p->db->mallocFailed ) return 0;
71223  assert( addr>=0 && addr<p->nOp );
71224  pOp = &p->aOp[addr];
71225  freeP4(p->db, pOp->p4type, pOp->p4.p);
71226  pOp->p4type = P4_NOTUSED;
71227  pOp->p4.z = 0;
71228  pOp->opcode = OP_Noop;
71229  return 1;
71230}
71231
71232/*
71233** If the last opcode is "op" and it is not a jump destination,
71234** then remove it.  Return true if and only if an opcode was removed.
71235*/
71236SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
71237  if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
71238    return sqlite3VdbeChangeToNoop(p, p->nOp-1);
71239  }else{
71240    return 0;
71241  }
71242}
71243
71244/*
71245** Change the value of the P4 operand for a specific instruction.
71246** This routine is useful when a large program is loaded from a
71247** static array using sqlite3VdbeAddOpList but we want to make a
71248** few minor changes to the program.
71249**
71250** If n>=0 then the P4 operand is dynamic, meaning that a copy of
71251** the string is made into memory obtained from sqlite3_malloc().
71252** A value of n==0 means copy bytes of zP4 up to and including the
71253** first null byte.  If n>0 then copy n+1 bytes of zP4.
71254**
71255** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
71256** to a string or structure that is guaranteed to exist for the lifetime of
71257** the Vdbe. In these cases we can just copy the pointer.
71258**
71259** If addr<0 then change P4 on the most recently inserted instruction.
71260*/
71261static void SQLITE_NOINLINE vdbeChangeP4Full(
71262  Vdbe *p,
71263  Op *pOp,
71264  const char *zP4,
71265  int n
71266){
71267  if( pOp->p4type ){
71268    freeP4(p->db, pOp->p4type, pOp->p4.p);
71269    pOp->p4type = 0;
71270    pOp->p4.p = 0;
71271  }
71272  if( n<0 ){
71273    sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
71274  }else{
71275    if( n==0 ) n = sqlite3Strlen30(zP4);
71276    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
71277    pOp->p4type = P4_DYNAMIC;
71278  }
71279}
71280SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
71281  Op *pOp;
71282  sqlite3 *db;
71283  assert( p!=0 );
71284  db = p->db;
71285  assert( p->magic==VDBE_MAGIC_INIT );
71286  assert( p->aOp!=0 || db->mallocFailed );
71287  if( db->mallocFailed ){
71288    if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
71289    return;
71290  }
71291  assert( p->nOp>0 );
71292  assert( addr<p->nOp );
71293  if( addr<0 ){
71294    addr = p->nOp - 1;
71295  }
71296  pOp = &p->aOp[addr];
71297  if( n>=0 || pOp->p4type ){
71298    vdbeChangeP4Full(p, pOp, zP4, n);
71299    return;
71300  }
71301  if( n==P4_INT32 ){
71302    /* Note: this cast is safe, because the origin data point was an int
71303    ** that was cast to a (const char *). */
71304    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
71305    pOp->p4type = P4_INT32;
71306  }else if( zP4!=0 ){
71307    assert( n<0 );
71308    pOp->p4.p = (void*)zP4;
71309    pOp->p4type = (signed char)n;
71310    if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
71311  }
71312}
71313
71314/*
71315** Set the P4 on the most recently added opcode to the KeyInfo for the
71316** index given.
71317*/
71318SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
71319  Vdbe *v = pParse->pVdbe;
71320  assert( v!=0 );
71321  assert( pIdx!=0 );
71322  sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
71323                      P4_KEYINFO);
71324}
71325
71326#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71327/*
71328** Change the comment on the most recently coded instruction.  Or
71329** insert a No-op and add the comment to that new instruction.  This
71330** makes the code easier to read during debugging.  None of this happens
71331** in a production build.
71332*/
71333static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
71334  assert( p->nOp>0 || p->aOp==0 );
71335  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
71336  if( p->nOp ){
71337    assert( p->aOp );
71338    sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
71339    p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
71340  }
71341}
71342SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
71343  va_list ap;
71344  if( p ){
71345    va_start(ap, zFormat);
71346    vdbeVComment(p, zFormat, ap);
71347    va_end(ap);
71348  }
71349}
71350SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
71351  va_list ap;
71352  if( p ){
71353    sqlite3VdbeAddOp0(p, OP_Noop);
71354    va_start(ap, zFormat);
71355    vdbeVComment(p, zFormat, ap);
71356    va_end(ap);
71357  }
71358}
71359#endif  /* NDEBUG */
71360
71361#ifdef SQLITE_VDBE_COVERAGE
71362/*
71363** Set the value if the iSrcLine field for the previously coded instruction.
71364*/
71365SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
71366  sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
71367}
71368#endif /* SQLITE_VDBE_COVERAGE */
71369
71370/*
71371** Return the opcode for a given address.  If the address is -1, then
71372** return the most recently inserted opcode.
71373**
71374** If a memory allocation error has occurred prior to the calling of this
71375** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
71376** is readable but not writable, though it is cast to a writable value.
71377** The return of a dummy opcode allows the call to continue functioning
71378** after an OOM fault without having to check to see if the return from
71379** this routine is a valid pointer.  But because the dummy.opcode is 0,
71380** dummy will never be written to.  This is verified by code inspection and
71381** by running with Valgrind.
71382*/
71383SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
71384  /* C89 specifies that the constant "dummy" will be initialized to all
71385  ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
71386  static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
71387  assert( p->magic==VDBE_MAGIC_INIT );
71388  if( addr<0 ){
71389    addr = p->nOp - 1;
71390  }
71391  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
71392  if( p->db->mallocFailed ){
71393    return (VdbeOp*)&dummy;
71394  }else{
71395    return &p->aOp[addr];
71396  }
71397}
71398
71399#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
71400/*
71401** Return an integer value for one of the parameters to the opcode pOp
71402** determined by character c.
71403*/
71404static int translateP(char c, const Op *pOp){
71405  if( c=='1' ) return pOp->p1;
71406  if( c=='2' ) return pOp->p2;
71407  if( c=='3' ) return pOp->p3;
71408  if( c=='4' ) return pOp->p4.i;
71409  return pOp->p5;
71410}
71411
71412/*
71413** Compute a string for the "comment" field of a VDBE opcode listing.
71414**
71415** The Synopsis: field in comments in the vdbe.c source file gets converted
71416** to an extra string that is appended to the sqlite3OpcodeName().  In the
71417** absence of other comments, this synopsis becomes the comment on the opcode.
71418** Some translation occurs:
71419**
71420**       "PX"      ->  "r[X]"
71421**       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
71422**       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
71423**       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
71424*/
71425static int displayComment(
71426  const Op *pOp,     /* The opcode to be commented */
71427  const char *zP4,   /* Previously obtained value for P4 */
71428  char *zTemp,       /* Write result here */
71429  int nTemp          /* Space available in zTemp[] */
71430){
71431  const char *zOpName;
71432  const char *zSynopsis;
71433  int nOpName;
71434  int ii, jj;
71435  zOpName = sqlite3OpcodeName(pOp->opcode);
71436  nOpName = sqlite3Strlen30(zOpName);
71437  if( zOpName[nOpName+1] ){
71438    int seenCom = 0;
71439    char c;
71440    zSynopsis = zOpName += nOpName + 1;
71441    for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
71442      if( c=='P' ){
71443        c = zSynopsis[++ii];
71444        if( c=='4' ){
71445          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
71446        }else if( c=='X' ){
71447          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
71448          seenCom = 1;
71449        }else{
71450          int v1 = translateP(c, pOp);
71451          int v2;
71452          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
71453          if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
71454            ii += 3;
71455            jj += sqlite3Strlen30(zTemp+jj);
71456            v2 = translateP(zSynopsis[ii], pOp);
71457            if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
71458              ii += 2;
71459              v2++;
71460            }
71461            if( v2>1 ){
71462              sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
71463            }
71464          }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
71465            ii += 4;
71466          }
71467        }
71468        jj += sqlite3Strlen30(zTemp+jj);
71469      }else{
71470        zTemp[jj++] = c;
71471      }
71472    }
71473    if( !seenCom && jj<nTemp-5 && pOp->zComment ){
71474      sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
71475      jj += sqlite3Strlen30(zTemp+jj);
71476    }
71477    if( jj<nTemp ) zTemp[jj] = 0;
71478  }else if( pOp->zComment ){
71479    sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
71480    jj = sqlite3Strlen30(zTemp);
71481  }else{
71482    zTemp[0] = 0;
71483    jj = 0;
71484  }
71485  return jj;
71486}
71487#endif /* SQLITE_DEBUG */
71488
71489#if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
71490/*
71491** Translate the P4.pExpr value for an OP_CursorHint opcode into text
71492** that can be displayed in the P4 column of EXPLAIN output.
71493*/
71494static void displayP4Expr(StrAccum *p, Expr *pExpr){
71495  const char *zOp = 0;
71496  switch( pExpr->op ){
71497    case TK_STRING:
71498      sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
71499      break;
71500    case TK_INTEGER:
71501      sqlite3XPrintf(p, "%d", pExpr->u.iValue);
71502      break;
71503    case TK_NULL:
71504      sqlite3XPrintf(p, "NULL");
71505      break;
71506    case TK_REGISTER: {
71507      sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
71508      break;
71509    }
71510    case TK_COLUMN: {
71511      if( pExpr->iColumn<0 ){
71512        sqlite3XPrintf(p, "rowid");
71513      }else{
71514        sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
71515      }
71516      break;
71517    }
71518    case TK_LT:      zOp = "LT";      break;
71519    case TK_LE:      zOp = "LE";      break;
71520    case TK_GT:      zOp = "GT";      break;
71521    case TK_GE:      zOp = "GE";      break;
71522    case TK_NE:      zOp = "NE";      break;
71523    case TK_EQ:      zOp = "EQ";      break;
71524    case TK_IS:      zOp = "IS";      break;
71525    case TK_ISNOT:   zOp = "ISNOT";   break;
71526    case TK_AND:     zOp = "AND";     break;
71527    case TK_OR:      zOp = "OR";      break;
71528    case TK_PLUS:    zOp = "ADD";     break;
71529    case TK_STAR:    zOp = "MUL";     break;
71530    case TK_MINUS:   zOp = "SUB";     break;
71531    case TK_REM:     zOp = "REM";     break;
71532    case TK_BITAND:  zOp = "BITAND";  break;
71533    case TK_BITOR:   zOp = "BITOR";   break;
71534    case TK_SLASH:   zOp = "DIV";     break;
71535    case TK_LSHIFT:  zOp = "LSHIFT";  break;
71536    case TK_RSHIFT:  zOp = "RSHIFT";  break;
71537    case TK_CONCAT:  zOp = "CONCAT";  break;
71538    case TK_UMINUS:  zOp = "MINUS";   break;
71539    case TK_UPLUS:   zOp = "PLUS";    break;
71540    case TK_BITNOT:  zOp = "BITNOT";  break;
71541    case TK_NOT:     zOp = "NOT";     break;
71542    case TK_ISNULL:  zOp = "ISNULL";  break;
71543    case TK_NOTNULL: zOp = "NOTNULL"; break;
71544
71545    default:
71546      sqlite3XPrintf(p, "%s", "expr");
71547      break;
71548  }
71549
71550  if( zOp ){
71551    sqlite3XPrintf(p, "%s(", zOp);
71552    displayP4Expr(p, pExpr->pLeft);
71553    if( pExpr->pRight ){
71554      sqlite3StrAccumAppend(p, ",", 1);
71555      displayP4Expr(p, pExpr->pRight);
71556    }
71557    sqlite3StrAccumAppend(p, ")", 1);
71558  }
71559}
71560#endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
71561
71562
71563#if VDBE_DISPLAY_P4
71564/*
71565** Compute a string that describes the P4 parameter for an opcode.
71566** Use zTemp for any required temporary buffer space.
71567*/
71568static char *displayP4(Op *pOp, char *zTemp, int nTemp){
71569  char *zP4 = zTemp;
71570  StrAccum x;
71571  assert( nTemp>=20 );
71572  sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
71573  switch( pOp->p4type ){
71574    case P4_KEYINFO: {
71575      int j;
71576      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
71577      assert( pKeyInfo->aSortOrder!=0 );
71578      sqlite3XPrintf(&x, "k(%d", pKeyInfo->nField);
71579      for(j=0; j<pKeyInfo->nField; j++){
71580        CollSeq *pColl = pKeyInfo->aColl[j];
71581        const char *zColl = pColl ? pColl->zName : "";
71582        if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
71583        sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
71584      }
71585      sqlite3StrAccumAppend(&x, ")", 1);
71586      break;
71587    }
71588#ifdef SQLITE_ENABLE_CURSOR_HINTS
71589    case P4_EXPR: {
71590      displayP4Expr(&x, pOp->p4.pExpr);
71591      break;
71592    }
71593#endif
71594    case P4_COLLSEQ: {
71595      CollSeq *pColl = pOp->p4.pColl;
71596      sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
71597      break;
71598    }
71599    case P4_FUNCDEF: {
71600      FuncDef *pDef = pOp->p4.pFunc;
71601      sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
71602      break;
71603    }
71604#ifdef SQLITE_DEBUG
71605    case P4_FUNCCTX: {
71606      FuncDef *pDef = pOp->p4.pCtx->pFunc;
71607      sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
71608      break;
71609    }
71610#endif
71611    case P4_INT64: {
71612      sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
71613      break;
71614    }
71615    case P4_INT32: {
71616      sqlite3XPrintf(&x, "%d", pOp->p4.i);
71617      break;
71618    }
71619    case P4_REAL: {
71620      sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
71621      break;
71622    }
71623    case P4_MEM: {
71624      Mem *pMem = pOp->p4.pMem;
71625      if( pMem->flags & MEM_Str ){
71626        zP4 = pMem->z;
71627      }else if( pMem->flags & MEM_Int ){
71628        sqlite3XPrintf(&x, "%lld", pMem->u.i);
71629      }else if( pMem->flags & MEM_Real ){
71630        sqlite3XPrintf(&x, "%.16g", pMem->u.r);
71631      }else if( pMem->flags & MEM_Null ){
71632        zP4 = "NULL";
71633      }else{
71634        assert( pMem->flags & MEM_Blob );
71635        zP4 = "(blob)";
71636      }
71637      break;
71638    }
71639#ifndef SQLITE_OMIT_VIRTUALTABLE
71640    case P4_VTAB: {
71641      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
71642      sqlite3XPrintf(&x, "vtab:%p", pVtab);
71643      break;
71644    }
71645#endif
71646    case P4_INTARRAY: {
71647      int i;
71648      int *ai = pOp->p4.ai;
71649      int n = ai[0];   /* The first element of an INTARRAY is always the
71650                       ** count of the number of elements to follow */
71651      for(i=1; i<n; i++){
71652        sqlite3XPrintf(&x, ",%d", ai[i]);
71653      }
71654      zTemp[0] = '[';
71655      sqlite3StrAccumAppend(&x, "]", 1);
71656      break;
71657    }
71658    case P4_SUBPROGRAM: {
71659      sqlite3XPrintf(&x, "program");
71660      break;
71661    }
71662    case P4_ADVANCE: {
71663      zTemp[0] = 0;
71664      break;
71665    }
71666    case P4_TABLE: {
71667      sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
71668      break;
71669    }
71670    default: {
71671      zP4 = pOp->p4.z;
71672      if( zP4==0 ){
71673        zP4 = zTemp;
71674        zTemp[0] = 0;
71675      }
71676    }
71677  }
71678  sqlite3StrAccumFinish(&x);
71679  assert( zP4!=0 );
71680  return zP4;
71681}
71682#endif /* VDBE_DISPLAY_P4 */
71683
71684/*
71685** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
71686**
71687** The prepared statements need to know in advance the complete set of
71688** attached databases that will be use.  A mask of these databases
71689** is maintained in p->btreeMask.  The p->lockMask value is the subset of
71690** p->btreeMask of databases that will require a lock.
71691*/
71692SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
71693  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
71694  assert( i<(int)sizeof(p->btreeMask)*8 );
71695  DbMaskSet(p->btreeMask, i);
71696  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
71697    DbMaskSet(p->lockMask, i);
71698  }
71699}
71700
71701#if !defined(SQLITE_OMIT_SHARED_CACHE)
71702/*
71703** If SQLite is compiled to support shared-cache mode and to be threadsafe,
71704** this routine obtains the mutex associated with each BtShared structure
71705** that may be accessed by the VM passed as an argument. In doing so it also
71706** sets the BtShared.db member of each of the BtShared structures, ensuring
71707** that the correct busy-handler callback is invoked if required.
71708**
71709** If SQLite is not threadsafe but does support shared-cache mode, then
71710** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
71711** of all of BtShared structures accessible via the database handle
71712** associated with the VM.
71713**
71714** If SQLite is not threadsafe and does not support shared-cache mode, this
71715** function is a no-op.
71716**
71717** The p->btreeMask field is a bitmask of all btrees that the prepared
71718** statement p will ever use.  Let N be the number of bits in p->btreeMask
71719** corresponding to btrees that use shared cache.  Then the runtime of
71720** this routine is N*N.  But as N is rarely more than 1, this should not
71721** be a problem.
71722*/
71723SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
71724  int i;
71725  sqlite3 *db;
71726  Db *aDb;
71727  int nDb;
71728  if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
71729  db = p->db;
71730  aDb = db->aDb;
71731  nDb = db->nDb;
71732  for(i=0; i<nDb; i++){
71733    if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
71734      sqlite3BtreeEnter(aDb[i].pBt);
71735    }
71736  }
71737}
71738#endif
71739
71740#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
71741/*
71742** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
71743*/
71744static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
71745  int i;
71746  sqlite3 *db;
71747  Db *aDb;
71748  int nDb;
71749  db = p->db;
71750  aDb = db->aDb;
71751  nDb = db->nDb;
71752  for(i=0; i<nDb; i++){
71753    if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
71754      sqlite3BtreeLeave(aDb[i].pBt);
71755    }
71756  }
71757}
71758SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
71759  if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
71760  vdbeLeave(p);
71761}
71762#endif
71763
71764#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
71765/*
71766** Print a single opcode.  This routine is used for debugging only.
71767*/
71768SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
71769  char *zP4;
71770  char zPtr[50];
71771  char zCom[100];
71772  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
71773  if( pOut==0 ) pOut = stdout;
71774  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
71775#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71776  displayComment(pOp, zP4, zCom, sizeof(zCom));
71777#else
71778  zCom[0] = 0;
71779#endif
71780  /* NB:  The sqlite3OpcodeName() function is implemented by code created
71781  ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
71782  ** information from the vdbe.c source text */
71783  fprintf(pOut, zFormat1, pc,
71784      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
71785      zCom
71786  );
71787  fflush(pOut);
71788}
71789#endif
71790
71791/*
71792** Release an array of N Mem elements
71793*/
71794static void releaseMemArray(Mem *p, int N){
71795  if( p && N ){
71796    Mem *pEnd = &p[N];
71797    sqlite3 *db = p->db;
71798    if( db->pnBytesFreed ){
71799      do{
71800        if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
71801      }while( (++p)<pEnd );
71802      return;
71803    }
71804    do{
71805      assert( (&p[1])==pEnd || p[0].db==p[1].db );
71806      assert( sqlite3VdbeCheckMemInvariants(p) );
71807
71808      /* This block is really an inlined version of sqlite3VdbeMemRelease()
71809      ** that takes advantage of the fact that the memory cell value is
71810      ** being set to NULL after releasing any dynamic resources.
71811      **
71812      ** The justification for duplicating code is that according to
71813      ** callgrind, this causes a certain test case to hit the CPU 4.7
71814      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
71815      ** sqlite3MemRelease() were called from here. With -O2, this jumps
71816      ** to 6.6 percent. The test case is inserting 1000 rows into a table
71817      ** with no indexes using a single prepared INSERT statement, bind()
71818      ** and reset(). Inserts are grouped into a transaction.
71819      */
71820      testcase( p->flags & MEM_Agg );
71821      testcase( p->flags & MEM_Dyn );
71822      testcase( p->flags & MEM_Frame );
71823      testcase( p->flags & MEM_RowSet );
71824      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
71825        sqlite3VdbeMemRelease(p);
71826      }else if( p->szMalloc ){
71827        sqlite3DbFree(db, p->zMalloc);
71828        p->szMalloc = 0;
71829      }
71830
71831      p->flags = MEM_Undefined;
71832    }while( (++p)<pEnd );
71833  }
71834}
71835
71836/*
71837** Delete a VdbeFrame object and its contents. VdbeFrame objects are
71838** allocated by the OP_Program opcode in sqlite3VdbeExec().
71839*/
71840SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
71841  int i;
71842  Mem *aMem = VdbeFrameMem(p);
71843  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
71844  for(i=0; i<p->nChildCsr; i++){
71845    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
71846  }
71847  releaseMemArray(aMem, p->nChildMem);
71848  sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
71849  sqlite3DbFree(p->v->db, p);
71850}
71851
71852#ifndef SQLITE_OMIT_EXPLAIN
71853/*
71854** Give a listing of the program in the virtual machine.
71855**
71856** The interface is the same as sqlite3VdbeExec().  But instead of
71857** running the code, it invokes the callback once for each instruction.
71858** This feature is used to implement "EXPLAIN".
71859**
71860** When p->explain==1, each instruction is listed.  When
71861** p->explain==2, only OP_Explain instructions are listed and these
71862** are shown in a different format.  p->explain==2 is used to implement
71863** EXPLAIN QUERY PLAN.
71864**
71865** When p->explain==1, first the main program is listed, then each of
71866** the trigger subprograms are listed one by one.
71867*/
71868SQLITE_PRIVATE int sqlite3VdbeList(
71869  Vdbe *p                   /* The VDBE */
71870){
71871  int nRow;                            /* Stop when row count reaches this */
71872  int nSub = 0;                        /* Number of sub-vdbes seen so far */
71873  SubProgram **apSub = 0;              /* Array of sub-vdbes */
71874  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
71875  sqlite3 *db = p->db;                 /* The database connection */
71876  int i;                               /* Loop counter */
71877  int rc = SQLITE_OK;                  /* Return code */
71878  Mem *pMem = &p->aMem[1];             /* First Mem of result set */
71879
71880  assert( p->explain );
71881  assert( p->magic==VDBE_MAGIC_RUN );
71882  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
71883
71884  /* Even though this opcode does not use dynamic strings for
71885  ** the result, result columns may become dynamic if the user calls
71886  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
71887  */
71888  releaseMemArray(pMem, 8);
71889  p->pResultSet = 0;
71890
71891  if( p->rc==SQLITE_NOMEM_BKPT ){
71892    /* This happens if a malloc() inside a call to sqlite3_column_text() or
71893    ** sqlite3_column_text16() failed.  */
71894    sqlite3OomFault(db);
71895    return SQLITE_ERROR;
71896  }
71897
71898  /* When the number of output rows reaches nRow, that means the
71899  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
71900  ** nRow is the sum of the number of rows in the main program, plus
71901  ** the sum of the number of rows in all trigger subprograms encountered
71902  ** so far.  The nRow value will increase as new trigger subprograms are
71903  ** encountered, but p->pc will eventually catch up to nRow.
71904  */
71905  nRow = p->nOp;
71906  if( p->explain==1 ){
71907    /* The first 8 memory cells are used for the result set.  So we will
71908    ** commandeer the 9th cell to use as storage for an array of pointers
71909    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
71910    ** cells.  */
71911    assert( p->nMem>9 );
71912    pSub = &p->aMem[9];
71913    if( pSub->flags&MEM_Blob ){
71914      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
71915      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
71916      nSub = pSub->n/sizeof(Vdbe*);
71917      apSub = (SubProgram **)pSub->z;
71918    }
71919    for(i=0; i<nSub; i++){
71920      nRow += apSub[i]->nOp;
71921    }
71922  }
71923
71924  do{
71925    i = p->pc++;
71926  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
71927  if( i>=nRow ){
71928    p->rc = SQLITE_OK;
71929    rc = SQLITE_DONE;
71930  }else if( db->u1.isInterrupted ){
71931    p->rc = SQLITE_INTERRUPT;
71932    rc = SQLITE_ERROR;
71933    sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
71934  }else{
71935    char *zP4;
71936    Op *pOp;
71937    if( i<p->nOp ){
71938      /* The output line number is small enough that we are still in the
71939      ** main program. */
71940      pOp = &p->aOp[i];
71941    }else{
71942      /* We are currently listing subprograms.  Figure out which one and
71943      ** pick up the appropriate opcode. */
71944      int j;
71945      i -= p->nOp;
71946      for(j=0; i>=apSub[j]->nOp; j++){
71947        i -= apSub[j]->nOp;
71948      }
71949      pOp = &apSub[j]->aOp[i];
71950    }
71951    if( p->explain==1 ){
71952      pMem->flags = MEM_Int;
71953      pMem->u.i = i;                                /* Program counter */
71954      pMem++;
71955
71956      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
71957      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
71958      assert( pMem->z!=0 );
71959      pMem->n = sqlite3Strlen30(pMem->z);
71960      pMem->enc = SQLITE_UTF8;
71961      pMem++;
71962
71963      /* When an OP_Program opcode is encounter (the only opcode that has
71964      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
71965      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
71966      ** has not already been seen.
71967      */
71968      if( pOp->p4type==P4_SUBPROGRAM ){
71969        int nByte = (nSub+1)*sizeof(SubProgram*);
71970        int j;
71971        for(j=0; j<nSub; j++){
71972          if( apSub[j]==pOp->p4.pProgram ) break;
71973        }
71974        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
71975          apSub = (SubProgram **)pSub->z;
71976          apSub[nSub++] = pOp->p4.pProgram;
71977          pSub->flags |= MEM_Blob;
71978          pSub->n = nSub*sizeof(SubProgram*);
71979        }
71980      }
71981    }
71982
71983    pMem->flags = MEM_Int;
71984    pMem->u.i = pOp->p1;                          /* P1 */
71985    pMem++;
71986
71987    pMem->flags = MEM_Int;
71988    pMem->u.i = pOp->p2;                          /* P2 */
71989    pMem++;
71990
71991    pMem->flags = MEM_Int;
71992    pMem->u.i = pOp->p3;                          /* P3 */
71993    pMem++;
71994
71995    if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
71996      assert( p->db->mallocFailed );
71997      return SQLITE_ERROR;
71998    }
71999    pMem->flags = MEM_Str|MEM_Term;
72000    zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
72001    if( zP4!=pMem->z ){
72002      sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
72003    }else{
72004      assert( pMem->z!=0 );
72005      pMem->n = sqlite3Strlen30(pMem->z);
72006      pMem->enc = SQLITE_UTF8;
72007    }
72008    pMem++;
72009
72010    if( p->explain==1 ){
72011      if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
72012        assert( p->db->mallocFailed );
72013        return SQLITE_ERROR;
72014      }
72015      pMem->flags = MEM_Str|MEM_Term;
72016      pMem->n = 2;
72017      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
72018      pMem->enc = SQLITE_UTF8;
72019      pMem++;
72020
72021#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
72022      if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
72023        assert( p->db->mallocFailed );
72024        return SQLITE_ERROR;
72025      }
72026      pMem->flags = MEM_Str|MEM_Term;
72027      pMem->n = displayComment(pOp, zP4, pMem->z, 500);
72028      pMem->enc = SQLITE_UTF8;
72029#else
72030      pMem->flags = MEM_Null;                       /* Comment */
72031#endif
72032    }
72033
72034    p->nResColumn = 8 - 4*(p->explain-1);
72035    p->pResultSet = &p->aMem[1];
72036    p->rc = SQLITE_OK;
72037    rc = SQLITE_ROW;
72038  }
72039  return rc;
72040}
72041#endif /* SQLITE_OMIT_EXPLAIN */
72042
72043#ifdef SQLITE_DEBUG
72044/*
72045** Print the SQL that was used to generate a VDBE program.
72046*/
72047SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
72048  const char *z = 0;
72049  if( p->zSql ){
72050    z = p->zSql;
72051  }else if( p->nOp>=1 ){
72052    const VdbeOp *pOp = &p->aOp[0];
72053    if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
72054      z = pOp->p4.z;
72055      while( sqlite3Isspace(*z) ) z++;
72056    }
72057  }
72058  if( z ) printf("SQL: [%s]\n", z);
72059}
72060#endif
72061
72062#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
72063/*
72064** Print an IOTRACE message showing SQL content.
72065*/
72066SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
72067  int nOp = p->nOp;
72068  VdbeOp *pOp;
72069  if( sqlite3IoTrace==0 ) return;
72070  if( nOp<1 ) return;
72071  pOp = &p->aOp[0];
72072  if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
72073    int i, j;
72074    char z[1000];
72075    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
72076    for(i=0; sqlite3Isspace(z[i]); i++){}
72077    for(j=0; z[i]; i++){
72078      if( sqlite3Isspace(z[i]) ){
72079        if( z[i-1]!=' ' ){
72080          z[j++] = ' ';
72081        }
72082      }else{
72083        z[j++] = z[i];
72084      }
72085    }
72086    z[j] = 0;
72087    sqlite3IoTrace("SQL %s\n", z);
72088  }
72089}
72090#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
72091
72092/* An instance of this object describes bulk memory available for use
72093** by subcomponents of a prepared statement.  Space is allocated out
72094** of a ReusableSpace object by the allocSpace() routine below.
72095*/
72096struct ReusableSpace {
72097  u8 *pSpace;          /* Available memory */
72098  int nFree;           /* Bytes of available memory */
72099  int nNeeded;         /* Total bytes that could not be allocated */
72100};
72101
72102/* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
72103** from the ReusableSpace object.  Return a pointer to the allocated
72104** memory on success.  If insufficient memory is available in the
72105** ReusableSpace object, increase the ReusableSpace.nNeeded
72106** value by the amount needed and return NULL.
72107**
72108** If pBuf is not initially NULL, that means that the memory has already
72109** been allocated by a prior call to this routine, so just return a copy
72110** of pBuf and leave ReusableSpace unchanged.
72111**
72112** This allocator is employed to repurpose unused slots at the end of the
72113** opcode array of prepared state for other memory needs of the prepared
72114** statement.
72115*/
72116static void *allocSpace(
72117  struct ReusableSpace *p,  /* Bulk memory available for allocation */
72118  void *pBuf,               /* Pointer to a prior allocation */
72119  int nByte                 /* Bytes of memory needed */
72120){
72121  assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
72122  if( pBuf==0 ){
72123    nByte = ROUND8(nByte);
72124    if( nByte <= p->nFree ){
72125      p->nFree -= nByte;
72126      pBuf = &p->pSpace[p->nFree];
72127    }else{
72128      p->nNeeded += nByte;
72129    }
72130  }
72131  assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
72132  return pBuf;
72133}
72134
72135/*
72136** Rewind the VDBE back to the beginning in preparation for
72137** running it.
72138*/
72139SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
72140#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
72141  int i;
72142#endif
72143  assert( p!=0 );
72144  assert( p->magic==VDBE_MAGIC_INIT );
72145
72146  /* There should be at least one opcode.
72147  */
72148  assert( p->nOp>0 );
72149
72150  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
72151  p->magic = VDBE_MAGIC_RUN;
72152
72153#ifdef SQLITE_DEBUG
72154  for(i=0; i<p->nMem; i++){
72155    assert( p->aMem[i].db==p->db );
72156  }
72157#endif
72158  p->pc = -1;
72159  p->rc = SQLITE_OK;
72160  p->errorAction = OE_Abort;
72161  p->nChange = 0;
72162  p->cacheCtr = 1;
72163  p->minWriteFileFormat = 255;
72164  p->iStatement = 0;
72165  p->nFkConstraint = 0;
72166#ifdef VDBE_PROFILE
72167  for(i=0; i<p->nOp; i++){
72168    p->aOp[i].cnt = 0;
72169    p->aOp[i].cycles = 0;
72170  }
72171#endif
72172}
72173
72174/*
72175** Prepare a virtual machine for execution for the first time after
72176** creating the virtual machine.  This involves things such
72177** as allocating registers and initializing the program counter.
72178** After the VDBE has be prepped, it can be executed by one or more
72179** calls to sqlite3VdbeExec().
72180**
72181** This function may be called exactly once on each virtual machine.
72182** After this routine is called the VM has been "packaged" and is ready
72183** to run.  After this routine is called, further calls to
72184** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
72185** the Vdbe from the Parse object that helped generate it so that the
72186** the Vdbe becomes an independent entity and the Parse object can be
72187** destroyed.
72188**
72189** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
72190** to its initial state after it has been run.
72191*/
72192SQLITE_PRIVATE void sqlite3VdbeMakeReady(
72193  Vdbe *p,                       /* The VDBE */
72194  Parse *pParse                  /* Parsing context */
72195){
72196  sqlite3 *db;                   /* The database connection */
72197  int nVar;                      /* Number of parameters */
72198  int nMem;                      /* Number of VM memory registers */
72199  int nCursor;                   /* Number of cursors required */
72200  int nArg;                      /* Number of arguments in subprograms */
72201  int nOnce;                     /* Number of OP_Once instructions */
72202  int n;                         /* Loop counter */
72203  struct ReusableSpace x;        /* Reusable bulk memory */
72204
72205  assert( p!=0 );
72206  assert( p->nOp>0 );
72207  assert( pParse!=0 );
72208  assert( p->magic==VDBE_MAGIC_INIT );
72209  assert( pParse==p->pParse );
72210  db = p->db;
72211  assert( db->mallocFailed==0 );
72212  nVar = pParse->nVar;
72213  nMem = pParse->nMem;
72214  nCursor = pParse->nTab;
72215  nArg = pParse->nMaxArg;
72216  nOnce = pParse->nOnce;
72217  if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
72218
72219  /* Each cursor uses a memory cell.  The first cursor (cursor 0) can
72220  ** use aMem[0] which is not otherwise used by the VDBE program.  Allocate
72221  ** space at the end of aMem[] for cursors 1 and greater.
72222  ** See also: allocateCursor().
72223  */
72224  nMem += nCursor;
72225  if( nCursor==0 && nMem>0 ) nMem++;  /* Space for aMem[0] even if not used */
72226
72227  /* Figure out how much reusable memory is available at the end of the
72228  ** opcode array.  This extra memory will be reallocated for other elements
72229  ** of the prepared statement.
72230  */
72231  n = ROUND8(sizeof(Op)*p->nOp);              /* Bytes of opcode memory used */
72232  x.pSpace = &((u8*)p->aOp)[n];               /* Unused opcode memory */
72233  assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
72234  x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n);  /* Bytes of unused memory */
72235  assert( x.nFree>=0 );
72236  if( x.nFree>0 ){
72237    memset(x.pSpace, 0, x.nFree);
72238    assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
72239  }
72240
72241  resolveP2Values(p, &nArg);
72242  p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
72243  if( pParse->explain && nMem<10 ){
72244    nMem = 10;
72245  }
72246  p->expired = 0;
72247
72248  /* Memory for registers, parameters, cursor, etc, is allocated in one or two
72249  ** passes.  On the first pass, we try to reuse unused memory at the
72250  ** end of the opcode array.  If we are unable to satisfy all memory
72251  ** requirements by reusing the opcode array tail, then the second
72252  ** pass will fill in the remainder using a fresh memory allocation.
72253  **
72254  ** This two-pass approach that reuses as much memory as possible from
72255  ** the leftover memory at the end of the opcode array.  This can significantly
72256  ** reduce the amount of memory held by a prepared statement.
72257  */
72258  do {
72259    x.nNeeded = 0;
72260    p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
72261    p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
72262    p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
72263    p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
72264    p->aOnceFlag = allocSpace(&x, p->aOnceFlag, nOnce);
72265#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
72266    p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
72267#endif
72268    if( x.nNeeded==0 ) break;
72269    x.pSpace = p->pFree = sqlite3DbMallocZero(db, x.nNeeded);
72270    x.nFree = x.nNeeded;
72271  }while( !db->mallocFailed );
72272
72273  p->nCursor = nCursor;
72274  p->nOnceFlag = nOnce;
72275  if( p->aVar ){
72276    p->nVar = (ynVar)nVar;
72277    for(n=0; n<nVar; n++){
72278      p->aVar[n].flags = MEM_Null;
72279      p->aVar[n].db = db;
72280    }
72281  }
72282  p->nzVar = pParse->nzVar;
72283  p->azVar = pParse->azVar;
72284  pParse->nzVar =  0;
72285  pParse->azVar = 0;
72286  if( p->aMem ){
72287    p->nMem = nMem;
72288    for(n=0; n<nMem; n++){
72289      p->aMem[n].flags = MEM_Undefined;
72290      p->aMem[n].db = db;
72291    }
72292  }
72293  p->explain = pParse->explain;
72294  sqlite3VdbeRewind(p);
72295}
72296
72297/*
72298** Close a VDBE cursor and release all the resources that cursor
72299** happens to hold.
72300*/
72301SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
72302  if( pCx==0 ){
72303    return;
72304  }
72305  assert( pCx->pBt==0 || pCx->eCurType==CURTYPE_BTREE );
72306  switch( pCx->eCurType ){
72307    case CURTYPE_SORTER: {
72308      sqlite3VdbeSorterClose(p->db, pCx);
72309      break;
72310    }
72311    case CURTYPE_BTREE: {
72312      if( pCx->pBt ){
72313        sqlite3BtreeClose(pCx->pBt);
72314        /* The pCx->pCursor will be close automatically, if it exists, by
72315        ** the call above. */
72316      }else{
72317        assert( pCx->uc.pCursor!=0 );
72318        sqlite3BtreeCloseCursor(pCx->uc.pCursor);
72319      }
72320      break;
72321    }
72322#ifndef SQLITE_OMIT_VIRTUALTABLE
72323    case CURTYPE_VTAB: {
72324      sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
72325      const sqlite3_module *pModule = pVCur->pVtab->pModule;
72326      assert( pVCur->pVtab->nRef>0 );
72327      pVCur->pVtab->nRef--;
72328      pModule->xClose(pVCur);
72329      break;
72330    }
72331#endif
72332  }
72333}
72334
72335/*
72336** Close all cursors in the current frame.
72337*/
72338static void closeCursorsInFrame(Vdbe *p){
72339  if( p->apCsr ){
72340    int i;
72341    for(i=0; i<p->nCursor; i++){
72342      VdbeCursor *pC = p->apCsr[i];
72343      if( pC ){
72344        sqlite3VdbeFreeCursor(p, pC);
72345        p->apCsr[i] = 0;
72346      }
72347    }
72348  }
72349}
72350
72351/*
72352** Copy the values stored in the VdbeFrame structure to its Vdbe. This
72353** is used, for example, when a trigger sub-program is halted to restore
72354** control to the main program.
72355*/
72356SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
72357  Vdbe *v = pFrame->v;
72358  closeCursorsInFrame(v);
72359#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
72360  v->anExec = pFrame->anExec;
72361#endif
72362  v->aOnceFlag = pFrame->aOnceFlag;
72363  v->nOnceFlag = pFrame->nOnceFlag;
72364  v->aOp = pFrame->aOp;
72365  v->nOp = pFrame->nOp;
72366  v->aMem = pFrame->aMem;
72367  v->nMem = pFrame->nMem;
72368  v->apCsr = pFrame->apCsr;
72369  v->nCursor = pFrame->nCursor;
72370  v->db->lastRowid = pFrame->lastRowid;
72371  v->nChange = pFrame->nChange;
72372  v->db->nChange = pFrame->nDbChange;
72373  sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
72374  v->pAuxData = pFrame->pAuxData;
72375  pFrame->pAuxData = 0;
72376  return pFrame->pc;
72377}
72378
72379/*
72380** Close all cursors.
72381**
72382** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
72383** cell array. This is necessary as the memory cell array may contain
72384** pointers to VdbeFrame objects, which may in turn contain pointers to
72385** open cursors.
72386*/
72387static void closeAllCursors(Vdbe *p){
72388  if( p->pFrame ){
72389    VdbeFrame *pFrame;
72390    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
72391    sqlite3VdbeFrameRestore(pFrame);
72392    p->pFrame = 0;
72393    p->nFrame = 0;
72394  }
72395  assert( p->nFrame==0 );
72396  closeCursorsInFrame(p);
72397  if( p->aMem ){
72398    releaseMemArray(p->aMem, p->nMem);
72399  }
72400  while( p->pDelFrame ){
72401    VdbeFrame *pDel = p->pDelFrame;
72402    p->pDelFrame = pDel->pParent;
72403    sqlite3VdbeFrameDelete(pDel);
72404  }
72405
72406  /* Delete any auxdata allocations made by the VM */
72407  if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
72408  assert( p->pAuxData==0 );
72409}
72410
72411/*
72412** Clean up the VM after a single run.
72413*/
72414static void Cleanup(Vdbe *p){
72415  sqlite3 *db = p->db;
72416
72417#ifdef SQLITE_DEBUG
72418  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
72419  ** Vdbe.aMem[] arrays have already been cleaned up.  */
72420  int i;
72421  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
72422  if( p->aMem ){
72423    for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
72424  }
72425#endif
72426
72427  sqlite3DbFree(db, p->zErrMsg);
72428  p->zErrMsg = 0;
72429  p->pResultSet = 0;
72430}
72431
72432/*
72433** Set the number of result columns that will be returned by this SQL
72434** statement. This is now set at compile time, rather than during
72435** execution of the vdbe program so that sqlite3_column_count() can
72436** be called on an SQL statement before sqlite3_step().
72437*/
72438SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
72439  Mem *pColName;
72440  int n;
72441  sqlite3 *db = p->db;
72442
72443  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
72444  sqlite3DbFree(db, p->aColName);
72445  n = nResColumn*COLNAME_N;
72446  p->nResColumn = (u16)nResColumn;
72447  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
72448  if( p->aColName==0 ) return;
72449  while( n-- > 0 ){
72450    pColName->flags = MEM_Null;
72451    pColName->db = p->db;
72452    pColName++;
72453  }
72454}
72455
72456/*
72457** Set the name of the idx'th column to be returned by the SQL statement.
72458** zName must be a pointer to a nul terminated string.
72459**
72460** This call must be made after a call to sqlite3VdbeSetNumCols().
72461**
72462** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
72463** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
72464** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
72465*/
72466SQLITE_PRIVATE int sqlite3VdbeSetColName(
72467  Vdbe *p,                         /* Vdbe being configured */
72468  int idx,                         /* Index of column zName applies to */
72469  int var,                         /* One of the COLNAME_* constants */
72470  const char *zName,               /* Pointer to buffer containing name */
72471  void (*xDel)(void*)              /* Memory management strategy for zName */
72472){
72473  int rc;
72474  Mem *pColName;
72475  assert( idx<p->nResColumn );
72476  assert( var<COLNAME_N );
72477  if( p->db->mallocFailed ){
72478    assert( !zName || xDel!=SQLITE_DYNAMIC );
72479    return SQLITE_NOMEM_BKPT;
72480  }
72481  assert( p->aColName!=0 );
72482  pColName = &(p->aColName[idx+var*p->nResColumn]);
72483  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
72484  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
72485  return rc;
72486}
72487
72488/*
72489** A read or write transaction may or may not be active on database handle
72490** db. If a transaction is active, commit it. If there is a
72491** write-transaction spanning more than one database file, this routine
72492** takes care of the master journal trickery.
72493*/
72494static int vdbeCommit(sqlite3 *db, Vdbe *p){
72495  int i;
72496  int nTrans = 0;  /* Number of databases with an active write-transaction
72497                   ** that are candidates for a two-phase commit using a
72498                   ** master-journal */
72499  int rc = SQLITE_OK;
72500  int needXcommit = 0;
72501
72502#ifdef SQLITE_OMIT_VIRTUALTABLE
72503  /* With this option, sqlite3VtabSync() is defined to be simply
72504  ** SQLITE_OK so p is not used.
72505  */
72506  UNUSED_PARAMETER(p);
72507#endif
72508
72509  /* Before doing anything else, call the xSync() callback for any
72510  ** virtual module tables written in this transaction. This has to
72511  ** be done before determining whether a master journal file is
72512  ** required, as an xSync() callback may add an attached database
72513  ** to the transaction.
72514  */
72515  rc = sqlite3VtabSync(db, p);
72516
72517  /* This loop determines (a) if the commit hook should be invoked and
72518  ** (b) how many database files have open write transactions, not
72519  ** including the temp database. (b) is important because if more than
72520  ** one database file has an open write transaction, a master journal
72521  ** file is required for an atomic commit.
72522  */
72523  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72524    Btree *pBt = db->aDb[i].pBt;
72525    if( sqlite3BtreeIsInTrans(pBt) ){
72526      /* Whether or not a database might need a master journal depends upon
72527      ** its journal mode (among other things).  This matrix determines which
72528      ** journal modes use a master journal and which do not */
72529      static const u8 aMJNeeded[] = {
72530        /* DELETE   */  1,
72531        /* PERSIST   */ 1,
72532        /* OFF       */ 0,
72533        /* TRUNCATE  */ 1,
72534        /* MEMORY    */ 0,
72535        /* WAL       */ 0
72536      };
72537      Pager *pPager;   /* Pager associated with pBt */
72538      needXcommit = 1;
72539      sqlite3BtreeEnter(pBt);
72540      pPager = sqlite3BtreePager(pBt);
72541      if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
72542       && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
72543      ){
72544        assert( i!=1 );
72545        nTrans++;
72546      }
72547      rc = sqlite3PagerExclusiveLock(pPager);
72548      sqlite3BtreeLeave(pBt);
72549    }
72550  }
72551  if( rc!=SQLITE_OK ){
72552    return rc;
72553  }
72554
72555  /* If there are any write-transactions at all, invoke the commit hook */
72556  if( needXcommit && db->xCommitCallback ){
72557    rc = db->xCommitCallback(db->pCommitArg);
72558    if( rc ){
72559      return SQLITE_CONSTRAINT_COMMITHOOK;
72560    }
72561  }
72562
72563  /* The simple case - no more than one database file (not counting the
72564  ** TEMP database) has a transaction active.   There is no need for the
72565  ** master-journal.
72566  **
72567  ** If the return value of sqlite3BtreeGetFilename() is a zero length
72568  ** string, it means the main database is :memory: or a temp file.  In
72569  ** that case we do not support atomic multi-file commits, so use the
72570  ** simple case then too.
72571  */
72572  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
72573   || nTrans<=1
72574  ){
72575    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72576      Btree *pBt = db->aDb[i].pBt;
72577      if( pBt ){
72578        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
72579      }
72580    }
72581
72582    /* Do the commit only if all databases successfully complete phase 1.
72583    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
72584    ** IO error while deleting or truncating a journal file. It is unlikely,
72585    ** but could happen. In this case abandon processing and return the error.
72586    */
72587    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72588      Btree *pBt = db->aDb[i].pBt;
72589      if( pBt ){
72590        rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
72591      }
72592    }
72593    if( rc==SQLITE_OK ){
72594      sqlite3VtabCommit(db);
72595    }
72596  }
72597
72598  /* The complex case - There is a multi-file write-transaction active.
72599  ** This requires a master journal file to ensure the transaction is
72600  ** committed atomically.
72601  */
72602#ifndef SQLITE_OMIT_DISKIO
72603  else{
72604    sqlite3_vfs *pVfs = db->pVfs;
72605    char *zMaster = 0;   /* File-name for the master journal */
72606    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
72607    sqlite3_file *pMaster = 0;
72608    i64 offset = 0;
72609    int res;
72610    int retryCount = 0;
72611    int nMainFile;
72612
72613    /* Select a master journal file name */
72614    nMainFile = sqlite3Strlen30(zMainFile);
72615    zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
72616    if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
72617    do {
72618      u32 iRandom;
72619      if( retryCount ){
72620        if( retryCount>100 ){
72621          sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
72622          sqlite3OsDelete(pVfs, zMaster, 0);
72623          break;
72624        }else if( retryCount==1 ){
72625          sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
72626        }
72627      }
72628      retryCount++;
72629      sqlite3_randomness(sizeof(iRandom), &iRandom);
72630      sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
72631                               (iRandom>>8)&0xffffff, iRandom&0xff);
72632      /* The antipenultimate character of the master journal name must
72633      ** be "9" to avoid name collisions when using 8+3 filenames. */
72634      assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
72635      sqlite3FileSuffix3(zMainFile, zMaster);
72636      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
72637    }while( rc==SQLITE_OK && res );
72638    if( rc==SQLITE_OK ){
72639      /* Open the master journal. */
72640      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
72641          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
72642          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
72643      );
72644    }
72645    if( rc!=SQLITE_OK ){
72646      sqlite3DbFree(db, zMaster);
72647      return rc;
72648    }
72649
72650    /* Write the name of each database file in the transaction into the new
72651    ** master journal file. If an error occurs at this point close
72652    ** and delete the master journal file. All the individual journal files
72653    ** still have 'null' as the master journal pointer, so they will roll
72654    ** back independently if a failure occurs.
72655    */
72656    for(i=0; i<db->nDb; i++){
72657      Btree *pBt = db->aDb[i].pBt;
72658      if( sqlite3BtreeIsInTrans(pBt) ){
72659        char const *zFile = sqlite3BtreeGetJournalname(pBt);
72660        if( zFile==0 ){
72661          continue;  /* Ignore TEMP and :memory: databases */
72662        }
72663        assert( zFile[0]!=0 );
72664        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
72665        offset += sqlite3Strlen30(zFile)+1;
72666        if( rc!=SQLITE_OK ){
72667          sqlite3OsCloseFree(pMaster);
72668          sqlite3OsDelete(pVfs, zMaster, 0);
72669          sqlite3DbFree(db, zMaster);
72670          return rc;
72671        }
72672      }
72673    }
72674
72675    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
72676    ** flag is set this is not required.
72677    */
72678    if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
72679     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
72680    ){
72681      sqlite3OsCloseFree(pMaster);
72682      sqlite3OsDelete(pVfs, zMaster, 0);
72683      sqlite3DbFree(db, zMaster);
72684      return rc;
72685    }
72686
72687    /* Sync all the db files involved in the transaction. The same call
72688    ** sets the master journal pointer in each individual journal. If
72689    ** an error occurs here, do not delete the master journal file.
72690    **
72691    ** If the error occurs during the first call to
72692    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
72693    ** master journal file will be orphaned. But we cannot delete it,
72694    ** in case the master journal file name was written into the journal
72695    ** file before the failure occurred.
72696    */
72697    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72698      Btree *pBt = db->aDb[i].pBt;
72699      if( pBt ){
72700        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
72701      }
72702    }
72703    sqlite3OsCloseFree(pMaster);
72704    assert( rc!=SQLITE_BUSY );
72705    if( rc!=SQLITE_OK ){
72706      sqlite3DbFree(db, zMaster);
72707      return rc;
72708    }
72709
72710    /* Delete the master journal file. This commits the transaction. After
72711    ** doing this the directory is synced again before any individual
72712    ** transaction files are deleted.
72713    */
72714    rc = sqlite3OsDelete(pVfs, zMaster, 1);
72715    sqlite3DbFree(db, zMaster);
72716    zMaster = 0;
72717    if( rc ){
72718      return rc;
72719    }
72720
72721    /* All files and directories have already been synced, so the following
72722    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
72723    ** deleting or truncating journals. If something goes wrong while
72724    ** this is happening we don't really care. The integrity of the
72725    ** transaction is already guaranteed, but some stray 'cold' journals
72726    ** may be lying around. Returning an error code won't help matters.
72727    */
72728    disable_simulated_io_errors();
72729    sqlite3BeginBenignMalloc();
72730    for(i=0; i<db->nDb; i++){
72731      Btree *pBt = db->aDb[i].pBt;
72732      if( pBt ){
72733        sqlite3BtreeCommitPhaseTwo(pBt, 1);
72734      }
72735    }
72736    sqlite3EndBenignMalloc();
72737    enable_simulated_io_errors();
72738
72739    sqlite3VtabCommit(db);
72740  }
72741#endif
72742
72743  return rc;
72744}
72745
72746/*
72747** This routine checks that the sqlite3.nVdbeActive count variable
72748** matches the number of vdbe's in the list sqlite3.pVdbe that are
72749** currently active. An assertion fails if the two counts do not match.
72750** This is an internal self-check only - it is not an essential processing
72751** step.
72752**
72753** This is a no-op if NDEBUG is defined.
72754*/
72755#ifndef NDEBUG
72756static void checkActiveVdbeCnt(sqlite3 *db){
72757  Vdbe *p;
72758  int cnt = 0;
72759  int nWrite = 0;
72760  int nRead = 0;
72761  p = db->pVdbe;
72762  while( p ){
72763    if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
72764      cnt++;
72765      if( p->readOnly==0 ) nWrite++;
72766      if( p->bIsReader ) nRead++;
72767    }
72768    p = p->pNext;
72769  }
72770  assert( cnt==db->nVdbeActive );
72771  assert( nWrite==db->nVdbeWrite );
72772  assert( nRead==db->nVdbeRead );
72773}
72774#else
72775#define checkActiveVdbeCnt(x)
72776#endif
72777
72778/*
72779** If the Vdbe passed as the first argument opened a statement-transaction,
72780** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
72781** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
72782** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
72783** statement transaction is committed.
72784**
72785** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
72786** Otherwise SQLITE_OK.
72787*/
72788SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
72789  sqlite3 *const db = p->db;
72790  int rc = SQLITE_OK;
72791
72792  /* If p->iStatement is greater than zero, then this Vdbe opened a
72793  ** statement transaction that should be closed here. The only exception
72794  ** is that an IO error may have occurred, causing an emergency rollback.
72795  ** In this case (db->nStatement==0), and there is nothing to do.
72796  */
72797  if( db->nStatement && p->iStatement ){
72798    int i;
72799    const int iSavepoint = p->iStatement-1;
72800
72801    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
72802    assert( db->nStatement>0 );
72803    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
72804
72805    for(i=0; i<db->nDb; i++){
72806      int rc2 = SQLITE_OK;
72807      Btree *pBt = db->aDb[i].pBt;
72808      if( pBt ){
72809        if( eOp==SAVEPOINT_ROLLBACK ){
72810          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
72811        }
72812        if( rc2==SQLITE_OK ){
72813          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
72814        }
72815        if( rc==SQLITE_OK ){
72816          rc = rc2;
72817        }
72818      }
72819    }
72820    db->nStatement--;
72821    p->iStatement = 0;
72822
72823    if( rc==SQLITE_OK ){
72824      if( eOp==SAVEPOINT_ROLLBACK ){
72825        rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
72826      }
72827      if( rc==SQLITE_OK ){
72828        rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
72829      }
72830    }
72831
72832    /* If the statement transaction is being rolled back, also restore the
72833    ** database handles deferred constraint counter to the value it had when
72834    ** the statement transaction was opened.  */
72835    if( eOp==SAVEPOINT_ROLLBACK ){
72836      db->nDeferredCons = p->nStmtDefCons;
72837      db->nDeferredImmCons = p->nStmtDefImmCons;
72838    }
72839  }
72840  return rc;
72841}
72842
72843/*
72844** This function is called when a transaction opened by the database
72845** handle associated with the VM passed as an argument is about to be
72846** committed. If there are outstanding deferred foreign key constraint
72847** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
72848**
72849** If there are outstanding FK violations and this function returns
72850** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
72851** and write an error message to it. Then return SQLITE_ERROR.
72852*/
72853#ifndef SQLITE_OMIT_FOREIGN_KEY
72854SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
72855  sqlite3 *db = p->db;
72856  if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
72857   || (!deferred && p->nFkConstraint>0)
72858  ){
72859    p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
72860    p->errorAction = OE_Abort;
72861    sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
72862    return SQLITE_ERROR;
72863  }
72864  return SQLITE_OK;
72865}
72866#endif
72867
72868/*
72869** This routine is called the when a VDBE tries to halt.  If the VDBE
72870** has made changes and is in autocommit mode, then commit those
72871** changes.  If a rollback is needed, then do the rollback.
72872**
72873** This routine is the only way to move the state of a VM from
72874** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
72875** call this on a VM that is in the SQLITE_MAGIC_HALT state.
72876**
72877** Return an error code.  If the commit could not complete because of
72878** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
72879** means the close did not happen and needs to be repeated.
72880*/
72881SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
72882  int rc;                         /* Used to store transient return codes */
72883  sqlite3 *db = p->db;
72884
72885  /* This function contains the logic that determines if a statement or
72886  ** transaction will be committed or rolled back as a result of the
72887  ** execution of this virtual machine.
72888  **
72889  ** If any of the following errors occur:
72890  **
72891  **     SQLITE_NOMEM
72892  **     SQLITE_IOERR
72893  **     SQLITE_FULL
72894  **     SQLITE_INTERRUPT
72895  **
72896  ** Then the internal cache might have been left in an inconsistent
72897  ** state.  We need to rollback the statement transaction, if there is
72898  ** one, or the complete transaction if there is no statement transaction.
72899  */
72900
72901  if( db->mallocFailed ){
72902    p->rc = SQLITE_NOMEM_BKPT;
72903  }
72904  if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
72905  closeAllCursors(p);
72906  if( p->magic!=VDBE_MAGIC_RUN ){
72907    return SQLITE_OK;
72908  }
72909  checkActiveVdbeCnt(db);
72910
72911  /* No commit or rollback needed if the program never started or if the
72912  ** SQL statement does not read or write a database file.  */
72913  if( p->pc>=0 && p->bIsReader ){
72914    int mrc;   /* Primary error code from p->rc */
72915    int eStatementOp = 0;
72916    int isSpecialError;            /* Set to true if a 'special' error */
72917
72918    /* Lock all btrees used by the statement */
72919    sqlite3VdbeEnter(p);
72920
72921    /* Check for one of the special errors */
72922    mrc = p->rc & 0xff;
72923    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
72924                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
72925    if( isSpecialError ){
72926      /* If the query was read-only and the error code is SQLITE_INTERRUPT,
72927      ** no rollback is necessary. Otherwise, at least a savepoint
72928      ** transaction must be rolled back to restore the database to a
72929      ** consistent state.
72930      **
72931      ** Even if the statement is read-only, it is important to perform
72932      ** a statement or transaction rollback operation. If the error
72933      ** occurred while writing to the journal, sub-journal or database
72934      ** file as part of an effort to free up cache space (see function
72935      ** pagerStress() in pager.c), the rollback is required to restore
72936      ** the pager to a consistent state.
72937      */
72938      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
72939        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
72940          eStatementOp = SAVEPOINT_ROLLBACK;
72941        }else{
72942          /* We are forced to roll back the active transaction. Before doing
72943          ** so, abort any other statements this handle currently has active.
72944          */
72945          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
72946          sqlite3CloseSavepoints(db);
72947          db->autoCommit = 1;
72948          p->nChange = 0;
72949        }
72950      }
72951    }
72952
72953    /* Check for immediate foreign key violations. */
72954    if( p->rc==SQLITE_OK ){
72955      sqlite3VdbeCheckFk(p, 0);
72956    }
72957
72958    /* If the auto-commit flag is set and this is the only active writer
72959    ** VM, then we do either a commit or rollback of the current transaction.
72960    **
72961    ** Note: This block also runs if one of the special errors handled
72962    ** above has occurred.
72963    */
72964    if( !sqlite3VtabInSync(db)
72965     && db->autoCommit
72966     && db->nVdbeWrite==(p->readOnly==0)
72967    ){
72968      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
72969        rc = sqlite3VdbeCheckFk(p, 1);
72970        if( rc!=SQLITE_OK ){
72971          if( NEVER(p->readOnly) ){
72972            sqlite3VdbeLeave(p);
72973            return SQLITE_ERROR;
72974          }
72975          rc = SQLITE_CONSTRAINT_FOREIGNKEY;
72976        }else{
72977          /* The auto-commit flag is true, the vdbe program was successful
72978          ** or hit an 'OR FAIL' constraint and there are no deferred foreign
72979          ** key constraints to hold up the transaction. This means a commit
72980          ** is required. */
72981          rc = vdbeCommit(db, p);
72982        }
72983        if( rc==SQLITE_BUSY && p->readOnly ){
72984          sqlite3VdbeLeave(p);
72985          return SQLITE_BUSY;
72986        }else if( rc!=SQLITE_OK ){
72987          p->rc = rc;
72988          sqlite3RollbackAll(db, SQLITE_OK);
72989          p->nChange = 0;
72990        }else{
72991          db->nDeferredCons = 0;
72992          db->nDeferredImmCons = 0;
72993          db->flags &= ~SQLITE_DeferFKs;
72994          sqlite3CommitInternalChanges(db);
72995        }
72996      }else{
72997        sqlite3RollbackAll(db, SQLITE_OK);
72998        p->nChange = 0;
72999      }
73000      db->nStatement = 0;
73001    }else if( eStatementOp==0 ){
73002      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
73003        eStatementOp = SAVEPOINT_RELEASE;
73004      }else if( p->errorAction==OE_Abort ){
73005        eStatementOp = SAVEPOINT_ROLLBACK;
73006      }else{
73007        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
73008        sqlite3CloseSavepoints(db);
73009        db->autoCommit = 1;
73010        p->nChange = 0;
73011      }
73012    }
73013
73014    /* If eStatementOp is non-zero, then a statement transaction needs to
73015    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
73016    ** do so. If this operation returns an error, and the current statement
73017    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
73018    ** current statement error code.
73019    */
73020    if( eStatementOp ){
73021      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
73022      if( rc ){
73023        if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
73024          p->rc = rc;
73025          sqlite3DbFree(db, p->zErrMsg);
73026          p->zErrMsg = 0;
73027        }
73028        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
73029        sqlite3CloseSavepoints(db);
73030        db->autoCommit = 1;
73031        p->nChange = 0;
73032      }
73033    }
73034
73035    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
73036    ** has been rolled back, update the database connection change-counter.
73037    */
73038    if( p->changeCntOn ){
73039      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
73040        sqlite3VdbeSetChanges(db, p->nChange);
73041      }else{
73042        sqlite3VdbeSetChanges(db, 0);
73043      }
73044      p->nChange = 0;
73045    }
73046
73047    /* Release the locks */
73048    sqlite3VdbeLeave(p);
73049  }
73050
73051  /* We have successfully halted and closed the VM.  Record this fact. */
73052  if( p->pc>=0 ){
73053    db->nVdbeActive--;
73054    if( !p->readOnly ) db->nVdbeWrite--;
73055    if( p->bIsReader ) db->nVdbeRead--;
73056    assert( db->nVdbeActive>=db->nVdbeRead );
73057    assert( db->nVdbeRead>=db->nVdbeWrite );
73058    assert( db->nVdbeWrite>=0 );
73059  }
73060  p->magic = VDBE_MAGIC_HALT;
73061  checkActiveVdbeCnt(db);
73062  if( db->mallocFailed ){
73063    p->rc = SQLITE_NOMEM_BKPT;
73064  }
73065
73066  /* If the auto-commit flag is set to true, then any locks that were held
73067  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
73068  ** to invoke any required unlock-notify callbacks.
73069  */
73070  if( db->autoCommit ){
73071    sqlite3ConnectionUnlocked(db);
73072  }
73073
73074  assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
73075  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
73076}
73077
73078
73079/*
73080** Each VDBE holds the result of the most recent sqlite3_step() call
73081** in p->rc.  This routine sets that result back to SQLITE_OK.
73082*/
73083SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
73084  p->rc = SQLITE_OK;
73085}
73086
73087/*
73088** Copy the error code and error message belonging to the VDBE passed
73089** as the first argument to its database handle (so that they will be
73090** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
73091**
73092** This function does not clear the VDBE error code or message, just
73093** copies them to the database handle.
73094*/
73095SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
73096  sqlite3 *db = p->db;
73097  int rc = p->rc;
73098  if( p->zErrMsg ){
73099    db->bBenignMalloc++;
73100    sqlite3BeginBenignMalloc();
73101    if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
73102    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
73103    sqlite3EndBenignMalloc();
73104    db->bBenignMalloc--;
73105    db->errCode = rc;
73106  }else{
73107    sqlite3Error(db, rc);
73108  }
73109  return rc;
73110}
73111
73112#ifdef SQLITE_ENABLE_SQLLOG
73113/*
73114** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
73115** invoke it.
73116*/
73117static void vdbeInvokeSqllog(Vdbe *v){
73118  if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
73119    char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
73120    assert( v->db->init.busy==0 );
73121    if( zExpanded ){
73122      sqlite3GlobalConfig.xSqllog(
73123          sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
73124      );
73125      sqlite3DbFree(v->db, zExpanded);
73126    }
73127  }
73128}
73129#else
73130# define vdbeInvokeSqllog(x)
73131#endif
73132
73133/*
73134** Clean up a VDBE after execution but do not delete the VDBE just yet.
73135** Write any error messages into *pzErrMsg.  Return the result code.
73136**
73137** After this routine is run, the VDBE should be ready to be executed
73138** again.
73139**
73140** To look at it another way, this routine resets the state of the
73141** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
73142** VDBE_MAGIC_INIT.
73143*/
73144SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
73145  sqlite3 *db;
73146  db = p->db;
73147
73148  /* If the VM did not run to completion or if it encountered an
73149  ** error, then it might not have been halted properly.  So halt
73150  ** it now.
73151  */
73152  sqlite3VdbeHalt(p);
73153
73154  /* If the VDBE has be run even partially, then transfer the error code
73155  ** and error message from the VDBE into the main database structure.  But
73156  ** if the VDBE has just been set to run but has not actually executed any
73157  ** instructions yet, leave the main database error information unchanged.
73158  */
73159  if( p->pc>=0 ){
73160    vdbeInvokeSqllog(p);
73161    sqlite3VdbeTransferError(p);
73162    sqlite3DbFree(db, p->zErrMsg);
73163    p->zErrMsg = 0;
73164    if( p->runOnlyOnce ) p->expired = 1;
73165  }else if( p->rc && p->expired ){
73166    /* The expired flag was set on the VDBE before the first call
73167    ** to sqlite3_step(). For consistency (since sqlite3_step() was
73168    ** called), set the database error in this case as well.
73169    */
73170    sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
73171    sqlite3DbFree(db, p->zErrMsg);
73172    p->zErrMsg = 0;
73173  }
73174
73175  /* Reclaim all memory used by the VDBE
73176  */
73177  Cleanup(p);
73178
73179  /* Save profiling information from this VDBE run.
73180  */
73181#ifdef VDBE_PROFILE
73182  {
73183    FILE *out = fopen("vdbe_profile.out", "a");
73184    if( out ){
73185      int i;
73186      fprintf(out, "---- ");
73187      for(i=0; i<p->nOp; i++){
73188        fprintf(out, "%02x", p->aOp[i].opcode);
73189      }
73190      fprintf(out, "\n");
73191      if( p->zSql ){
73192        char c, pc = 0;
73193        fprintf(out, "-- ");
73194        for(i=0; (c = p->zSql[i])!=0; i++){
73195          if( pc=='\n' ) fprintf(out, "-- ");
73196          putc(c, out);
73197          pc = c;
73198        }
73199        if( pc!='\n' ) fprintf(out, "\n");
73200      }
73201      for(i=0; i<p->nOp; i++){
73202        char zHdr[100];
73203        sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
73204           p->aOp[i].cnt,
73205           p->aOp[i].cycles,
73206           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
73207        );
73208        fprintf(out, "%s", zHdr);
73209        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
73210      }
73211      fclose(out);
73212    }
73213  }
73214#endif
73215  p->iCurrentTime = 0;
73216  p->magic = VDBE_MAGIC_INIT;
73217  return p->rc & db->errMask;
73218}
73219
73220/*
73221** Clean up and delete a VDBE after execution.  Return an integer which is
73222** the result code.  Write any error message text into *pzErrMsg.
73223*/
73224SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
73225  int rc = SQLITE_OK;
73226  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
73227    rc = sqlite3VdbeReset(p);
73228    assert( (rc & p->db->errMask)==rc );
73229  }
73230  sqlite3VdbeDelete(p);
73231  return rc;
73232}
73233
73234/*
73235** If parameter iOp is less than zero, then invoke the destructor for
73236** all auxiliary data pointers currently cached by the VM passed as
73237** the first argument.
73238**
73239** Or, if iOp is greater than or equal to zero, then the destructor is
73240** only invoked for those auxiliary data pointers created by the user
73241** function invoked by the OP_Function opcode at instruction iOp of
73242** VM pVdbe, and only then if:
73243**
73244**    * the associated function parameter is the 32nd or later (counting
73245**      from left to right), or
73246**
73247**    * the corresponding bit in argument mask is clear (where the first
73248**      function parameter corresponds to bit 0 etc.).
73249*/
73250SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
73251  while( *pp ){
73252    AuxData *pAux = *pp;
73253    if( (iOp<0)
73254     || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
73255    ){
73256      testcase( pAux->iArg==31 );
73257      if( pAux->xDelete ){
73258        pAux->xDelete(pAux->pAux);
73259      }
73260      *pp = pAux->pNext;
73261      sqlite3DbFree(db, pAux);
73262    }else{
73263      pp= &pAux->pNext;
73264    }
73265  }
73266}
73267
73268/*
73269** Free all memory associated with the Vdbe passed as the second argument,
73270** except for object itself, which is preserved.
73271**
73272** The difference between this function and sqlite3VdbeDelete() is that
73273** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
73274** the database connection and frees the object itself.
73275*/
73276SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
73277  SubProgram *pSub, *pNext;
73278  int i;
73279  assert( p->db==0 || p->db==db );
73280  releaseMemArray(p->aVar, p->nVar);
73281  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
73282  for(pSub=p->pProgram; pSub; pSub=pNext){
73283    pNext = pSub->pNext;
73284    vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
73285    sqlite3DbFree(db, pSub);
73286  }
73287  for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
73288  sqlite3DbFree(db, p->azVar);
73289  vdbeFreeOpArray(db, p->aOp, p->nOp);
73290  sqlite3DbFree(db, p->aColName);
73291  sqlite3DbFree(db, p->zSql);
73292  sqlite3DbFree(db, p->pFree);
73293#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
73294  for(i=0; i<p->nScan; i++){
73295    sqlite3DbFree(db, p->aScan[i].zName);
73296  }
73297  sqlite3DbFree(db, p->aScan);
73298#endif
73299}
73300
73301/*
73302** Delete an entire VDBE.
73303*/
73304SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
73305  sqlite3 *db;
73306
73307  if( NEVER(p==0) ) return;
73308  db = p->db;
73309  assert( sqlite3_mutex_held(db->mutex) );
73310  sqlite3VdbeClearObject(db, p);
73311  if( p->pPrev ){
73312    p->pPrev->pNext = p->pNext;
73313  }else{
73314    assert( db->pVdbe==p );
73315    db->pVdbe = p->pNext;
73316  }
73317  if( p->pNext ){
73318    p->pNext->pPrev = p->pPrev;
73319  }
73320  p->magic = VDBE_MAGIC_DEAD;
73321  p->db = 0;
73322  sqlite3DbFree(db, p);
73323}
73324
73325/*
73326** The cursor "p" has a pending seek operation that has not yet been
73327** carried out.  Seek the cursor now.  If an error occurs, return
73328** the appropriate error code.
73329*/
73330static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
73331  int res, rc;
73332#ifdef SQLITE_TEST
73333  extern int sqlite3_search_count;
73334#endif
73335  assert( p->deferredMoveto );
73336  assert( p->isTable );
73337  assert( p->eCurType==CURTYPE_BTREE );
73338  rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
73339  if( rc ) return rc;
73340  if( res!=0 ) return SQLITE_CORRUPT_BKPT;
73341#ifdef SQLITE_TEST
73342  sqlite3_search_count++;
73343#endif
73344  p->deferredMoveto = 0;
73345  p->cacheStatus = CACHE_STALE;
73346  return SQLITE_OK;
73347}
73348
73349/*
73350** Something has moved cursor "p" out of place.  Maybe the row it was
73351** pointed to was deleted out from under it.  Or maybe the btree was
73352** rebalanced.  Whatever the cause, try to restore "p" to the place it
73353** is supposed to be pointing.  If the row was deleted out from under the
73354** cursor, set the cursor to point to a NULL row.
73355*/
73356static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
73357  int isDifferentRow, rc;
73358  assert( p->eCurType==CURTYPE_BTREE );
73359  assert( p->uc.pCursor!=0 );
73360  assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
73361  rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
73362  p->cacheStatus = CACHE_STALE;
73363  if( isDifferentRow ) p->nullRow = 1;
73364  return rc;
73365}
73366
73367/*
73368** Check to ensure that the cursor is valid.  Restore the cursor
73369** if need be.  Return any I/O error from the restore operation.
73370*/
73371SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
73372  assert( p->eCurType==CURTYPE_BTREE );
73373  if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
73374    return handleMovedCursor(p);
73375  }
73376  return SQLITE_OK;
73377}
73378
73379/*
73380** Make sure the cursor p is ready to read or write the row to which it
73381** was last positioned.  Return an error code if an OOM fault or I/O error
73382** prevents us from positioning the cursor to its correct position.
73383**
73384** If a MoveTo operation is pending on the given cursor, then do that
73385** MoveTo now.  If no move is pending, check to see if the row has been
73386** deleted out from under the cursor and if it has, mark the row as
73387** a NULL row.
73388**
73389** If the cursor is already pointing to the correct row and that row has
73390** not been deleted out from under the cursor, then this routine is a no-op.
73391*/
73392SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
73393  VdbeCursor *p = *pp;
73394  if( p->eCurType==CURTYPE_BTREE ){
73395    if( p->deferredMoveto ){
73396      int iMap;
73397      if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
73398        *pp = p->pAltCursor;
73399        *piCol = iMap - 1;
73400        return SQLITE_OK;
73401      }
73402      return handleDeferredMoveto(p);
73403    }
73404    if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
73405      return handleMovedCursor(p);
73406    }
73407  }
73408  return SQLITE_OK;
73409}
73410
73411/*
73412** The following functions:
73413**
73414** sqlite3VdbeSerialType()
73415** sqlite3VdbeSerialTypeLen()
73416** sqlite3VdbeSerialLen()
73417** sqlite3VdbeSerialPut()
73418** sqlite3VdbeSerialGet()
73419**
73420** encapsulate the code that serializes values for storage in SQLite
73421** data and index records. Each serialized value consists of a
73422** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
73423** integer, stored as a varint.
73424**
73425** In an SQLite index record, the serial type is stored directly before
73426** the blob of data that it corresponds to. In a table record, all serial
73427** types are stored at the start of the record, and the blobs of data at
73428** the end. Hence these functions allow the caller to handle the
73429** serial-type and data blob separately.
73430**
73431** The following table describes the various storage classes for data:
73432**
73433**   serial type        bytes of data      type
73434**   --------------     ---------------    ---------------
73435**      0                     0            NULL
73436**      1                     1            signed integer
73437**      2                     2            signed integer
73438**      3                     3            signed integer
73439**      4                     4            signed integer
73440**      5                     6            signed integer
73441**      6                     8            signed integer
73442**      7                     8            IEEE float
73443**      8                     0            Integer constant 0
73444**      9                     0            Integer constant 1
73445**     10,11                               reserved for expansion
73446**    N>=12 and even       (N-12)/2        BLOB
73447**    N>=13 and odd        (N-13)/2        text
73448**
73449** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
73450** of SQLite will not understand those serial types.
73451*/
73452
73453/*
73454** Return the serial-type for the value stored in pMem.
73455*/
73456SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
73457  int flags = pMem->flags;
73458  u32 n;
73459
73460  assert( pLen!=0 );
73461  if( flags&MEM_Null ){
73462    *pLen = 0;
73463    return 0;
73464  }
73465  if( flags&MEM_Int ){
73466    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
73467#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
73468    i64 i = pMem->u.i;
73469    u64 u;
73470    if( i<0 ){
73471      u = ~i;
73472    }else{
73473      u = i;
73474    }
73475    if( u<=127 ){
73476      if( (i&1)==i && file_format>=4 ){
73477        *pLen = 0;
73478        return 8+(u32)u;
73479      }else{
73480        *pLen = 1;
73481        return 1;
73482      }
73483    }
73484    if( u<=32767 ){ *pLen = 2; return 2; }
73485    if( u<=8388607 ){ *pLen = 3; return 3; }
73486    if( u<=2147483647 ){ *pLen = 4; return 4; }
73487    if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
73488    *pLen = 8;
73489    return 6;
73490  }
73491  if( flags&MEM_Real ){
73492    *pLen = 8;
73493    return 7;
73494  }
73495  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
73496  assert( pMem->n>=0 );
73497  n = (u32)pMem->n;
73498  if( flags & MEM_Zero ){
73499    n += pMem->u.nZero;
73500  }
73501  *pLen = n;
73502  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
73503}
73504
73505/*
73506** The sizes for serial types less than 128
73507*/
73508static const u8 sqlite3SmallTypeSizes[] = {
73509        /*  0   1   2   3   4   5   6   7   8   9 */
73510/*   0 */   0,  1,  2,  3,  4,  6,  8,  8,  0,  0,
73511/*  10 */   0,  0,  0,  0,  1,  1,  2,  2,  3,  3,
73512/*  20 */   4,  4,  5,  5,  6,  6,  7,  7,  8,  8,
73513/*  30 */   9,  9, 10, 10, 11, 11, 12, 12, 13, 13,
73514/*  40 */  14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
73515/*  50 */  19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
73516/*  60 */  24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
73517/*  70 */  29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
73518/*  80 */  34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
73519/*  90 */  39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
73520/* 100 */  44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
73521/* 110 */  49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
73522/* 120 */  54, 54, 55, 55, 56, 56, 57, 57
73523};
73524
73525/*
73526** Return the length of the data corresponding to the supplied serial-type.
73527*/
73528SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
73529  if( serial_type>=128 ){
73530    return (serial_type-12)/2;
73531  }else{
73532    assert( serial_type<12
73533            || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
73534    return sqlite3SmallTypeSizes[serial_type];
73535  }
73536}
73537SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
73538  assert( serial_type<128 );
73539  return sqlite3SmallTypeSizes[serial_type];
73540}
73541
73542/*
73543** If we are on an architecture with mixed-endian floating
73544** points (ex: ARM7) then swap the lower 4 bytes with the
73545** upper 4 bytes.  Return the result.
73546**
73547** For most architectures, this is a no-op.
73548**
73549** (later):  It is reported to me that the mixed-endian problem
73550** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
73551** that early versions of GCC stored the two words of a 64-bit
73552** float in the wrong order.  And that error has been propagated
73553** ever since.  The blame is not necessarily with GCC, though.
73554** GCC might have just copying the problem from a prior compiler.
73555** I am also told that newer versions of GCC that follow a different
73556** ABI get the byte order right.
73557**
73558** Developers using SQLite on an ARM7 should compile and run their
73559** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
73560** enabled, some asserts below will ensure that the byte order of
73561** floating point values is correct.
73562**
73563** (2007-08-30)  Frank van Vugt has studied this problem closely
73564** and has send his findings to the SQLite developers.  Frank
73565** writes that some Linux kernels offer floating point hardware
73566** emulation that uses only 32-bit mantissas instead of a full
73567** 48-bits as required by the IEEE standard.  (This is the
73568** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
73569** byte swapping becomes very complicated.  To avoid problems,
73570** the necessary byte swapping is carried out using a 64-bit integer
73571** rather than a 64-bit float.  Frank assures us that the code here
73572** works for him.  We, the developers, have no way to independently
73573** verify this, but Frank seems to know what he is talking about
73574** so we trust him.
73575*/
73576#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
73577static u64 floatSwap(u64 in){
73578  union {
73579    u64 r;
73580    u32 i[2];
73581  } u;
73582  u32 t;
73583
73584  u.r = in;
73585  t = u.i[0];
73586  u.i[0] = u.i[1];
73587  u.i[1] = t;
73588  return u.r;
73589}
73590# define swapMixedEndianFloat(X)  X = floatSwap(X)
73591#else
73592# define swapMixedEndianFloat(X)
73593#endif
73594
73595/*
73596** Write the serialized data blob for the value stored in pMem into
73597** buf. It is assumed that the caller has allocated sufficient space.
73598** Return the number of bytes written.
73599**
73600** nBuf is the amount of space left in buf[].  The caller is responsible
73601** for allocating enough space to buf[] to hold the entire field, exclusive
73602** of the pMem->u.nZero bytes for a MEM_Zero value.
73603**
73604** Return the number of bytes actually written into buf[].  The number
73605** of bytes in the zero-filled tail is included in the return value only
73606** if those bytes were zeroed in buf[].
73607*/
73608SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
73609  u32 len;
73610
73611  /* Integer and Real */
73612  if( serial_type<=7 && serial_type>0 ){
73613    u64 v;
73614    u32 i;
73615    if( serial_type==7 ){
73616      assert( sizeof(v)==sizeof(pMem->u.r) );
73617      memcpy(&v, &pMem->u.r, sizeof(v));
73618      swapMixedEndianFloat(v);
73619    }else{
73620      v = pMem->u.i;
73621    }
73622    len = i = sqlite3SmallTypeSizes[serial_type];
73623    assert( i>0 );
73624    do{
73625      buf[--i] = (u8)(v&0xFF);
73626      v >>= 8;
73627    }while( i );
73628    return len;
73629  }
73630
73631  /* String or blob */
73632  if( serial_type>=12 ){
73633    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
73634             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
73635    len = pMem->n;
73636    if( len>0 ) memcpy(buf, pMem->z, len);
73637    return len;
73638  }
73639
73640  /* NULL or constants 0 or 1 */
73641  return 0;
73642}
73643
73644/* Input "x" is a sequence of unsigned characters that represent a
73645** big-endian integer.  Return the equivalent native integer
73646*/
73647#define ONE_BYTE_INT(x)    ((i8)(x)[0])
73648#define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
73649#define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
73650#define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
73651#define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
73652
73653/*
73654** Deserialize the data blob pointed to by buf as serial type serial_type
73655** and store the result in pMem.  Return the number of bytes read.
73656**
73657** This function is implemented as two separate routines for performance.
73658** The few cases that require local variables are broken out into a separate
73659** routine so that in most cases the overhead of moving the stack pointer
73660** is avoided.
73661*/
73662static u32 SQLITE_NOINLINE serialGet(
73663  const unsigned char *buf,     /* Buffer to deserialize from */
73664  u32 serial_type,              /* Serial type to deserialize */
73665  Mem *pMem                     /* Memory cell to write value into */
73666){
73667  u64 x = FOUR_BYTE_UINT(buf);
73668  u32 y = FOUR_BYTE_UINT(buf+4);
73669  x = (x<<32) + y;
73670  if( serial_type==6 ){
73671    /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
73672    ** twos-complement integer. */
73673    pMem->u.i = *(i64*)&x;
73674    pMem->flags = MEM_Int;
73675    testcase( pMem->u.i<0 );
73676  }else{
73677    /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
73678    ** floating point number. */
73679#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
73680    /* Verify that integers and floating point values use the same
73681    ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
73682    ** defined that 64-bit floating point values really are mixed
73683    ** endian.
73684    */
73685    static const u64 t1 = ((u64)0x3ff00000)<<32;
73686    static const double r1 = 1.0;
73687    u64 t2 = t1;
73688    swapMixedEndianFloat(t2);
73689    assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
73690#endif
73691    assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
73692    swapMixedEndianFloat(x);
73693    memcpy(&pMem->u.r, &x, sizeof(x));
73694    pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
73695  }
73696  return 8;
73697}
73698SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
73699  const unsigned char *buf,     /* Buffer to deserialize from */
73700  u32 serial_type,              /* Serial type to deserialize */
73701  Mem *pMem                     /* Memory cell to write value into */
73702){
73703  switch( serial_type ){
73704    case 10:   /* Reserved for future use */
73705    case 11:   /* Reserved for future use */
73706    case 0: {  /* Null */
73707      /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
73708      pMem->flags = MEM_Null;
73709      break;
73710    }
73711    case 1: {
73712      /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
73713      ** integer. */
73714      pMem->u.i = ONE_BYTE_INT(buf);
73715      pMem->flags = MEM_Int;
73716      testcase( pMem->u.i<0 );
73717      return 1;
73718    }
73719    case 2: { /* 2-byte signed integer */
73720      /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
73721      ** twos-complement integer. */
73722      pMem->u.i = TWO_BYTE_INT(buf);
73723      pMem->flags = MEM_Int;
73724      testcase( pMem->u.i<0 );
73725      return 2;
73726    }
73727    case 3: { /* 3-byte signed integer */
73728      /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
73729      ** twos-complement integer. */
73730      pMem->u.i = THREE_BYTE_INT(buf);
73731      pMem->flags = MEM_Int;
73732      testcase( pMem->u.i<0 );
73733      return 3;
73734    }
73735    case 4: { /* 4-byte signed integer */
73736      /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
73737      ** twos-complement integer. */
73738      pMem->u.i = FOUR_BYTE_INT(buf);
73739#ifdef __HP_cc
73740      /* Work around a sign-extension bug in the HP compiler for HP/UX */
73741      if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
73742#endif
73743      pMem->flags = MEM_Int;
73744      testcase( pMem->u.i<0 );
73745      return 4;
73746    }
73747    case 5: { /* 6-byte signed integer */
73748      /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
73749      ** twos-complement integer. */
73750      pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
73751      pMem->flags = MEM_Int;
73752      testcase( pMem->u.i<0 );
73753      return 6;
73754    }
73755    case 6:   /* 8-byte signed integer */
73756    case 7: { /* IEEE floating point */
73757      /* These use local variables, so do them in a separate routine
73758      ** to avoid having to move the frame pointer in the common case */
73759      return serialGet(buf,serial_type,pMem);
73760    }
73761    case 8:    /* Integer 0 */
73762    case 9: {  /* Integer 1 */
73763      /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
73764      /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
73765      pMem->u.i = serial_type-8;
73766      pMem->flags = MEM_Int;
73767      return 0;
73768    }
73769    default: {
73770      /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
73771      ** length.
73772      ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
73773      ** (N-13)/2 bytes in length. */
73774      static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
73775      pMem->z = (char *)buf;
73776      pMem->n = (serial_type-12)/2;
73777      pMem->flags = aFlag[serial_type&1];
73778      return pMem->n;
73779    }
73780  }
73781  return 0;
73782}
73783/*
73784** This routine is used to allocate sufficient space for an UnpackedRecord
73785** structure large enough to be used with sqlite3VdbeRecordUnpack() if
73786** the first argument is a pointer to KeyInfo structure pKeyInfo.
73787**
73788** The space is either allocated using sqlite3DbMallocRaw() or from within
73789** the unaligned buffer passed via the second and third arguments (presumably
73790** stack space). If the former, then *ppFree is set to a pointer that should
73791** be eventually freed by the caller using sqlite3DbFree(). Or, if the
73792** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
73793** before returning.
73794**
73795** If an OOM error occurs, NULL is returned.
73796*/
73797SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
73798  KeyInfo *pKeyInfo,              /* Description of the record */
73799  char *pSpace,                   /* Unaligned space available */
73800  int szSpace,                    /* Size of pSpace[] in bytes */
73801  char **ppFree                   /* OUT: Caller should free this pointer */
73802){
73803  UnpackedRecord *p;              /* Unpacked record to return */
73804  int nOff;                       /* Increment pSpace by nOff to align it */
73805  int nByte;                      /* Number of bytes required for *p */
73806
73807  /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
73808  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
73809  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
73810  */
73811  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
73812  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
73813  if( nByte>szSpace+nOff ){
73814    p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
73815    *ppFree = (char *)p;
73816    if( !p ) return 0;
73817  }else{
73818    p = (UnpackedRecord*)&pSpace[nOff];
73819    *ppFree = 0;
73820  }
73821
73822  p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
73823  assert( pKeyInfo->aSortOrder!=0 );
73824  p->pKeyInfo = pKeyInfo;
73825  p->nField = pKeyInfo->nField + 1;
73826  return p;
73827}
73828
73829/*
73830** Given the nKey-byte encoding of a record in pKey[], populate the
73831** UnpackedRecord structure indicated by the fourth argument with the
73832** contents of the decoded record.
73833*/
73834SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
73835  KeyInfo *pKeyInfo,     /* Information about the record format */
73836  int nKey,              /* Size of the binary record */
73837  const void *pKey,      /* The binary record */
73838  UnpackedRecord *p      /* Populate this structure before returning. */
73839){
73840  const unsigned char *aKey = (const unsigned char *)pKey;
73841  int d;
73842  u32 idx;                        /* Offset in aKey[] to read from */
73843  u16 u;                          /* Unsigned loop counter */
73844  u32 szHdr;
73845  Mem *pMem = p->aMem;
73846
73847  p->default_rc = 0;
73848  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
73849  idx = getVarint32(aKey, szHdr);
73850  d = szHdr;
73851  u = 0;
73852  while( idx<szHdr && d<=nKey ){
73853    u32 serial_type;
73854
73855    idx += getVarint32(&aKey[idx], serial_type);
73856    pMem->enc = pKeyInfo->enc;
73857    pMem->db = pKeyInfo->db;
73858    /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
73859    pMem->szMalloc = 0;
73860    pMem->z = 0;
73861    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
73862    pMem++;
73863    if( (++u)>=p->nField ) break;
73864  }
73865  assert( u<=pKeyInfo->nField + 1 );
73866  p->nField = u;
73867}
73868
73869#if SQLITE_DEBUG
73870/*
73871** This function compares two index or table record keys in the same way
73872** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
73873** this function deserializes and compares values using the
73874** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
73875** in assert() statements to ensure that the optimized code in
73876** sqlite3VdbeRecordCompare() returns results with these two primitives.
73877**
73878** Return true if the result of comparison is equivalent to desiredResult.
73879** Return false if there is a disagreement.
73880*/
73881static int vdbeRecordCompareDebug(
73882  int nKey1, const void *pKey1, /* Left key */
73883  const UnpackedRecord *pPKey2, /* Right key */
73884  int desiredResult             /* Correct answer */
73885){
73886  u32 d1;            /* Offset into aKey[] of next data element */
73887  u32 idx1;          /* Offset into aKey[] of next header element */
73888  u32 szHdr1;        /* Number of bytes in header */
73889  int i = 0;
73890  int rc = 0;
73891  const unsigned char *aKey1 = (const unsigned char *)pKey1;
73892  KeyInfo *pKeyInfo;
73893  Mem mem1;
73894
73895  pKeyInfo = pPKey2->pKeyInfo;
73896  if( pKeyInfo->db==0 ) return 1;
73897  mem1.enc = pKeyInfo->enc;
73898  mem1.db = pKeyInfo->db;
73899  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
73900  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
73901
73902  /* Compilers may complain that mem1.u.i is potentially uninitialized.
73903  ** We could initialize it, as shown here, to silence those complaints.
73904  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
73905  ** the unnecessary initialization has a measurable negative performance
73906  ** impact, since this routine is a very high runner.  And so, we choose
73907  ** to ignore the compiler warnings and leave this variable uninitialized.
73908  */
73909  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
73910
73911  idx1 = getVarint32(aKey1, szHdr1);
73912  if( szHdr1>98307 ) return SQLITE_CORRUPT;
73913  d1 = szHdr1;
73914  assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
73915  assert( pKeyInfo->aSortOrder!=0 );
73916  assert( pKeyInfo->nField>0 );
73917  assert( idx1<=szHdr1 || CORRUPT_DB );
73918  do{
73919    u32 serial_type1;
73920
73921    /* Read the serial types for the next element in each key. */
73922    idx1 += getVarint32( aKey1+idx1, serial_type1 );
73923
73924    /* Verify that there is enough key space remaining to avoid
73925    ** a buffer overread.  The "d1+serial_type1+2" subexpression will
73926    ** always be greater than or equal to the amount of required key space.
73927    ** Use that approximation to avoid the more expensive call to
73928    ** sqlite3VdbeSerialTypeLen() in the common case.
73929    */
73930    if( d1+serial_type1+2>(u32)nKey1
73931     && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
73932    ){
73933      break;
73934    }
73935
73936    /* Extract the values to be compared.
73937    */
73938    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
73939
73940    /* Do the comparison
73941    */
73942    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
73943    if( rc!=0 ){
73944      assert( mem1.szMalloc==0 );  /* See comment below */
73945      if( pKeyInfo->aSortOrder[i] ){
73946        rc = -rc;  /* Invert the result for DESC sort order. */
73947      }
73948      goto debugCompareEnd;
73949    }
73950    i++;
73951  }while( idx1<szHdr1 && i<pPKey2->nField );
73952
73953  /* No memory allocation is ever used on mem1.  Prove this using
73954  ** the following assert().  If the assert() fails, it indicates a
73955  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
73956  */
73957  assert( mem1.szMalloc==0 );
73958
73959  /* rc==0 here means that one of the keys ran out of fields and
73960  ** all the fields up to that point were equal. Return the default_rc
73961  ** value.  */
73962  rc = pPKey2->default_rc;
73963
73964debugCompareEnd:
73965  if( desiredResult==0 && rc==0 ) return 1;
73966  if( desiredResult<0 && rc<0 ) return 1;
73967  if( desiredResult>0 && rc>0 ) return 1;
73968  if( CORRUPT_DB ) return 1;
73969  if( pKeyInfo->db->mallocFailed ) return 1;
73970  return 0;
73971}
73972#endif
73973
73974#if SQLITE_DEBUG
73975/*
73976** Count the number of fields (a.k.a. columns) in the record given by
73977** pKey,nKey.  The verify that this count is less than or equal to the
73978** limit given by pKeyInfo->nField + pKeyInfo->nXField.
73979**
73980** If this constraint is not satisfied, it means that the high-speed
73981** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
73982** not work correctly.  If this assert() ever fires, it probably means
73983** that the KeyInfo.nField or KeyInfo.nXField values were computed
73984** incorrectly.
73985*/
73986static void vdbeAssertFieldCountWithinLimits(
73987  int nKey, const void *pKey,   /* The record to verify */
73988  const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
73989){
73990  int nField = 0;
73991  u32 szHdr;
73992  u32 idx;
73993  u32 notUsed;
73994  const unsigned char *aKey = (const unsigned char*)pKey;
73995
73996  if( CORRUPT_DB ) return;
73997  idx = getVarint32(aKey, szHdr);
73998  assert( nKey>=0 );
73999  assert( szHdr<=(u32)nKey );
74000  while( idx<szHdr ){
74001    idx += getVarint32(aKey+idx, notUsed);
74002    nField++;
74003  }
74004  assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
74005}
74006#else
74007# define vdbeAssertFieldCountWithinLimits(A,B,C)
74008#endif
74009
74010/*
74011** Both *pMem1 and *pMem2 contain string values. Compare the two values
74012** using the collation sequence pColl. As usual, return a negative , zero
74013** or positive value if *pMem1 is less than, equal to or greater than
74014** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
74015*/
74016static int vdbeCompareMemString(
74017  const Mem *pMem1,
74018  const Mem *pMem2,
74019  const CollSeq *pColl,
74020  u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
74021){
74022  if( pMem1->enc==pColl->enc ){
74023    /* The strings are already in the correct encoding.  Call the
74024     ** comparison function directly */
74025    return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
74026  }else{
74027    int rc;
74028    const void *v1, *v2;
74029    int n1, n2;
74030    Mem c1;
74031    Mem c2;
74032    sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
74033    sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
74034    sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
74035    sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
74036    v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
74037    n1 = v1==0 ? 0 : c1.n;
74038    v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
74039    n2 = v2==0 ? 0 : c2.n;
74040    rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
74041    if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
74042    sqlite3VdbeMemRelease(&c1);
74043    sqlite3VdbeMemRelease(&c2);
74044    return rc;
74045  }
74046}
74047
74048/*
74049** Compare two blobs.  Return negative, zero, or positive if the first
74050** is less than, equal to, or greater than the second, respectively.
74051** If one blob is a prefix of the other, then the shorter is the lessor.
74052*/
74053static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
74054  int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
74055  if( c ) return c;
74056  return pB1->n - pB2->n;
74057}
74058
74059/*
74060** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
74061** number.  Return negative, zero, or positive if the first (i64) is less than,
74062** equal to, or greater than the second (double).
74063*/
74064static int sqlite3IntFloatCompare(i64 i, double r){
74065  if( sizeof(LONGDOUBLE_TYPE)>8 ){
74066    LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
74067    if( x<r ) return -1;
74068    if( x>r ) return +1;
74069    return 0;
74070  }else{
74071    i64 y;
74072    double s;
74073    if( r<-9223372036854775808.0 ) return +1;
74074    if( r>9223372036854775807.0 ) return -1;
74075    y = (i64)r;
74076    if( i<y ) return -1;
74077    if( i>y ){
74078      if( y==SMALLEST_INT64 && r>0.0 ) return -1;
74079      return +1;
74080    }
74081    s = (double)i;
74082    if( s<r ) return -1;
74083    if( s>r ) return +1;
74084    return 0;
74085  }
74086}
74087
74088/*
74089** Compare the values contained by the two memory cells, returning
74090** negative, zero or positive if pMem1 is less than, equal to, or greater
74091** than pMem2. Sorting order is NULL's first, followed by numbers (integers
74092** and reals) sorted numerically, followed by text ordered by the collating
74093** sequence pColl and finally blob's ordered by memcmp().
74094**
74095** Two NULL values are considered equal by this function.
74096*/
74097SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
74098  int f1, f2;
74099  int combined_flags;
74100
74101  f1 = pMem1->flags;
74102  f2 = pMem2->flags;
74103  combined_flags = f1|f2;
74104  assert( (combined_flags & MEM_RowSet)==0 );
74105
74106  /* If one value is NULL, it is less than the other. If both values
74107  ** are NULL, return 0.
74108  */
74109  if( combined_flags&MEM_Null ){
74110    return (f2&MEM_Null) - (f1&MEM_Null);
74111  }
74112
74113  /* At least one of the two values is a number
74114  */
74115  if( combined_flags&(MEM_Int|MEM_Real) ){
74116    if( (f1 & f2 & MEM_Int)!=0 ){
74117      if( pMem1->u.i < pMem2->u.i ) return -1;
74118      if( pMem1->u.i > pMem2->u.i ) return +1;
74119      return 0;
74120    }
74121    if( (f1 & f2 & MEM_Real)!=0 ){
74122      if( pMem1->u.r < pMem2->u.r ) return -1;
74123      if( pMem1->u.r > pMem2->u.r ) return +1;
74124      return 0;
74125    }
74126    if( (f1&MEM_Int)!=0 ){
74127      if( (f2&MEM_Real)!=0 ){
74128        return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
74129      }else{
74130        return -1;
74131      }
74132    }
74133    if( (f1&MEM_Real)!=0 ){
74134      if( (f2&MEM_Int)!=0 ){
74135        return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
74136      }else{
74137        return -1;
74138      }
74139    }
74140    return +1;
74141  }
74142
74143  /* If one value is a string and the other is a blob, the string is less.
74144  ** If both are strings, compare using the collating functions.
74145  */
74146  if( combined_flags&MEM_Str ){
74147    if( (f1 & MEM_Str)==0 ){
74148      return 1;
74149    }
74150    if( (f2 & MEM_Str)==0 ){
74151      return -1;
74152    }
74153
74154    assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
74155    assert( pMem1->enc==SQLITE_UTF8 ||
74156            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
74157
74158    /* The collation sequence must be defined at this point, even if
74159    ** the user deletes the collation sequence after the vdbe program is
74160    ** compiled (this was not always the case).
74161    */
74162    assert( !pColl || pColl->xCmp );
74163
74164    if( pColl ){
74165      return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
74166    }
74167    /* If a NULL pointer was passed as the collate function, fall through
74168    ** to the blob case and use memcmp().  */
74169  }
74170
74171  /* Both values must be blobs.  Compare using memcmp().  */
74172  return sqlite3BlobCompare(pMem1, pMem2);
74173}
74174
74175
74176/*
74177** The first argument passed to this function is a serial-type that
74178** corresponds to an integer - all values between 1 and 9 inclusive
74179** except 7. The second points to a buffer containing an integer value
74180** serialized according to serial_type. This function deserializes
74181** and returns the value.
74182*/
74183static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
74184  u32 y;
74185  assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
74186  switch( serial_type ){
74187    case 0:
74188    case 1:
74189      testcase( aKey[0]&0x80 );
74190      return ONE_BYTE_INT(aKey);
74191    case 2:
74192      testcase( aKey[0]&0x80 );
74193      return TWO_BYTE_INT(aKey);
74194    case 3:
74195      testcase( aKey[0]&0x80 );
74196      return THREE_BYTE_INT(aKey);
74197    case 4: {
74198      testcase( aKey[0]&0x80 );
74199      y = FOUR_BYTE_UINT(aKey);
74200      return (i64)*(int*)&y;
74201    }
74202    case 5: {
74203      testcase( aKey[0]&0x80 );
74204      return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
74205    }
74206    case 6: {
74207      u64 x = FOUR_BYTE_UINT(aKey);
74208      testcase( aKey[0]&0x80 );
74209      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
74210      return (i64)*(i64*)&x;
74211    }
74212  }
74213
74214  return (serial_type - 8);
74215}
74216
74217/*
74218** This function compares the two table rows or index records
74219** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
74220** or positive integer if key1 is less than, equal to or
74221** greater than key2.  The {nKey1, pKey1} key must be a blob
74222** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
74223** key must be a parsed key such as obtained from
74224** sqlite3VdbeParseRecord.
74225**
74226** If argument bSkip is non-zero, it is assumed that the caller has already
74227** determined that the first fields of the keys are equal.
74228**
74229** Key1 and Key2 do not have to contain the same number of fields. If all
74230** fields that appear in both keys are equal, then pPKey2->default_rc is
74231** returned.
74232**
74233** If database corruption is discovered, set pPKey2->errCode to
74234** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
74235** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
74236** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
74237*/
74238SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
74239  int nKey1, const void *pKey1,   /* Left key */
74240  UnpackedRecord *pPKey2,         /* Right key */
74241  int bSkip                       /* If true, skip the first field */
74242){
74243  u32 d1;                         /* Offset into aKey[] of next data element */
74244  int i;                          /* Index of next field to compare */
74245  u32 szHdr1;                     /* Size of record header in bytes */
74246  u32 idx1;                       /* Offset of first type in header */
74247  int rc = 0;                     /* Return value */
74248  Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
74249  KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
74250  const unsigned char *aKey1 = (const unsigned char *)pKey1;
74251  Mem mem1;
74252
74253  /* If bSkip is true, then the caller has already determined that the first
74254  ** two elements in the keys are equal. Fix the various stack variables so
74255  ** that this routine begins comparing at the second field. */
74256  if( bSkip ){
74257    u32 s1;
74258    idx1 = 1 + getVarint32(&aKey1[1], s1);
74259    szHdr1 = aKey1[0];
74260    d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
74261    i = 1;
74262    pRhs++;
74263  }else{
74264    idx1 = getVarint32(aKey1, szHdr1);
74265    d1 = szHdr1;
74266    if( d1>(unsigned)nKey1 ){
74267      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74268      return 0;  /* Corruption */
74269    }
74270    i = 0;
74271  }
74272
74273  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
74274  assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
74275       || CORRUPT_DB );
74276  assert( pPKey2->pKeyInfo->aSortOrder!=0 );
74277  assert( pPKey2->pKeyInfo->nField>0 );
74278  assert( idx1<=szHdr1 || CORRUPT_DB );
74279  do{
74280    u32 serial_type;
74281
74282    /* RHS is an integer */
74283    if( pRhs->flags & MEM_Int ){
74284      serial_type = aKey1[idx1];
74285      testcase( serial_type==12 );
74286      if( serial_type>=10 ){
74287        rc = +1;
74288      }else if( serial_type==0 ){
74289        rc = -1;
74290      }else if( serial_type==7 ){
74291        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
74292        rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
74293      }else{
74294        i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
74295        i64 rhs = pRhs->u.i;
74296        if( lhs<rhs ){
74297          rc = -1;
74298        }else if( lhs>rhs ){
74299          rc = +1;
74300        }
74301      }
74302    }
74303
74304    /* RHS is real */
74305    else if( pRhs->flags & MEM_Real ){
74306      serial_type = aKey1[idx1];
74307      if( serial_type>=10 ){
74308        /* Serial types 12 or greater are strings and blobs (greater than
74309        ** numbers). Types 10 and 11 are currently "reserved for future
74310        ** use", so it doesn't really matter what the results of comparing
74311        ** them to numberic values are.  */
74312        rc = +1;
74313      }else if( serial_type==0 ){
74314        rc = -1;
74315      }else{
74316        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
74317        if( serial_type==7 ){
74318          if( mem1.u.r<pRhs->u.r ){
74319            rc = -1;
74320          }else if( mem1.u.r>pRhs->u.r ){
74321            rc = +1;
74322          }
74323        }else{
74324          rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
74325        }
74326      }
74327    }
74328
74329    /* RHS is a string */
74330    else if( pRhs->flags & MEM_Str ){
74331      getVarint32(&aKey1[idx1], serial_type);
74332      testcase( serial_type==12 );
74333      if( serial_type<12 ){
74334        rc = -1;
74335      }else if( !(serial_type & 0x01) ){
74336        rc = +1;
74337      }else{
74338        mem1.n = (serial_type - 12) / 2;
74339        testcase( (d1+mem1.n)==(unsigned)nKey1 );
74340        testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
74341        if( (d1+mem1.n) > (unsigned)nKey1 ){
74342          pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74343          return 0;                /* Corruption */
74344        }else if( pKeyInfo->aColl[i] ){
74345          mem1.enc = pKeyInfo->enc;
74346          mem1.db = pKeyInfo->db;
74347          mem1.flags = MEM_Str;
74348          mem1.z = (char*)&aKey1[d1];
74349          rc = vdbeCompareMemString(
74350              &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
74351          );
74352        }else{
74353          int nCmp = MIN(mem1.n, pRhs->n);
74354          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
74355          if( rc==0 ) rc = mem1.n - pRhs->n;
74356        }
74357      }
74358    }
74359
74360    /* RHS is a blob */
74361    else if( pRhs->flags & MEM_Blob ){
74362      getVarint32(&aKey1[idx1], serial_type);
74363      testcase( serial_type==12 );
74364      if( serial_type<12 || (serial_type & 0x01) ){
74365        rc = -1;
74366      }else{
74367        int nStr = (serial_type - 12) / 2;
74368        testcase( (d1+nStr)==(unsigned)nKey1 );
74369        testcase( (d1+nStr+1)==(unsigned)nKey1 );
74370        if( (d1+nStr) > (unsigned)nKey1 ){
74371          pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74372          return 0;                /* Corruption */
74373        }else{
74374          int nCmp = MIN(nStr, pRhs->n);
74375          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
74376          if( rc==0 ) rc = nStr - pRhs->n;
74377        }
74378      }
74379    }
74380
74381    /* RHS is null */
74382    else{
74383      serial_type = aKey1[idx1];
74384      rc = (serial_type!=0);
74385    }
74386
74387    if( rc!=0 ){
74388      if( pKeyInfo->aSortOrder[i] ){
74389        rc = -rc;
74390      }
74391      assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
74392      assert( mem1.szMalloc==0 );  /* See comment below */
74393      return rc;
74394    }
74395
74396    i++;
74397    pRhs++;
74398    d1 += sqlite3VdbeSerialTypeLen(serial_type);
74399    idx1 += sqlite3VarintLen(serial_type);
74400  }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
74401
74402  /* No memory allocation is ever used on mem1.  Prove this using
74403  ** the following assert().  If the assert() fails, it indicates a
74404  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
74405  assert( mem1.szMalloc==0 );
74406
74407  /* rc==0 here means that one or both of the keys ran out of fields and
74408  ** all the fields up to that point were equal. Return the default_rc
74409  ** value.  */
74410  assert( CORRUPT_DB
74411       || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
74412       || pKeyInfo->db->mallocFailed
74413  );
74414  pPKey2->eqSeen = 1;
74415  return pPKey2->default_rc;
74416}
74417SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
74418  int nKey1, const void *pKey1,   /* Left key */
74419  UnpackedRecord *pPKey2          /* Right key */
74420){
74421  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
74422}
74423
74424
74425/*
74426** This function is an optimized version of sqlite3VdbeRecordCompare()
74427** that (a) the first field of pPKey2 is an integer, and (b) the
74428** size-of-header varint at the start of (pKey1/nKey1) fits in a single
74429** byte (i.e. is less than 128).
74430**
74431** To avoid concerns about buffer overreads, this routine is only used
74432** on schemas where the maximum valid header size is 63 bytes or less.
74433*/
74434static int vdbeRecordCompareInt(
74435  int nKey1, const void *pKey1, /* Left key */
74436  UnpackedRecord *pPKey2        /* Right key */
74437){
74438  const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
74439  int serial_type = ((const u8*)pKey1)[1];
74440  int res;
74441  u32 y;
74442  u64 x;
74443  i64 v = pPKey2->aMem[0].u.i;
74444  i64 lhs;
74445
74446  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
74447  assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
74448  switch( serial_type ){
74449    case 1: { /* 1-byte signed integer */
74450      lhs = ONE_BYTE_INT(aKey);
74451      testcase( lhs<0 );
74452      break;
74453    }
74454    case 2: { /* 2-byte signed integer */
74455      lhs = TWO_BYTE_INT(aKey);
74456      testcase( lhs<0 );
74457      break;
74458    }
74459    case 3: { /* 3-byte signed integer */
74460      lhs = THREE_BYTE_INT(aKey);
74461      testcase( lhs<0 );
74462      break;
74463    }
74464    case 4: { /* 4-byte signed integer */
74465      y = FOUR_BYTE_UINT(aKey);
74466      lhs = (i64)*(int*)&y;
74467      testcase( lhs<0 );
74468      break;
74469    }
74470    case 5: { /* 6-byte signed integer */
74471      lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
74472      testcase( lhs<0 );
74473      break;
74474    }
74475    case 6: { /* 8-byte signed integer */
74476      x = FOUR_BYTE_UINT(aKey);
74477      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
74478      lhs = *(i64*)&x;
74479      testcase( lhs<0 );
74480      break;
74481    }
74482    case 8:
74483      lhs = 0;
74484      break;
74485    case 9:
74486      lhs = 1;
74487      break;
74488
74489    /* This case could be removed without changing the results of running
74490    ** this code. Including it causes gcc to generate a faster switch
74491    ** statement (since the range of switch targets now starts at zero and
74492    ** is contiguous) but does not cause any duplicate code to be generated
74493    ** (as gcc is clever enough to combine the two like cases). Other
74494    ** compilers might be similar.  */
74495    case 0: case 7:
74496      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
74497
74498    default:
74499      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
74500  }
74501
74502  if( v>lhs ){
74503    res = pPKey2->r1;
74504  }else if( v<lhs ){
74505    res = pPKey2->r2;
74506  }else if( pPKey2->nField>1 ){
74507    /* The first fields of the two keys are equal. Compare the trailing
74508    ** fields.  */
74509    res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
74510  }else{
74511    /* The first fields of the two keys are equal and there are no trailing
74512    ** fields. Return pPKey2->default_rc in this case. */
74513    res = pPKey2->default_rc;
74514    pPKey2->eqSeen = 1;
74515  }
74516
74517  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
74518  return res;
74519}
74520
74521/*
74522** This function is an optimized version of sqlite3VdbeRecordCompare()
74523** that (a) the first field of pPKey2 is a string, that (b) the first field
74524** uses the collation sequence BINARY and (c) that the size-of-header varint
74525** at the start of (pKey1/nKey1) fits in a single byte.
74526*/
74527static int vdbeRecordCompareString(
74528  int nKey1, const void *pKey1, /* Left key */
74529  UnpackedRecord *pPKey2        /* Right key */
74530){
74531  const u8 *aKey1 = (const u8*)pKey1;
74532  int serial_type;
74533  int res;
74534
74535  assert( pPKey2->aMem[0].flags & MEM_Str );
74536  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
74537  getVarint32(&aKey1[1], serial_type);
74538  if( serial_type<12 ){
74539    res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
74540  }else if( !(serial_type & 0x01) ){
74541    res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
74542  }else{
74543    int nCmp;
74544    int nStr;
74545    int szHdr = aKey1[0];
74546
74547    nStr = (serial_type-12) / 2;
74548    if( (szHdr + nStr) > nKey1 ){
74549      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74550      return 0;    /* Corruption */
74551    }
74552    nCmp = MIN( pPKey2->aMem[0].n, nStr );
74553    res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
74554
74555    if( res==0 ){
74556      res = nStr - pPKey2->aMem[0].n;
74557      if( res==0 ){
74558        if( pPKey2->nField>1 ){
74559          res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
74560        }else{
74561          res = pPKey2->default_rc;
74562          pPKey2->eqSeen = 1;
74563        }
74564      }else if( res>0 ){
74565        res = pPKey2->r2;
74566      }else{
74567        res = pPKey2->r1;
74568      }
74569    }else if( res>0 ){
74570      res = pPKey2->r2;
74571    }else{
74572      res = pPKey2->r1;
74573    }
74574  }
74575
74576  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
74577       || CORRUPT_DB
74578       || pPKey2->pKeyInfo->db->mallocFailed
74579  );
74580  return res;
74581}
74582
74583/*
74584** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
74585** suitable for comparing serialized records to the unpacked record passed
74586** as the only argument.
74587*/
74588SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
74589  /* varintRecordCompareInt() and varintRecordCompareString() both assume
74590  ** that the size-of-header varint that occurs at the start of each record
74591  ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
74592  ** also assumes that it is safe to overread a buffer by at least the
74593  ** maximum possible legal header size plus 8 bytes. Because there is
74594  ** guaranteed to be at least 74 (but not 136) bytes of padding following each
74595  ** buffer passed to varintRecordCompareInt() this makes it convenient to
74596  ** limit the size of the header to 64 bytes in cases where the first field
74597  ** is an integer.
74598  **
74599  ** The easiest way to enforce this limit is to consider only records with
74600  ** 13 fields or less. If the first field is an integer, the maximum legal
74601  ** header size is (12*5 + 1 + 1) bytes.  */
74602  if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
74603    int flags = p->aMem[0].flags;
74604    if( p->pKeyInfo->aSortOrder[0] ){
74605      p->r1 = 1;
74606      p->r2 = -1;
74607    }else{
74608      p->r1 = -1;
74609      p->r2 = 1;
74610    }
74611    if( (flags & MEM_Int) ){
74612      return vdbeRecordCompareInt;
74613    }
74614    testcase( flags & MEM_Real );
74615    testcase( flags & MEM_Null );
74616    testcase( flags & MEM_Blob );
74617    if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
74618      assert( flags & MEM_Str );
74619      return vdbeRecordCompareString;
74620    }
74621  }
74622
74623  return sqlite3VdbeRecordCompare;
74624}
74625
74626/*
74627** pCur points at an index entry created using the OP_MakeRecord opcode.
74628** Read the rowid (the last field in the record) and store it in *rowid.
74629** Return SQLITE_OK if everything works, or an error code otherwise.
74630**
74631** pCur might be pointing to text obtained from a corrupt database file.
74632** So the content cannot be trusted.  Do appropriate checks on the content.
74633*/
74634SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
74635  i64 nCellKey = 0;
74636  int rc;
74637  u32 szHdr;        /* Size of the header */
74638  u32 typeRowid;    /* Serial type of the rowid */
74639  u32 lenRowid;     /* Size of the rowid */
74640  Mem m, v;
74641
74642  /* Get the size of the index entry.  Only indices entries of less
74643  ** than 2GiB are support - anything large must be database corruption.
74644  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
74645  ** this code can safely assume that nCellKey is 32-bits
74646  */
74647  assert( sqlite3BtreeCursorIsValid(pCur) );
74648  nCellKey = sqlite3BtreePayloadSize(pCur);
74649  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
74650
74651  /* Read in the complete content of the index entry */
74652  sqlite3VdbeMemInit(&m, db, 0);
74653  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
74654  if( rc ){
74655    return rc;
74656  }
74657
74658  /* The index entry must begin with a header size */
74659  (void)getVarint32((u8*)m.z, szHdr);
74660  testcase( szHdr==3 );
74661  testcase( szHdr==m.n );
74662  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
74663    goto idx_rowid_corruption;
74664  }
74665
74666  /* The last field of the index should be an integer - the ROWID.
74667  ** Verify that the last entry really is an integer. */
74668  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
74669  testcase( typeRowid==1 );
74670  testcase( typeRowid==2 );
74671  testcase( typeRowid==3 );
74672  testcase( typeRowid==4 );
74673  testcase( typeRowid==5 );
74674  testcase( typeRowid==6 );
74675  testcase( typeRowid==8 );
74676  testcase( typeRowid==9 );
74677  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
74678    goto idx_rowid_corruption;
74679  }
74680  lenRowid = sqlite3SmallTypeSizes[typeRowid];
74681  testcase( (u32)m.n==szHdr+lenRowid );
74682  if( unlikely((u32)m.n<szHdr+lenRowid) ){
74683    goto idx_rowid_corruption;
74684  }
74685
74686  /* Fetch the integer off the end of the index record */
74687  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
74688  *rowid = v.u.i;
74689  sqlite3VdbeMemRelease(&m);
74690  return SQLITE_OK;
74691
74692  /* Jump here if database corruption is detected after m has been
74693  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
74694idx_rowid_corruption:
74695  testcase( m.szMalloc!=0 );
74696  sqlite3VdbeMemRelease(&m);
74697  return SQLITE_CORRUPT_BKPT;
74698}
74699
74700/*
74701** Compare the key of the index entry that cursor pC is pointing to against
74702** the key string in pUnpacked.  Write into *pRes a number
74703** that is negative, zero, or positive if pC is less than, equal to,
74704** or greater than pUnpacked.  Return SQLITE_OK on success.
74705**
74706** pUnpacked is either created without a rowid or is truncated so that it
74707** omits the rowid at the end.  The rowid at the end of the index entry
74708** is ignored as well.  Hence, this routine only compares the prefixes
74709** of the keys prior to the final rowid, not the entire key.
74710*/
74711SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
74712  sqlite3 *db,                     /* Database connection */
74713  VdbeCursor *pC,                  /* The cursor to compare against */
74714  UnpackedRecord *pUnpacked,       /* Unpacked version of key */
74715  int *res                         /* Write the comparison result here */
74716){
74717  i64 nCellKey = 0;
74718  int rc;
74719  BtCursor *pCur;
74720  Mem m;
74721
74722  assert( pC->eCurType==CURTYPE_BTREE );
74723  pCur = pC->uc.pCursor;
74724  assert( sqlite3BtreeCursorIsValid(pCur) );
74725  nCellKey = sqlite3BtreePayloadSize(pCur);
74726  /* nCellKey will always be between 0 and 0xffffffff because of the way
74727  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
74728  if( nCellKey<=0 || nCellKey>0x7fffffff ){
74729    *res = 0;
74730    return SQLITE_CORRUPT_BKPT;
74731  }
74732  sqlite3VdbeMemInit(&m, db, 0);
74733  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
74734  if( rc ){
74735    return rc;
74736  }
74737  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
74738  sqlite3VdbeMemRelease(&m);
74739  return SQLITE_OK;
74740}
74741
74742/*
74743** This routine sets the value to be returned by subsequent calls to
74744** sqlite3_changes() on the database handle 'db'.
74745*/
74746SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
74747  assert( sqlite3_mutex_held(db->mutex) );
74748  db->nChange = nChange;
74749  db->nTotalChange += nChange;
74750}
74751
74752/*
74753** Set a flag in the vdbe to update the change counter when it is finalised
74754** or reset.
74755*/
74756SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
74757  v->changeCntOn = 1;
74758}
74759
74760/*
74761** Mark every prepared statement associated with a database connection
74762** as expired.
74763**
74764** An expired statement means that recompilation of the statement is
74765** recommend.  Statements expire when things happen that make their
74766** programs obsolete.  Removing user-defined functions or collating
74767** sequences, or changing an authorization function are the types of
74768** things that make prepared statements obsolete.
74769*/
74770SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
74771  Vdbe *p;
74772  for(p = db->pVdbe; p; p=p->pNext){
74773    p->expired = 1;
74774  }
74775}
74776
74777/*
74778** Return the database associated with the Vdbe.
74779*/
74780SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
74781  return v->db;
74782}
74783
74784/*
74785** Return a pointer to an sqlite3_value structure containing the value bound
74786** parameter iVar of VM v. Except, if the value is an SQL NULL, return
74787** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
74788** constants) to the value before returning it.
74789**
74790** The returned value must be freed by the caller using sqlite3ValueFree().
74791*/
74792SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
74793  assert( iVar>0 );
74794  if( v ){
74795    Mem *pMem = &v->aVar[iVar-1];
74796    if( 0==(pMem->flags & MEM_Null) ){
74797      sqlite3_value *pRet = sqlite3ValueNew(v->db);
74798      if( pRet ){
74799        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
74800        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
74801      }
74802      return pRet;
74803    }
74804  }
74805  return 0;
74806}
74807
74808/*
74809** Configure SQL variable iVar so that binding a new value to it signals
74810** to sqlite3_reoptimize() that re-preparing the statement may result
74811** in a better query plan.
74812*/
74813SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
74814  assert( iVar>0 );
74815  if( iVar>32 ){
74816    v->expmask = 0xffffffff;
74817  }else{
74818    v->expmask |= ((u32)1 << (iVar-1));
74819  }
74820}
74821
74822#ifndef SQLITE_OMIT_VIRTUALTABLE
74823/*
74824** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
74825** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
74826** in memory obtained from sqlite3DbMalloc).
74827*/
74828SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
74829  if( pVtab->zErrMsg ){
74830    sqlite3 *db = p->db;
74831    sqlite3DbFree(db, p->zErrMsg);
74832    p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
74833    sqlite3_free(pVtab->zErrMsg);
74834    pVtab->zErrMsg = 0;
74835  }
74836}
74837#endif /* SQLITE_OMIT_VIRTUALTABLE */
74838
74839#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
74840
74841/*
74842** If the second argument is not NULL, release any allocations associated
74843** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
74844** structure itself, using sqlite3DbFree().
74845**
74846** This function is used to free UnpackedRecord structures allocated by
74847** the vdbeUnpackRecord() function found in vdbeapi.c.
74848*/
74849static void vdbeFreeUnpacked(sqlite3 *db, UnpackedRecord *p){
74850  if( p ){
74851    int i;
74852    for(i=0; i<p->nField; i++){
74853      Mem *pMem = &p->aMem[i];
74854      if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
74855    }
74856    sqlite3DbFree(db, p);
74857  }
74858}
74859#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
74860
74861#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
74862/*
74863** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
74864** then cursor passed as the second argument should point to the row about
74865** to be update or deleted. If the application calls sqlite3_preupdate_old(),
74866** the required value will be read from the row the cursor points to.
74867*/
74868SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
74869  Vdbe *v,                        /* Vdbe pre-update hook is invoked by */
74870  VdbeCursor *pCsr,               /* Cursor to grab old.* values from */
74871  int op,                         /* SQLITE_INSERT, UPDATE or DELETE */
74872  const char *zDb,                /* Database name */
74873  Table *pTab,                    /* Modified table */
74874  i64 iKey1,                      /* Initial key value */
74875  int iReg                        /* Register for new.* record */
74876){
74877  sqlite3 *db = v->db;
74878  i64 iKey2;
74879  PreUpdate preupdate;
74880  const char *zTbl = pTab->zName;
74881  static const u8 fakeSortOrder = 0;
74882
74883  assert( db->pPreUpdate==0 );
74884  memset(&preupdate, 0, sizeof(PreUpdate));
74885  if( op==SQLITE_UPDATE ){
74886    iKey2 = v->aMem[iReg].u.i;
74887  }else{
74888    iKey2 = iKey1;
74889  }
74890
74891  assert( pCsr->nField==pTab->nCol
74892       || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
74893  );
74894
74895  preupdate.v = v;
74896  preupdate.pCsr = pCsr;
74897  preupdate.op = op;
74898  preupdate.iNewReg = iReg;
74899  preupdate.keyinfo.db = db;
74900  preupdate.keyinfo.enc = ENC(db);
74901  preupdate.keyinfo.nField = pTab->nCol;
74902  preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
74903  preupdate.iKey1 = iKey1;
74904  preupdate.iKey2 = iKey2;
74905  preupdate.iPKey = pTab->iPKey;
74906
74907  db->pPreUpdate = &preupdate;
74908  db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
74909  db->pPreUpdate = 0;
74910  sqlite3DbFree(db, preupdate.aRecord);
74911  vdbeFreeUnpacked(db, preupdate.pUnpacked);
74912  vdbeFreeUnpacked(db, preupdate.pNewUnpacked);
74913  if( preupdate.aNew ){
74914    int i;
74915    for(i=0; i<pCsr->nField; i++){
74916      sqlite3VdbeMemRelease(&preupdate.aNew[i]);
74917    }
74918    sqlite3DbFree(db, preupdate.aNew);
74919  }
74920}
74921#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
74922
74923/************** End of vdbeaux.c *********************************************/
74924/************** Begin file vdbeapi.c *****************************************/
74925/*
74926** 2004 May 26
74927**
74928** The author disclaims copyright to this source code.  In place of
74929** a legal notice, here is a blessing:
74930**
74931**    May you do good and not evil.
74932**    May you find forgiveness for yourself and forgive others.
74933**    May you share freely, never taking more than you give.
74934**
74935*************************************************************************
74936**
74937** This file contains code use to implement APIs that are part of the
74938** VDBE.
74939*/
74940/* #include "sqliteInt.h" */
74941/* #include "vdbeInt.h" */
74942
74943#ifndef SQLITE_OMIT_DEPRECATED
74944/*
74945** Return TRUE (non-zero) of the statement supplied as an argument needs
74946** to be recompiled.  A statement needs to be recompiled whenever the
74947** execution environment changes in a way that would alter the program
74948** that sqlite3_prepare() generates.  For example, if new functions or
74949** collating sequences are registered or if an authorizer function is
74950** added or changed.
74951*/
74952SQLITE_API int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt *pStmt){
74953  Vdbe *p = (Vdbe*)pStmt;
74954  return p==0 || p->expired;
74955}
74956#endif
74957
74958/*
74959** Check on a Vdbe to make sure it has not been finalized.  Log
74960** an error and return true if it has been finalized (or is otherwise
74961** invalid).  Return false if it is ok.
74962*/
74963static int vdbeSafety(Vdbe *p){
74964  if( p->db==0 ){
74965    sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
74966    return 1;
74967  }else{
74968    return 0;
74969  }
74970}
74971static int vdbeSafetyNotNull(Vdbe *p){
74972  if( p==0 ){
74973    sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
74974    return 1;
74975  }else{
74976    return vdbeSafety(p);
74977  }
74978}
74979
74980#ifndef SQLITE_OMIT_TRACE
74981/*
74982** Invoke the profile callback.  This routine is only called if we already
74983** know that the profile callback is defined and needs to be invoked.
74984*/
74985static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
74986  sqlite3_int64 iNow;
74987  sqlite3_int64 iElapse;
74988  assert( p->startTime>0 );
74989  assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 );
74990  assert( db->init.busy==0 );
74991  assert( p->zSql!=0 );
74992  sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
74993  iElapse = (iNow - p->startTime)*1000000;
74994  if( db->xProfile ){
74995    db->xProfile(db->pProfileArg, p->zSql, iElapse);
74996  }
74997  if( db->mTrace & SQLITE_TRACE_PROFILE ){
74998    db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
74999  }
75000  p->startTime = 0;
75001}
75002/*
75003** The checkProfileCallback(DB,P) macro checks to see if a profile callback
75004** is needed, and it invokes the callback if it is needed.
75005*/
75006# define checkProfileCallback(DB,P) \
75007   if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
75008#else
75009# define checkProfileCallback(DB,P)  /*no-op*/
75010#endif
75011
75012/*
75013** The following routine destroys a virtual machine that is created by
75014** the sqlite3_compile() routine. The integer returned is an SQLITE_
75015** success/failure code that describes the result of executing the virtual
75016** machine.
75017**
75018** This routine sets the error code and string returned by
75019** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
75020*/
75021SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt){
75022  int rc;
75023  if( pStmt==0 ){
75024    /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
75025    ** pointer is a harmless no-op. */
75026    rc = SQLITE_OK;
75027  }else{
75028    Vdbe *v = (Vdbe*)pStmt;
75029    sqlite3 *db = v->db;
75030    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
75031    sqlite3_mutex_enter(db->mutex);
75032    checkProfileCallback(db, v);
75033    rc = sqlite3VdbeFinalize(v);
75034    rc = sqlite3ApiExit(db, rc);
75035    sqlite3LeaveMutexAndCloseZombie(db);
75036  }
75037  return rc;
75038}
75039
75040/*
75041** Terminate the current execution of an SQL statement and reset it
75042** back to its starting state so that it can be reused. A success code from
75043** the prior execution is returned.
75044**
75045** This routine sets the error code and string returned by
75046** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
75047*/
75048SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt){
75049  int rc;
75050  if( pStmt==0 ){
75051    rc = SQLITE_OK;
75052  }else{
75053    Vdbe *v = (Vdbe*)pStmt;
75054    sqlite3 *db = v->db;
75055    sqlite3_mutex_enter(db->mutex);
75056    checkProfileCallback(db, v);
75057    rc = sqlite3VdbeReset(v);
75058    sqlite3VdbeRewind(v);
75059    assert( (rc & (db->errMask))==rc );
75060    rc = sqlite3ApiExit(db, rc);
75061    sqlite3_mutex_leave(db->mutex);
75062  }
75063  return rc;
75064}
75065
75066/*
75067** Set all the parameters in the compiled SQL statement to NULL.
75068*/
75069SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt *pStmt){
75070  int i;
75071  int rc = SQLITE_OK;
75072  Vdbe *p = (Vdbe*)pStmt;
75073#if SQLITE_THREADSAFE
75074  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
75075#endif
75076  sqlite3_mutex_enter(mutex);
75077  for(i=0; i<p->nVar; i++){
75078    sqlite3VdbeMemRelease(&p->aVar[i]);
75079    p->aVar[i].flags = MEM_Null;
75080  }
75081  if( p->isPrepareV2 && p->expmask ){
75082    p->expired = 1;
75083  }
75084  sqlite3_mutex_leave(mutex);
75085  return rc;
75086}
75087
75088
75089/**************************** sqlite3_value_  *******************************
75090** The following routines extract information from a Mem or sqlite3_value
75091** structure.
75092*/
75093SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value *pVal){
75094  Mem *p = (Mem*)pVal;
75095  if( p->flags & (MEM_Blob|MEM_Str) ){
75096    if( sqlite3VdbeMemExpandBlob(p)!=SQLITE_OK ){
75097      assert( p->flags==MEM_Null && p->z==0 );
75098      return 0;
75099    }
75100    p->flags |= MEM_Blob;
75101    return p->n ? p->z : 0;
75102  }else{
75103    return sqlite3_value_text(pVal);
75104  }
75105}
75106SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value *pVal){
75107  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
75108}
75109SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value *pVal){
75110  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
75111}
75112SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value *pVal){
75113  return sqlite3VdbeRealValue((Mem*)pVal);
75114}
75115SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value *pVal){
75116  return (int)sqlite3VdbeIntValue((Mem*)pVal);
75117}
75118SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value *pVal){
75119  return sqlite3VdbeIntValue((Mem*)pVal);
75120}
75121SQLITE_API unsigned int SQLITE_STDCALL sqlite3_value_subtype(sqlite3_value *pVal){
75122  Mem *pMem = (Mem*)pVal;
75123  return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
75124}
75125SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value *pVal){
75126  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
75127}
75128#ifndef SQLITE_OMIT_UTF16
75129SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value* pVal){
75130  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
75131}
75132SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value *pVal){
75133  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
75134}
75135SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value *pVal){
75136  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
75137}
75138#endif /* SQLITE_OMIT_UTF16 */
75139/* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
75140** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
75141** point number string BLOB NULL
75142*/
75143SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value* pVal){
75144  static const u8 aType[] = {
75145     SQLITE_BLOB,     /* 0x00 */
75146     SQLITE_NULL,     /* 0x01 */
75147     SQLITE_TEXT,     /* 0x02 */
75148     SQLITE_NULL,     /* 0x03 */
75149     SQLITE_INTEGER,  /* 0x04 */
75150     SQLITE_NULL,     /* 0x05 */
75151     SQLITE_INTEGER,  /* 0x06 */
75152     SQLITE_NULL,     /* 0x07 */
75153     SQLITE_FLOAT,    /* 0x08 */
75154     SQLITE_NULL,     /* 0x09 */
75155     SQLITE_FLOAT,    /* 0x0a */
75156     SQLITE_NULL,     /* 0x0b */
75157     SQLITE_INTEGER,  /* 0x0c */
75158     SQLITE_NULL,     /* 0x0d */
75159     SQLITE_INTEGER,  /* 0x0e */
75160     SQLITE_NULL,     /* 0x0f */
75161     SQLITE_BLOB,     /* 0x10 */
75162     SQLITE_NULL,     /* 0x11 */
75163     SQLITE_TEXT,     /* 0x12 */
75164     SQLITE_NULL,     /* 0x13 */
75165     SQLITE_INTEGER,  /* 0x14 */
75166     SQLITE_NULL,     /* 0x15 */
75167     SQLITE_INTEGER,  /* 0x16 */
75168     SQLITE_NULL,     /* 0x17 */
75169     SQLITE_FLOAT,    /* 0x18 */
75170     SQLITE_NULL,     /* 0x19 */
75171     SQLITE_FLOAT,    /* 0x1a */
75172     SQLITE_NULL,     /* 0x1b */
75173     SQLITE_INTEGER,  /* 0x1c */
75174     SQLITE_NULL,     /* 0x1d */
75175     SQLITE_INTEGER,  /* 0x1e */
75176     SQLITE_NULL,     /* 0x1f */
75177  };
75178  return aType[pVal->flags&MEM_AffMask];
75179}
75180
75181/* Make a copy of an sqlite3_value object
75182*/
75183SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_value_dup(const sqlite3_value *pOrig){
75184  sqlite3_value *pNew;
75185  if( pOrig==0 ) return 0;
75186  pNew = sqlite3_malloc( sizeof(*pNew) );
75187  if( pNew==0 ) return 0;
75188  memset(pNew, 0, sizeof(*pNew));
75189  memcpy(pNew, pOrig, MEMCELLSIZE);
75190  pNew->flags &= ~MEM_Dyn;
75191  pNew->db = 0;
75192  if( pNew->flags&(MEM_Str|MEM_Blob) ){
75193    pNew->flags &= ~(MEM_Static|MEM_Dyn);
75194    pNew->flags |= MEM_Ephem;
75195    if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
75196      sqlite3ValueFree(pNew);
75197      pNew = 0;
75198    }
75199  }
75200  return pNew;
75201}
75202
75203/* Destroy an sqlite3_value object previously obtained from
75204** sqlite3_value_dup().
75205*/
75206SQLITE_API void SQLITE_STDCALL sqlite3_value_free(sqlite3_value *pOld){
75207  sqlite3ValueFree(pOld);
75208}
75209
75210
75211/**************************** sqlite3_result_  *******************************
75212** The following routines are used by user-defined functions to specify
75213** the function result.
75214**
75215** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
75216** result as a string or blob but if the string or blob is too large, it
75217** then sets the error code to SQLITE_TOOBIG
75218**
75219** The invokeValueDestructor(P,X) routine invokes destructor function X()
75220** on value P is not going to be used and need to be destroyed.
75221*/
75222static void setResultStrOrError(
75223  sqlite3_context *pCtx,  /* Function context */
75224  const char *z,          /* String pointer */
75225  int n,                  /* Bytes in string, or negative */
75226  u8 enc,                 /* Encoding of z.  0 for BLOBs */
75227  void (*xDel)(void*)     /* Destructor function */
75228){
75229  if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
75230    sqlite3_result_error_toobig(pCtx);
75231  }
75232}
75233static int invokeValueDestructor(
75234  const void *p,             /* Value to destroy */
75235  void (*xDel)(void*),       /* The destructor */
75236  sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */
75237){
75238  assert( xDel!=SQLITE_DYNAMIC );
75239  if( xDel==0 ){
75240    /* noop */
75241  }else if( xDel==SQLITE_TRANSIENT ){
75242    /* noop */
75243  }else{
75244    xDel((void*)p);
75245  }
75246  if( pCtx ) sqlite3_result_error_toobig(pCtx);
75247  return SQLITE_TOOBIG;
75248}
75249SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(
75250  sqlite3_context *pCtx,
75251  const void *z,
75252  int n,
75253  void (*xDel)(void *)
75254){
75255  assert( n>=0 );
75256  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75257  setResultStrOrError(pCtx, z, n, 0, xDel);
75258}
75259SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(
75260  sqlite3_context *pCtx,
75261  const void *z,
75262  sqlite3_uint64 n,
75263  void (*xDel)(void *)
75264){
75265  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75266  assert( xDel!=SQLITE_DYNAMIC );
75267  if( n>0x7fffffff ){
75268    (void)invokeValueDestructor(z, xDel, pCtx);
75269  }else{
75270    setResultStrOrError(pCtx, z, (int)n, 0, xDel);
75271  }
75272}
75273SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context *pCtx, double rVal){
75274  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75275  sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
75276}
75277SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
75278  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75279  pCtx->isError = SQLITE_ERROR;
75280  pCtx->fErrorOrAux = 1;
75281  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
75282}
75283#ifndef SQLITE_OMIT_UTF16
75284SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
75285  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75286  pCtx->isError = SQLITE_ERROR;
75287  pCtx->fErrorOrAux = 1;
75288  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
75289}
75290#endif
75291SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context *pCtx, int iVal){
75292  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75293  sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
75294}
75295SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
75296  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75297  sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
75298}
75299SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context *pCtx){
75300  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75301  sqlite3VdbeMemSetNull(pCtx->pOut);
75302}
75303SQLITE_API void SQLITE_STDCALL sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
75304  Mem *pOut = pCtx->pOut;
75305  assert( sqlite3_mutex_held(pOut->db->mutex) );
75306  pOut->eSubtype = eSubtype & 0xff;
75307  pOut->flags |= MEM_Subtype;
75308}
75309SQLITE_API void SQLITE_STDCALL sqlite3_result_text(
75310  sqlite3_context *pCtx,
75311  const char *z,
75312  int n,
75313  void (*xDel)(void *)
75314){
75315  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75316  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
75317}
75318SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(
75319  sqlite3_context *pCtx,
75320  const char *z,
75321  sqlite3_uint64 n,
75322  void (*xDel)(void *),
75323  unsigned char enc
75324){
75325  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75326  assert( xDel!=SQLITE_DYNAMIC );
75327  if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
75328  if( n>0x7fffffff ){
75329    (void)invokeValueDestructor(z, xDel, pCtx);
75330  }else{
75331    setResultStrOrError(pCtx, z, (int)n, enc, xDel);
75332  }
75333}
75334#ifndef SQLITE_OMIT_UTF16
75335SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(
75336  sqlite3_context *pCtx,
75337  const void *z,
75338  int n,
75339  void (*xDel)(void *)
75340){
75341  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75342  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
75343}
75344SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(
75345  sqlite3_context *pCtx,
75346  const void *z,
75347  int n,
75348  void (*xDel)(void *)
75349){
75350  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75351  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
75352}
75353SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(
75354  sqlite3_context *pCtx,
75355  const void *z,
75356  int n,
75357  void (*xDel)(void *)
75358){
75359  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75360  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
75361}
75362#endif /* SQLITE_OMIT_UTF16 */
75363SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
75364  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75365  sqlite3VdbeMemCopy(pCtx->pOut, pValue);
75366}
75367SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
75368  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75369  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
75370}
75371SQLITE_API int SQLITE_STDCALL sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
75372  Mem *pOut = pCtx->pOut;
75373  assert( sqlite3_mutex_held(pOut->db->mutex) );
75374  if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
75375    return SQLITE_TOOBIG;
75376  }
75377  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
75378  return SQLITE_OK;
75379}
75380SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
75381  pCtx->isError = errCode;
75382  pCtx->fErrorOrAux = 1;
75383#ifdef SQLITE_DEBUG
75384  if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
75385#endif
75386  if( pCtx->pOut->flags & MEM_Null ){
75387    sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
75388                         SQLITE_UTF8, SQLITE_STATIC);
75389  }
75390}
75391
75392/* Force an SQLITE_TOOBIG error. */
75393SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context *pCtx){
75394  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75395  pCtx->isError = SQLITE_TOOBIG;
75396  pCtx->fErrorOrAux = 1;
75397  sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
75398                       SQLITE_UTF8, SQLITE_STATIC);
75399}
75400
75401/* An SQLITE_NOMEM error. */
75402SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context *pCtx){
75403  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75404  sqlite3VdbeMemSetNull(pCtx->pOut);
75405  pCtx->isError = SQLITE_NOMEM_BKPT;
75406  pCtx->fErrorOrAux = 1;
75407  sqlite3OomFault(pCtx->pOut->db);
75408}
75409
75410/*
75411** This function is called after a transaction has been committed. It
75412** invokes callbacks registered with sqlite3_wal_hook() as required.
75413*/
75414static int doWalCallbacks(sqlite3 *db){
75415  int rc = SQLITE_OK;
75416#ifndef SQLITE_OMIT_WAL
75417  int i;
75418  for(i=0; i<db->nDb; i++){
75419    Btree *pBt = db->aDb[i].pBt;
75420    if( pBt ){
75421      int nEntry;
75422      sqlite3BtreeEnter(pBt);
75423      nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
75424      sqlite3BtreeLeave(pBt);
75425      if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
75426        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
75427      }
75428    }
75429  }
75430#endif
75431  return rc;
75432}
75433
75434
75435/*
75436** Execute the statement pStmt, either until a row of data is ready, the
75437** statement is completely executed or an error occurs.
75438**
75439** This routine implements the bulk of the logic behind the sqlite_step()
75440** API.  The only thing omitted is the automatic recompile if a
75441** schema change has occurred.  That detail is handled by the
75442** outer sqlite3_step() wrapper procedure.
75443*/
75444static int sqlite3Step(Vdbe *p){
75445  sqlite3 *db;
75446  int rc;
75447
75448  assert(p);
75449  if( p->magic!=VDBE_MAGIC_RUN ){
75450    /* We used to require that sqlite3_reset() be called before retrying
75451    ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
75452    ** with version 3.7.0, we changed this so that sqlite3_reset() would
75453    ** be called automatically instead of throwing the SQLITE_MISUSE error.
75454    ** This "automatic-reset" change is not technically an incompatibility,
75455    ** since any application that receives an SQLITE_MISUSE is broken by
75456    ** definition.
75457    **
75458    ** Nevertheless, some published applications that were originally written
75459    ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
75460    ** returns, and those were broken by the automatic-reset change.  As a
75461    ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
75462    ** legacy behavior of returning SQLITE_MISUSE for cases where the
75463    ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
75464    ** or SQLITE_BUSY error.
75465    */
75466#ifdef SQLITE_OMIT_AUTORESET
75467    if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
75468      sqlite3_reset((sqlite3_stmt*)p);
75469    }else{
75470      return SQLITE_MISUSE_BKPT;
75471    }
75472#else
75473    sqlite3_reset((sqlite3_stmt*)p);
75474#endif
75475  }
75476
75477  /* Check that malloc() has not failed. If it has, return early. */
75478  db = p->db;
75479  if( db->mallocFailed ){
75480    p->rc = SQLITE_NOMEM;
75481    return SQLITE_NOMEM_BKPT;
75482  }
75483
75484  if( p->pc<=0 && p->expired ){
75485    p->rc = SQLITE_SCHEMA;
75486    rc = SQLITE_ERROR;
75487    goto end_of_step;
75488  }
75489  if( p->pc<0 ){
75490    /* If there are no other statements currently running, then
75491    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
75492    ** from interrupting a statement that has not yet started.
75493    */
75494    if( db->nVdbeActive==0 ){
75495      db->u1.isInterrupted = 0;
75496    }
75497
75498    assert( db->nVdbeWrite>0 || db->autoCommit==0
75499        || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
75500    );
75501
75502#ifndef SQLITE_OMIT_TRACE
75503    if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0)
75504        && !db->init.busy && p->zSql ){
75505      sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
75506    }else{
75507      assert( p->startTime==0 );
75508    }
75509#endif
75510
75511    db->nVdbeActive++;
75512    if( p->readOnly==0 ) db->nVdbeWrite++;
75513    if( p->bIsReader ) db->nVdbeRead++;
75514    p->pc = 0;
75515  }
75516#ifdef SQLITE_DEBUG
75517  p->rcApp = SQLITE_OK;
75518#endif
75519#ifndef SQLITE_OMIT_EXPLAIN
75520  if( p->explain ){
75521    rc = sqlite3VdbeList(p);
75522  }else
75523#endif /* SQLITE_OMIT_EXPLAIN */
75524  {
75525    db->nVdbeExec++;
75526    rc = sqlite3VdbeExec(p);
75527    db->nVdbeExec--;
75528  }
75529
75530#ifndef SQLITE_OMIT_TRACE
75531  /* If the statement completed successfully, invoke the profile callback */
75532  if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
75533#endif
75534
75535  if( rc==SQLITE_DONE ){
75536    assert( p->rc==SQLITE_OK );
75537    p->rc = doWalCallbacks(db);
75538    if( p->rc!=SQLITE_OK ){
75539      rc = SQLITE_ERROR;
75540    }
75541  }
75542
75543  db->errCode = rc;
75544  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
75545    p->rc = SQLITE_NOMEM_BKPT;
75546  }
75547end_of_step:
75548  /* At this point local variable rc holds the value that should be
75549  ** returned if this statement was compiled using the legacy
75550  ** sqlite3_prepare() interface. According to the docs, this can only
75551  ** be one of the values in the first assert() below. Variable p->rc
75552  ** contains the value that would be returned if sqlite3_finalize()
75553  ** were called on statement p.
75554  */
75555  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
75556       || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
75557  );
75558  assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
75559  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
75560    /* If this statement was prepared using sqlite3_prepare_v2(), and an
75561    ** error has occurred, then return the error code in p->rc to the
75562    ** caller. Set the error code in the database handle to the same value.
75563    */
75564    rc = sqlite3VdbeTransferError(p);
75565  }
75566  return (rc&db->errMask);
75567}
75568
75569/*
75570** This is the top-level implementation of sqlite3_step().  Call
75571** sqlite3Step() to do most of the work.  If a schema error occurs,
75572** call sqlite3Reprepare() and try again.
75573*/
75574SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt *pStmt){
75575  int rc = SQLITE_OK;      /* Result from sqlite3Step() */
75576  int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
75577  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
75578  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
75579  sqlite3 *db;             /* The database connection */
75580
75581  if( vdbeSafetyNotNull(v) ){
75582    return SQLITE_MISUSE_BKPT;
75583  }
75584  db = v->db;
75585  sqlite3_mutex_enter(db->mutex);
75586  v->doingRerun = 0;
75587  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
75588         && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
75589    int savedPc = v->pc;
75590    rc2 = rc = sqlite3Reprepare(v);
75591    if( rc!=SQLITE_OK) break;
75592    sqlite3_reset(pStmt);
75593    if( savedPc>=0 ) v->doingRerun = 1;
75594    assert( v->expired==0 );
75595  }
75596  if( rc2!=SQLITE_OK ){
75597    /* This case occurs after failing to recompile an sql statement.
75598    ** The error message from the SQL compiler has already been loaded
75599    ** into the database handle. This block copies the error message
75600    ** from the database handle into the statement and sets the statement
75601    ** program counter to 0 to ensure that when the statement is
75602    ** finalized or reset the parser error message is available via
75603    ** sqlite3_errmsg() and sqlite3_errcode().
75604    */
75605    const char *zErr = (const char *)sqlite3_value_text(db->pErr);
75606    sqlite3DbFree(db, v->zErrMsg);
75607    if( !db->mallocFailed ){
75608      v->zErrMsg = sqlite3DbStrDup(db, zErr);
75609      v->rc = rc2;
75610    } else {
75611      v->zErrMsg = 0;
75612      v->rc = rc = SQLITE_NOMEM_BKPT;
75613    }
75614  }
75615  rc = sqlite3ApiExit(db, rc);
75616  sqlite3_mutex_leave(db->mutex);
75617  return rc;
75618}
75619
75620
75621/*
75622** Extract the user data from a sqlite3_context structure and return a
75623** pointer to it.
75624*/
75625SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context *p){
75626  assert( p && p->pFunc );
75627  return p->pFunc->pUserData;
75628}
75629
75630/*
75631** Extract the user data from a sqlite3_context structure and return a
75632** pointer to it.
75633**
75634** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
75635** returns a copy of the pointer to the database connection (the 1st
75636** parameter) of the sqlite3_create_function() and
75637** sqlite3_create_function16() routines that originally registered the
75638** application defined function.
75639*/
75640SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context *p){
75641  assert( p && p->pOut );
75642  return p->pOut->db;
75643}
75644
75645/*
75646** Return the current time for a statement.  If the current time
75647** is requested more than once within the same run of a single prepared
75648** statement, the exact same time is returned for each invocation regardless
75649** of the amount of time that elapses between invocations.  In other words,
75650** the time returned is always the time of the first call.
75651*/
75652SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
75653  int rc;
75654#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
75655  sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
75656  assert( p->pVdbe!=0 );
75657#else
75658  sqlite3_int64 iTime = 0;
75659  sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
75660#endif
75661  if( *piTime==0 ){
75662    rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
75663    if( rc ) *piTime = 0;
75664  }
75665  return *piTime;
75666}
75667
75668/*
75669** The following is the implementation of an SQL function that always
75670** fails with an error message stating that the function is used in the
75671** wrong context.  The sqlite3_overload_function() API might construct
75672** SQL function that use this routine so that the functions will exist
75673** for name resolution but are actually overloaded by the xFindFunction
75674** method of virtual tables.
75675*/
75676SQLITE_PRIVATE void sqlite3InvalidFunction(
75677  sqlite3_context *context,  /* The function calling context */
75678  int NotUsed,               /* Number of arguments to the function */
75679  sqlite3_value **NotUsed2   /* Value of each argument */
75680){
75681  const char *zName = context->pFunc->zName;
75682  char *zErr;
75683  UNUSED_PARAMETER2(NotUsed, NotUsed2);
75684  zErr = sqlite3_mprintf(
75685      "unable to use function %s in the requested context", zName);
75686  sqlite3_result_error(context, zErr, -1);
75687  sqlite3_free(zErr);
75688}
75689
75690/*
75691** Create a new aggregate context for p and return a pointer to
75692** its pMem->z element.
75693*/
75694static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
75695  Mem *pMem = p->pMem;
75696  assert( (pMem->flags & MEM_Agg)==0 );
75697  if( nByte<=0 ){
75698    sqlite3VdbeMemSetNull(pMem);
75699    pMem->z = 0;
75700  }else{
75701    sqlite3VdbeMemClearAndResize(pMem, nByte);
75702    pMem->flags = MEM_Agg;
75703    pMem->u.pDef = p->pFunc;
75704    if( pMem->z ){
75705      memset(pMem->z, 0, nByte);
75706    }
75707  }
75708  return (void*)pMem->z;
75709}
75710
75711/*
75712** Allocate or return the aggregate context for a user function.  A new
75713** context is allocated on the first call.  Subsequent calls return the
75714** same context that was returned on prior calls.
75715*/
75716SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context *p, int nByte){
75717  assert( p && p->pFunc && p->pFunc->xFinalize );
75718  assert( sqlite3_mutex_held(p->pOut->db->mutex) );
75719  testcase( nByte<0 );
75720  if( (p->pMem->flags & MEM_Agg)==0 ){
75721    return createAggContext(p, nByte);
75722  }else{
75723    return (void*)p->pMem->z;
75724  }
75725}
75726
75727/*
75728** Return the auxiliary data pointer, if any, for the iArg'th argument to
75729** the user-function defined by pCtx.
75730*/
75731SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
75732  AuxData *pAuxData;
75733
75734  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75735#if SQLITE_ENABLE_STAT3_OR_STAT4
75736  if( pCtx->pVdbe==0 ) return 0;
75737#else
75738  assert( pCtx->pVdbe!=0 );
75739#endif
75740  for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
75741    if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
75742  }
75743
75744  return (pAuxData ? pAuxData->pAux : 0);
75745}
75746
75747/*
75748** Set the auxiliary data pointer and delete function, for the iArg'th
75749** argument to the user-function defined by pCtx. Any previous value is
75750** deleted by calling the delete function specified when it was set.
75751*/
75752SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(
75753  sqlite3_context *pCtx,
75754  int iArg,
75755  void *pAux,
75756  void (*xDelete)(void*)
75757){
75758  AuxData *pAuxData;
75759  Vdbe *pVdbe = pCtx->pVdbe;
75760
75761  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75762  if( iArg<0 ) goto failed;
75763#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
75764  if( pVdbe==0 ) goto failed;
75765#else
75766  assert( pVdbe!=0 );
75767#endif
75768
75769  for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
75770    if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
75771  }
75772  if( pAuxData==0 ){
75773    pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
75774    if( !pAuxData ) goto failed;
75775    pAuxData->iOp = pCtx->iOp;
75776    pAuxData->iArg = iArg;
75777    pAuxData->pNext = pVdbe->pAuxData;
75778    pVdbe->pAuxData = pAuxData;
75779    if( pCtx->fErrorOrAux==0 ){
75780      pCtx->isError = 0;
75781      pCtx->fErrorOrAux = 1;
75782    }
75783  }else if( pAuxData->xDelete ){
75784    pAuxData->xDelete(pAuxData->pAux);
75785  }
75786
75787  pAuxData->pAux = pAux;
75788  pAuxData->xDelete = xDelete;
75789  return;
75790
75791failed:
75792  if( xDelete ){
75793    xDelete(pAux);
75794  }
75795}
75796
75797#ifndef SQLITE_OMIT_DEPRECATED
75798/*
75799** Return the number of times the Step function of an aggregate has been
75800** called.
75801**
75802** This function is deprecated.  Do not use it for new code.  It is
75803** provide only to avoid breaking legacy code.  New aggregate function
75804** implementations should keep their own counts within their aggregate
75805** context.
75806*/
75807SQLITE_API int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context *p){
75808  assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
75809  return p->pMem->n;
75810}
75811#endif
75812
75813/*
75814** Return the number of columns in the result set for the statement pStmt.
75815*/
75816SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt){
75817  Vdbe *pVm = (Vdbe *)pStmt;
75818  return pVm ? pVm->nResColumn : 0;
75819}
75820
75821/*
75822** Return the number of values available from the current row of the
75823** currently executing statement pStmt.
75824*/
75825SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt){
75826  Vdbe *pVm = (Vdbe *)pStmt;
75827  if( pVm==0 || pVm->pResultSet==0 ) return 0;
75828  return pVm->nResColumn;
75829}
75830
75831/*
75832** Return a pointer to static memory containing an SQL NULL value.
75833*/
75834static const Mem *columnNullValue(void){
75835  /* Even though the Mem structure contains an element
75836  ** of type i64, on certain architectures (x86) with certain compiler
75837  ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
75838  ** instead of an 8-byte one. This all works fine, except that when
75839  ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
75840  ** that a Mem structure is located on an 8-byte boundary. To prevent
75841  ** these assert()s from failing, when building with SQLITE_DEBUG defined
75842  ** using gcc, we force nullMem to be 8-byte aligned using the magical
75843  ** __attribute__((aligned(8))) macro.  */
75844  static const Mem nullMem
75845#if defined(SQLITE_DEBUG) && defined(__GNUC__)
75846    __attribute__((aligned(8)))
75847#endif
75848    = {
75849        /* .u          = */ {0},
75850        /* .flags      = */ (u16)MEM_Null,
75851        /* .enc        = */ (u8)0,
75852        /* .eSubtype   = */ (u8)0,
75853        /* .n          = */ (int)0,
75854        /* .z          = */ (char*)0,
75855        /* .zMalloc    = */ (char*)0,
75856        /* .szMalloc   = */ (int)0,
75857        /* .uTemp      = */ (u32)0,
75858        /* .db         = */ (sqlite3*)0,
75859        /* .xDel       = */ (void(*)(void*))0,
75860#ifdef SQLITE_DEBUG
75861        /* .pScopyFrom = */ (Mem*)0,
75862        /* .pFiller    = */ (void*)0,
75863#endif
75864      };
75865  return &nullMem;
75866}
75867
75868/*
75869** Check to see if column iCol of the given statement is valid.  If
75870** it is, return a pointer to the Mem for the value of that column.
75871** If iCol is not valid, return a pointer to a Mem which has a value
75872** of NULL.
75873*/
75874static Mem *columnMem(sqlite3_stmt *pStmt, int i){
75875  Vdbe *pVm;
75876  Mem *pOut;
75877
75878  pVm = (Vdbe *)pStmt;
75879  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
75880    sqlite3_mutex_enter(pVm->db->mutex);
75881    pOut = &pVm->pResultSet[i];
75882  }else{
75883    if( pVm && ALWAYS(pVm->db) ){
75884      sqlite3_mutex_enter(pVm->db->mutex);
75885      sqlite3Error(pVm->db, SQLITE_RANGE);
75886    }
75887    pOut = (Mem*)columnNullValue();
75888  }
75889  return pOut;
75890}
75891
75892/*
75893** This function is called after invoking an sqlite3_value_XXX function on a
75894** column value (i.e. a value returned by evaluating an SQL expression in the
75895** select list of a SELECT statement) that may cause a malloc() failure. If
75896** malloc() has failed, the threads mallocFailed flag is cleared and the result
75897** code of statement pStmt set to SQLITE_NOMEM.
75898**
75899** Specifically, this is called from within:
75900**
75901**     sqlite3_column_int()
75902**     sqlite3_column_int64()
75903**     sqlite3_column_text()
75904**     sqlite3_column_text16()
75905**     sqlite3_column_real()
75906**     sqlite3_column_bytes()
75907**     sqlite3_column_bytes16()
75908**     sqiite3_column_blob()
75909*/
75910static void columnMallocFailure(sqlite3_stmt *pStmt)
75911{
75912  /* If malloc() failed during an encoding conversion within an
75913  ** sqlite3_column_XXX API, then set the return code of the statement to
75914  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
75915  ** and _finalize() will return NOMEM.
75916  */
75917  Vdbe *p = (Vdbe *)pStmt;
75918  if( p ){
75919    p->rc = sqlite3ApiExit(p->db, p->rc);
75920    sqlite3_mutex_leave(p->db->mutex);
75921  }
75922}
75923
75924/**************************** sqlite3_column_  *******************************
75925** The following routines are used to access elements of the current row
75926** in the result set.
75927*/
75928SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
75929  const void *val;
75930  val = sqlite3_value_blob( columnMem(pStmt,i) );
75931  /* Even though there is no encoding conversion, value_blob() might
75932  ** need to call malloc() to expand the result of a zeroblob()
75933  ** expression.
75934  */
75935  columnMallocFailure(pStmt);
75936  return val;
75937}
75938SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
75939  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
75940  columnMallocFailure(pStmt);
75941  return val;
75942}
75943SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
75944  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
75945  columnMallocFailure(pStmt);
75946  return val;
75947}
75948SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt *pStmt, int i){
75949  double val = sqlite3_value_double( columnMem(pStmt,i) );
75950  columnMallocFailure(pStmt);
75951  return val;
75952}
75953SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt *pStmt, int i){
75954  int val = sqlite3_value_int( columnMem(pStmt,i) );
75955  columnMallocFailure(pStmt);
75956  return val;
75957}
75958SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
75959  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
75960  columnMallocFailure(pStmt);
75961  return val;
75962}
75963SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt *pStmt, int i){
75964  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
75965  columnMallocFailure(pStmt);
75966  return val;
75967}
75968SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt *pStmt, int i){
75969  Mem *pOut = columnMem(pStmt, i);
75970  if( pOut->flags&MEM_Static ){
75971    pOut->flags &= ~MEM_Static;
75972    pOut->flags |= MEM_Ephem;
75973  }
75974  columnMallocFailure(pStmt);
75975  return (sqlite3_value *)pOut;
75976}
75977#ifndef SQLITE_OMIT_UTF16
75978SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
75979  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
75980  columnMallocFailure(pStmt);
75981  return val;
75982}
75983#endif /* SQLITE_OMIT_UTF16 */
75984SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt *pStmt, int i){
75985  int iType = sqlite3_value_type( columnMem(pStmt,i) );
75986  columnMallocFailure(pStmt);
75987  return iType;
75988}
75989
75990/*
75991** Convert the N-th element of pStmt->pColName[] into a string using
75992** xFunc() then return that string.  If N is out of range, return 0.
75993**
75994** There are up to 5 names for each column.  useType determines which
75995** name is returned.  Here are the names:
75996**
75997**    0      The column name as it should be displayed for output
75998**    1      The datatype name for the column
75999**    2      The name of the database that the column derives from
76000**    3      The name of the table that the column derives from
76001**    4      The name of the table column that the result column derives from
76002**
76003** If the result is not a simple column reference (if it is an expression
76004** or a constant) then useTypes 2, 3, and 4 return NULL.
76005*/
76006static const void *columnName(
76007  sqlite3_stmt *pStmt,
76008  int N,
76009  const void *(*xFunc)(Mem*),
76010  int useType
76011){
76012  const void *ret;
76013  Vdbe *p;
76014  int n;
76015  sqlite3 *db;
76016#ifdef SQLITE_ENABLE_API_ARMOR
76017  if( pStmt==0 ){
76018    (void)SQLITE_MISUSE_BKPT;
76019    return 0;
76020  }
76021#endif
76022  ret = 0;
76023  p = (Vdbe *)pStmt;
76024  db = p->db;
76025  assert( db!=0 );
76026  n = sqlite3_column_count(pStmt);
76027  if( N<n && N>=0 ){
76028    N += useType*n;
76029    sqlite3_mutex_enter(db->mutex);
76030    assert( db->mallocFailed==0 );
76031    ret = xFunc(&p->aColName[N]);
76032     /* A malloc may have failed inside of the xFunc() call. If this
76033    ** is the case, clear the mallocFailed flag and return NULL.
76034    */
76035    if( db->mallocFailed ){
76036      sqlite3OomClear(db);
76037      ret = 0;
76038    }
76039    sqlite3_mutex_leave(db->mutex);
76040  }
76041  return ret;
76042}
76043
76044/*
76045** Return the name of the Nth column of the result set returned by SQL
76046** statement pStmt.
76047*/
76048SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt *pStmt, int N){
76049  return columnName(
76050      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
76051}
76052#ifndef SQLITE_OMIT_UTF16
76053SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
76054  return columnName(
76055      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
76056}
76057#endif
76058
76059/*
76060** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
76061** not define OMIT_DECLTYPE.
76062*/
76063#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
76064# error "Must not define both SQLITE_OMIT_DECLTYPE \
76065         and SQLITE_ENABLE_COLUMN_METADATA"
76066#endif
76067
76068#ifndef SQLITE_OMIT_DECLTYPE
76069/*
76070** Return the column declaration type (if applicable) of the 'i'th column
76071** of the result set of SQL statement pStmt.
76072*/
76073SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
76074  return columnName(
76075      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
76076}
76077#ifndef SQLITE_OMIT_UTF16
76078SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
76079  return columnName(
76080      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
76081}
76082#endif /* SQLITE_OMIT_UTF16 */
76083#endif /* SQLITE_OMIT_DECLTYPE */
76084
76085#ifdef SQLITE_ENABLE_COLUMN_METADATA
76086/*
76087** Return the name of the database from which a result column derives.
76088** NULL is returned if the result column is an expression or constant or
76089** anything else which is not an unambiguous reference to a database column.
76090*/
76091SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
76092  return columnName(
76093      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
76094}
76095#ifndef SQLITE_OMIT_UTF16
76096SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
76097  return columnName(
76098      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
76099}
76100#endif /* SQLITE_OMIT_UTF16 */
76101
76102/*
76103** Return the name of the table from which a result column derives.
76104** NULL is returned if the result column is an expression or constant or
76105** anything else which is not an unambiguous reference to a database column.
76106*/
76107SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
76108  return columnName(
76109      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
76110}
76111#ifndef SQLITE_OMIT_UTF16
76112SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
76113  return columnName(
76114      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
76115}
76116#endif /* SQLITE_OMIT_UTF16 */
76117
76118/*
76119** Return the name of the table column from which a result column derives.
76120** NULL is returned if the result column is an expression or constant or
76121** anything else which is not an unambiguous reference to a database column.
76122*/
76123SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
76124  return columnName(
76125      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
76126}
76127#ifndef SQLITE_OMIT_UTF16
76128SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
76129  return columnName(
76130      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
76131}
76132#endif /* SQLITE_OMIT_UTF16 */
76133#endif /* SQLITE_ENABLE_COLUMN_METADATA */
76134
76135
76136/******************************* sqlite3_bind_  ***************************
76137**
76138** Routines used to attach values to wildcards in a compiled SQL statement.
76139*/
76140/*
76141** Unbind the value bound to variable i in virtual machine p. This is the
76142** the same as binding a NULL value to the column. If the "i" parameter is
76143** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
76144**
76145** A successful evaluation of this routine acquires the mutex on p.
76146** the mutex is released if any kind of error occurs.
76147**
76148** The error code stored in database p->db is overwritten with the return
76149** value in any case.
76150*/
76151static int vdbeUnbind(Vdbe *p, int i){
76152  Mem *pVar;
76153  if( vdbeSafetyNotNull(p) ){
76154    return SQLITE_MISUSE_BKPT;
76155  }
76156  sqlite3_mutex_enter(p->db->mutex);
76157  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
76158    sqlite3Error(p->db, SQLITE_MISUSE);
76159    sqlite3_mutex_leave(p->db->mutex);
76160    sqlite3_log(SQLITE_MISUSE,
76161        "bind on a busy prepared statement: [%s]", p->zSql);
76162    return SQLITE_MISUSE_BKPT;
76163  }
76164  if( i<1 || i>p->nVar ){
76165    sqlite3Error(p->db, SQLITE_RANGE);
76166    sqlite3_mutex_leave(p->db->mutex);
76167    return SQLITE_RANGE;
76168  }
76169  i--;
76170  pVar = &p->aVar[i];
76171  sqlite3VdbeMemRelease(pVar);
76172  pVar->flags = MEM_Null;
76173  sqlite3Error(p->db, SQLITE_OK);
76174
76175  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
76176  ** binding a new value to this variable invalidates the current query plan.
76177  **
76178  ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
76179  ** parameter in the WHERE clause might influence the choice of query plan
76180  ** for a statement, then the statement will be automatically recompiled,
76181  ** as if there had been a schema change, on the first sqlite3_step() call
76182  ** following any change to the bindings of that parameter.
76183  */
76184  if( p->isPrepareV2 &&
76185     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
76186  ){
76187    p->expired = 1;
76188  }
76189  return SQLITE_OK;
76190}
76191
76192/*
76193** Bind a text or BLOB value.
76194*/
76195static int bindText(
76196  sqlite3_stmt *pStmt,   /* The statement to bind against */
76197  int i,                 /* Index of the parameter to bind */
76198  const void *zData,     /* Pointer to the data to be bound */
76199  int nData,             /* Number of bytes of data to be bound */
76200  void (*xDel)(void*),   /* Destructor for the data */
76201  u8 encoding            /* Encoding for the data */
76202){
76203  Vdbe *p = (Vdbe *)pStmt;
76204  Mem *pVar;
76205  int rc;
76206
76207  rc = vdbeUnbind(p, i);
76208  if( rc==SQLITE_OK ){
76209    if( zData!=0 ){
76210      pVar = &p->aVar[i-1];
76211      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
76212      if( rc==SQLITE_OK && encoding!=0 ){
76213        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
76214      }
76215      sqlite3Error(p->db, rc);
76216      rc = sqlite3ApiExit(p->db, rc);
76217    }
76218    sqlite3_mutex_leave(p->db->mutex);
76219  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
76220    xDel((void*)zData);
76221  }
76222  return rc;
76223}
76224
76225
76226/*
76227** Bind a blob value to an SQL statement variable.
76228*/
76229SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(
76230  sqlite3_stmt *pStmt,
76231  int i,
76232  const void *zData,
76233  int nData,
76234  void (*xDel)(void*)
76235){
76236#ifdef SQLITE_ENABLE_API_ARMOR
76237  if( nData<0 ) return SQLITE_MISUSE_BKPT;
76238#endif
76239  return bindText(pStmt, i, zData, nData, xDel, 0);
76240}
76241SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(
76242  sqlite3_stmt *pStmt,
76243  int i,
76244  const void *zData,
76245  sqlite3_uint64 nData,
76246  void (*xDel)(void*)
76247){
76248  assert( xDel!=SQLITE_DYNAMIC );
76249  if( nData>0x7fffffff ){
76250    return invokeValueDestructor(zData, xDel, 0);
76251  }else{
76252    return bindText(pStmt, i, zData, (int)nData, xDel, 0);
76253  }
76254}
76255SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
76256  int rc;
76257  Vdbe *p = (Vdbe *)pStmt;
76258  rc = vdbeUnbind(p, i);
76259  if( rc==SQLITE_OK ){
76260    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
76261    sqlite3_mutex_leave(p->db->mutex);
76262  }
76263  return rc;
76264}
76265SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
76266  return sqlite3_bind_int64(p, i, (i64)iValue);
76267}
76268SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
76269  int rc;
76270  Vdbe *p = (Vdbe *)pStmt;
76271  rc = vdbeUnbind(p, i);
76272  if( rc==SQLITE_OK ){
76273    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
76274    sqlite3_mutex_leave(p->db->mutex);
76275  }
76276  return rc;
76277}
76278SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
76279  int rc;
76280  Vdbe *p = (Vdbe*)pStmt;
76281  rc = vdbeUnbind(p, i);
76282  if( rc==SQLITE_OK ){
76283    sqlite3_mutex_leave(p->db->mutex);
76284  }
76285  return rc;
76286}
76287SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(
76288  sqlite3_stmt *pStmt,
76289  int i,
76290  const char *zData,
76291  int nData,
76292  void (*xDel)(void*)
76293){
76294  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
76295}
76296SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(
76297  sqlite3_stmt *pStmt,
76298  int i,
76299  const char *zData,
76300  sqlite3_uint64 nData,
76301  void (*xDel)(void*),
76302  unsigned char enc
76303){
76304  assert( xDel!=SQLITE_DYNAMIC );
76305  if( nData>0x7fffffff ){
76306    return invokeValueDestructor(zData, xDel, 0);
76307  }else{
76308    if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
76309    return bindText(pStmt, i, zData, (int)nData, xDel, enc);
76310  }
76311}
76312#ifndef SQLITE_OMIT_UTF16
76313SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(
76314  sqlite3_stmt *pStmt,
76315  int i,
76316  const void *zData,
76317  int nData,
76318  void (*xDel)(void*)
76319){
76320  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
76321}
76322#endif /* SQLITE_OMIT_UTF16 */
76323SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
76324  int rc;
76325  switch( sqlite3_value_type((sqlite3_value*)pValue) ){
76326    case SQLITE_INTEGER: {
76327      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
76328      break;
76329    }
76330    case SQLITE_FLOAT: {
76331      rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
76332      break;
76333    }
76334    case SQLITE_BLOB: {
76335      if( pValue->flags & MEM_Zero ){
76336        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
76337      }else{
76338        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
76339      }
76340      break;
76341    }
76342    case SQLITE_TEXT: {
76343      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
76344                              pValue->enc);
76345      break;
76346    }
76347    default: {
76348      rc = sqlite3_bind_null(pStmt, i);
76349      break;
76350    }
76351  }
76352  return rc;
76353}
76354SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
76355  int rc;
76356  Vdbe *p = (Vdbe *)pStmt;
76357  rc = vdbeUnbind(p, i);
76358  if( rc==SQLITE_OK ){
76359    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
76360    sqlite3_mutex_leave(p->db->mutex);
76361  }
76362  return rc;
76363}
76364SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
76365  int rc;
76366  Vdbe *p = (Vdbe *)pStmt;
76367  sqlite3_mutex_enter(p->db->mutex);
76368  if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
76369    rc = SQLITE_TOOBIG;
76370  }else{
76371    assert( (n & 0x7FFFFFFF)==n );
76372    rc = sqlite3_bind_zeroblob(pStmt, i, n);
76373  }
76374  rc = sqlite3ApiExit(p->db, rc);
76375  sqlite3_mutex_leave(p->db->mutex);
76376  return rc;
76377}
76378
76379/*
76380** Return the number of wildcards that can be potentially bound to.
76381** This routine is added to support DBD::SQLite.
76382*/
76383SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
76384  Vdbe *p = (Vdbe*)pStmt;
76385  return p ? p->nVar : 0;
76386}
76387
76388/*
76389** Return the name of a wildcard parameter.  Return NULL if the index
76390** is out of range or if the wildcard is unnamed.
76391**
76392** The result is always UTF-8.
76393*/
76394SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
76395  Vdbe *p = (Vdbe*)pStmt;
76396  if( p==0 || i<1 || i>p->nzVar ){
76397    return 0;
76398  }
76399  return p->azVar[i-1];
76400}
76401
76402/*
76403** Given a wildcard parameter name, return the index of the variable
76404** with that name.  If there is no variable with the given name,
76405** return 0.
76406*/
76407SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
76408  int i;
76409  if( p==0 ){
76410    return 0;
76411  }
76412  if( zName ){
76413    for(i=0; i<p->nzVar; i++){
76414      const char *z = p->azVar[i];
76415      if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
76416        return i+1;
76417      }
76418    }
76419  }
76420  return 0;
76421}
76422SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
76423  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
76424}
76425
76426/*
76427** Transfer all bindings from the first statement over to the second.
76428*/
76429SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
76430  Vdbe *pFrom = (Vdbe*)pFromStmt;
76431  Vdbe *pTo = (Vdbe*)pToStmt;
76432  int i;
76433  assert( pTo->db==pFrom->db );
76434  assert( pTo->nVar==pFrom->nVar );
76435  sqlite3_mutex_enter(pTo->db->mutex);
76436  for(i=0; i<pFrom->nVar; i++){
76437    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
76438  }
76439  sqlite3_mutex_leave(pTo->db->mutex);
76440  return SQLITE_OK;
76441}
76442
76443#ifndef SQLITE_OMIT_DEPRECATED
76444/*
76445** Deprecated external interface.  Internal/core SQLite code
76446** should call sqlite3TransferBindings.
76447**
76448** It is misuse to call this routine with statements from different
76449** database connections.  But as this is a deprecated interface, we
76450** will not bother to check for that condition.
76451**
76452** If the two statements contain a different number of bindings, then
76453** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
76454** SQLITE_OK is returned.
76455*/
76456SQLITE_API int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
76457  Vdbe *pFrom = (Vdbe*)pFromStmt;
76458  Vdbe *pTo = (Vdbe*)pToStmt;
76459  if( pFrom->nVar!=pTo->nVar ){
76460    return SQLITE_ERROR;
76461  }
76462  if( pTo->isPrepareV2 && pTo->expmask ){
76463    pTo->expired = 1;
76464  }
76465  if( pFrom->isPrepareV2 && pFrom->expmask ){
76466    pFrom->expired = 1;
76467  }
76468  return sqlite3TransferBindings(pFromStmt, pToStmt);
76469}
76470#endif
76471
76472/*
76473** Return the sqlite3* database handle to which the prepared statement given
76474** in the argument belongs.  This is the same database handle that was
76475** the first argument to the sqlite3_prepare() that was used to create
76476** the statement in the first place.
76477*/
76478SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt *pStmt){
76479  return pStmt ? ((Vdbe*)pStmt)->db : 0;
76480}
76481
76482/*
76483** Return true if the prepared statement is guaranteed to not modify the
76484** database.
76485*/
76486SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
76487  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
76488}
76489
76490/*
76491** Return true if the prepared statement is in need of being reset.
76492*/
76493SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt *pStmt){
76494  Vdbe *v = (Vdbe*)pStmt;
76495  return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
76496}
76497
76498/*
76499** Return a pointer to the next prepared statement after pStmt associated
76500** with database connection pDb.  If pStmt is NULL, return the first
76501** prepared statement for the database connection.  Return NULL if there
76502** are no more.
76503*/
76504SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
76505  sqlite3_stmt *pNext;
76506#ifdef SQLITE_ENABLE_API_ARMOR
76507  if( !sqlite3SafetyCheckOk(pDb) ){
76508    (void)SQLITE_MISUSE_BKPT;
76509    return 0;
76510  }
76511#endif
76512  sqlite3_mutex_enter(pDb->mutex);
76513  if( pStmt==0 ){
76514    pNext = (sqlite3_stmt*)pDb->pVdbe;
76515  }else{
76516    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
76517  }
76518  sqlite3_mutex_leave(pDb->mutex);
76519  return pNext;
76520}
76521
76522/*
76523** Return the value of a status counter for a prepared statement
76524*/
76525SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
76526  Vdbe *pVdbe = (Vdbe*)pStmt;
76527  u32 v;
76528#ifdef SQLITE_ENABLE_API_ARMOR
76529  if( !pStmt ){
76530    (void)SQLITE_MISUSE_BKPT;
76531    return 0;
76532  }
76533#endif
76534  v = pVdbe->aCounter[op];
76535  if( resetFlag ) pVdbe->aCounter[op] = 0;
76536  return (int)v;
76537}
76538
76539/*
76540** Return the SQL associated with a prepared statement
76541*/
76542SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt){
76543  Vdbe *p = (Vdbe *)pStmt;
76544  return p ? p->zSql : 0;
76545}
76546
76547/*
76548** Return the SQL associated with a prepared statement with
76549** bound parameters expanded.  Space to hold the returned string is
76550** obtained from sqlite3_malloc().  The caller is responsible for
76551** freeing the returned string by passing it to sqlite3_free().
76552**
76553** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
76554** expanded bound parameters.
76555*/
76556SQLITE_API char *SQLITE_STDCALL sqlite3_expanded_sql(sqlite3_stmt *pStmt){
76557#ifdef SQLITE_OMIT_TRACE
76558  return 0;
76559#else
76560  char *z = 0;
76561  const char *zSql = sqlite3_sql(pStmt);
76562  if( zSql ){
76563    Vdbe *p = (Vdbe *)pStmt;
76564    sqlite3_mutex_enter(p->db->mutex);
76565    z = sqlite3VdbeExpandSql(p, zSql);
76566    sqlite3_mutex_leave(p->db->mutex);
76567  }
76568  return z;
76569#endif
76570}
76571
76572#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76573/*
76574** Allocate and populate an UnpackedRecord structure based on the serialized
76575** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
76576** if successful, or a NULL pointer if an OOM error is encountered.
76577*/
76578static UnpackedRecord *vdbeUnpackRecord(
76579  KeyInfo *pKeyInfo,
76580  int nKey,
76581  const void *pKey
76582){
76583  char *dummy;                    /* Dummy argument for AllocUnpackedRecord() */
76584  UnpackedRecord *pRet;           /* Return value */
76585
76586  pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo, 0, 0, &dummy);
76587  if( pRet ){
76588    memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nField+1));
76589    sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
76590  }
76591  return pRet;
76592}
76593
76594/*
76595** This function is called from within a pre-update callback to retrieve
76596** a field of the row currently being updated or deleted.
76597*/
76598SQLITE_API int SQLITE_STDCALL sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
76599  PreUpdate *p = db->pPreUpdate;
76600  int rc = SQLITE_OK;
76601
76602  /* Test that this call is being made from within an SQLITE_DELETE or
76603  ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
76604  if( !p || p->op==SQLITE_INSERT ){
76605    rc = SQLITE_MISUSE_BKPT;
76606    goto preupdate_old_out;
76607  }
76608  if( iIdx>=p->pCsr->nField || iIdx<0 ){
76609    rc = SQLITE_RANGE;
76610    goto preupdate_old_out;
76611  }
76612
76613  /* If the old.* record has not yet been loaded into memory, do so now. */
76614  if( p->pUnpacked==0 ){
76615    u32 nRec;
76616    u8 *aRec;
76617
76618    nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
76619    aRec = sqlite3DbMallocRaw(db, nRec);
76620    if( !aRec ) goto preupdate_old_out;
76621    rc = sqlite3BtreeData(p->pCsr->uc.pCursor, 0, nRec, aRec);
76622    if( rc==SQLITE_OK ){
76623      p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
76624      if( !p->pUnpacked ) rc = SQLITE_NOMEM;
76625    }
76626    if( rc!=SQLITE_OK ){
76627      sqlite3DbFree(db, aRec);
76628      goto preupdate_old_out;
76629    }
76630    p->aRecord = aRec;
76631  }
76632
76633  if( iIdx>=p->pUnpacked->nField ){
76634    *ppValue = (sqlite3_value *)columnNullValue();
76635  }else{
76636    *ppValue = &p->pUnpacked->aMem[iIdx];
76637    if( iIdx==p->iPKey ){
76638      sqlite3VdbeMemSetInt64(*ppValue, p->iKey1);
76639    }
76640  }
76641
76642 preupdate_old_out:
76643  sqlite3Error(db, rc);
76644  return sqlite3ApiExit(db, rc);
76645}
76646#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76647
76648#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76649/*
76650** This function is called from within a pre-update callback to retrieve
76651** the number of columns in the row being updated, deleted or inserted.
76652*/
76653SQLITE_API int SQLITE_STDCALL sqlite3_preupdate_count(sqlite3 *db){
76654  PreUpdate *p = db->pPreUpdate;
76655  return (p ? p->keyinfo.nField : 0);
76656}
76657#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76658
76659#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76660/*
76661** This function is designed to be called from within a pre-update callback
76662** only. It returns zero if the change that caused the callback was made
76663** immediately by a user SQL statement. Or, if the change was made by a
76664** trigger program, it returns the number of trigger programs currently
76665** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
76666** top-level trigger etc.).
76667**
76668** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
76669** or SET DEFAULT action is considered a trigger.
76670*/
76671SQLITE_API int SQLITE_STDCALL sqlite3_preupdate_depth(sqlite3 *db){
76672  PreUpdate *p = db->pPreUpdate;
76673  return (p ? p->v->nFrame : 0);
76674}
76675#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76676
76677#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76678/*
76679** This function is called from within a pre-update callback to retrieve
76680** a field of the row currently being updated or inserted.
76681*/
76682SQLITE_API int SQLITE_STDCALL sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
76683  PreUpdate *p = db->pPreUpdate;
76684  int rc = SQLITE_OK;
76685  Mem *pMem;
76686
76687  if( !p || p->op==SQLITE_DELETE ){
76688    rc = SQLITE_MISUSE_BKPT;
76689    goto preupdate_new_out;
76690  }
76691  if( iIdx>=p->pCsr->nField || iIdx<0 ){
76692    rc = SQLITE_RANGE;
76693    goto preupdate_new_out;
76694  }
76695
76696  if( p->op==SQLITE_INSERT ){
76697    /* For an INSERT, memory cell p->iNewReg contains the serialized record
76698    ** that is being inserted. Deserialize it. */
76699    UnpackedRecord *pUnpack = p->pNewUnpacked;
76700    if( !pUnpack ){
76701      Mem *pData = &p->v->aMem[p->iNewReg];
76702      rc = sqlite3VdbeMemExpandBlob(pData);
76703      if( rc!=SQLITE_OK ) goto preupdate_new_out;
76704      pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
76705      if( !pUnpack ){
76706        rc = SQLITE_NOMEM;
76707        goto preupdate_new_out;
76708      }
76709      p->pNewUnpacked = pUnpack;
76710    }
76711    if( iIdx>=pUnpack->nField ){
76712      pMem = (sqlite3_value *)columnNullValue();
76713    }else{
76714      pMem = &pUnpack->aMem[iIdx];
76715      if( iIdx==p->iPKey ){
76716        sqlite3VdbeMemSetInt64(pMem, p->iKey2);
76717      }
76718    }
76719  }else{
76720    /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
76721    ** value. Make a copy of the cell contents and return a pointer to it.
76722    ** It is not safe to return a pointer to the memory cell itself as the
76723    ** caller may modify the value text encoding.
76724    */
76725    assert( p->op==SQLITE_UPDATE );
76726    if( !p->aNew ){
76727      p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
76728      if( !p->aNew ){
76729        rc = SQLITE_NOMEM;
76730        goto preupdate_new_out;
76731      }
76732    }
76733    assert( iIdx>=0 && iIdx<p->pCsr->nField );
76734    pMem = &p->aNew[iIdx];
76735    if( pMem->flags==0 ){
76736      if( iIdx==p->iPKey ){
76737        sqlite3VdbeMemSetInt64(pMem, p->iKey2);
76738      }else{
76739        rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
76740        if( rc!=SQLITE_OK ) goto preupdate_new_out;
76741      }
76742    }
76743  }
76744  *ppValue = pMem;
76745
76746 preupdate_new_out:
76747  sqlite3Error(db, rc);
76748  return sqlite3ApiExit(db, rc);
76749}
76750#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76751
76752#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
76753/*
76754** Return status data for a single loop within query pStmt.
76755*/
76756SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
76757  sqlite3_stmt *pStmt,            /* Prepared statement being queried */
76758  int idx,                        /* Index of loop to report on */
76759  int iScanStatusOp,              /* Which metric to return */
76760  void *pOut                      /* OUT: Write the answer here */
76761){
76762  Vdbe *p = (Vdbe*)pStmt;
76763  ScanStatus *pScan;
76764  if( idx<0 || idx>=p->nScan ) return 1;
76765  pScan = &p->aScan[idx];
76766  switch( iScanStatusOp ){
76767    case SQLITE_SCANSTAT_NLOOP: {
76768      *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
76769      break;
76770    }
76771    case SQLITE_SCANSTAT_NVISIT: {
76772      *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
76773      break;
76774    }
76775    case SQLITE_SCANSTAT_EST: {
76776      double r = 1.0;
76777      LogEst x = pScan->nEst;
76778      while( x<100 ){
76779        x += 10;
76780        r *= 0.5;
76781      }
76782      *(double*)pOut = r*sqlite3LogEstToInt(x);
76783      break;
76784    }
76785    case SQLITE_SCANSTAT_NAME: {
76786      *(const char**)pOut = pScan->zName;
76787      break;
76788    }
76789    case SQLITE_SCANSTAT_EXPLAIN: {
76790      if( pScan->addrExplain ){
76791        *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
76792      }else{
76793        *(const char**)pOut = 0;
76794      }
76795      break;
76796    }
76797    case SQLITE_SCANSTAT_SELECTID: {
76798      if( pScan->addrExplain ){
76799        *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
76800      }else{
76801        *(int*)pOut = -1;
76802      }
76803      break;
76804    }
76805    default: {
76806      return 1;
76807    }
76808  }
76809  return 0;
76810}
76811
76812/*
76813** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
76814*/
76815SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
76816  Vdbe *p = (Vdbe*)pStmt;
76817  memset(p->anExec, 0, p->nOp * sizeof(i64));
76818}
76819#endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
76820
76821/************** End of vdbeapi.c *********************************************/
76822/************** Begin file vdbetrace.c ***************************************/
76823/*
76824** 2009 November 25
76825**
76826** The author disclaims copyright to this source code.  In place of
76827** a legal notice, here is a blessing:
76828**
76829**    May you do good and not evil.
76830**    May you find forgiveness for yourself and forgive others.
76831**    May you share freely, never taking more than you give.
76832**
76833*************************************************************************
76834**
76835** This file contains code used to insert the values of host parameters
76836** (aka "wildcards") into the SQL text output by sqlite3_trace().
76837**
76838** The Vdbe parse-tree explainer is also found here.
76839*/
76840/* #include "sqliteInt.h" */
76841/* #include "vdbeInt.h" */
76842
76843#ifndef SQLITE_OMIT_TRACE
76844
76845/*
76846** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
76847** bytes in this text up to but excluding the first character in
76848** a host parameter.  If the text contains no host parameters, return
76849** the total number of bytes in the text.
76850*/
76851static int findNextHostParameter(const char *zSql, int *pnToken){
76852  int tokenType;
76853  int nTotal = 0;
76854  int n;
76855
76856  *pnToken = 0;
76857  while( zSql[0] ){
76858    n = sqlite3GetToken((u8*)zSql, &tokenType);
76859    assert( n>0 && tokenType!=TK_ILLEGAL );
76860    if( tokenType==TK_VARIABLE ){
76861      *pnToken = n;
76862      break;
76863    }
76864    nTotal += n;
76865    zSql += n;
76866  }
76867  return nTotal;
76868}
76869
76870/*
76871** This function returns a pointer to a nul-terminated string in memory
76872** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
76873** string contains a copy of zRawSql but with host parameters expanded to
76874** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
76875** then the returned string holds a copy of zRawSql with "-- " prepended
76876** to each line of text.
76877**
76878** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
76879** then long strings and blobs are truncated to that many bytes.  This
76880** can be used to prevent unreasonably large trace strings when dealing
76881** with large (multi-megabyte) strings and blobs.
76882**
76883** The calling function is responsible for making sure the memory returned
76884** is eventually freed.
76885**
76886** ALGORITHM:  Scan the input string looking for host parameters in any of
76887** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
76888** string literals, quoted identifier names, and comments.  For text forms,
76889** the host parameter index is found by scanning the prepared
76890** statement for the corresponding OP_Variable opcode.  Once the host
76891** parameter index is known, locate the value in p->aVar[].  Then render
76892** the value as a literal in place of the host parameter name.
76893*/
76894SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
76895  Vdbe *p,                 /* The prepared statement being evaluated */
76896  const char *zRawSql      /* Raw text of the SQL statement */
76897){
76898  sqlite3 *db;             /* The database connection */
76899  int idx = 0;             /* Index of a host parameter */
76900  int nextIndex = 1;       /* Index of next ? host parameter */
76901  int n;                   /* Length of a token prefix */
76902  int nToken;              /* Length of the parameter token */
76903  int i;                   /* Loop counter */
76904  Mem *pVar;               /* Value of a host parameter */
76905  StrAccum out;            /* Accumulate the output here */
76906#ifndef SQLITE_OMIT_UTF16
76907  Mem utf8;                /* Used to convert UTF16 parameters into UTF8 for display */
76908#endif
76909  char zBase[100];         /* Initial working space */
76910
76911  db = p->db;
76912  sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
76913                      db->aLimit[SQLITE_LIMIT_LENGTH]);
76914  if( db->nVdbeExec>1 ){
76915    while( *zRawSql ){
76916      const char *zStart = zRawSql;
76917      while( *(zRawSql++)!='\n' && *zRawSql );
76918      sqlite3StrAccumAppend(&out, "-- ", 3);
76919      assert( (zRawSql - zStart) > 0 );
76920      sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
76921    }
76922  }else if( p->nVar==0 ){
76923    sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
76924  }else{
76925    while( zRawSql[0] ){
76926      n = findNextHostParameter(zRawSql, &nToken);
76927      assert( n>0 );
76928      sqlite3StrAccumAppend(&out, zRawSql, n);
76929      zRawSql += n;
76930      assert( zRawSql[0] || nToken==0 );
76931      if( nToken==0 ) break;
76932      if( zRawSql[0]=='?' ){
76933        if( nToken>1 ){
76934          assert( sqlite3Isdigit(zRawSql[1]) );
76935          sqlite3GetInt32(&zRawSql[1], &idx);
76936        }else{
76937          idx = nextIndex;
76938        }
76939      }else{
76940        assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
76941                zRawSql[0]=='@' || zRawSql[0]=='#' );
76942        testcase( zRawSql[0]==':' );
76943        testcase( zRawSql[0]=='$' );
76944        testcase( zRawSql[0]=='@' );
76945        testcase( zRawSql[0]=='#' );
76946        idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
76947        assert( idx>0 );
76948      }
76949      zRawSql += nToken;
76950      nextIndex = idx + 1;
76951      assert( idx>0 && idx<=p->nVar );
76952      pVar = &p->aVar[idx-1];
76953      if( pVar->flags & MEM_Null ){
76954        sqlite3StrAccumAppend(&out, "NULL", 4);
76955      }else if( pVar->flags & MEM_Int ){
76956        sqlite3XPrintf(&out, "%lld", pVar->u.i);
76957      }else if( pVar->flags & MEM_Real ){
76958        sqlite3XPrintf(&out, "%!.15g", pVar->u.r);
76959      }else if( pVar->flags & MEM_Str ){
76960        int nOut;  /* Number of bytes of the string text to include in output */
76961#ifndef SQLITE_OMIT_UTF16
76962        u8 enc = ENC(db);
76963        if( enc!=SQLITE_UTF8 ){
76964          memset(&utf8, 0, sizeof(utf8));
76965          utf8.db = db;
76966          sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
76967          if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
76968            out.accError = STRACCUM_NOMEM;
76969            out.nAlloc = 0;
76970          }
76971          pVar = &utf8;
76972        }
76973#endif
76974        nOut = pVar->n;
76975#ifdef SQLITE_TRACE_SIZE_LIMIT
76976        if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
76977          nOut = SQLITE_TRACE_SIZE_LIMIT;
76978          while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
76979        }
76980#endif
76981        sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
76982#ifdef SQLITE_TRACE_SIZE_LIMIT
76983        if( nOut<pVar->n ){
76984          sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
76985        }
76986#endif
76987#ifndef SQLITE_OMIT_UTF16
76988        if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
76989#endif
76990      }else if( pVar->flags & MEM_Zero ){
76991        sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
76992      }else{
76993        int nOut;  /* Number of bytes of the blob to include in output */
76994        assert( pVar->flags & MEM_Blob );
76995        sqlite3StrAccumAppend(&out, "x'", 2);
76996        nOut = pVar->n;
76997#ifdef SQLITE_TRACE_SIZE_LIMIT
76998        if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
76999#endif
77000        for(i=0; i<nOut; i++){
77001          sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
77002        }
77003        sqlite3StrAccumAppend(&out, "'", 1);
77004#ifdef SQLITE_TRACE_SIZE_LIMIT
77005        if( nOut<pVar->n ){
77006          sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
77007        }
77008#endif
77009      }
77010    }
77011  }
77012  if( out.accError ) sqlite3StrAccumReset(&out);
77013  return sqlite3StrAccumFinish(&out);
77014}
77015
77016#endif /* #ifndef SQLITE_OMIT_TRACE */
77017
77018/************** End of vdbetrace.c *******************************************/
77019/************** Begin file vdbe.c ********************************************/
77020/*
77021** 2001 September 15
77022**
77023** The author disclaims copyright to this source code.  In place of
77024** a legal notice, here is a blessing:
77025**
77026**    May you do good and not evil.
77027**    May you find forgiveness for yourself and forgive others.
77028**    May you share freely, never taking more than you give.
77029**
77030*************************************************************************
77031** The code in this file implements the function that runs the
77032** bytecode of a prepared statement.
77033**
77034** Various scripts scan this source file in order to generate HTML
77035** documentation, headers files, or other derived files.  The formatting
77036** of the code in this file is, therefore, important.  See other comments
77037** in this file for details.  If in doubt, do not deviate from existing
77038** commenting and indentation practices when changing or adding code.
77039*/
77040/* #include "sqliteInt.h" */
77041/* #include "vdbeInt.h" */
77042
77043/*
77044** Invoke this macro on memory cells just prior to changing the
77045** value of the cell.  This macro verifies that shallow copies are
77046** not misused.  A shallow copy of a string or blob just copies a
77047** pointer to the string or blob, not the content.  If the original
77048** is changed while the copy is still in use, the string or blob might
77049** be changed out from under the copy.  This macro verifies that nothing
77050** like that ever happens.
77051*/
77052#ifdef SQLITE_DEBUG
77053# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
77054#else
77055# define memAboutToChange(P,M)
77056#endif
77057
77058/*
77059** The following global variable is incremented every time a cursor
77060** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
77061** procedures use this information to make sure that indices are
77062** working correctly.  This variable has no function other than to
77063** help verify the correct operation of the library.
77064*/
77065#ifdef SQLITE_TEST
77066SQLITE_API int sqlite3_search_count = 0;
77067#endif
77068
77069/*
77070** When this global variable is positive, it gets decremented once before
77071** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
77072** field of the sqlite3 structure is set in order to simulate an interrupt.
77073**
77074** This facility is used for testing purposes only.  It does not function
77075** in an ordinary build.
77076*/
77077#ifdef SQLITE_TEST
77078SQLITE_API int sqlite3_interrupt_count = 0;
77079#endif
77080
77081/*
77082** The next global variable is incremented each type the OP_Sort opcode
77083** is executed.  The test procedures use this information to make sure that
77084** sorting is occurring or not occurring at appropriate times.   This variable
77085** has no function other than to help verify the correct operation of the
77086** library.
77087*/
77088#ifdef SQLITE_TEST
77089SQLITE_API int sqlite3_sort_count = 0;
77090#endif
77091
77092/*
77093** The next global variable records the size of the largest MEM_Blob
77094** or MEM_Str that has been used by a VDBE opcode.  The test procedures
77095** use this information to make sure that the zero-blob functionality
77096** is working correctly.   This variable has no function other than to
77097** help verify the correct operation of the library.
77098*/
77099#ifdef SQLITE_TEST
77100SQLITE_API int sqlite3_max_blobsize = 0;
77101static void updateMaxBlobsize(Mem *p){
77102  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
77103    sqlite3_max_blobsize = p->n;
77104  }
77105}
77106#endif
77107
77108/*
77109** This macro evaluates to true if either the update hook or the preupdate
77110** hook are enabled for database connect DB.
77111*/
77112#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
77113# define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
77114#else
77115# define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
77116#endif
77117
77118/*
77119** The next global variable is incremented each time the OP_Found opcode
77120** is executed. This is used to test whether or not the foreign key
77121** operation implemented using OP_FkIsZero is working. This variable
77122** has no function other than to help verify the correct operation of the
77123** library.
77124*/
77125#ifdef SQLITE_TEST
77126SQLITE_API int sqlite3_found_count = 0;
77127#endif
77128
77129/*
77130** Test a register to see if it exceeds the current maximum blob size.
77131** If it does, record the new maximum blob size.
77132*/
77133#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
77134# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
77135#else
77136# define UPDATE_MAX_BLOBSIZE(P)
77137#endif
77138
77139/*
77140** Invoke the VDBE coverage callback, if that callback is defined.  This
77141** feature is used for test suite validation only and does not appear an
77142** production builds.
77143**
77144** M is an integer, 2 or 3, that indices how many different ways the
77145** branch can go.  It is usually 2.  "I" is the direction the branch
77146** goes.  0 means falls through.  1 means branch is taken.  2 means the
77147** second alternative branch is taken.
77148**
77149** iSrcLine is the source code line (from the __LINE__ macro) that
77150** generated the VDBE instruction.  This instrumentation assumes that all
77151** source code is in a single file (the amalgamation).  Special values 1
77152** and 2 for the iSrcLine parameter mean that this particular branch is
77153** always taken or never taken, respectively.
77154*/
77155#if !defined(SQLITE_VDBE_COVERAGE)
77156# define VdbeBranchTaken(I,M)
77157#else
77158# define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
77159  static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
77160    if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
77161      M = iSrcLine;
77162      /* Assert the truth of VdbeCoverageAlwaysTaken() and
77163      ** VdbeCoverageNeverTaken() */
77164      assert( (M & I)==I );
77165    }else{
77166      if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
77167      sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
77168                                      iSrcLine,I,M);
77169    }
77170  }
77171#endif
77172
77173/*
77174** Convert the given register into a string if it isn't one
77175** already. Return non-zero if a malloc() fails.
77176*/
77177#define Stringify(P, enc) \
77178   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
77179     { goto no_mem; }
77180
77181/*
77182** An ephemeral string value (signified by the MEM_Ephem flag) contains
77183** a pointer to a dynamically allocated string where some other entity
77184** is responsible for deallocating that string.  Because the register
77185** does not control the string, it might be deleted without the register
77186** knowing it.
77187**
77188** This routine converts an ephemeral string into a dynamically allocated
77189** string that the register itself controls.  In other words, it
77190** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
77191*/
77192#define Deephemeralize(P) \
77193   if( ((P)->flags&MEM_Ephem)!=0 \
77194       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
77195
77196/* Return true if the cursor was opened using the OP_OpenSorter opcode. */
77197#define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
77198
77199/*
77200** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
77201** if we run out of memory.
77202*/
77203static VdbeCursor *allocateCursor(
77204  Vdbe *p,              /* The virtual machine */
77205  int iCur,             /* Index of the new VdbeCursor */
77206  int nField,           /* Number of fields in the table or index */
77207  int iDb,              /* Database the cursor belongs to, or -1 */
77208  u8 eCurType           /* Type of the new cursor */
77209){
77210  /* Find the memory cell that will be used to store the blob of memory
77211  ** required for this VdbeCursor structure. It is convenient to use a
77212  ** vdbe memory cell to manage the memory allocation required for a
77213  ** VdbeCursor structure for the following reasons:
77214  **
77215  **   * Sometimes cursor numbers are used for a couple of different
77216  **     purposes in a vdbe program. The different uses might require
77217  **     different sized allocations. Memory cells provide growable
77218  **     allocations.
77219  **
77220  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
77221  **     be freed lazily via the sqlite3_release_memory() API. This
77222  **     minimizes the number of malloc calls made by the system.
77223  **
77224  ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
77225  ** the top of the register space.  Cursor 1 is at Mem[p->nMem-1].
77226  ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
77227  */
77228  Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
77229
77230  int nByte;
77231  VdbeCursor *pCx = 0;
77232  nByte =
77233      ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
77234      (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
77235
77236  assert( iCur>=0 && iCur<p->nCursor );
77237  if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
77238    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
77239    p->apCsr[iCur] = 0;
77240  }
77241  if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
77242    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
77243    memset(pCx, 0, sizeof(VdbeCursor));
77244    pCx->eCurType = eCurType;
77245    pCx->iDb = iDb;
77246    pCx->nField = nField;
77247    pCx->aOffset = &pCx->aType[nField];
77248    if( eCurType==CURTYPE_BTREE ){
77249      pCx->uc.pCursor = (BtCursor*)
77250          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
77251      sqlite3BtreeCursorZero(pCx->uc.pCursor);
77252    }
77253  }
77254  return pCx;
77255}
77256
77257/*
77258** Try to convert a value into a numeric representation if we can
77259** do so without loss of information.  In other words, if the string
77260** looks like a number, convert it into a number.  If it does not
77261** look like a number, leave it alone.
77262**
77263** If the bTryForInt flag is true, then extra effort is made to give
77264** an integer representation.  Strings that look like floating point
77265** values but which have no fractional component (example: '48.00')
77266** will have a MEM_Int representation when bTryForInt is true.
77267**
77268** If bTryForInt is false, then if the input string contains a decimal
77269** point or exponential notation, the result is only MEM_Real, even
77270** if there is an exact integer representation of the quantity.
77271*/
77272static void applyNumericAffinity(Mem *pRec, int bTryForInt){
77273  double rValue;
77274  i64 iValue;
77275  u8 enc = pRec->enc;
77276  assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
77277  if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
77278  if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
77279    pRec->u.i = iValue;
77280    pRec->flags |= MEM_Int;
77281  }else{
77282    pRec->u.r = rValue;
77283    pRec->flags |= MEM_Real;
77284    if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
77285  }
77286}
77287
77288/*
77289** Processing is determine by the affinity parameter:
77290**
77291** SQLITE_AFF_INTEGER:
77292** SQLITE_AFF_REAL:
77293** SQLITE_AFF_NUMERIC:
77294**    Try to convert pRec to an integer representation or a
77295**    floating-point representation if an integer representation
77296**    is not possible.  Note that the integer representation is
77297**    always preferred, even if the affinity is REAL, because
77298**    an integer representation is more space efficient on disk.
77299**
77300** SQLITE_AFF_TEXT:
77301**    Convert pRec to a text representation.
77302**
77303** SQLITE_AFF_BLOB:
77304**    No-op.  pRec is unchanged.
77305*/
77306static void applyAffinity(
77307  Mem *pRec,          /* The value to apply affinity to */
77308  char affinity,      /* The affinity to be applied */
77309  u8 enc              /* Use this text encoding */
77310){
77311  if( affinity>=SQLITE_AFF_NUMERIC ){
77312    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
77313             || affinity==SQLITE_AFF_NUMERIC );
77314    if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
77315      if( (pRec->flags & MEM_Real)==0 ){
77316        if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
77317      }else{
77318        sqlite3VdbeIntegerAffinity(pRec);
77319      }
77320    }
77321  }else if( affinity==SQLITE_AFF_TEXT ){
77322    /* Only attempt the conversion to TEXT if there is an integer or real
77323    ** representation (blob and NULL do not get converted) but no string
77324    ** representation.  It would be harmless to repeat the conversion if
77325    ** there is already a string rep, but it is pointless to waste those
77326    ** CPU cycles. */
77327    if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
77328      if( (pRec->flags&(MEM_Real|MEM_Int)) ){
77329        sqlite3VdbeMemStringify(pRec, enc, 1);
77330      }
77331    }
77332    pRec->flags &= ~(MEM_Real|MEM_Int);
77333  }
77334}
77335
77336/*
77337** Try to convert the type of a function argument or a result column
77338** into a numeric representation.  Use either INTEGER or REAL whichever
77339** is appropriate.  But only do the conversion if it is possible without
77340** loss of information and return the revised type of the argument.
77341*/
77342SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value *pVal){
77343  int eType = sqlite3_value_type(pVal);
77344  if( eType==SQLITE_TEXT ){
77345    Mem *pMem = (Mem*)pVal;
77346    applyNumericAffinity(pMem, 0);
77347    eType = sqlite3_value_type(pVal);
77348  }
77349  return eType;
77350}
77351
77352/*
77353** Exported version of applyAffinity(). This one works on sqlite3_value*,
77354** not the internal Mem* type.
77355*/
77356SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
77357  sqlite3_value *pVal,
77358  u8 affinity,
77359  u8 enc
77360){
77361  applyAffinity((Mem *)pVal, affinity, enc);
77362}
77363
77364/*
77365** pMem currently only holds a string type (or maybe a BLOB that we can
77366** interpret as a string if we want to).  Compute its corresponding
77367** numeric type, if has one.  Set the pMem->u.r and pMem->u.i fields
77368** accordingly.
77369*/
77370static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
77371  assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
77372  assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
77373  if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
77374    return 0;
77375  }
77376  if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
77377    return MEM_Int;
77378  }
77379  return MEM_Real;
77380}
77381
77382/*
77383** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
77384** none.
77385**
77386** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
77387** But it does set pMem->u.r and pMem->u.i appropriately.
77388*/
77389static u16 numericType(Mem *pMem){
77390  if( pMem->flags & (MEM_Int|MEM_Real) ){
77391    return pMem->flags & (MEM_Int|MEM_Real);
77392  }
77393  if( pMem->flags & (MEM_Str|MEM_Blob) ){
77394    return computeNumericType(pMem);
77395  }
77396  return 0;
77397}
77398
77399#ifdef SQLITE_DEBUG
77400/*
77401** Write a nice string representation of the contents of cell pMem
77402** into buffer zBuf, length nBuf.
77403*/
77404SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
77405  char *zCsr = zBuf;
77406  int f = pMem->flags;
77407
77408  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
77409
77410  if( f&MEM_Blob ){
77411    int i;
77412    char c;
77413    if( f & MEM_Dyn ){
77414      c = 'z';
77415      assert( (f & (MEM_Static|MEM_Ephem))==0 );
77416    }else if( f & MEM_Static ){
77417      c = 't';
77418      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
77419    }else if( f & MEM_Ephem ){
77420      c = 'e';
77421      assert( (f & (MEM_Static|MEM_Dyn))==0 );
77422    }else{
77423      c = 's';
77424    }
77425
77426    sqlite3_snprintf(100, zCsr, "%c", c);
77427    zCsr += sqlite3Strlen30(zCsr);
77428    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
77429    zCsr += sqlite3Strlen30(zCsr);
77430    for(i=0; i<16 && i<pMem->n; i++){
77431      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
77432      zCsr += sqlite3Strlen30(zCsr);
77433    }
77434    for(i=0; i<16 && i<pMem->n; i++){
77435      char z = pMem->z[i];
77436      if( z<32 || z>126 ) *zCsr++ = '.';
77437      else *zCsr++ = z;
77438    }
77439
77440    sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
77441    zCsr += sqlite3Strlen30(zCsr);
77442    if( f & MEM_Zero ){
77443      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
77444      zCsr += sqlite3Strlen30(zCsr);
77445    }
77446    *zCsr = '\0';
77447  }else if( f & MEM_Str ){
77448    int j, k;
77449    zBuf[0] = ' ';
77450    if( f & MEM_Dyn ){
77451      zBuf[1] = 'z';
77452      assert( (f & (MEM_Static|MEM_Ephem))==0 );
77453    }else if( f & MEM_Static ){
77454      zBuf[1] = 't';
77455      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
77456    }else if( f & MEM_Ephem ){
77457      zBuf[1] = 'e';
77458      assert( (f & (MEM_Static|MEM_Dyn))==0 );
77459    }else{
77460      zBuf[1] = 's';
77461    }
77462    k = 2;
77463    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
77464    k += sqlite3Strlen30(&zBuf[k]);
77465    zBuf[k++] = '[';
77466    for(j=0; j<15 && j<pMem->n; j++){
77467      u8 c = pMem->z[j];
77468      if( c>=0x20 && c<0x7f ){
77469        zBuf[k++] = c;
77470      }else{
77471        zBuf[k++] = '.';
77472      }
77473    }
77474    zBuf[k++] = ']';
77475    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
77476    k += sqlite3Strlen30(&zBuf[k]);
77477    zBuf[k++] = 0;
77478  }
77479}
77480#endif
77481
77482#ifdef SQLITE_DEBUG
77483/*
77484** Print the value of a register for tracing purposes:
77485*/
77486static void memTracePrint(Mem *p){
77487  if( p->flags & MEM_Undefined ){
77488    printf(" undefined");
77489  }else if( p->flags & MEM_Null ){
77490    printf(" NULL");
77491  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
77492    printf(" si:%lld", p->u.i);
77493  }else if( p->flags & MEM_Int ){
77494    printf(" i:%lld", p->u.i);
77495#ifndef SQLITE_OMIT_FLOATING_POINT
77496  }else if( p->flags & MEM_Real ){
77497    printf(" r:%g", p->u.r);
77498#endif
77499  }else if( p->flags & MEM_RowSet ){
77500    printf(" (rowset)");
77501  }else{
77502    char zBuf[200];
77503    sqlite3VdbeMemPrettyPrint(p, zBuf);
77504    printf(" %s", zBuf);
77505  }
77506  if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
77507}
77508static void registerTrace(int iReg, Mem *p){
77509  printf("REG[%d] = ", iReg);
77510  memTracePrint(p);
77511  printf("\n");
77512}
77513#endif
77514
77515#ifdef SQLITE_DEBUG
77516#  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
77517#else
77518#  define REGISTER_TRACE(R,M)
77519#endif
77520
77521
77522#ifdef VDBE_PROFILE
77523
77524/*
77525** hwtime.h contains inline assembler code for implementing
77526** high-performance timing routines.
77527*/
77528/************** Include hwtime.h in the middle of vdbe.c *********************/
77529/************** Begin file hwtime.h ******************************************/
77530/*
77531** 2008 May 27
77532**
77533** The author disclaims copyright to this source code.  In place of
77534** a legal notice, here is a blessing:
77535**
77536**    May you do good and not evil.
77537**    May you find forgiveness for yourself and forgive others.
77538**    May you share freely, never taking more than you give.
77539**
77540******************************************************************************
77541**
77542** This file contains inline asm code for retrieving "high-performance"
77543** counters for x86 class CPUs.
77544*/
77545#ifndef SQLITE_HWTIME_H
77546#define SQLITE_HWTIME_H
77547
77548/*
77549** The following routine only works on pentium-class (or newer) processors.
77550** It uses the RDTSC opcode to read the cycle count value out of the
77551** processor and returns that value.  This can be used for high-res
77552** profiling.
77553*/
77554#if (defined(__GNUC__) || defined(_MSC_VER)) && \
77555      (defined(i386) || defined(__i386__) || defined(_M_IX86))
77556
77557  #if defined(__GNUC__)
77558
77559  __inline__ sqlite_uint64 sqlite3Hwtime(void){
77560     unsigned int lo, hi;
77561     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
77562     return (sqlite_uint64)hi << 32 | lo;
77563  }
77564
77565  #elif defined(_MSC_VER)
77566
77567  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
77568     __asm {
77569        rdtsc
77570        ret       ; return value at EDX:EAX
77571     }
77572  }
77573
77574  #endif
77575
77576#elif (defined(__GNUC__) && defined(__x86_64__))
77577
77578  __inline__ sqlite_uint64 sqlite3Hwtime(void){
77579      unsigned long val;
77580      __asm__ __volatile__ ("rdtsc" : "=A" (val));
77581      return val;
77582  }
77583
77584#elif (defined(__GNUC__) && defined(__ppc__))
77585
77586  __inline__ sqlite_uint64 sqlite3Hwtime(void){
77587      unsigned long long retval;
77588      unsigned long junk;
77589      __asm__ __volatile__ ("\n\
77590          1:      mftbu   %1\n\
77591                  mftb    %L0\n\
77592                  mftbu   %0\n\
77593                  cmpw    %0,%1\n\
77594                  bne     1b"
77595                  : "=r" (retval), "=r" (junk));
77596      return retval;
77597  }
77598
77599#else
77600
77601  #error Need implementation of sqlite3Hwtime() for your platform.
77602
77603  /*
77604  ** To compile without implementing sqlite3Hwtime() for your platform,
77605  ** you can remove the above #error and use the following
77606  ** stub function.  You will lose timing support for many
77607  ** of the debugging and testing utilities, but it should at
77608  ** least compile and run.
77609  */
77610SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
77611
77612#endif
77613
77614#endif /* !defined(SQLITE_HWTIME_H) */
77615
77616/************** End of hwtime.h **********************************************/
77617/************** Continuing where we left off in vdbe.c ***********************/
77618
77619#endif
77620
77621#ifndef NDEBUG
77622/*
77623** This function is only called from within an assert() expression. It
77624** checks that the sqlite3.nTransaction variable is correctly set to
77625** the number of non-transaction savepoints currently in the
77626** linked list starting at sqlite3.pSavepoint.
77627**
77628** Usage:
77629**
77630**     assert( checkSavepointCount(db) );
77631*/
77632static int checkSavepointCount(sqlite3 *db){
77633  int n = 0;
77634  Savepoint *p;
77635  for(p=db->pSavepoint; p; p=p->pNext) n++;
77636  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
77637  return 1;
77638}
77639#endif
77640
77641/*
77642** Return the register of pOp->p2 after first preparing it to be
77643** overwritten with an integer value.
77644*/
77645static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
77646  sqlite3VdbeMemSetNull(pOut);
77647  pOut->flags = MEM_Int;
77648  return pOut;
77649}
77650static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
77651  Mem *pOut;
77652  assert( pOp->p2>0 );
77653  assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77654  pOut = &p->aMem[pOp->p2];
77655  memAboutToChange(p, pOut);
77656  if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
77657    return out2PrereleaseWithClear(pOut);
77658  }else{
77659    pOut->flags = MEM_Int;
77660    return pOut;
77661  }
77662}
77663
77664
77665/*
77666** Execute as much of a VDBE program as we can.
77667** This is the core of sqlite3_step().
77668*/
77669SQLITE_PRIVATE int sqlite3VdbeExec(
77670  Vdbe *p                    /* The VDBE */
77671){
77672  Op *aOp = p->aOp;          /* Copy of p->aOp */
77673  Op *pOp = aOp;             /* Current operation */
77674#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
77675  Op *pOrigOp;               /* Value of pOp at the top of the loop */
77676#endif
77677#ifdef SQLITE_DEBUG
77678  int nExtraDelete = 0;      /* Verifies FORDELETE and AUXDELETE flags */
77679#endif
77680  int rc = SQLITE_OK;        /* Value to return */
77681  sqlite3 *db = p->db;       /* The database */
77682  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
77683  u8 encoding = ENC(db);     /* The database encoding */
77684  int iCompare = 0;          /* Result of last OP_Compare operation */
77685  unsigned nVmStep = 0;      /* Number of virtual machine steps */
77686#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77687  unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
77688#endif
77689  Mem *aMem = p->aMem;       /* Copy of p->aMem */
77690  Mem *pIn1 = 0;             /* 1st input operand */
77691  Mem *pIn2 = 0;             /* 2nd input operand */
77692  Mem *pIn3 = 0;             /* 3rd input operand */
77693  Mem *pOut = 0;             /* Output operand */
77694  int *aPermute = 0;         /* Permutation of columns for OP_Compare */
77695  i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
77696#ifdef VDBE_PROFILE
77697  u64 start;                 /* CPU clock count at start of opcode */
77698#endif
77699  /*** INSERT STACK UNION HERE ***/
77700
77701  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
77702  sqlite3VdbeEnter(p);
77703  if( p->rc==SQLITE_NOMEM ){
77704    /* This happens if a malloc() inside a call to sqlite3_column_text() or
77705    ** sqlite3_column_text16() failed.  */
77706    goto no_mem;
77707  }
77708  assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
77709  assert( p->bIsReader || p->readOnly!=0 );
77710  p->rc = SQLITE_OK;
77711  p->iCurrentTime = 0;
77712  assert( p->explain==0 );
77713  p->pResultSet = 0;
77714  db->busyHandler.nBusy = 0;
77715  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
77716  sqlite3VdbeIOTraceSql(p);
77717#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77718  if( db->xProgress ){
77719    u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
77720    assert( 0 < db->nProgressOps );
77721    nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
77722  }
77723#endif
77724#ifdef SQLITE_DEBUG
77725  sqlite3BeginBenignMalloc();
77726  if( p->pc==0
77727   && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
77728  ){
77729    int i;
77730    int once = 1;
77731    sqlite3VdbePrintSql(p);
77732    if( p->db->flags & SQLITE_VdbeListing ){
77733      printf("VDBE Program Listing:\n");
77734      for(i=0; i<p->nOp; i++){
77735        sqlite3VdbePrintOp(stdout, i, &aOp[i]);
77736      }
77737    }
77738    if( p->db->flags & SQLITE_VdbeEQP ){
77739      for(i=0; i<p->nOp; i++){
77740        if( aOp[i].opcode==OP_Explain ){
77741          if( once ) printf("VDBE Query Plan:\n");
77742          printf("%s\n", aOp[i].p4.z);
77743          once = 0;
77744        }
77745      }
77746    }
77747    if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
77748  }
77749  sqlite3EndBenignMalloc();
77750#endif
77751  for(pOp=&aOp[p->pc]; 1; pOp++){
77752    /* Errors are detected by individual opcodes, with an immediate
77753    ** jumps to abort_due_to_error. */
77754    assert( rc==SQLITE_OK );
77755
77756    assert( pOp>=aOp && pOp<&aOp[p->nOp]);
77757#ifdef VDBE_PROFILE
77758    start = sqlite3Hwtime();
77759#endif
77760    nVmStep++;
77761#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
77762    if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
77763#endif
77764
77765    /* Only allow tracing if SQLITE_DEBUG is defined.
77766    */
77767#ifdef SQLITE_DEBUG
77768    if( db->flags & SQLITE_VdbeTrace ){
77769      sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
77770    }
77771#endif
77772
77773
77774    /* Check to see if we need to simulate an interrupt.  This only happens
77775    ** if we have a special test build.
77776    */
77777#ifdef SQLITE_TEST
77778    if( sqlite3_interrupt_count>0 ){
77779      sqlite3_interrupt_count--;
77780      if( sqlite3_interrupt_count==0 ){
77781        sqlite3_interrupt(db);
77782      }
77783    }
77784#endif
77785
77786    /* Sanity checking on other operands */
77787#ifdef SQLITE_DEBUG
77788    {
77789      u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
77790      if( (opProperty & OPFLG_IN1)!=0 ){
77791        assert( pOp->p1>0 );
77792        assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
77793        assert( memIsValid(&aMem[pOp->p1]) );
77794        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
77795        REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
77796      }
77797      if( (opProperty & OPFLG_IN2)!=0 ){
77798        assert( pOp->p2>0 );
77799        assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77800        assert( memIsValid(&aMem[pOp->p2]) );
77801        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
77802        REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
77803      }
77804      if( (opProperty & OPFLG_IN3)!=0 ){
77805        assert( pOp->p3>0 );
77806        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
77807        assert( memIsValid(&aMem[pOp->p3]) );
77808        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
77809        REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
77810      }
77811      if( (opProperty & OPFLG_OUT2)!=0 ){
77812        assert( pOp->p2>0 );
77813        assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77814        memAboutToChange(p, &aMem[pOp->p2]);
77815      }
77816      if( (opProperty & OPFLG_OUT3)!=0 ){
77817        assert( pOp->p3>0 );
77818        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
77819        memAboutToChange(p, &aMem[pOp->p3]);
77820      }
77821    }
77822#endif
77823#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
77824    pOrigOp = pOp;
77825#endif
77826
77827    switch( pOp->opcode ){
77828
77829/*****************************************************************************
77830** What follows is a massive switch statement where each case implements a
77831** separate instruction in the virtual machine.  If we follow the usual
77832** indentation conventions, each case should be indented by 6 spaces.  But
77833** that is a lot of wasted space on the left margin.  So the code within
77834** the switch statement will break with convention and be flush-left. Another
77835** big comment (similar to this one) will mark the point in the code where
77836** we transition back to normal indentation.
77837**
77838** The formatting of each case is important.  The makefile for SQLite
77839** generates two C files "opcodes.h" and "opcodes.c" by scanning this
77840** file looking for lines that begin with "case OP_".  The opcodes.h files
77841** will be filled with #defines that give unique integer values to each
77842** opcode and the opcodes.c file is filled with an array of strings where
77843** each string is the symbolic name for the corresponding opcode.  If the
77844** case statement is followed by a comment of the form "/# same as ... #/"
77845** that comment is used to determine the particular value of the opcode.
77846**
77847** Other keywords in the comment that follows each case are used to
77848** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
77849** Keywords include: in1, in2, in3, out2, out3.  See
77850** the mkopcodeh.awk script for additional information.
77851**
77852** Documentation about VDBE opcodes is generated by scanning this file
77853** for lines of that contain "Opcode:".  That line and all subsequent
77854** comment lines are used in the generation of the opcode.html documentation
77855** file.
77856**
77857** SUMMARY:
77858**
77859**     Formatting is important to scripts that scan this file.
77860**     Do not deviate from the formatting style currently in use.
77861**
77862*****************************************************************************/
77863
77864/* Opcode:  Goto * P2 * * *
77865**
77866** An unconditional jump to address P2.
77867** The next instruction executed will be
77868** the one at index P2 from the beginning of
77869** the program.
77870**
77871** The P1 parameter is not actually used by this opcode.  However, it
77872** is sometimes set to 1 instead of 0 as a hint to the command-line shell
77873** that this Goto is the bottom of a loop and that the lines from P2 down
77874** to the current line should be indented for EXPLAIN output.
77875*/
77876case OP_Goto: {             /* jump */
77877jump_to_p2_and_check_for_interrupt:
77878  pOp = &aOp[pOp->p2 - 1];
77879
77880  /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
77881  ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
77882  ** completion.  Check to see if sqlite3_interrupt() has been called
77883  ** or if the progress callback needs to be invoked.
77884  **
77885  ** This code uses unstructured "goto" statements and does not look clean.
77886  ** But that is not due to sloppy coding habits. The code is written this
77887  ** way for performance, to avoid having to run the interrupt and progress
77888  ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
77889  ** faster according to "valgrind --tool=cachegrind" */
77890check_for_interrupt:
77891  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
77892#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77893  /* Call the progress callback if it is configured and the required number
77894  ** of VDBE ops have been executed (either since this invocation of
77895  ** sqlite3VdbeExec() or since last time the progress callback was called).
77896  ** If the progress callback returns non-zero, exit the virtual machine with
77897  ** a return code SQLITE_ABORT.
77898  */
77899  if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
77900    assert( db->nProgressOps!=0 );
77901    nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
77902    if( db->xProgress(db->pProgressArg) ){
77903      rc = SQLITE_INTERRUPT;
77904      goto abort_due_to_error;
77905    }
77906  }
77907#endif
77908
77909  break;
77910}
77911
77912/* Opcode:  Gosub P1 P2 * * *
77913**
77914** Write the current address onto register P1
77915** and then jump to address P2.
77916*/
77917case OP_Gosub: {            /* jump */
77918  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
77919  pIn1 = &aMem[pOp->p1];
77920  assert( VdbeMemDynamic(pIn1)==0 );
77921  memAboutToChange(p, pIn1);
77922  pIn1->flags = MEM_Int;
77923  pIn1->u.i = (int)(pOp-aOp);
77924  REGISTER_TRACE(pOp->p1, pIn1);
77925
77926  /* Most jump operations do a goto to this spot in order to update
77927  ** the pOp pointer. */
77928jump_to_p2:
77929  pOp = &aOp[pOp->p2 - 1];
77930  break;
77931}
77932
77933/* Opcode:  Return P1 * * * *
77934**
77935** Jump to the next instruction after the address in register P1.  After
77936** the jump, register P1 becomes undefined.
77937*/
77938case OP_Return: {           /* in1 */
77939  pIn1 = &aMem[pOp->p1];
77940  assert( pIn1->flags==MEM_Int );
77941  pOp = &aOp[pIn1->u.i];
77942  pIn1->flags = MEM_Undefined;
77943  break;
77944}
77945
77946/* Opcode: InitCoroutine P1 P2 P3 * *
77947**
77948** Set up register P1 so that it will Yield to the coroutine
77949** located at address P3.
77950**
77951** If P2!=0 then the coroutine implementation immediately follows
77952** this opcode.  So jump over the coroutine implementation to
77953** address P2.
77954**
77955** See also: EndCoroutine
77956*/
77957case OP_InitCoroutine: {     /* jump */
77958  assert( pOp->p1>0 &&  pOp->p1<=(p->nMem+1 - p->nCursor) );
77959  assert( pOp->p2>=0 && pOp->p2<p->nOp );
77960  assert( pOp->p3>=0 && pOp->p3<p->nOp );
77961  pOut = &aMem[pOp->p1];
77962  assert( !VdbeMemDynamic(pOut) );
77963  pOut->u.i = pOp->p3 - 1;
77964  pOut->flags = MEM_Int;
77965  if( pOp->p2 ) goto jump_to_p2;
77966  break;
77967}
77968
77969/* Opcode:  EndCoroutine P1 * * * *
77970**
77971** The instruction at the address in register P1 is a Yield.
77972** Jump to the P2 parameter of that Yield.
77973** After the jump, register P1 becomes undefined.
77974**
77975** See also: InitCoroutine
77976*/
77977case OP_EndCoroutine: {           /* in1 */
77978  VdbeOp *pCaller;
77979  pIn1 = &aMem[pOp->p1];
77980  assert( pIn1->flags==MEM_Int );
77981  assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
77982  pCaller = &aOp[pIn1->u.i];
77983  assert( pCaller->opcode==OP_Yield );
77984  assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
77985  pOp = &aOp[pCaller->p2 - 1];
77986  pIn1->flags = MEM_Undefined;
77987  break;
77988}
77989
77990/* Opcode:  Yield P1 P2 * * *
77991**
77992** Swap the program counter with the value in register P1.  This
77993** has the effect of yielding to a coroutine.
77994**
77995** If the coroutine that is launched by this instruction ends with
77996** Yield or Return then continue to the next instruction.  But if
77997** the coroutine launched by this instruction ends with
77998** EndCoroutine, then jump to P2 rather than continuing with the
77999** next instruction.
78000**
78001** See also: InitCoroutine
78002*/
78003case OP_Yield: {            /* in1, jump */
78004  int pcDest;
78005  pIn1 = &aMem[pOp->p1];
78006  assert( VdbeMemDynamic(pIn1)==0 );
78007  pIn1->flags = MEM_Int;
78008  pcDest = (int)pIn1->u.i;
78009  pIn1->u.i = (int)(pOp - aOp);
78010  REGISTER_TRACE(pOp->p1, pIn1);
78011  pOp = &aOp[pcDest];
78012  break;
78013}
78014
78015/* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
78016** Synopsis:  if r[P3]=null halt
78017**
78018** Check the value in register P3.  If it is NULL then Halt using
78019** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
78020** value in register P3 is not NULL, then this routine is a no-op.
78021** The P5 parameter should be 1.
78022*/
78023case OP_HaltIfNull: {      /* in3 */
78024  pIn3 = &aMem[pOp->p3];
78025  if( (pIn3->flags & MEM_Null)==0 ) break;
78026  /* Fall through into OP_Halt */
78027}
78028
78029/* Opcode:  Halt P1 P2 * P4 P5
78030**
78031** Exit immediately.  All open cursors, etc are closed
78032** automatically.
78033**
78034** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
78035** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
78036** For errors, it can be some other value.  If P1!=0 then P2 will determine
78037** whether or not to rollback the current transaction.  Do not rollback
78038** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
78039** then back out all changes that have occurred during this execution of the
78040** VDBE, but do not rollback the transaction.
78041**
78042** If P4 is not null then it is an error message string.
78043**
78044** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
78045**
78046**    0:  (no change)
78047**    1:  NOT NULL contraint failed: P4
78048**    2:  UNIQUE constraint failed: P4
78049**    3:  CHECK constraint failed: P4
78050**    4:  FOREIGN KEY constraint failed: P4
78051**
78052** If P5 is not zero and P4 is NULL, then everything after the ":" is
78053** omitted.
78054**
78055** There is an implied "Halt 0 0 0" instruction inserted at the very end of
78056** every program.  So a jump past the last instruction of the program
78057** is the same as executing Halt.
78058*/
78059case OP_Halt: {
78060  VdbeFrame *pFrame;
78061  int pcx;
78062
78063  pcx = (int)(pOp - aOp);
78064  if( pOp->p1==SQLITE_OK && p->pFrame ){
78065    /* Halt the sub-program. Return control to the parent frame. */
78066    pFrame = p->pFrame;
78067    p->pFrame = pFrame->pParent;
78068    p->nFrame--;
78069    sqlite3VdbeSetChanges(db, p->nChange);
78070    pcx = sqlite3VdbeFrameRestore(pFrame);
78071    lastRowid = db->lastRowid;
78072    if( pOp->p2==OE_Ignore ){
78073      /* Instruction pcx is the OP_Program that invoked the sub-program
78074      ** currently being halted. If the p2 instruction of this OP_Halt
78075      ** instruction is set to OE_Ignore, then the sub-program is throwing
78076      ** an IGNORE exception. In this case jump to the address specified
78077      ** as the p2 of the calling OP_Program.  */
78078      pcx = p->aOp[pcx].p2-1;
78079    }
78080    aOp = p->aOp;
78081    aMem = p->aMem;
78082    pOp = &aOp[pcx];
78083    break;
78084  }
78085  p->rc = pOp->p1;
78086  p->errorAction = (u8)pOp->p2;
78087  p->pc = pcx;
78088  assert( pOp->p5>=0 && pOp->p5<=4 );
78089  if( p->rc ){
78090    if( pOp->p5 ){
78091      static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
78092                                             "FOREIGN KEY" };
78093      testcase( pOp->p5==1 );
78094      testcase( pOp->p5==2 );
78095      testcase( pOp->p5==3 );
78096      testcase( pOp->p5==4 );
78097      sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
78098      if( pOp->p4.z ){
78099        p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
78100      }
78101    }else{
78102      sqlite3VdbeError(p, "%s", pOp->p4.z);
78103    }
78104    sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
78105  }
78106  rc = sqlite3VdbeHalt(p);
78107  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
78108  if( rc==SQLITE_BUSY ){
78109    p->rc = SQLITE_BUSY;
78110  }else{
78111    assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
78112    assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
78113    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
78114  }
78115  goto vdbe_return;
78116}
78117
78118/* Opcode: Integer P1 P2 * * *
78119** Synopsis: r[P2]=P1
78120**
78121** The 32-bit integer value P1 is written into register P2.
78122*/
78123case OP_Integer: {         /* out2 */
78124  pOut = out2Prerelease(p, pOp);
78125  pOut->u.i = pOp->p1;
78126  break;
78127}
78128
78129/* Opcode: Int64 * P2 * P4 *
78130** Synopsis: r[P2]=P4
78131**
78132** P4 is a pointer to a 64-bit integer value.
78133** Write that value into register P2.
78134*/
78135case OP_Int64: {           /* out2 */
78136  pOut = out2Prerelease(p, pOp);
78137  assert( pOp->p4.pI64!=0 );
78138  pOut->u.i = *pOp->p4.pI64;
78139  break;
78140}
78141
78142#ifndef SQLITE_OMIT_FLOATING_POINT
78143/* Opcode: Real * P2 * P4 *
78144** Synopsis: r[P2]=P4
78145**
78146** P4 is a pointer to a 64-bit floating point value.
78147** Write that value into register P2.
78148*/
78149case OP_Real: {            /* same as TK_FLOAT, out2 */
78150  pOut = out2Prerelease(p, pOp);
78151  pOut->flags = MEM_Real;
78152  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
78153  pOut->u.r = *pOp->p4.pReal;
78154  break;
78155}
78156#endif
78157
78158/* Opcode: String8 * P2 * P4 *
78159** Synopsis: r[P2]='P4'
78160**
78161** P4 points to a nul terminated UTF-8 string. This opcode is transformed
78162** into a String opcode before it is executed for the first time.  During
78163** this transformation, the length of string P4 is computed and stored
78164** as the P1 parameter.
78165*/
78166case OP_String8: {         /* same as TK_STRING, out2 */
78167  assert( pOp->p4.z!=0 );
78168  pOut = out2Prerelease(p, pOp);
78169  pOp->opcode = OP_String;
78170  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
78171
78172#ifndef SQLITE_OMIT_UTF16
78173  if( encoding!=SQLITE_UTF8 ){
78174    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
78175    assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
78176    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
78177    assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
78178    assert( VdbeMemDynamic(pOut)==0 );
78179    pOut->szMalloc = 0;
78180    pOut->flags |= MEM_Static;
78181    if( pOp->p4type==P4_DYNAMIC ){
78182      sqlite3DbFree(db, pOp->p4.z);
78183    }
78184    pOp->p4type = P4_DYNAMIC;
78185    pOp->p4.z = pOut->z;
78186    pOp->p1 = pOut->n;
78187  }
78188  testcase( rc==SQLITE_TOOBIG );
78189#endif
78190  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78191    goto too_big;
78192  }
78193  assert( rc==SQLITE_OK );
78194  /* Fall through to the next case, OP_String */
78195}
78196
78197/* Opcode: String P1 P2 P3 P4 P5
78198** Synopsis: r[P2]='P4' (len=P1)
78199**
78200** The string value P4 of length P1 (bytes) is stored in register P2.
78201**
78202** If P3 is not zero and the content of register P3 is equal to P5, then
78203** the datatype of the register P2 is converted to BLOB.  The content is
78204** the same sequence of bytes, it is merely interpreted as a BLOB instead
78205** of a string, as if it had been CAST.  In other words:
78206**
78207** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
78208*/
78209case OP_String: {          /* out2 */
78210  assert( pOp->p4.z!=0 );
78211  pOut = out2Prerelease(p, pOp);
78212  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
78213  pOut->z = pOp->p4.z;
78214  pOut->n = pOp->p1;
78215  pOut->enc = encoding;
78216  UPDATE_MAX_BLOBSIZE(pOut);
78217#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
78218  if( pOp->p3>0 ){
78219    assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
78220    pIn3 = &aMem[pOp->p3];
78221    assert( pIn3->flags & MEM_Int );
78222    if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
78223  }
78224#endif
78225  break;
78226}
78227
78228/* Opcode: Null P1 P2 P3 * *
78229** Synopsis:  r[P2..P3]=NULL
78230**
78231** Write a NULL into registers P2.  If P3 greater than P2, then also write
78232** NULL into register P3 and every register in between P2 and P3.  If P3
78233** is less than P2 (typically P3 is zero) then only register P2 is
78234** set to NULL.
78235**
78236** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
78237** NULL values will not compare equal even if SQLITE_NULLEQ is set on
78238** OP_Ne or OP_Eq.
78239*/
78240case OP_Null: {           /* out2 */
78241  int cnt;
78242  u16 nullFlag;
78243  pOut = out2Prerelease(p, pOp);
78244  cnt = pOp->p3-pOp->p2;
78245  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
78246  pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
78247  while( cnt>0 ){
78248    pOut++;
78249    memAboutToChange(p, pOut);
78250    sqlite3VdbeMemSetNull(pOut);
78251    pOut->flags = nullFlag;
78252    cnt--;
78253  }
78254  break;
78255}
78256
78257/* Opcode: SoftNull P1 * * * *
78258** Synopsis:  r[P1]=NULL
78259**
78260** Set register P1 to have the value NULL as seen by the OP_MakeRecord
78261** instruction, but do not free any string or blob memory associated with
78262** the register, so that if the value was a string or blob that was
78263** previously copied using OP_SCopy, the copies will continue to be valid.
78264*/
78265case OP_SoftNull: {
78266  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
78267  pOut = &aMem[pOp->p1];
78268  pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
78269  break;
78270}
78271
78272/* Opcode: Blob P1 P2 * P4 *
78273** Synopsis: r[P2]=P4 (len=P1)
78274**
78275** P4 points to a blob of data P1 bytes long.  Store this
78276** blob in register P2.
78277*/
78278case OP_Blob: {                /* out2 */
78279  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
78280  pOut = out2Prerelease(p, pOp);
78281  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
78282  pOut->enc = encoding;
78283  UPDATE_MAX_BLOBSIZE(pOut);
78284  break;
78285}
78286
78287/* Opcode: Variable P1 P2 * P4 *
78288** Synopsis: r[P2]=parameter(P1,P4)
78289**
78290** Transfer the values of bound parameter P1 into register P2
78291**
78292** If the parameter is named, then its name appears in P4.
78293** The P4 value is used by sqlite3_bind_parameter_name().
78294*/
78295case OP_Variable: {            /* out2 */
78296  Mem *pVar;       /* Value being transferred */
78297
78298  assert( pOp->p1>0 && pOp->p1<=p->nVar );
78299  assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
78300  pVar = &p->aVar[pOp->p1 - 1];
78301  if( sqlite3VdbeMemTooBig(pVar) ){
78302    goto too_big;
78303  }
78304  pOut = out2Prerelease(p, pOp);
78305  sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
78306  UPDATE_MAX_BLOBSIZE(pOut);
78307  break;
78308}
78309
78310/* Opcode: Move P1 P2 P3 * *
78311** Synopsis:  r[P2@P3]=r[P1@P3]
78312**
78313** Move the P3 values in register P1..P1+P3-1 over into
78314** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
78315** left holding a NULL.  It is an error for register ranges
78316** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
78317** for P3 to be less than 1.
78318*/
78319case OP_Move: {
78320  int n;           /* Number of registers left to copy */
78321  int p1;          /* Register to copy from */
78322  int p2;          /* Register to copy to */
78323
78324  n = pOp->p3;
78325  p1 = pOp->p1;
78326  p2 = pOp->p2;
78327  assert( n>0 && p1>0 && p2>0 );
78328  assert( p1+n<=p2 || p2+n<=p1 );
78329
78330  pIn1 = &aMem[p1];
78331  pOut = &aMem[p2];
78332  do{
78333    assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
78334    assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
78335    assert( memIsValid(pIn1) );
78336    memAboutToChange(p, pOut);
78337    sqlite3VdbeMemMove(pOut, pIn1);
78338#ifdef SQLITE_DEBUG
78339    if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
78340      pOut->pScopyFrom += pOp->p2 - p1;
78341    }
78342#endif
78343    Deephemeralize(pOut);
78344    REGISTER_TRACE(p2++, pOut);
78345    pIn1++;
78346    pOut++;
78347  }while( --n );
78348  break;
78349}
78350
78351/* Opcode: Copy P1 P2 P3 * *
78352** Synopsis: r[P2@P3+1]=r[P1@P3+1]
78353**
78354** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
78355**
78356** This instruction makes a deep copy of the value.  A duplicate
78357** is made of any string or blob constant.  See also OP_SCopy.
78358*/
78359case OP_Copy: {
78360  int n;
78361
78362  n = pOp->p3;
78363  pIn1 = &aMem[pOp->p1];
78364  pOut = &aMem[pOp->p2];
78365  assert( pOut!=pIn1 );
78366  while( 1 ){
78367    sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
78368    Deephemeralize(pOut);
78369#ifdef SQLITE_DEBUG
78370    pOut->pScopyFrom = 0;
78371#endif
78372    REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
78373    if( (n--)==0 ) break;
78374    pOut++;
78375    pIn1++;
78376  }
78377  break;
78378}
78379
78380/* Opcode: SCopy P1 P2 * * *
78381** Synopsis: r[P2]=r[P1]
78382**
78383** Make a shallow copy of register P1 into register P2.
78384**
78385** This instruction makes a shallow copy of the value.  If the value
78386** is a string or blob, then the copy is only a pointer to the
78387** original and hence if the original changes so will the copy.
78388** Worse, if the original is deallocated, the copy becomes invalid.
78389** Thus the program must guarantee that the original will not change
78390** during the lifetime of the copy.  Use OP_Copy to make a complete
78391** copy.
78392*/
78393case OP_SCopy: {            /* out2 */
78394  pIn1 = &aMem[pOp->p1];
78395  pOut = &aMem[pOp->p2];
78396  assert( pOut!=pIn1 );
78397  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
78398#ifdef SQLITE_DEBUG
78399  if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
78400#endif
78401  break;
78402}
78403
78404/* Opcode: IntCopy P1 P2 * * *
78405** Synopsis: r[P2]=r[P1]
78406**
78407** Transfer the integer value held in register P1 into register P2.
78408**
78409** This is an optimized version of SCopy that works only for integer
78410** values.
78411*/
78412case OP_IntCopy: {            /* out2 */
78413  pIn1 = &aMem[pOp->p1];
78414  assert( (pIn1->flags & MEM_Int)!=0 );
78415  pOut = &aMem[pOp->p2];
78416  sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
78417  break;
78418}
78419
78420/* Opcode: ResultRow P1 P2 * * *
78421** Synopsis:  output=r[P1@P2]
78422**
78423** The registers P1 through P1+P2-1 contain a single row of
78424** results. This opcode causes the sqlite3_step() call to terminate
78425** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
78426** structure to provide access to the r(P1)..r(P1+P2-1) values as
78427** the result row.
78428*/
78429case OP_ResultRow: {
78430  Mem *pMem;
78431  int i;
78432  assert( p->nResColumn==pOp->p2 );
78433  assert( pOp->p1>0 );
78434  assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
78435
78436#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
78437  /* Run the progress counter just before returning.
78438  */
78439  if( db->xProgress!=0
78440   && nVmStep>=nProgressLimit
78441   && db->xProgress(db->pProgressArg)!=0
78442  ){
78443    rc = SQLITE_INTERRUPT;
78444    goto abort_due_to_error;
78445  }
78446#endif
78447
78448  /* If this statement has violated immediate foreign key constraints, do
78449  ** not return the number of rows modified. And do not RELEASE the statement
78450  ** transaction. It needs to be rolled back.  */
78451  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
78452    assert( db->flags&SQLITE_CountRows );
78453    assert( p->usesStmtJournal );
78454    goto abort_due_to_error;
78455  }
78456
78457  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
78458  ** DML statements invoke this opcode to return the number of rows
78459  ** modified to the user. This is the only way that a VM that
78460  ** opens a statement transaction may invoke this opcode.
78461  **
78462  ** In case this is such a statement, close any statement transaction
78463  ** opened by this VM before returning control to the user. This is to
78464  ** ensure that statement-transactions are always nested, not overlapping.
78465  ** If the open statement-transaction is not closed here, then the user
78466  ** may step another VM that opens its own statement transaction. This
78467  ** may lead to overlapping statement transactions.
78468  **
78469  ** The statement transaction is never a top-level transaction.  Hence
78470  ** the RELEASE call below can never fail.
78471  */
78472  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
78473  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
78474  assert( rc==SQLITE_OK );
78475
78476  /* Invalidate all ephemeral cursor row caches */
78477  p->cacheCtr = (p->cacheCtr + 2)|1;
78478
78479  /* Make sure the results of the current row are \000 terminated
78480  ** and have an assigned type.  The results are de-ephemeralized as
78481  ** a side effect.
78482  */
78483  pMem = p->pResultSet = &aMem[pOp->p1];
78484  for(i=0; i<pOp->p2; i++){
78485    assert( memIsValid(&pMem[i]) );
78486    Deephemeralize(&pMem[i]);
78487    assert( (pMem[i].flags & MEM_Ephem)==0
78488            || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
78489    sqlite3VdbeMemNulTerminate(&pMem[i]);
78490    REGISTER_TRACE(pOp->p1+i, &pMem[i]);
78491  }
78492  if( db->mallocFailed ) goto no_mem;
78493
78494  if( db->mTrace & SQLITE_TRACE_ROW ){
78495    db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
78496  }
78497
78498  /* Return SQLITE_ROW
78499  */
78500  p->pc = (int)(pOp - aOp) + 1;
78501  rc = SQLITE_ROW;
78502  goto vdbe_return;
78503}
78504
78505/* Opcode: Concat P1 P2 P3 * *
78506** Synopsis: r[P3]=r[P2]+r[P1]
78507**
78508** Add the text in register P1 onto the end of the text in
78509** register P2 and store the result in register P3.
78510** If either the P1 or P2 text are NULL then store NULL in P3.
78511**
78512**   P3 = P2 || P1
78513**
78514** It is illegal for P1 and P3 to be the same register. Sometimes,
78515** if P3 is the same register as P2, the implementation is able
78516** to avoid a memcpy().
78517*/
78518case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
78519  i64 nByte;
78520
78521  pIn1 = &aMem[pOp->p1];
78522  pIn2 = &aMem[pOp->p2];
78523  pOut = &aMem[pOp->p3];
78524  assert( pIn1!=pOut );
78525  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
78526    sqlite3VdbeMemSetNull(pOut);
78527    break;
78528  }
78529  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
78530  Stringify(pIn1, encoding);
78531  Stringify(pIn2, encoding);
78532  nByte = pIn1->n + pIn2->n;
78533  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78534    goto too_big;
78535  }
78536  if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
78537    goto no_mem;
78538  }
78539  MemSetTypeFlag(pOut, MEM_Str);
78540  if( pOut!=pIn2 ){
78541    memcpy(pOut->z, pIn2->z, pIn2->n);
78542  }
78543  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
78544  pOut->z[nByte]=0;
78545  pOut->z[nByte+1] = 0;
78546  pOut->flags |= MEM_Term;
78547  pOut->n = (int)nByte;
78548  pOut->enc = encoding;
78549  UPDATE_MAX_BLOBSIZE(pOut);
78550  break;
78551}
78552
78553/* Opcode: Add P1 P2 P3 * *
78554** Synopsis:  r[P3]=r[P1]+r[P2]
78555**
78556** Add the value in register P1 to the value in register P2
78557** and store the result in register P3.
78558** If either input is NULL, the result is NULL.
78559*/
78560/* Opcode: Multiply P1 P2 P3 * *
78561** Synopsis:  r[P3]=r[P1]*r[P2]
78562**
78563**
78564** Multiply the value in register P1 by the value in register P2
78565** and store the result in register P3.
78566** If either input is NULL, the result is NULL.
78567*/
78568/* Opcode: Subtract P1 P2 P3 * *
78569** Synopsis:  r[P3]=r[P2]-r[P1]
78570**
78571** Subtract the value in register P1 from the value in register P2
78572** and store the result in register P3.
78573** If either input is NULL, the result is NULL.
78574*/
78575/* Opcode: Divide P1 P2 P3 * *
78576** Synopsis:  r[P3]=r[P2]/r[P1]
78577**
78578** Divide the value in register P1 by the value in register P2
78579** and store the result in register P3 (P3=P2/P1). If the value in
78580** register P1 is zero, then the result is NULL. If either input is
78581** NULL, the result is NULL.
78582*/
78583/* Opcode: Remainder P1 P2 P3 * *
78584** Synopsis:  r[P3]=r[P2]%r[P1]
78585**
78586** Compute the remainder after integer register P2 is divided by
78587** register P1 and store the result in register P3.
78588** If the value in register P1 is zero the result is NULL.
78589** If either operand is NULL, the result is NULL.
78590*/
78591case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
78592case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
78593case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
78594case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
78595case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
78596  char bIntint;   /* Started out as two integer operands */
78597  u16 flags;      /* Combined MEM_* flags from both inputs */
78598  u16 type1;      /* Numeric type of left operand */
78599  u16 type2;      /* Numeric type of right operand */
78600  i64 iA;         /* Integer value of left operand */
78601  i64 iB;         /* Integer value of right operand */
78602  double rA;      /* Real value of left operand */
78603  double rB;      /* Real value of right operand */
78604
78605  pIn1 = &aMem[pOp->p1];
78606  type1 = numericType(pIn1);
78607  pIn2 = &aMem[pOp->p2];
78608  type2 = numericType(pIn2);
78609  pOut = &aMem[pOp->p3];
78610  flags = pIn1->flags | pIn2->flags;
78611  if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
78612  if( (type1 & type2 & MEM_Int)!=0 ){
78613    iA = pIn1->u.i;
78614    iB = pIn2->u.i;
78615    bIntint = 1;
78616    switch( pOp->opcode ){
78617      case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
78618      case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
78619      case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
78620      case OP_Divide: {
78621        if( iA==0 ) goto arithmetic_result_is_null;
78622        if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
78623        iB /= iA;
78624        break;
78625      }
78626      default: {
78627        if( iA==0 ) goto arithmetic_result_is_null;
78628        if( iA==-1 ) iA = 1;
78629        iB %= iA;
78630        break;
78631      }
78632    }
78633    pOut->u.i = iB;
78634    MemSetTypeFlag(pOut, MEM_Int);
78635  }else{
78636    bIntint = 0;
78637fp_math:
78638    rA = sqlite3VdbeRealValue(pIn1);
78639    rB = sqlite3VdbeRealValue(pIn2);
78640    switch( pOp->opcode ){
78641      case OP_Add:         rB += rA;       break;
78642      case OP_Subtract:    rB -= rA;       break;
78643      case OP_Multiply:    rB *= rA;       break;
78644      case OP_Divide: {
78645        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
78646        if( rA==(double)0 ) goto arithmetic_result_is_null;
78647        rB /= rA;
78648        break;
78649      }
78650      default: {
78651        iA = (i64)rA;
78652        iB = (i64)rB;
78653        if( iA==0 ) goto arithmetic_result_is_null;
78654        if( iA==-1 ) iA = 1;
78655        rB = (double)(iB % iA);
78656        break;
78657      }
78658    }
78659#ifdef SQLITE_OMIT_FLOATING_POINT
78660    pOut->u.i = rB;
78661    MemSetTypeFlag(pOut, MEM_Int);
78662#else
78663    if( sqlite3IsNaN(rB) ){
78664      goto arithmetic_result_is_null;
78665    }
78666    pOut->u.r = rB;
78667    MemSetTypeFlag(pOut, MEM_Real);
78668    if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
78669      sqlite3VdbeIntegerAffinity(pOut);
78670    }
78671#endif
78672  }
78673  break;
78674
78675arithmetic_result_is_null:
78676  sqlite3VdbeMemSetNull(pOut);
78677  break;
78678}
78679
78680/* Opcode: CollSeq P1 * * P4
78681**
78682** P4 is a pointer to a CollSeq struct. If the next call to a user function
78683** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
78684** be returned. This is used by the built-in min(), max() and nullif()
78685** functions.
78686**
78687** If P1 is not zero, then it is a register that a subsequent min() or
78688** max() aggregate will set to 1 if the current row is not the minimum or
78689** maximum.  The P1 register is initialized to 0 by this instruction.
78690**
78691** The interface used by the implementation of the aforementioned functions
78692** to retrieve the collation sequence set by this opcode is not available
78693** publicly.  Only built-in functions have access to this feature.
78694*/
78695case OP_CollSeq: {
78696  assert( pOp->p4type==P4_COLLSEQ );
78697  if( pOp->p1 ){
78698    sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
78699  }
78700  break;
78701}
78702
78703/* Opcode: Function0 P1 P2 P3 P4 P5
78704** Synopsis: r[P3]=func(r[P2@P5])
78705**
78706** Invoke a user function (P4 is a pointer to a FuncDef object that
78707** defines the function) with P5 arguments taken from register P2 and
78708** successors.  The result of the function is stored in register P3.
78709** Register P3 must not be one of the function inputs.
78710**
78711** P1 is a 32-bit bitmask indicating whether or not each argument to the
78712** function was determined to be constant at compile time. If the first
78713** argument was constant then bit 0 of P1 is set. This is used to determine
78714** whether meta data associated with a user function argument using the
78715** sqlite3_set_auxdata() API may be safely retained until the next
78716** invocation of this opcode.
78717**
78718** See also: Function, AggStep, AggFinal
78719*/
78720/* Opcode: Function P1 P2 P3 P4 P5
78721** Synopsis: r[P3]=func(r[P2@P5])
78722**
78723** Invoke a user function (P4 is a pointer to an sqlite3_context object that
78724** contains a pointer to the function to be run) with P5 arguments taken
78725** from register P2 and successors.  The result of the function is stored
78726** in register P3.  Register P3 must not be one of the function inputs.
78727**
78728** P1 is a 32-bit bitmask indicating whether or not each argument to the
78729** function was determined to be constant at compile time. If the first
78730** argument was constant then bit 0 of P1 is set. This is used to determine
78731** whether meta data associated with a user function argument using the
78732** sqlite3_set_auxdata() API may be safely retained until the next
78733** invocation of this opcode.
78734**
78735** SQL functions are initially coded as OP_Function0 with P4 pointing
78736** to a FuncDef object.  But on first evaluation, the P4 operand is
78737** automatically converted into an sqlite3_context object and the operation
78738** changed to this OP_Function opcode.  In this way, the initialization of
78739** the sqlite3_context object occurs only once, rather than once for each
78740** evaluation of the function.
78741**
78742** See also: Function0, AggStep, AggFinal
78743*/
78744case OP_Function0: {
78745  int n;
78746  sqlite3_context *pCtx;
78747
78748  assert( pOp->p4type==P4_FUNCDEF );
78749  n = pOp->p5;
78750  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
78751  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
78752  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
78753  pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
78754  if( pCtx==0 ) goto no_mem;
78755  pCtx->pOut = 0;
78756  pCtx->pFunc = pOp->p4.pFunc;
78757  pCtx->iOp = (int)(pOp - aOp);
78758  pCtx->pVdbe = p;
78759  pCtx->argc = n;
78760  pOp->p4type = P4_FUNCCTX;
78761  pOp->p4.pCtx = pCtx;
78762  pOp->opcode = OP_Function;
78763  /* Fall through into OP_Function */
78764}
78765case OP_Function: {
78766  int i;
78767  sqlite3_context *pCtx;
78768
78769  assert( pOp->p4type==P4_FUNCCTX );
78770  pCtx = pOp->p4.pCtx;
78771
78772  /* If this function is inside of a trigger, the register array in aMem[]
78773  ** might change from one evaluation to the next.  The next block of code
78774  ** checks to see if the register array has changed, and if so it
78775  ** reinitializes the relavant parts of the sqlite3_context object */
78776  pOut = &aMem[pOp->p3];
78777  if( pCtx->pOut != pOut ){
78778    pCtx->pOut = pOut;
78779    for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
78780  }
78781
78782  memAboutToChange(p, pCtx->pOut);
78783#ifdef SQLITE_DEBUG
78784  for(i=0; i<pCtx->argc; i++){
78785    assert( memIsValid(pCtx->argv[i]) );
78786    REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
78787  }
78788#endif
78789  MemSetTypeFlag(pCtx->pOut, MEM_Null);
78790  pCtx->fErrorOrAux = 0;
78791  db->lastRowid = lastRowid;
78792  (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
78793  lastRowid = db->lastRowid;  /* Remember rowid changes made by xSFunc */
78794
78795  /* If the function returned an error, throw an exception */
78796  if( pCtx->fErrorOrAux ){
78797    if( pCtx->isError ){
78798      sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
78799      rc = pCtx->isError;
78800    }
78801    sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
78802    if( rc ) goto abort_due_to_error;
78803  }
78804
78805  /* Copy the result of the function into register P3 */
78806  if( pOut->flags & (MEM_Str|MEM_Blob) ){
78807    sqlite3VdbeChangeEncoding(pCtx->pOut, encoding);
78808    if( sqlite3VdbeMemTooBig(pCtx->pOut) ) goto too_big;
78809  }
78810
78811  REGISTER_TRACE(pOp->p3, pCtx->pOut);
78812  UPDATE_MAX_BLOBSIZE(pCtx->pOut);
78813  break;
78814}
78815
78816/* Opcode: BitAnd P1 P2 P3 * *
78817** Synopsis:  r[P3]=r[P1]&r[P2]
78818**
78819** Take the bit-wise AND of the values in register P1 and P2 and
78820** store the result in register P3.
78821** If either input is NULL, the result is NULL.
78822*/
78823/* Opcode: BitOr P1 P2 P3 * *
78824** Synopsis:  r[P3]=r[P1]|r[P2]
78825**
78826** Take the bit-wise OR of the values in register P1 and P2 and
78827** store the result in register P3.
78828** If either input is NULL, the result is NULL.
78829*/
78830/* Opcode: ShiftLeft P1 P2 P3 * *
78831** Synopsis:  r[P3]=r[P2]<<r[P1]
78832**
78833** Shift the integer value in register P2 to the left by the
78834** number of bits specified by the integer in register P1.
78835** Store the result in register P3.
78836** If either input is NULL, the result is NULL.
78837*/
78838/* Opcode: ShiftRight P1 P2 P3 * *
78839** Synopsis:  r[P3]=r[P2]>>r[P1]
78840**
78841** Shift the integer value in register P2 to the right by the
78842** number of bits specified by the integer in register P1.
78843** Store the result in register P3.
78844** If either input is NULL, the result is NULL.
78845*/
78846case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
78847case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
78848case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
78849case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
78850  i64 iA;
78851  u64 uA;
78852  i64 iB;
78853  u8 op;
78854
78855  pIn1 = &aMem[pOp->p1];
78856  pIn2 = &aMem[pOp->p2];
78857  pOut = &aMem[pOp->p3];
78858  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
78859    sqlite3VdbeMemSetNull(pOut);
78860    break;
78861  }
78862  iA = sqlite3VdbeIntValue(pIn2);
78863  iB = sqlite3VdbeIntValue(pIn1);
78864  op = pOp->opcode;
78865  if( op==OP_BitAnd ){
78866    iA &= iB;
78867  }else if( op==OP_BitOr ){
78868    iA |= iB;
78869  }else if( iB!=0 ){
78870    assert( op==OP_ShiftRight || op==OP_ShiftLeft );
78871
78872    /* If shifting by a negative amount, shift in the other direction */
78873    if( iB<0 ){
78874      assert( OP_ShiftRight==OP_ShiftLeft+1 );
78875      op = 2*OP_ShiftLeft + 1 - op;
78876      iB = iB>(-64) ? -iB : 64;
78877    }
78878
78879    if( iB>=64 ){
78880      iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
78881    }else{
78882      memcpy(&uA, &iA, sizeof(uA));
78883      if( op==OP_ShiftLeft ){
78884        uA <<= iB;
78885      }else{
78886        uA >>= iB;
78887        /* Sign-extend on a right shift of a negative number */
78888        if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
78889      }
78890      memcpy(&iA, &uA, sizeof(iA));
78891    }
78892  }
78893  pOut->u.i = iA;
78894  MemSetTypeFlag(pOut, MEM_Int);
78895  break;
78896}
78897
78898/* Opcode: AddImm  P1 P2 * * *
78899** Synopsis:  r[P1]=r[P1]+P2
78900**
78901** Add the constant P2 to the value in register P1.
78902** The result is always an integer.
78903**
78904** To force any register to be an integer, just add 0.
78905*/
78906case OP_AddImm: {            /* in1 */
78907  pIn1 = &aMem[pOp->p1];
78908  memAboutToChange(p, pIn1);
78909  sqlite3VdbeMemIntegerify(pIn1);
78910  pIn1->u.i += pOp->p2;
78911  break;
78912}
78913
78914/* Opcode: MustBeInt P1 P2 * * *
78915**
78916** Force the value in register P1 to be an integer.  If the value
78917** in P1 is not an integer and cannot be converted into an integer
78918** without data loss, then jump immediately to P2, or if P2==0
78919** raise an SQLITE_MISMATCH exception.
78920*/
78921case OP_MustBeInt: {            /* jump, in1 */
78922  pIn1 = &aMem[pOp->p1];
78923  if( (pIn1->flags & MEM_Int)==0 ){
78924    applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
78925    VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
78926    if( (pIn1->flags & MEM_Int)==0 ){
78927      if( pOp->p2==0 ){
78928        rc = SQLITE_MISMATCH;
78929        goto abort_due_to_error;
78930      }else{
78931        goto jump_to_p2;
78932      }
78933    }
78934  }
78935  MemSetTypeFlag(pIn1, MEM_Int);
78936  break;
78937}
78938
78939#ifndef SQLITE_OMIT_FLOATING_POINT
78940/* Opcode: RealAffinity P1 * * * *
78941**
78942** If register P1 holds an integer convert it to a real value.
78943**
78944** This opcode is used when extracting information from a column that
78945** has REAL affinity.  Such column values may still be stored as
78946** integers, for space efficiency, but after extraction we want them
78947** to have only a real value.
78948*/
78949case OP_RealAffinity: {                  /* in1 */
78950  pIn1 = &aMem[pOp->p1];
78951  if( pIn1->flags & MEM_Int ){
78952    sqlite3VdbeMemRealify(pIn1);
78953  }
78954  break;
78955}
78956#endif
78957
78958#ifndef SQLITE_OMIT_CAST
78959/* Opcode: Cast P1 P2 * * *
78960** Synopsis: affinity(r[P1])
78961**
78962** Force the value in register P1 to be the type defined by P2.
78963**
78964** <ul>
78965** <li value="97"> TEXT
78966** <li value="98"> BLOB
78967** <li value="99"> NUMERIC
78968** <li value="100"> INTEGER
78969** <li value="101"> REAL
78970** </ul>
78971**
78972** A NULL value is not changed by this routine.  It remains NULL.
78973*/
78974case OP_Cast: {                  /* in1 */
78975  assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
78976  testcase( pOp->p2==SQLITE_AFF_TEXT );
78977  testcase( pOp->p2==SQLITE_AFF_BLOB );
78978  testcase( pOp->p2==SQLITE_AFF_NUMERIC );
78979  testcase( pOp->p2==SQLITE_AFF_INTEGER );
78980  testcase( pOp->p2==SQLITE_AFF_REAL );
78981  pIn1 = &aMem[pOp->p1];
78982  memAboutToChange(p, pIn1);
78983  rc = ExpandBlob(pIn1);
78984  sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
78985  UPDATE_MAX_BLOBSIZE(pIn1);
78986  if( rc ) goto abort_due_to_error;
78987  break;
78988}
78989#endif /* SQLITE_OMIT_CAST */
78990
78991/* Opcode: Lt P1 P2 P3 P4 P5
78992** Synopsis: if r[P1]<r[P3] goto P2
78993**
78994** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
78995** jump to address P2.
78996**
78997** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
78998** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
78999** bit is clear then fall through if either operand is NULL.
79000**
79001** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
79002** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
79003** to coerce both inputs according to this affinity before the
79004** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
79005** affinity is used. Note that the affinity conversions are stored
79006** back into the input registers P1 and P3.  So this opcode can cause
79007** persistent changes to registers P1 and P3.
79008**
79009** Once any conversions have taken place, and neither value is NULL,
79010** the values are compared. If both values are blobs then memcmp() is
79011** used to determine the results of the comparison.  If both values
79012** are text, then the appropriate collating function specified in
79013** P4 is  used to do the comparison.  If P4 is not specified then
79014** memcmp() is used to compare text string.  If both values are
79015** numeric, then a numeric comparison is used. If the two values
79016** are of different types, then numbers are considered less than
79017** strings and strings are considered less than blobs.
79018**
79019** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
79020** store a boolean result (either 0, or 1, or NULL) in register P2.
79021**
79022** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
79023** equal to one another, provided that they do not have their MEM_Cleared
79024** bit set.
79025*/
79026/* Opcode: Ne P1 P2 P3 P4 P5
79027** Synopsis: if r[P1]!=r[P3] goto P2
79028**
79029** This works just like the Lt opcode except that the jump is taken if
79030** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
79031** additional information.
79032**
79033** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
79034** true or false and is never NULL.  If both operands are NULL then the result
79035** of comparison is false.  If either operand is NULL then the result is true.
79036** If neither operand is NULL the result is the same as it would be if
79037** the SQLITE_NULLEQ flag were omitted from P5.
79038*/
79039/* Opcode: Eq P1 P2 P3 P4 P5
79040** Synopsis: if r[P1]==r[P3] goto P2
79041**
79042** This works just like the Lt opcode except that the jump is taken if
79043** the operands in registers P1 and P3 are equal.
79044** See the Lt opcode for additional information.
79045**
79046** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
79047** true or false and is never NULL.  If both operands are NULL then the result
79048** of comparison is true.  If either operand is NULL then the result is false.
79049** If neither operand is NULL the result is the same as it would be if
79050** the SQLITE_NULLEQ flag were omitted from P5.
79051*/
79052/* Opcode: Le P1 P2 P3 P4 P5
79053** Synopsis: if r[P1]<=r[P3] goto P2
79054**
79055** This works just like the Lt opcode except that the jump is taken if
79056** the content of register P3 is less than or equal to the content of
79057** register P1.  See the Lt opcode for additional information.
79058*/
79059/* Opcode: Gt P1 P2 P3 P4 P5
79060** Synopsis: if r[P1]>r[P3] goto P2
79061**
79062** This works just like the Lt opcode except that the jump is taken if
79063** the content of register P3 is greater than the content of
79064** register P1.  See the Lt opcode for additional information.
79065*/
79066/* Opcode: Ge P1 P2 P3 P4 P5
79067** Synopsis: if r[P1]>=r[P3] goto P2
79068**
79069** This works just like the Lt opcode except that the jump is taken if
79070** the content of register P3 is greater than or equal to the content of
79071** register P1.  See the Lt opcode for additional information.
79072*/
79073case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
79074case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
79075case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
79076case OP_Le:               /* same as TK_LE, jump, in1, in3 */
79077case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
79078case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
79079  int res;            /* Result of the comparison of pIn1 against pIn3 */
79080  char affinity;      /* Affinity to use for comparison */
79081  u16 flags1;         /* Copy of initial value of pIn1->flags */
79082  u16 flags3;         /* Copy of initial value of pIn3->flags */
79083
79084  pIn1 = &aMem[pOp->p1];
79085  pIn3 = &aMem[pOp->p3];
79086  flags1 = pIn1->flags;
79087  flags3 = pIn3->flags;
79088  if( (flags1 | flags3)&MEM_Null ){
79089    /* One or both operands are NULL */
79090    if( pOp->p5 & SQLITE_NULLEQ ){
79091      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
79092      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
79093      ** or not both operands are null.
79094      */
79095      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
79096      assert( (flags1 & MEM_Cleared)==0 );
79097      assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
79098      if( (flags1&MEM_Null)!=0
79099       && (flags3&MEM_Null)!=0
79100       && (flags3&MEM_Cleared)==0
79101      ){
79102        res = 0;  /* Results are equal */
79103      }else{
79104        res = 1;  /* Results are not equal */
79105      }
79106    }else{
79107      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
79108      ** then the result is always NULL.
79109      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
79110      */
79111      if( pOp->p5 & SQLITE_STOREP2 ){
79112        pOut = &aMem[pOp->p2];
79113        memAboutToChange(p, pOut);
79114        MemSetTypeFlag(pOut, MEM_Null);
79115        REGISTER_TRACE(pOp->p2, pOut);
79116      }else{
79117        VdbeBranchTaken(2,3);
79118        if( pOp->p5 & SQLITE_JUMPIFNULL ){
79119          goto jump_to_p2;
79120        }
79121      }
79122      break;
79123    }
79124  }else{
79125    /* Neither operand is NULL.  Do a comparison. */
79126    affinity = pOp->p5 & SQLITE_AFF_MASK;
79127    if( affinity>=SQLITE_AFF_NUMERIC ){
79128      if( (flags1 | flags3)&MEM_Str ){
79129        if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
79130          applyNumericAffinity(pIn1,0);
79131          flags3 = pIn3->flags;
79132        }
79133        if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
79134          applyNumericAffinity(pIn3,0);
79135        }
79136      }
79137    }else if( affinity==SQLITE_AFF_TEXT ){
79138      if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
79139        testcase( pIn1->flags & MEM_Int );
79140        testcase( pIn1->flags & MEM_Real );
79141        sqlite3VdbeMemStringify(pIn1, encoding, 1);
79142        testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
79143        flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
79144        flags3 = pIn3->flags;
79145      }
79146      if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
79147        testcase( pIn3->flags & MEM_Int );
79148        testcase( pIn3->flags & MEM_Real );
79149        sqlite3VdbeMemStringify(pIn3, encoding, 1);
79150        testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
79151        flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
79152      }
79153    }
79154    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
79155    if( flags1 & MEM_Zero ){
79156      sqlite3VdbeMemExpandBlob(pIn1);
79157      flags1 &= ~MEM_Zero;
79158    }
79159    if( flags3 & MEM_Zero ){
79160      sqlite3VdbeMemExpandBlob(pIn3);
79161      flags3 &= ~MEM_Zero;
79162    }
79163    res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
79164  }
79165  switch( pOp->opcode ){
79166    case OP_Eq:    res = res==0;     break;
79167    case OP_Ne:    res = res!=0;     break;
79168    case OP_Lt:    res = res<0;      break;
79169    case OP_Le:    res = res<=0;     break;
79170    case OP_Gt:    res = res>0;      break;
79171    default:       res = res>=0;     break;
79172  }
79173
79174  /* Undo any changes made by applyAffinity() to the input registers. */
79175  assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
79176  pIn1->flags = flags1;
79177  assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
79178  pIn3->flags = flags3;
79179
79180  if( pOp->p5 & SQLITE_STOREP2 ){
79181    pOut = &aMem[pOp->p2];
79182    memAboutToChange(p, pOut);
79183    MemSetTypeFlag(pOut, MEM_Int);
79184    pOut->u.i = res;
79185    REGISTER_TRACE(pOp->p2, pOut);
79186  }else{
79187    VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
79188    if( res ){
79189      goto jump_to_p2;
79190    }
79191  }
79192  break;
79193}
79194
79195/* Opcode: Permutation * * * P4 *
79196**
79197** Set the permutation used by the OP_Compare operator to be the array
79198** of integers in P4.
79199**
79200** The permutation is only valid until the next OP_Compare that has
79201** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
79202** occur immediately prior to the OP_Compare.
79203**
79204** The first integer in the P4 integer array is the length of the array
79205** and does not become part of the permutation.
79206*/
79207case OP_Permutation: {
79208  assert( pOp->p4type==P4_INTARRAY );
79209  assert( pOp->p4.ai );
79210  aPermute = pOp->p4.ai + 1;
79211  break;
79212}
79213
79214/* Opcode: Compare P1 P2 P3 P4 P5
79215** Synopsis: r[P1@P3] <-> r[P2@P3]
79216**
79217** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
79218** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
79219** the comparison for use by the next OP_Jump instruct.
79220**
79221** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
79222** determined by the most recent OP_Permutation operator.  If the
79223** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
79224** order.
79225**
79226** P4 is a KeyInfo structure that defines collating sequences and sort
79227** orders for the comparison.  The permutation applies to registers
79228** only.  The KeyInfo elements are used sequentially.
79229**
79230** The comparison is a sort comparison, so NULLs compare equal,
79231** NULLs are less than numbers, numbers are less than strings,
79232** and strings are less than blobs.
79233*/
79234case OP_Compare: {
79235  int n;
79236  int i;
79237  int p1;
79238  int p2;
79239  const KeyInfo *pKeyInfo;
79240  int idx;
79241  CollSeq *pColl;    /* Collating sequence to use on this term */
79242  int bRev;          /* True for DESCENDING sort order */
79243
79244  if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
79245  n = pOp->p3;
79246  pKeyInfo = pOp->p4.pKeyInfo;
79247  assert( n>0 );
79248  assert( pKeyInfo!=0 );
79249  p1 = pOp->p1;
79250  p2 = pOp->p2;
79251#if SQLITE_DEBUG
79252  if( aPermute ){
79253    int k, mx = 0;
79254    for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
79255    assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
79256    assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
79257  }else{
79258    assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
79259    assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
79260  }
79261#endif /* SQLITE_DEBUG */
79262  for(i=0; i<n; i++){
79263    idx = aPermute ? aPermute[i] : i;
79264    assert( memIsValid(&aMem[p1+idx]) );
79265    assert( memIsValid(&aMem[p2+idx]) );
79266    REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
79267    REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
79268    assert( i<pKeyInfo->nField );
79269    pColl = pKeyInfo->aColl[i];
79270    bRev = pKeyInfo->aSortOrder[i];
79271    iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
79272    if( iCompare ){
79273      if( bRev ) iCompare = -iCompare;
79274      break;
79275    }
79276  }
79277  aPermute = 0;
79278  break;
79279}
79280
79281/* Opcode: Jump P1 P2 P3 * *
79282**
79283** Jump to the instruction at address P1, P2, or P3 depending on whether
79284** in the most recent OP_Compare instruction the P1 vector was less than
79285** equal to, or greater than the P2 vector, respectively.
79286*/
79287case OP_Jump: {             /* jump */
79288  if( iCompare<0 ){
79289    VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
79290  }else if( iCompare==0 ){
79291    VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
79292  }else{
79293    VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
79294  }
79295  break;
79296}
79297
79298/* Opcode: And P1 P2 P3 * *
79299** Synopsis: r[P3]=(r[P1] && r[P2])
79300**
79301** Take the logical AND of the values in registers P1 and P2 and
79302** write the result into register P3.
79303**
79304** If either P1 or P2 is 0 (false) then the result is 0 even if
79305** the other input is NULL.  A NULL and true or two NULLs give
79306** a NULL output.
79307*/
79308/* Opcode: Or P1 P2 P3 * *
79309** Synopsis: r[P3]=(r[P1] || r[P2])
79310**
79311** Take the logical OR of the values in register P1 and P2 and
79312** store the answer in register P3.
79313**
79314** If either P1 or P2 is nonzero (true) then the result is 1 (true)
79315** even if the other input is NULL.  A NULL and false or two NULLs
79316** give a NULL output.
79317*/
79318case OP_And:              /* same as TK_AND, in1, in2, out3 */
79319case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
79320  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
79321  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
79322
79323  pIn1 = &aMem[pOp->p1];
79324  if( pIn1->flags & MEM_Null ){
79325    v1 = 2;
79326  }else{
79327    v1 = sqlite3VdbeIntValue(pIn1)!=0;
79328  }
79329  pIn2 = &aMem[pOp->p2];
79330  if( pIn2->flags & MEM_Null ){
79331    v2 = 2;
79332  }else{
79333    v2 = sqlite3VdbeIntValue(pIn2)!=0;
79334  }
79335  if( pOp->opcode==OP_And ){
79336    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
79337    v1 = and_logic[v1*3+v2];
79338  }else{
79339    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
79340    v1 = or_logic[v1*3+v2];
79341  }
79342  pOut = &aMem[pOp->p3];
79343  if( v1==2 ){
79344    MemSetTypeFlag(pOut, MEM_Null);
79345  }else{
79346    pOut->u.i = v1;
79347    MemSetTypeFlag(pOut, MEM_Int);
79348  }
79349  break;
79350}
79351
79352/* Opcode: Not P1 P2 * * *
79353** Synopsis: r[P2]= !r[P1]
79354**
79355** Interpret the value in register P1 as a boolean value.  Store the
79356** boolean complement in register P2.  If the value in register P1 is
79357** NULL, then a NULL is stored in P2.
79358*/
79359case OP_Not: {                /* same as TK_NOT, in1, out2 */
79360  pIn1 = &aMem[pOp->p1];
79361  pOut = &aMem[pOp->p2];
79362  sqlite3VdbeMemSetNull(pOut);
79363  if( (pIn1->flags & MEM_Null)==0 ){
79364    pOut->flags = MEM_Int;
79365    pOut->u.i = !sqlite3VdbeIntValue(pIn1);
79366  }
79367  break;
79368}
79369
79370/* Opcode: BitNot P1 P2 * * *
79371** Synopsis: r[P1]= ~r[P1]
79372**
79373** Interpret the content of register P1 as an integer.  Store the
79374** ones-complement of the P1 value into register P2.  If P1 holds
79375** a NULL then store a NULL in P2.
79376*/
79377case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
79378  pIn1 = &aMem[pOp->p1];
79379  pOut = &aMem[pOp->p2];
79380  sqlite3VdbeMemSetNull(pOut);
79381  if( (pIn1->flags & MEM_Null)==0 ){
79382    pOut->flags = MEM_Int;
79383    pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
79384  }
79385  break;
79386}
79387
79388/* Opcode: Once P1 P2 * * *
79389**
79390** Check the "once" flag number P1. If it is set, jump to instruction P2.
79391** Otherwise, set the flag and fall through to the next instruction.
79392** In other words, this opcode causes all following opcodes up through P2
79393** (but not including P2) to run just once and to be skipped on subsequent
79394** times through the loop.
79395**
79396** All "once" flags are initially cleared whenever a prepared statement
79397** first begins to run.
79398*/
79399case OP_Once: {             /* jump */
79400  assert( pOp->p1<p->nOnceFlag );
79401  VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
79402  if( p->aOnceFlag[pOp->p1] ){
79403    goto jump_to_p2;
79404  }else{
79405    p->aOnceFlag[pOp->p1] = 1;
79406  }
79407  break;
79408}
79409
79410/* Opcode: If P1 P2 P3 * *
79411**
79412** Jump to P2 if the value in register P1 is true.  The value
79413** is considered true if it is numeric and non-zero.  If the value
79414** in P1 is NULL then take the jump if and only if P3 is non-zero.
79415*/
79416/* Opcode: IfNot P1 P2 P3 * *
79417**
79418** Jump to P2 if the value in register P1 is False.  The value
79419** is considered false if it has a numeric value of zero.  If the value
79420** in P1 is NULL then take the jump if and only if P3 is non-zero.
79421*/
79422case OP_If:                 /* jump, in1 */
79423case OP_IfNot: {            /* jump, in1 */
79424  int c;
79425  pIn1 = &aMem[pOp->p1];
79426  if( pIn1->flags & MEM_Null ){
79427    c = pOp->p3;
79428  }else{
79429#ifdef SQLITE_OMIT_FLOATING_POINT
79430    c = sqlite3VdbeIntValue(pIn1)!=0;
79431#else
79432    c = sqlite3VdbeRealValue(pIn1)!=0.0;
79433#endif
79434    if( pOp->opcode==OP_IfNot ) c = !c;
79435  }
79436  VdbeBranchTaken(c!=0, 2);
79437  if( c ){
79438    goto jump_to_p2;
79439  }
79440  break;
79441}
79442
79443/* Opcode: IsNull P1 P2 * * *
79444** Synopsis:  if r[P1]==NULL goto P2
79445**
79446** Jump to P2 if the value in register P1 is NULL.
79447*/
79448case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
79449  pIn1 = &aMem[pOp->p1];
79450  VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
79451  if( (pIn1->flags & MEM_Null)!=0 ){
79452    goto jump_to_p2;
79453  }
79454  break;
79455}
79456
79457/* Opcode: NotNull P1 P2 * * *
79458** Synopsis: if r[P1]!=NULL goto P2
79459**
79460** Jump to P2 if the value in register P1 is not NULL.
79461*/
79462case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
79463  pIn1 = &aMem[pOp->p1];
79464  VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
79465  if( (pIn1->flags & MEM_Null)==0 ){
79466    goto jump_to_p2;
79467  }
79468  break;
79469}
79470
79471/* Opcode: Column P1 P2 P3 P4 P5
79472** Synopsis:  r[P3]=PX
79473**
79474** Interpret the data that cursor P1 points to as a structure built using
79475** the MakeRecord instruction.  (See the MakeRecord opcode for additional
79476** information about the format of the data.)  Extract the P2-th column
79477** from this record.  If there are less that (P2+1)
79478** values in the record, extract a NULL.
79479**
79480** The value extracted is stored in register P3.
79481**
79482** If the column contains fewer than P2 fields, then extract a NULL.  Or,
79483** if the P4 argument is a P4_MEM use the value of the P4 argument as
79484** the result.
79485**
79486** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
79487** then the cache of the cursor is reset prior to extracting the column.
79488** The first OP_Column against a pseudo-table after the value of the content
79489** register has changed should have this bit set.
79490**
79491** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
79492** the result is guaranteed to only be used as the argument of a length()
79493** or typeof() function, respectively.  The loading of large blobs can be
79494** skipped for length() and all content loading can be skipped for typeof().
79495*/
79496case OP_Column: {
79497  int p2;            /* column number to retrieve */
79498  VdbeCursor *pC;    /* The VDBE cursor */
79499  BtCursor *pCrsr;   /* The BTree cursor */
79500  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
79501  int len;           /* The length of the serialized data for the column */
79502  int i;             /* Loop counter */
79503  Mem *pDest;        /* Where to write the extracted value */
79504  Mem sMem;          /* For storing the record being decoded */
79505  const u8 *zData;   /* Part of the record being decoded */
79506  const u8 *zHdr;    /* Next unparsed byte of the header */
79507  const u8 *zEndHdr; /* Pointer to first byte after the header */
79508  u32 offset;        /* Offset into the data */
79509  u64 offset64;      /* 64-bit offset */
79510  u32 avail;         /* Number of bytes of available data */
79511  u32 t;             /* A type code from the record header */
79512  Mem *pReg;         /* PseudoTable input register */
79513
79514  pC = p->apCsr[pOp->p1];
79515  p2 = pOp->p2;
79516
79517  /* If the cursor cache is stale, bring it up-to-date */
79518  rc = sqlite3VdbeCursorMoveto(&pC, &p2);
79519  if( rc ) goto abort_due_to_error;
79520
79521  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
79522  pDest = &aMem[pOp->p3];
79523  memAboutToChange(p, pDest);
79524  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
79525  assert( pC!=0 );
79526  assert( p2<pC->nField );
79527  aOffset = pC->aOffset;
79528  assert( pC->eCurType!=CURTYPE_VTAB );
79529  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
79530  assert( pC->eCurType!=CURTYPE_SORTER );
79531  pCrsr = pC->uc.pCursor;
79532
79533  if( pC->cacheStatus!=p->cacheCtr ){                /*OPTIMIZATION-IF-FALSE*/
79534    if( pC->nullRow ){
79535      if( pC->eCurType==CURTYPE_PSEUDO ){
79536        assert( pC->uc.pseudoTableReg>0 );
79537        pReg = &aMem[pC->uc.pseudoTableReg];
79538        assert( pReg->flags & MEM_Blob );
79539        assert( memIsValid(pReg) );
79540        pC->payloadSize = pC->szRow = avail = pReg->n;
79541        pC->aRow = (u8*)pReg->z;
79542      }else{
79543        sqlite3VdbeMemSetNull(pDest);
79544        goto op_column_out;
79545      }
79546    }else{
79547      assert( pC->eCurType==CURTYPE_BTREE );
79548      assert( pCrsr );
79549      assert( sqlite3BtreeCursorIsValid(pCrsr) );
79550      pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
79551      pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &avail);
79552      assert( avail<=65536 );  /* Maximum page size is 64KiB */
79553      if( pC->payloadSize <= (u32)avail ){
79554        pC->szRow = pC->payloadSize;
79555      }else if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
79556        goto too_big;
79557      }else{
79558        pC->szRow = avail;
79559      }
79560    }
79561    pC->cacheStatus = p->cacheCtr;
79562    pC->iHdrOffset = getVarint32(pC->aRow, offset);
79563    pC->nHdrParsed = 0;
79564    aOffset[0] = offset;
79565
79566
79567    if( avail<offset ){      /*OPTIMIZATION-IF-FALSE*/
79568      /* pC->aRow does not have to hold the entire row, but it does at least
79569      ** need to cover the header of the record.  If pC->aRow does not contain
79570      ** the complete header, then set it to zero, forcing the header to be
79571      ** dynamically allocated. */
79572      pC->aRow = 0;
79573      pC->szRow = 0;
79574
79575      /* Make sure a corrupt database has not given us an oversize header.
79576      ** Do this now to avoid an oversize memory allocation.
79577      **
79578      ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
79579      ** types use so much data space that there can only be 4096 and 32 of
79580      ** them, respectively.  So the maximum header length results from a
79581      ** 3-byte type for each of the maximum of 32768 columns plus three
79582      ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
79583      */
79584      if( offset > 98307 || offset > pC->payloadSize ){
79585        rc = SQLITE_CORRUPT_BKPT;
79586        goto abort_due_to_error;
79587      }
79588    }else if( offset>0 ){ /*OPTIMIZATION-IF-TRUE*/
79589      /* The following goto is an optimization.  It can be omitted and
79590      ** everything will still work.  But OP_Column is measurably faster
79591      ** by skipping the subsequent conditional, which is always true.
79592      */
79593      zData = pC->aRow;
79594      assert( pC->nHdrParsed<=p2 );         /* Conditional skipped */
79595      goto op_column_read_header;
79596    }
79597  }
79598
79599  /* Make sure at least the first p2+1 entries of the header have been
79600  ** parsed and valid information is in aOffset[] and pC->aType[].
79601  */
79602  if( pC->nHdrParsed<=p2 ){
79603    /* If there is more header available for parsing in the record, try
79604    ** to extract additional fields up through the p2+1-th field
79605    */
79606    if( pC->iHdrOffset<aOffset[0] ){
79607      /* Make sure zData points to enough of the record to cover the header. */
79608      if( pC->aRow==0 ){
79609        memset(&sMem, 0, sizeof(sMem));
79610        rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0], !pC->isTable, &sMem);
79611        if( rc!=SQLITE_OK ) goto abort_due_to_error;
79612        zData = (u8*)sMem.z;
79613      }else{
79614        zData = pC->aRow;
79615      }
79616
79617      /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
79618    op_column_read_header:
79619      i = pC->nHdrParsed;
79620      offset64 = aOffset[i];
79621      zHdr = zData + pC->iHdrOffset;
79622      zEndHdr = zData + aOffset[0];
79623      do{
79624        if( (t = zHdr[0])<0x80 ){
79625          zHdr++;
79626          offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
79627        }else{
79628          zHdr += sqlite3GetVarint32(zHdr, &t);
79629          offset64 += sqlite3VdbeSerialTypeLen(t);
79630        }
79631        pC->aType[i++] = t;
79632        aOffset[i] = (u32)(offset64 & 0xffffffff);
79633      }while( i<=p2 && zHdr<zEndHdr );
79634
79635      /* The record is corrupt if any of the following are true:
79636      ** (1) the bytes of the header extend past the declared header size
79637      ** (2) the entire header was used but not all data was used
79638      ** (3) the end of the data extends beyond the end of the record.
79639      */
79640      if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
79641       || (offset64 > pC->payloadSize)
79642      ){
79643        if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
79644        rc = SQLITE_CORRUPT_BKPT;
79645        goto abort_due_to_error;
79646      }
79647
79648      pC->nHdrParsed = i;
79649      pC->iHdrOffset = (u32)(zHdr - zData);
79650      if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
79651    }else{
79652      t = 0;
79653    }
79654
79655    /* If after trying to extract new entries from the header, nHdrParsed is
79656    ** still not up to p2, that means that the record has fewer than p2
79657    ** columns.  So the result will be either the default value or a NULL.
79658    */
79659    if( pC->nHdrParsed<=p2 ){
79660      if( pOp->p4type==P4_MEM ){
79661        sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
79662      }else{
79663        sqlite3VdbeMemSetNull(pDest);
79664      }
79665      goto op_column_out;
79666    }
79667  }else{
79668    t = pC->aType[p2];
79669  }
79670
79671  /* Extract the content for the p2+1-th column.  Control can only
79672  ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
79673  ** all valid.
79674  */
79675  assert( p2<pC->nHdrParsed );
79676  assert( rc==SQLITE_OK );
79677  assert( sqlite3VdbeCheckMemInvariants(pDest) );
79678  if( VdbeMemDynamic(pDest) ){
79679    sqlite3VdbeMemSetNull(pDest);
79680  }
79681  assert( t==pC->aType[p2] );
79682  if( pC->szRow>=aOffset[p2+1] ){
79683    /* This is the common case where the desired content fits on the original
79684    ** page - where the content is not on an overflow page */
79685    zData = pC->aRow + aOffset[p2];
79686    if( t<12 ){
79687      sqlite3VdbeSerialGet(zData, t, pDest);
79688    }else{
79689      /* If the column value is a string, we need a persistent value, not
79690      ** a MEM_Ephem value.  This branch is a fast short-cut that is equivalent
79691      ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
79692      */
79693      static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
79694      pDest->n = len = (t-12)/2;
79695      pDest->enc = encoding;
79696      if( pDest->szMalloc < len+2 ){
79697        pDest->flags = MEM_Null;
79698        if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
79699      }else{
79700        pDest->z = pDest->zMalloc;
79701      }
79702      memcpy(pDest->z, zData, len);
79703      pDest->z[len] = 0;
79704      pDest->z[len+1] = 0;
79705      pDest->flags = aFlag[t&1];
79706    }
79707  }else{
79708    pDest->enc = encoding;
79709    /* This branch happens only when content is on overflow pages */
79710    if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
79711          && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
79712     || (len = sqlite3VdbeSerialTypeLen(t))==0
79713    ){
79714      /* Content is irrelevant for
79715      **    1. the typeof() function,
79716      **    2. the length(X) function if X is a blob, and
79717      **    3. if the content length is zero.
79718      ** So we might as well use bogus content rather than reading
79719      ** content from disk. */
79720      static u8 aZero[8];  /* This is the bogus content */
79721      sqlite3VdbeSerialGet(aZero, t, pDest);
79722    }else{
79723      rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
79724                                   pDest);
79725      if( rc!=SQLITE_OK ) goto abort_due_to_error;
79726      sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
79727      pDest->flags &= ~MEM_Ephem;
79728    }
79729  }
79730
79731op_column_out:
79732  UPDATE_MAX_BLOBSIZE(pDest);
79733  REGISTER_TRACE(pOp->p3, pDest);
79734  break;
79735}
79736
79737/* Opcode: Affinity P1 P2 * P4 *
79738** Synopsis: affinity(r[P1@P2])
79739**
79740** Apply affinities to a range of P2 registers starting with P1.
79741**
79742** P4 is a string that is P2 characters long. The nth character of the
79743** string indicates the column affinity that should be used for the nth
79744** memory cell in the range.
79745*/
79746case OP_Affinity: {
79747  const char *zAffinity;   /* The affinity to be applied */
79748  char cAff;               /* A single character of affinity */
79749
79750  zAffinity = pOp->p4.z;
79751  assert( zAffinity!=0 );
79752  assert( zAffinity[pOp->p2]==0 );
79753  pIn1 = &aMem[pOp->p1];
79754  while( (cAff = *(zAffinity++))!=0 ){
79755    assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
79756    assert( memIsValid(pIn1) );
79757    applyAffinity(pIn1, cAff, encoding);
79758    pIn1++;
79759  }
79760  break;
79761}
79762
79763/* Opcode: MakeRecord P1 P2 P3 P4 *
79764** Synopsis: r[P3]=mkrec(r[P1@P2])
79765**
79766** Convert P2 registers beginning with P1 into the [record format]
79767** use as a data record in a database table or as a key
79768** in an index.  The OP_Column opcode can decode the record later.
79769**
79770** P4 may be a string that is P2 characters long.  The nth character of the
79771** string indicates the column affinity that should be used for the nth
79772** field of the index key.
79773**
79774** The mapping from character to affinity is given by the SQLITE_AFF_
79775** macros defined in sqliteInt.h.
79776**
79777** If P4 is NULL then all index fields have the affinity BLOB.
79778*/
79779case OP_MakeRecord: {
79780  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
79781  Mem *pRec;             /* The new record */
79782  u64 nData;             /* Number of bytes of data space */
79783  int nHdr;              /* Number of bytes of header space */
79784  i64 nByte;             /* Data space required for this record */
79785  i64 nZero;             /* Number of zero bytes at the end of the record */
79786  int nVarint;           /* Number of bytes in a varint */
79787  u32 serial_type;       /* Type field */
79788  Mem *pData0;           /* First field to be combined into the record */
79789  Mem *pLast;            /* Last field of the record */
79790  int nField;            /* Number of fields in the record */
79791  char *zAffinity;       /* The affinity string for the record */
79792  int file_format;       /* File format to use for encoding */
79793  int i;                 /* Space used in zNewRecord[] header */
79794  int j;                 /* Space used in zNewRecord[] content */
79795  u32 len;               /* Length of a field */
79796
79797  /* Assuming the record contains N fields, the record format looks
79798  ** like this:
79799  **
79800  ** ------------------------------------------------------------------------
79801  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
79802  ** ------------------------------------------------------------------------
79803  **
79804  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
79805  ** and so forth.
79806  **
79807  ** Each type field is a varint representing the serial type of the
79808  ** corresponding data element (see sqlite3VdbeSerialType()). The
79809  ** hdr-size field is also a varint which is the offset from the beginning
79810  ** of the record to data0.
79811  */
79812  nData = 0;         /* Number of bytes of data space */
79813  nHdr = 0;          /* Number of bytes of header space */
79814  nZero = 0;         /* Number of zero bytes at the end of the record */
79815  nField = pOp->p1;
79816  zAffinity = pOp->p4.z;
79817  assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
79818  pData0 = &aMem[nField];
79819  nField = pOp->p2;
79820  pLast = &pData0[nField-1];
79821  file_format = p->minWriteFileFormat;
79822
79823  /* Identify the output register */
79824  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
79825  pOut = &aMem[pOp->p3];
79826  memAboutToChange(p, pOut);
79827
79828  /* Apply the requested affinity to all inputs
79829  */
79830  assert( pData0<=pLast );
79831  if( zAffinity ){
79832    pRec = pData0;
79833    do{
79834      applyAffinity(pRec++, *(zAffinity++), encoding);
79835      assert( zAffinity[0]==0 || pRec<=pLast );
79836    }while( zAffinity[0] );
79837  }
79838
79839  /* Loop through the elements that will make up the record to figure
79840  ** out how much space is required for the new record.
79841  */
79842  pRec = pLast;
79843  do{
79844    assert( memIsValid(pRec) );
79845    pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
79846    if( pRec->flags & MEM_Zero ){
79847      if( nData ){
79848        if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
79849      }else{
79850        nZero += pRec->u.nZero;
79851        len -= pRec->u.nZero;
79852      }
79853    }
79854    nData += len;
79855    testcase( serial_type==127 );
79856    testcase( serial_type==128 );
79857    nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
79858    if( pRec==pData0 ) break;
79859    pRec--;
79860  }while(1);
79861
79862  /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
79863  ** which determines the total number of bytes in the header. The varint
79864  ** value is the size of the header in bytes including the size varint
79865  ** itself. */
79866  testcase( nHdr==126 );
79867  testcase( nHdr==127 );
79868  if( nHdr<=126 ){
79869    /* The common case */
79870    nHdr += 1;
79871  }else{
79872    /* Rare case of a really large header */
79873    nVarint = sqlite3VarintLen(nHdr);
79874    nHdr += nVarint;
79875    if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
79876  }
79877  nByte = nHdr+nData;
79878  if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
79879    goto too_big;
79880  }
79881
79882  /* Make sure the output register has a buffer large enough to store
79883  ** the new record. The output register (pOp->p3) is not allowed to
79884  ** be one of the input registers (because the following call to
79885  ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
79886  */
79887  if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
79888    goto no_mem;
79889  }
79890  zNewRecord = (u8 *)pOut->z;
79891
79892  /* Write the record */
79893  i = putVarint32(zNewRecord, nHdr);
79894  j = nHdr;
79895  assert( pData0<=pLast );
79896  pRec = pData0;
79897  do{
79898    serial_type = pRec->uTemp;
79899    /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
79900    ** additional varints, one per column. */
79901    i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
79902    /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
79903    ** immediately follow the header. */
79904    j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
79905  }while( (++pRec)<=pLast );
79906  assert( i==nHdr );
79907  assert( j==nByte );
79908
79909  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
79910  pOut->n = (int)nByte;
79911  pOut->flags = MEM_Blob;
79912  if( nZero ){
79913    pOut->u.nZero = nZero;
79914    pOut->flags |= MEM_Zero;
79915  }
79916  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
79917  REGISTER_TRACE(pOp->p3, pOut);
79918  UPDATE_MAX_BLOBSIZE(pOut);
79919  break;
79920}
79921
79922/* Opcode: Count P1 P2 * * *
79923** Synopsis: r[P2]=count()
79924**
79925** Store the number of entries (an integer value) in the table or index
79926** opened by cursor P1 in register P2
79927*/
79928#ifndef SQLITE_OMIT_BTREECOUNT
79929case OP_Count: {         /* out2 */
79930  i64 nEntry;
79931  BtCursor *pCrsr;
79932
79933  assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
79934  pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
79935  assert( pCrsr );
79936  nEntry = 0;  /* Not needed.  Only used to silence a warning. */
79937  rc = sqlite3BtreeCount(pCrsr, &nEntry);
79938  if( rc ) goto abort_due_to_error;
79939  pOut = out2Prerelease(p, pOp);
79940  pOut->u.i = nEntry;
79941  break;
79942}
79943#endif
79944
79945/* Opcode: Savepoint P1 * * P4 *
79946**
79947** Open, release or rollback the savepoint named by parameter P4, depending
79948** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
79949** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
79950*/
79951case OP_Savepoint: {
79952  int p1;                         /* Value of P1 operand */
79953  char *zName;                    /* Name of savepoint */
79954  int nName;
79955  Savepoint *pNew;
79956  Savepoint *pSavepoint;
79957  Savepoint *pTmp;
79958  int iSavepoint;
79959  int ii;
79960
79961  p1 = pOp->p1;
79962  zName = pOp->p4.z;
79963
79964  /* Assert that the p1 parameter is valid. Also that if there is no open
79965  ** transaction, then there cannot be any savepoints.
79966  */
79967  assert( db->pSavepoint==0 || db->autoCommit==0 );
79968  assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
79969  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
79970  assert( checkSavepointCount(db) );
79971  assert( p->bIsReader );
79972
79973  if( p1==SAVEPOINT_BEGIN ){
79974    if( db->nVdbeWrite>0 ){
79975      /* A new savepoint cannot be created if there are active write
79976      ** statements (i.e. open read/write incremental blob handles).
79977      */
79978      sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
79979      rc = SQLITE_BUSY;
79980    }else{
79981      nName = sqlite3Strlen30(zName);
79982
79983#ifndef SQLITE_OMIT_VIRTUALTABLE
79984      /* This call is Ok even if this savepoint is actually a transaction
79985      ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
79986      ** If this is a transaction savepoint being opened, it is guaranteed
79987      ** that the db->aVTrans[] array is empty.  */
79988      assert( db->autoCommit==0 || db->nVTrans==0 );
79989      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
79990                                db->nStatement+db->nSavepoint);
79991      if( rc!=SQLITE_OK ) goto abort_due_to_error;
79992#endif
79993
79994      /* Create a new savepoint structure. */
79995      pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
79996      if( pNew ){
79997        pNew->zName = (char *)&pNew[1];
79998        memcpy(pNew->zName, zName, nName+1);
79999
80000        /* If there is no open transaction, then mark this as a special
80001        ** "transaction savepoint". */
80002        if( db->autoCommit ){
80003          db->autoCommit = 0;
80004          db->isTransactionSavepoint = 1;
80005        }else{
80006          db->nSavepoint++;
80007        }
80008
80009        /* Link the new savepoint into the database handle's list. */
80010        pNew->pNext = db->pSavepoint;
80011        db->pSavepoint = pNew;
80012        pNew->nDeferredCons = db->nDeferredCons;
80013        pNew->nDeferredImmCons = db->nDeferredImmCons;
80014      }
80015    }
80016  }else{
80017    iSavepoint = 0;
80018
80019    /* Find the named savepoint. If there is no such savepoint, then an
80020    ** an error is returned to the user.  */
80021    for(
80022      pSavepoint = db->pSavepoint;
80023      pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
80024      pSavepoint = pSavepoint->pNext
80025    ){
80026      iSavepoint++;
80027    }
80028    if( !pSavepoint ){
80029      sqlite3VdbeError(p, "no such savepoint: %s", zName);
80030      rc = SQLITE_ERROR;
80031    }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
80032      /* It is not possible to release (commit) a savepoint if there are
80033      ** active write statements.
80034      */
80035      sqlite3VdbeError(p, "cannot release savepoint - "
80036                          "SQL statements in progress");
80037      rc = SQLITE_BUSY;
80038    }else{
80039
80040      /* Determine whether or not this is a transaction savepoint. If so,
80041      ** and this is a RELEASE command, then the current transaction
80042      ** is committed.
80043      */
80044      int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
80045      if( isTransaction && p1==SAVEPOINT_RELEASE ){
80046        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
80047          goto vdbe_return;
80048        }
80049        db->autoCommit = 1;
80050        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
80051          p->pc = (int)(pOp - aOp);
80052          db->autoCommit = 0;
80053          p->rc = rc = SQLITE_BUSY;
80054          goto vdbe_return;
80055        }
80056        db->isTransactionSavepoint = 0;
80057        rc = p->rc;
80058      }else{
80059        int isSchemaChange;
80060        iSavepoint = db->nSavepoint - iSavepoint - 1;
80061        if( p1==SAVEPOINT_ROLLBACK ){
80062          isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
80063          for(ii=0; ii<db->nDb; ii++){
80064            rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
80065                                       SQLITE_ABORT_ROLLBACK,
80066                                       isSchemaChange==0);
80067            if( rc!=SQLITE_OK ) goto abort_due_to_error;
80068          }
80069        }else{
80070          isSchemaChange = 0;
80071        }
80072        for(ii=0; ii<db->nDb; ii++){
80073          rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
80074          if( rc!=SQLITE_OK ){
80075            goto abort_due_to_error;
80076          }
80077        }
80078        if( isSchemaChange ){
80079          sqlite3ExpirePreparedStatements(db);
80080          sqlite3ResetAllSchemasOfConnection(db);
80081          db->flags = (db->flags | SQLITE_InternChanges);
80082        }
80083      }
80084
80085      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
80086      ** savepoints nested inside of the savepoint being operated on. */
80087      while( db->pSavepoint!=pSavepoint ){
80088        pTmp = db->pSavepoint;
80089        db->pSavepoint = pTmp->pNext;
80090        sqlite3DbFree(db, pTmp);
80091        db->nSavepoint--;
80092      }
80093
80094      /* If it is a RELEASE, then destroy the savepoint being operated on
80095      ** too. If it is a ROLLBACK TO, then set the number of deferred
80096      ** constraint violations present in the database to the value stored
80097      ** when the savepoint was created.  */
80098      if( p1==SAVEPOINT_RELEASE ){
80099        assert( pSavepoint==db->pSavepoint );
80100        db->pSavepoint = pSavepoint->pNext;
80101        sqlite3DbFree(db, pSavepoint);
80102        if( !isTransaction ){
80103          db->nSavepoint--;
80104        }
80105      }else{
80106        db->nDeferredCons = pSavepoint->nDeferredCons;
80107        db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
80108      }
80109
80110      if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
80111        rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
80112        if( rc!=SQLITE_OK ) goto abort_due_to_error;
80113      }
80114    }
80115  }
80116  if( rc ) goto abort_due_to_error;
80117
80118  break;
80119}
80120
80121/* Opcode: AutoCommit P1 P2 * * *
80122**
80123** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
80124** back any currently active btree transactions. If there are any active
80125** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
80126** there are active writing VMs or active VMs that use shared cache.
80127**
80128** This instruction causes the VM to halt.
80129*/
80130case OP_AutoCommit: {
80131  int desiredAutoCommit;
80132  int iRollback;
80133
80134  desiredAutoCommit = pOp->p1;
80135  iRollback = pOp->p2;
80136  assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
80137  assert( desiredAutoCommit==1 || iRollback==0 );
80138  assert( db->nVdbeActive>0 );  /* At least this one VM is active */
80139  assert( p->bIsReader );
80140
80141  if( desiredAutoCommit!=db->autoCommit ){
80142    if( iRollback ){
80143      assert( desiredAutoCommit==1 );
80144      sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
80145      db->autoCommit = 1;
80146    }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
80147      /* If this instruction implements a COMMIT and other VMs are writing
80148      ** return an error indicating that the other VMs must complete first.
80149      */
80150      sqlite3VdbeError(p, "cannot commit transaction - "
80151                          "SQL statements in progress");
80152      rc = SQLITE_BUSY;
80153      goto abort_due_to_error;
80154    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
80155      goto vdbe_return;
80156    }else{
80157      db->autoCommit = (u8)desiredAutoCommit;
80158    }
80159    if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
80160      p->pc = (int)(pOp - aOp);
80161      db->autoCommit = (u8)(1-desiredAutoCommit);
80162      p->rc = rc = SQLITE_BUSY;
80163      goto vdbe_return;
80164    }
80165    assert( db->nStatement==0 );
80166    sqlite3CloseSavepoints(db);
80167    if( p->rc==SQLITE_OK ){
80168      rc = SQLITE_DONE;
80169    }else{
80170      rc = SQLITE_ERROR;
80171    }
80172    goto vdbe_return;
80173  }else{
80174    sqlite3VdbeError(p,
80175        (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
80176        (iRollback)?"cannot rollback - no transaction is active":
80177                   "cannot commit - no transaction is active"));
80178
80179    rc = SQLITE_ERROR;
80180    goto abort_due_to_error;
80181  }
80182  break;
80183}
80184
80185/* Opcode: Transaction P1 P2 P3 P4 P5
80186**
80187** Begin a transaction on database P1 if a transaction is not already
80188** active.
80189** If P2 is non-zero, then a write-transaction is started, or if a
80190** read-transaction is already active, it is upgraded to a write-transaction.
80191** If P2 is zero, then a read-transaction is started.
80192**
80193** P1 is the index of the database file on which the transaction is
80194** started.  Index 0 is the main database file and index 1 is the
80195** file used for temporary tables.  Indices of 2 or more are used for
80196** attached databases.
80197**
80198** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
80199** true (this flag is set if the Vdbe may modify more than one row and may
80200** throw an ABORT exception), a statement transaction may also be opened.
80201** More specifically, a statement transaction is opened iff the database
80202** connection is currently not in autocommit mode, or if there are other
80203** active statements. A statement transaction allows the changes made by this
80204** VDBE to be rolled back after an error without having to roll back the
80205** entire transaction. If no error is encountered, the statement transaction
80206** will automatically commit when the VDBE halts.
80207**
80208** If P5!=0 then this opcode also checks the schema cookie against P3
80209** and the schema generation counter against P4.
80210** The cookie changes its value whenever the database schema changes.
80211** This operation is used to detect when that the cookie has changed
80212** and that the current process needs to reread the schema.  If the schema
80213** cookie in P3 differs from the schema cookie in the database header or
80214** if the schema generation counter in P4 differs from the current
80215** generation counter, then an SQLITE_SCHEMA error is raised and execution
80216** halts.  The sqlite3_step() wrapper function might then reprepare the
80217** statement and rerun it from the beginning.
80218*/
80219case OP_Transaction: {
80220  Btree *pBt;
80221  int iMeta;
80222  int iGen;
80223
80224  assert( p->bIsReader );
80225  assert( p->readOnly==0 || pOp->p2==0 );
80226  assert( pOp->p1>=0 && pOp->p1<db->nDb );
80227  assert( DbMaskTest(p->btreeMask, pOp->p1) );
80228  if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
80229    rc = SQLITE_READONLY;
80230    goto abort_due_to_error;
80231  }
80232  pBt = db->aDb[pOp->p1].pBt;
80233
80234  if( pBt ){
80235    rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
80236    testcase( rc==SQLITE_BUSY_SNAPSHOT );
80237    testcase( rc==SQLITE_BUSY_RECOVERY );
80238    if( (rc&0xff)==SQLITE_BUSY ){
80239      p->pc = (int)(pOp - aOp);
80240      p->rc = rc;
80241      goto vdbe_return;
80242    }
80243    if( rc!=SQLITE_OK ){
80244      goto abort_due_to_error;
80245    }
80246
80247    if( pOp->p2 && p->usesStmtJournal
80248     && (db->autoCommit==0 || db->nVdbeRead>1)
80249    ){
80250      assert( sqlite3BtreeIsInTrans(pBt) );
80251      if( p->iStatement==0 ){
80252        assert( db->nStatement>=0 && db->nSavepoint>=0 );
80253        db->nStatement++;
80254        p->iStatement = db->nSavepoint + db->nStatement;
80255      }
80256
80257      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
80258      if( rc==SQLITE_OK ){
80259        rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
80260      }
80261
80262      /* Store the current value of the database handles deferred constraint
80263      ** counter. If the statement transaction needs to be rolled back,
80264      ** the value of this counter needs to be restored too.  */
80265      p->nStmtDefCons = db->nDeferredCons;
80266      p->nStmtDefImmCons = db->nDeferredImmCons;
80267    }
80268
80269    /* Gather the schema version number for checking:
80270    ** IMPLEMENTATION-OF: R-32195-19465 The schema version is used by SQLite
80271    ** each time a query is executed to ensure that the internal cache of the
80272    ** schema used when compiling the SQL query matches the schema of the
80273    ** database against which the compiled query is actually executed.
80274    */
80275    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
80276    iGen = db->aDb[pOp->p1].pSchema->iGeneration;
80277  }else{
80278    iGen = iMeta = 0;
80279  }
80280  assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
80281  if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
80282    sqlite3DbFree(db, p->zErrMsg);
80283    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
80284    /* If the schema-cookie from the database file matches the cookie
80285    ** stored with the in-memory representation of the schema, do
80286    ** not reload the schema from the database file.
80287    **
80288    ** If virtual-tables are in use, this is not just an optimization.
80289    ** Often, v-tables store their data in other SQLite tables, which
80290    ** are queried from within xNext() and other v-table methods using
80291    ** prepared queries. If such a query is out-of-date, we do not want to
80292    ** discard the database schema, as the user code implementing the
80293    ** v-table would have to be ready for the sqlite3_vtab structure itself
80294    ** to be invalidated whenever sqlite3_step() is called from within
80295    ** a v-table method.
80296    */
80297    if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
80298      sqlite3ResetOneSchema(db, pOp->p1);
80299    }
80300    p->expired = 1;
80301    rc = SQLITE_SCHEMA;
80302  }
80303  if( rc ) goto abort_due_to_error;
80304  break;
80305}
80306
80307/* Opcode: ReadCookie P1 P2 P3 * *
80308**
80309** Read cookie number P3 from database P1 and write it into register P2.
80310** P3==1 is the schema version.  P3==2 is the database format.
80311** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
80312** the main database file and P1==1 is the database file used to store
80313** temporary tables.
80314**
80315** There must be a read-lock on the database (either a transaction
80316** must be started or there must be an open cursor) before
80317** executing this instruction.
80318*/
80319case OP_ReadCookie: {               /* out2 */
80320  int iMeta;
80321  int iDb;
80322  int iCookie;
80323
80324  assert( p->bIsReader );
80325  iDb = pOp->p1;
80326  iCookie = pOp->p3;
80327  assert( pOp->p3<SQLITE_N_BTREE_META );
80328  assert( iDb>=0 && iDb<db->nDb );
80329  assert( db->aDb[iDb].pBt!=0 );
80330  assert( DbMaskTest(p->btreeMask, iDb) );
80331
80332  sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
80333  pOut = out2Prerelease(p, pOp);
80334  pOut->u.i = iMeta;
80335  break;
80336}
80337
80338/* Opcode: SetCookie P1 P2 P3 * *
80339**
80340** Write the integer value P3 into cookie number P2 of database P1.
80341** P2==1 is the schema version.  P2==2 is the database format.
80342** P2==3 is the recommended pager cache
80343** size, and so forth.  P1==0 is the main database file and P1==1 is the
80344** database file used to store temporary tables.
80345**
80346** A transaction must be started before executing this opcode.
80347*/
80348case OP_SetCookie: {
80349  Db *pDb;
80350  assert( pOp->p2<SQLITE_N_BTREE_META );
80351  assert( pOp->p1>=0 && pOp->p1<db->nDb );
80352  assert( DbMaskTest(p->btreeMask, pOp->p1) );
80353  assert( p->readOnly==0 );
80354  pDb = &db->aDb[pOp->p1];
80355  assert( pDb->pBt!=0 );
80356  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
80357  /* See note about index shifting on OP_ReadCookie */
80358  rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
80359  if( pOp->p2==BTREE_SCHEMA_VERSION ){
80360    /* When the schema cookie changes, record the new cookie internally */
80361    pDb->pSchema->schema_cookie = pOp->p3;
80362    db->flags |= SQLITE_InternChanges;
80363  }else if( pOp->p2==BTREE_FILE_FORMAT ){
80364    /* Record changes in the file format */
80365    pDb->pSchema->file_format = pOp->p3;
80366  }
80367  if( pOp->p1==1 ){
80368    /* Invalidate all prepared statements whenever the TEMP database
80369    ** schema is changed.  Ticket #1644 */
80370    sqlite3ExpirePreparedStatements(db);
80371    p->expired = 0;
80372  }
80373  if( rc ) goto abort_due_to_error;
80374  break;
80375}
80376
80377/* Opcode: OpenRead P1 P2 P3 P4 P5
80378** Synopsis: root=P2 iDb=P3
80379**
80380** Open a read-only cursor for the database table whose root page is
80381** P2 in a database file.  The database file is determined by P3.
80382** P3==0 means the main database, P3==1 means the database used for
80383** temporary tables, and P3>1 means used the corresponding attached
80384** database.  Give the new cursor an identifier of P1.  The P1
80385** values need not be contiguous but all P1 values should be small integers.
80386** It is an error for P1 to be negative.
80387**
80388** If P5!=0 then use the content of register P2 as the root page, not
80389** the value of P2 itself.
80390**
80391** There will be a read lock on the database whenever there is an
80392** open cursor.  If the database was unlocked prior to this instruction
80393** then a read lock is acquired as part of this instruction.  A read
80394** lock allows other processes to read the database but prohibits
80395** any other process from modifying the database.  The read lock is
80396** released when all cursors are closed.  If this instruction attempts
80397** to get a read lock but fails, the script terminates with an
80398** SQLITE_BUSY error code.
80399**
80400** The P4 value may be either an integer (P4_INT32) or a pointer to
80401** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
80402** structure, then said structure defines the content and collating
80403** sequence of the index being opened. Otherwise, if P4 is an integer
80404** value, it is set to the number of columns in the table.
80405**
80406** See also: OpenWrite, ReopenIdx
80407*/
80408/* Opcode: ReopenIdx P1 P2 P3 P4 P5
80409** Synopsis: root=P2 iDb=P3
80410**
80411** The ReopenIdx opcode works exactly like ReadOpen except that it first
80412** checks to see if the cursor on P1 is already open with a root page
80413** number of P2 and if it is this opcode becomes a no-op.  In other words,
80414** if the cursor is already open, do not reopen it.
80415**
80416** The ReopenIdx opcode may only be used with P5==0 and with P4 being
80417** a P4_KEYINFO object.  Furthermore, the P3 value must be the same as
80418** every other ReopenIdx or OpenRead for the same cursor number.
80419**
80420** See the OpenRead opcode documentation for additional information.
80421*/
80422/* Opcode: OpenWrite P1 P2 P3 P4 P5
80423** Synopsis: root=P2 iDb=P3
80424**
80425** Open a read/write cursor named P1 on the table or index whose root
80426** page is P2.  Or if P5!=0 use the content of register P2 to find the
80427** root page.
80428**
80429** The P4 value may be either an integer (P4_INT32) or a pointer to
80430** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
80431** structure, then said structure defines the content and collating
80432** sequence of the index being opened. Otherwise, if P4 is an integer
80433** value, it is set to the number of columns in the table, or to the
80434** largest index of any column of the table that is actually used.
80435**
80436** This instruction works just like OpenRead except that it opens the cursor
80437** in read/write mode.  For a given table, there can be one or more read-only
80438** cursors or a single read/write cursor but not both.
80439**
80440** See also OpenRead.
80441*/
80442case OP_ReopenIdx: {
80443  int nField;
80444  KeyInfo *pKeyInfo;
80445  int p2;
80446  int iDb;
80447  int wrFlag;
80448  Btree *pX;
80449  VdbeCursor *pCur;
80450  Db *pDb;
80451
80452  assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
80453  assert( pOp->p4type==P4_KEYINFO );
80454  pCur = p->apCsr[pOp->p1];
80455  if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
80456    assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
80457    goto open_cursor_set_hints;
80458  }
80459  /* If the cursor is not currently open or is open on a different
80460  ** index, then fall through into OP_OpenRead to force a reopen */
80461case OP_OpenRead:
80462case OP_OpenWrite:
80463
80464  assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
80465  assert( p->bIsReader );
80466  assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
80467          || p->readOnly==0 );
80468
80469  if( p->expired ){
80470    rc = SQLITE_ABORT_ROLLBACK;
80471    goto abort_due_to_error;
80472  }
80473
80474  nField = 0;
80475  pKeyInfo = 0;
80476  p2 = pOp->p2;
80477  iDb = pOp->p3;
80478  assert( iDb>=0 && iDb<db->nDb );
80479  assert( DbMaskTest(p->btreeMask, iDb) );
80480  pDb = &db->aDb[iDb];
80481  pX = pDb->pBt;
80482  assert( pX!=0 );
80483  if( pOp->opcode==OP_OpenWrite ){
80484    assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
80485    wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
80486    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80487    if( pDb->pSchema->file_format < p->minWriteFileFormat ){
80488      p->minWriteFileFormat = pDb->pSchema->file_format;
80489    }
80490  }else{
80491    wrFlag = 0;
80492  }
80493  if( pOp->p5 & OPFLAG_P2ISREG ){
80494    assert( p2>0 );
80495    assert( p2<=(p->nMem+1 - p->nCursor) );
80496    pIn2 = &aMem[p2];
80497    assert( memIsValid(pIn2) );
80498    assert( (pIn2->flags & MEM_Int)!=0 );
80499    sqlite3VdbeMemIntegerify(pIn2);
80500    p2 = (int)pIn2->u.i;
80501    /* The p2 value always comes from a prior OP_CreateTable opcode and
80502    ** that opcode will always set the p2 value to 2 or more or else fail.
80503    ** If there were a failure, the prepared statement would have halted
80504    ** before reaching this instruction. */
80505    assert( p2>=2 );
80506  }
80507  if( pOp->p4type==P4_KEYINFO ){
80508    pKeyInfo = pOp->p4.pKeyInfo;
80509    assert( pKeyInfo->enc==ENC(db) );
80510    assert( pKeyInfo->db==db );
80511    nField = pKeyInfo->nField+pKeyInfo->nXField;
80512  }else if( pOp->p4type==P4_INT32 ){
80513    nField = pOp->p4.i;
80514  }
80515  assert( pOp->p1>=0 );
80516  assert( nField>=0 );
80517  testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
80518  pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
80519  if( pCur==0 ) goto no_mem;
80520  pCur->nullRow = 1;
80521  pCur->isOrdered = 1;
80522  pCur->pgnoRoot = p2;
80523#ifdef SQLITE_DEBUG
80524  pCur->wrFlag = wrFlag;
80525#endif
80526  rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
80527  pCur->pKeyInfo = pKeyInfo;
80528  /* Set the VdbeCursor.isTable variable. Previous versions of
80529  ** SQLite used to check if the root-page flags were sane at this point
80530  ** and report database corruption if they were not, but this check has
80531  ** since moved into the btree layer.  */
80532  pCur->isTable = pOp->p4type!=P4_KEYINFO;
80533
80534open_cursor_set_hints:
80535  assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
80536  assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
80537  testcase( pOp->p5 & OPFLAG_BULKCSR );
80538#ifdef SQLITE_ENABLE_CURSOR_HINTS
80539  testcase( pOp->p2 & OPFLAG_SEEKEQ );
80540#endif
80541  sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
80542                               (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
80543  if( rc ) goto abort_due_to_error;
80544  break;
80545}
80546
80547/* Opcode: OpenEphemeral P1 P2 * P4 P5
80548** Synopsis: nColumn=P2
80549**
80550** Open a new cursor P1 to a transient table.
80551** The cursor is always opened read/write even if
80552** the main database is read-only.  The ephemeral
80553** table is deleted automatically when the cursor is closed.
80554**
80555** P2 is the number of columns in the ephemeral table.
80556** The cursor points to a BTree table if P4==0 and to a BTree index
80557** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
80558** that defines the format of keys in the index.
80559**
80560** The P5 parameter can be a mask of the BTREE_* flags defined
80561** in btree.h.  These flags control aspects of the operation of
80562** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
80563** added automatically.
80564*/
80565/* Opcode: OpenAutoindex P1 P2 * P4 *
80566** Synopsis: nColumn=P2
80567**
80568** This opcode works the same as OP_OpenEphemeral.  It has a
80569** different name to distinguish its use.  Tables created using
80570** by this opcode will be used for automatically created transient
80571** indices in joins.
80572*/
80573case OP_OpenAutoindex:
80574case OP_OpenEphemeral: {
80575  VdbeCursor *pCx;
80576  KeyInfo *pKeyInfo;
80577
80578  static const int vfsFlags =
80579      SQLITE_OPEN_READWRITE |
80580      SQLITE_OPEN_CREATE |
80581      SQLITE_OPEN_EXCLUSIVE |
80582      SQLITE_OPEN_DELETEONCLOSE |
80583      SQLITE_OPEN_TRANSIENT_DB;
80584  assert( pOp->p1>=0 );
80585  assert( pOp->p2>=0 );
80586  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
80587  if( pCx==0 ) goto no_mem;
80588  pCx->nullRow = 1;
80589  pCx->isEphemeral = 1;
80590  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
80591                        BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
80592  if( rc==SQLITE_OK ){
80593    rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
80594  }
80595  if( rc==SQLITE_OK ){
80596    /* If a transient index is required, create it by calling
80597    ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
80598    ** opening it. If a transient table is required, just use the
80599    ** automatically created table with root-page 1 (an BLOB_INTKEY table).
80600    */
80601    if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
80602      int pgno;
80603      assert( pOp->p4type==P4_KEYINFO );
80604      rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
80605      if( rc==SQLITE_OK ){
80606        assert( pgno==MASTER_ROOT+1 );
80607        assert( pKeyInfo->db==db );
80608        assert( pKeyInfo->enc==ENC(db) );
80609        pCx->pKeyInfo = pKeyInfo;
80610        rc = sqlite3BtreeCursor(pCx->pBt, pgno, BTREE_WRCSR,
80611                                pKeyInfo, pCx->uc.pCursor);
80612      }
80613      pCx->isTable = 0;
80614    }else{
80615      rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, BTREE_WRCSR,
80616                              0, pCx->uc.pCursor);
80617      pCx->isTable = 1;
80618    }
80619  }
80620  if( rc ) goto abort_due_to_error;
80621  pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
80622  break;
80623}
80624
80625/* Opcode: SorterOpen P1 P2 P3 P4 *
80626**
80627** This opcode works like OP_OpenEphemeral except that it opens
80628** a transient index that is specifically designed to sort large
80629** tables using an external merge-sort algorithm.
80630**
80631** If argument P3 is non-zero, then it indicates that the sorter may
80632** assume that a stable sort considering the first P3 fields of each
80633** key is sufficient to produce the required results.
80634*/
80635case OP_SorterOpen: {
80636  VdbeCursor *pCx;
80637
80638  assert( pOp->p1>=0 );
80639  assert( pOp->p2>=0 );
80640  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
80641  if( pCx==0 ) goto no_mem;
80642  pCx->pKeyInfo = pOp->p4.pKeyInfo;
80643  assert( pCx->pKeyInfo->db==db );
80644  assert( pCx->pKeyInfo->enc==ENC(db) );
80645  rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
80646  if( rc ) goto abort_due_to_error;
80647  break;
80648}
80649
80650/* Opcode: SequenceTest P1 P2 * * *
80651** Synopsis: if( cursor[P1].ctr++ ) pc = P2
80652**
80653** P1 is a sorter cursor. If the sequence counter is currently zero, jump
80654** to P2. Regardless of whether or not the jump is taken, increment the
80655** the sequence value.
80656*/
80657case OP_SequenceTest: {
80658  VdbeCursor *pC;
80659  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80660  pC = p->apCsr[pOp->p1];
80661  assert( isSorter(pC) );
80662  if( (pC->seqCount++)==0 ){
80663    goto jump_to_p2;
80664  }
80665  break;
80666}
80667
80668/* Opcode: OpenPseudo P1 P2 P3 * *
80669** Synopsis: P3 columns in r[P2]
80670**
80671** Open a new cursor that points to a fake table that contains a single
80672** row of data.  The content of that one row is the content of memory
80673** register P2.  In other words, cursor P1 becomes an alias for the
80674** MEM_Blob content contained in register P2.
80675**
80676** A pseudo-table created by this opcode is used to hold a single
80677** row output from the sorter so that the row can be decomposed into
80678** individual columns using the OP_Column opcode.  The OP_Column opcode
80679** is the only cursor opcode that works with a pseudo-table.
80680**
80681** P3 is the number of fields in the records that will be stored by
80682** the pseudo-table.
80683*/
80684case OP_OpenPseudo: {
80685  VdbeCursor *pCx;
80686
80687  assert( pOp->p1>=0 );
80688  assert( pOp->p3>=0 );
80689  pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
80690  if( pCx==0 ) goto no_mem;
80691  pCx->nullRow = 1;
80692  pCx->uc.pseudoTableReg = pOp->p2;
80693  pCx->isTable = 1;
80694  assert( pOp->p5==0 );
80695  break;
80696}
80697
80698/* Opcode: Close P1 * * * *
80699**
80700** Close a cursor previously opened as P1.  If P1 is not
80701** currently open, this instruction is a no-op.
80702*/
80703case OP_Close: {
80704  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80705  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
80706  p->apCsr[pOp->p1] = 0;
80707  break;
80708}
80709
80710#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
80711/* Opcode: ColumnsUsed P1 * * P4 *
80712**
80713** This opcode (which only exists if SQLite was compiled with
80714** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
80715** table or index for cursor P1 are used.  P4 is a 64-bit integer
80716** (P4_INT64) in which the first 63 bits are one for each of the
80717** first 63 columns of the table or index that are actually used
80718** by the cursor.  The high-order bit is set if any column after
80719** the 64th is used.
80720*/
80721case OP_ColumnsUsed: {
80722  VdbeCursor *pC;
80723  pC = p->apCsr[pOp->p1];
80724  assert( pC->eCurType==CURTYPE_BTREE );
80725  pC->maskUsed = *(u64*)pOp->p4.pI64;
80726  break;
80727}
80728#endif
80729
80730/* Opcode: SeekGE P1 P2 P3 P4 *
80731** Synopsis: key=r[P3@P4]
80732**
80733** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
80734** use the value in register P3 as the key.  If cursor P1 refers
80735** to an SQL index, then P3 is the first in an array of P4 registers
80736** that are used as an unpacked index key.
80737**
80738** Reposition cursor P1 so that  it points to the smallest entry that
80739** is greater than or equal to the key value. If there are no records
80740** greater than or equal to the key and P2 is not zero, then jump to P2.
80741**
80742** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
80743** opcode will always land on a record that equally equals the key, or
80744** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
80745** opcode must be followed by an IdxLE opcode with the same arguments.
80746** The IdxLE opcode will be skipped if this opcode succeeds, but the
80747** IdxLE opcode will be used on subsequent loop iterations.
80748**
80749** This opcode leaves the cursor configured to move in forward order,
80750** from the beginning toward the end.  In other words, the cursor is
80751** configured to use Next, not Prev.
80752**
80753** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
80754*/
80755/* Opcode: SeekGT P1 P2 P3 P4 *
80756** Synopsis: key=r[P3@P4]
80757**
80758** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
80759** use the value in register P3 as a key. If cursor P1 refers
80760** to an SQL index, then P3 is the first in an array of P4 registers
80761** that are used as an unpacked index key.
80762**
80763** Reposition cursor P1 so that  it points to the smallest entry that
80764** is greater than the key value. If there are no records greater than
80765** the key and P2 is not zero, then jump to P2.
80766**
80767** This opcode leaves the cursor configured to move in forward order,
80768** from the beginning toward the end.  In other words, the cursor is
80769** configured to use Next, not Prev.
80770**
80771** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
80772*/
80773/* Opcode: SeekLT P1 P2 P3 P4 *
80774** Synopsis: key=r[P3@P4]
80775**
80776** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
80777** use the value in register P3 as a key. If cursor P1 refers
80778** to an SQL index, then P3 is the first in an array of P4 registers
80779** that are used as an unpacked index key.
80780**
80781** Reposition cursor P1 so that  it points to the largest entry that
80782** is less than the key value. If there are no records less than
80783** the key and P2 is not zero, then jump to P2.
80784**
80785** This opcode leaves the cursor configured to move in reverse order,
80786** from the end toward the beginning.  In other words, the cursor is
80787** configured to use Prev, not Next.
80788**
80789** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
80790*/
80791/* Opcode: SeekLE P1 P2 P3 P4 *
80792** Synopsis: key=r[P3@P4]
80793**
80794** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
80795** use the value in register P3 as a key. If cursor P1 refers
80796** to an SQL index, then P3 is the first in an array of P4 registers
80797** that are used as an unpacked index key.
80798**
80799** Reposition cursor P1 so that it points to the largest entry that
80800** is less than or equal to the key value. If there are no records
80801** less than or equal to the key and P2 is not zero, then jump to P2.
80802**
80803** This opcode leaves the cursor configured to move in reverse order,
80804** from the end toward the beginning.  In other words, the cursor is
80805** configured to use Prev, not Next.
80806**
80807** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
80808** opcode will always land on a record that equally equals the key, or
80809** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
80810** opcode must be followed by an IdxGE opcode with the same arguments.
80811** The IdxGE opcode will be skipped if this opcode succeeds, but the
80812** IdxGE opcode will be used on subsequent loop iterations.
80813**
80814** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
80815*/
80816case OP_SeekLT:         /* jump, in3 */
80817case OP_SeekLE:         /* jump, in3 */
80818case OP_SeekGE:         /* jump, in3 */
80819case OP_SeekGT: {       /* jump, in3 */
80820  int res;           /* Comparison result */
80821  int oc;            /* Opcode */
80822  VdbeCursor *pC;    /* The cursor to seek */
80823  UnpackedRecord r;  /* The key to seek for */
80824  int nField;        /* Number of columns or fields in the key */
80825  i64 iKey;          /* The rowid we are to seek to */
80826  int eqOnly;        /* Only interested in == results */
80827
80828  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80829  assert( pOp->p2!=0 );
80830  pC = p->apCsr[pOp->p1];
80831  assert( pC!=0 );
80832  assert( pC->eCurType==CURTYPE_BTREE );
80833  assert( OP_SeekLE == OP_SeekLT+1 );
80834  assert( OP_SeekGE == OP_SeekLT+2 );
80835  assert( OP_SeekGT == OP_SeekLT+3 );
80836  assert( pC->isOrdered );
80837  assert( pC->uc.pCursor!=0 );
80838  oc = pOp->opcode;
80839  eqOnly = 0;
80840  pC->nullRow = 0;
80841#ifdef SQLITE_DEBUG
80842  pC->seekOp = pOp->opcode;
80843#endif
80844
80845  if( pC->isTable ){
80846    /* The BTREE_SEEK_EQ flag is only set on index cursors */
80847    assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0 );
80848
80849    /* The input value in P3 might be of any type: integer, real, string,
80850    ** blob, or NULL.  But it needs to be an integer before we can do
80851    ** the seek, so convert it. */
80852    pIn3 = &aMem[pOp->p3];
80853    if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
80854      applyNumericAffinity(pIn3, 0);
80855    }
80856    iKey = sqlite3VdbeIntValue(pIn3);
80857
80858    /* If the P3 value could not be converted into an integer without
80859    ** loss of information, then special processing is required... */
80860    if( (pIn3->flags & MEM_Int)==0 ){
80861      if( (pIn3->flags & MEM_Real)==0 ){
80862        /* If the P3 value cannot be converted into any kind of a number,
80863        ** then the seek is not possible, so jump to P2 */
80864        VdbeBranchTaken(1,2); goto jump_to_p2;
80865        break;
80866      }
80867
80868      /* If the approximation iKey is larger than the actual real search
80869      ** term, substitute >= for > and < for <=. e.g. if the search term
80870      ** is 4.9 and the integer approximation 5:
80871      **
80872      **        (x >  4.9)    ->     (x >= 5)
80873      **        (x <= 4.9)    ->     (x <  5)
80874      */
80875      if( pIn3->u.r<(double)iKey ){
80876        assert( OP_SeekGE==(OP_SeekGT-1) );
80877        assert( OP_SeekLT==(OP_SeekLE-1) );
80878        assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
80879        if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
80880      }
80881
80882      /* If the approximation iKey is smaller than the actual real search
80883      ** term, substitute <= for < and > for >=.  */
80884      else if( pIn3->u.r>(double)iKey ){
80885        assert( OP_SeekLE==(OP_SeekLT+1) );
80886        assert( OP_SeekGT==(OP_SeekGE+1) );
80887        assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
80888        if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
80889      }
80890    }
80891    rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
80892    pC->movetoTarget = iKey;  /* Used by OP_Delete */
80893    if( rc!=SQLITE_OK ){
80894      goto abort_due_to_error;
80895    }
80896  }else{
80897    /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
80898    ** OP_SeekLE opcodes are allowed, and these must be immediately followed
80899    ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
80900    */
80901    if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
80902      eqOnly = 1;
80903      assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
80904      assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
80905      assert( pOp[1].p1==pOp[0].p1 );
80906      assert( pOp[1].p2==pOp[0].p2 );
80907      assert( pOp[1].p3==pOp[0].p3 );
80908      assert( pOp[1].p4.i==pOp[0].p4.i );
80909    }
80910
80911    nField = pOp->p4.i;
80912    assert( pOp->p4type==P4_INT32 );
80913    assert( nField>0 );
80914    r.pKeyInfo = pC->pKeyInfo;
80915    r.nField = (u16)nField;
80916
80917    /* The next line of code computes as follows, only faster:
80918    **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
80919    **     r.default_rc = -1;
80920    **   }else{
80921    **     r.default_rc = +1;
80922    **   }
80923    */
80924    r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
80925    assert( oc!=OP_SeekGT || r.default_rc==-1 );
80926    assert( oc!=OP_SeekLE || r.default_rc==-1 );
80927    assert( oc!=OP_SeekGE || r.default_rc==+1 );
80928    assert( oc!=OP_SeekLT || r.default_rc==+1 );
80929
80930    r.aMem = &aMem[pOp->p3];
80931#ifdef SQLITE_DEBUG
80932    { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
80933#endif
80934    ExpandBlob(r.aMem);
80935    r.eqSeen = 0;
80936    rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
80937    if( rc!=SQLITE_OK ){
80938      goto abort_due_to_error;
80939    }
80940    if( eqOnly && r.eqSeen==0 ){
80941      assert( res!=0 );
80942      goto seek_not_found;
80943    }
80944  }
80945  pC->deferredMoveto = 0;
80946  pC->cacheStatus = CACHE_STALE;
80947#ifdef SQLITE_TEST
80948  sqlite3_search_count++;
80949#endif
80950  if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
80951    if( res<0 || (res==0 && oc==OP_SeekGT) ){
80952      res = 0;
80953      rc = sqlite3BtreeNext(pC->uc.pCursor, &res);
80954      if( rc!=SQLITE_OK ) goto abort_due_to_error;
80955    }else{
80956      res = 0;
80957    }
80958  }else{
80959    assert( oc==OP_SeekLT || oc==OP_SeekLE );
80960    if( res>0 || (res==0 && oc==OP_SeekLT) ){
80961      res = 0;
80962      rc = sqlite3BtreePrevious(pC->uc.pCursor, &res);
80963      if( rc!=SQLITE_OK ) goto abort_due_to_error;
80964    }else{
80965      /* res might be negative because the table is empty.  Check to
80966      ** see if this is the case.
80967      */
80968      res = sqlite3BtreeEof(pC->uc.pCursor);
80969    }
80970  }
80971seek_not_found:
80972  assert( pOp->p2>0 );
80973  VdbeBranchTaken(res!=0,2);
80974  if( res ){
80975    goto jump_to_p2;
80976  }else if( eqOnly ){
80977    assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
80978    pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
80979  }
80980  break;
80981}
80982
80983
80984/* Opcode: Found P1 P2 P3 P4 *
80985** Synopsis: key=r[P3@P4]
80986**
80987** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
80988** P4>0 then register P3 is the first of P4 registers that form an unpacked
80989** record.
80990**
80991** Cursor P1 is on an index btree.  If the record identified by P3 and P4
80992** is a prefix of any entry in P1 then a jump is made to P2 and
80993** P1 is left pointing at the matching entry.
80994**
80995** This operation leaves the cursor in a state where it can be
80996** advanced in the forward direction.  The Next instruction will work,
80997** but not the Prev instruction.
80998**
80999** See also: NotFound, NoConflict, NotExists. SeekGe
81000*/
81001/* Opcode: NotFound P1 P2 P3 P4 *
81002** Synopsis: key=r[P3@P4]
81003**
81004** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
81005** P4>0 then register P3 is the first of P4 registers that form an unpacked
81006** record.
81007**
81008** Cursor P1 is on an index btree.  If the record identified by P3 and P4
81009** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
81010** does contain an entry whose prefix matches the P3/P4 record then control
81011** falls through to the next instruction and P1 is left pointing at the
81012** matching entry.
81013**
81014** This operation leaves the cursor in a state where it cannot be
81015** advanced in either direction.  In other words, the Next and Prev
81016** opcodes do not work after this operation.
81017**
81018** See also: Found, NotExists, NoConflict
81019*/
81020/* Opcode: NoConflict P1 P2 P3 P4 *
81021** Synopsis: key=r[P3@P4]
81022**
81023** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
81024** P4>0 then register P3 is the first of P4 registers that form an unpacked
81025** record.
81026**
81027** Cursor P1 is on an index btree.  If the record identified by P3 and P4
81028** contains any NULL value, jump immediately to P2.  If all terms of the
81029** record are not-NULL then a check is done to determine if any row in the
81030** P1 index btree has a matching key prefix.  If there are no matches, jump
81031** immediately to P2.  If there is a match, fall through and leave the P1
81032** cursor pointing to the matching row.
81033**
81034** This opcode is similar to OP_NotFound with the exceptions that the
81035** branch is always taken if any part of the search key input is NULL.
81036**
81037** This operation leaves the cursor in a state where it cannot be
81038** advanced in either direction.  In other words, the Next and Prev
81039** opcodes do not work after this operation.
81040**
81041** See also: NotFound, Found, NotExists
81042*/
81043case OP_NoConflict:     /* jump, in3 */
81044case OP_NotFound:       /* jump, in3 */
81045case OP_Found: {        /* jump, in3 */
81046  int alreadyExists;
81047  int takeJump;
81048  int ii;
81049  VdbeCursor *pC;
81050  int res;
81051  char *pFree;
81052  UnpackedRecord *pIdxKey;
81053  UnpackedRecord r;
81054  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
81055
81056#ifdef SQLITE_TEST
81057  if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
81058#endif
81059
81060  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81061  assert( pOp->p4type==P4_INT32 );
81062  pC = p->apCsr[pOp->p1];
81063  assert( pC!=0 );
81064#ifdef SQLITE_DEBUG
81065  pC->seekOp = pOp->opcode;
81066#endif
81067  pIn3 = &aMem[pOp->p3];
81068  assert( pC->eCurType==CURTYPE_BTREE );
81069  assert( pC->uc.pCursor!=0 );
81070  assert( pC->isTable==0 );
81071  pFree = 0;
81072  if( pOp->p4.i>0 ){
81073    r.pKeyInfo = pC->pKeyInfo;
81074    r.nField = (u16)pOp->p4.i;
81075    r.aMem = pIn3;
81076    for(ii=0; ii<r.nField; ii++){
81077      assert( memIsValid(&r.aMem[ii]) );
81078      ExpandBlob(&r.aMem[ii]);
81079#ifdef SQLITE_DEBUG
81080      if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
81081#endif
81082    }
81083    pIdxKey = &r;
81084  }else{
81085    pIdxKey = sqlite3VdbeAllocUnpackedRecord(
81086        pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
81087    );
81088    if( pIdxKey==0 ) goto no_mem;
81089    assert( pIn3->flags & MEM_Blob );
81090    ExpandBlob(pIn3);
81091    sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
81092  }
81093  pIdxKey->default_rc = 0;
81094  takeJump = 0;
81095  if( pOp->opcode==OP_NoConflict ){
81096    /* For the OP_NoConflict opcode, take the jump if any of the
81097    ** input fields are NULL, since any key with a NULL will not
81098    ** conflict */
81099    for(ii=0; ii<pIdxKey->nField; ii++){
81100      if( pIdxKey->aMem[ii].flags & MEM_Null ){
81101        takeJump = 1;
81102        break;
81103      }
81104    }
81105  }
81106  rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
81107  sqlite3DbFree(db, pFree);
81108  if( rc!=SQLITE_OK ){
81109    goto abort_due_to_error;
81110  }
81111  pC->seekResult = res;
81112  alreadyExists = (res==0);
81113  pC->nullRow = 1-alreadyExists;
81114  pC->deferredMoveto = 0;
81115  pC->cacheStatus = CACHE_STALE;
81116  if( pOp->opcode==OP_Found ){
81117    VdbeBranchTaken(alreadyExists!=0,2);
81118    if( alreadyExists ) goto jump_to_p2;
81119  }else{
81120    VdbeBranchTaken(takeJump||alreadyExists==0,2);
81121    if( takeJump || !alreadyExists ) goto jump_to_p2;
81122  }
81123  break;
81124}
81125
81126/* Opcode: SeekRowid P1 P2 P3 * *
81127** Synopsis: intkey=r[P3]
81128**
81129** P1 is the index of a cursor open on an SQL table btree (with integer
81130** keys).  If register P3 does not contain an integer or if P1 does not
81131** contain a record with rowid P3 then jump immediately to P2.
81132** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
81133** a record with rowid P3 then
81134** leave the cursor pointing at that record and fall through to the next
81135** instruction.
81136**
81137** The OP_NotExists opcode performs the same operation, but with OP_NotExists
81138** the P3 register must be guaranteed to contain an integer value.  With this
81139** opcode, register P3 might not contain an integer.
81140**
81141** The OP_NotFound opcode performs the same operation on index btrees
81142** (with arbitrary multi-value keys).
81143**
81144** This opcode leaves the cursor in a state where it cannot be advanced
81145** in either direction.  In other words, the Next and Prev opcodes will
81146** not work following this opcode.
81147**
81148** See also: Found, NotFound, NoConflict, SeekRowid
81149*/
81150/* Opcode: NotExists P1 P2 P3 * *
81151** Synopsis: intkey=r[P3]
81152**
81153** P1 is the index of a cursor open on an SQL table btree (with integer
81154** keys).  P3 is an integer rowid.  If P1 does not contain a record with
81155** rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an
81156** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
81157** leave the cursor pointing at that record and fall through to the next
81158** instruction.
81159**
81160** The OP_SeekRowid opcode performs the same operation but also allows the
81161** P3 register to contain a non-integer value, in which case the jump is
81162** always taken.  This opcode requires that P3 always contain an integer.
81163**
81164** The OP_NotFound opcode performs the same operation on index btrees
81165** (with arbitrary multi-value keys).
81166**
81167** This opcode leaves the cursor in a state where it cannot be advanced
81168** in either direction.  In other words, the Next and Prev opcodes will
81169** not work following this opcode.
81170**
81171** See also: Found, NotFound, NoConflict, SeekRowid
81172*/
81173case OP_SeekRowid: {        /* jump, in3 */
81174  VdbeCursor *pC;
81175  BtCursor *pCrsr;
81176  int res;
81177  u64 iKey;
81178
81179  pIn3 = &aMem[pOp->p3];
81180  if( (pIn3->flags & MEM_Int)==0 ){
81181    applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
81182    if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
81183  }
81184  /* Fall through into OP_NotExists */
81185case OP_NotExists:          /* jump, in3 */
81186  pIn3 = &aMem[pOp->p3];
81187  assert( pIn3->flags & MEM_Int );
81188  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81189  pC = p->apCsr[pOp->p1];
81190  assert( pC!=0 );
81191#ifdef SQLITE_DEBUG
81192  pC->seekOp = 0;
81193#endif
81194  assert( pC->isTable );
81195  assert( pC->eCurType==CURTYPE_BTREE );
81196  pCrsr = pC->uc.pCursor;
81197  assert( pCrsr!=0 );
81198  res = 0;
81199  iKey = pIn3->u.i;
81200  rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
81201  assert( rc==SQLITE_OK || res==0 );
81202  pC->movetoTarget = iKey;  /* Used by OP_Delete */
81203  pC->nullRow = 0;
81204  pC->cacheStatus = CACHE_STALE;
81205  pC->deferredMoveto = 0;
81206  VdbeBranchTaken(res!=0,2);
81207  pC->seekResult = res;
81208  if( res!=0 ){
81209    assert( rc==SQLITE_OK );
81210    if( pOp->p2==0 ){
81211      rc = SQLITE_CORRUPT_BKPT;
81212    }else{
81213      goto jump_to_p2;
81214    }
81215  }
81216  if( rc ) goto abort_due_to_error;
81217  break;
81218}
81219
81220/* Opcode: Sequence P1 P2 * * *
81221** Synopsis: r[P2]=cursor[P1].ctr++
81222**
81223** Find the next available sequence number for cursor P1.
81224** Write the sequence number into register P2.
81225** The sequence number on the cursor is incremented after this
81226** instruction.
81227*/
81228case OP_Sequence: {           /* out2 */
81229  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81230  assert( p->apCsr[pOp->p1]!=0 );
81231  assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
81232  pOut = out2Prerelease(p, pOp);
81233  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
81234  break;
81235}
81236
81237
81238/* Opcode: NewRowid P1 P2 P3 * *
81239** Synopsis: r[P2]=rowid
81240**
81241** Get a new integer record number (a.k.a "rowid") used as the key to a table.
81242** The record number is not previously used as a key in the database
81243** table that cursor P1 points to.  The new record number is written
81244** written to register P2.
81245**
81246** If P3>0 then P3 is a register in the root frame of this VDBE that holds
81247** the largest previously generated record number. No new record numbers are
81248** allowed to be less than this value. When this value reaches its maximum,
81249** an SQLITE_FULL error is generated. The P3 register is updated with the '
81250** generated record number. This P3 mechanism is used to help implement the
81251** AUTOINCREMENT feature.
81252*/
81253case OP_NewRowid: {           /* out2 */
81254  i64 v;                 /* The new rowid */
81255  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
81256  int res;               /* Result of an sqlite3BtreeLast() */
81257  int cnt;               /* Counter to limit the number of searches */
81258  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
81259  VdbeFrame *pFrame;     /* Root frame of VDBE */
81260
81261  v = 0;
81262  res = 0;
81263  pOut = out2Prerelease(p, pOp);
81264  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81265  pC = p->apCsr[pOp->p1];
81266  assert( pC!=0 );
81267  assert( pC->eCurType==CURTYPE_BTREE );
81268  assert( pC->uc.pCursor!=0 );
81269  {
81270    /* The next rowid or record number (different terms for the same
81271    ** thing) is obtained in a two-step algorithm.
81272    **
81273    ** First we attempt to find the largest existing rowid and add one
81274    ** to that.  But if the largest existing rowid is already the maximum
81275    ** positive integer, we have to fall through to the second
81276    ** probabilistic algorithm
81277    **
81278    ** The second algorithm is to select a rowid at random and see if
81279    ** it already exists in the table.  If it does not exist, we have
81280    ** succeeded.  If the random rowid does exist, we select a new one
81281    ** and try again, up to 100 times.
81282    */
81283    assert( pC->isTable );
81284
81285#ifdef SQLITE_32BIT_ROWID
81286#   define MAX_ROWID 0x7fffffff
81287#else
81288    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
81289    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
81290    ** to provide the constant while making all compilers happy.
81291    */
81292#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
81293#endif
81294
81295    if( !pC->useRandomRowid ){
81296      rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
81297      if( rc!=SQLITE_OK ){
81298        goto abort_due_to_error;
81299      }
81300      if( res ){
81301        v = 1;   /* IMP: R-61914-48074 */
81302      }else{
81303        assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
81304        v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
81305        if( v>=MAX_ROWID ){
81306          pC->useRandomRowid = 1;
81307        }else{
81308          v++;   /* IMP: R-29538-34987 */
81309        }
81310      }
81311    }
81312
81313#ifndef SQLITE_OMIT_AUTOINCREMENT
81314    if( pOp->p3 ){
81315      /* Assert that P3 is a valid memory cell. */
81316      assert( pOp->p3>0 );
81317      if( p->pFrame ){
81318        for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
81319        /* Assert that P3 is a valid memory cell. */
81320        assert( pOp->p3<=pFrame->nMem );
81321        pMem = &pFrame->aMem[pOp->p3];
81322      }else{
81323        /* Assert that P3 is a valid memory cell. */
81324        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
81325        pMem = &aMem[pOp->p3];
81326        memAboutToChange(p, pMem);
81327      }
81328      assert( memIsValid(pMem) );
81329
81330      REGISTER_TRACE(pOp->p3, pMem);
81331      sqlite3VdbeMemIntegerify(pMem);
81332      assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
81333      if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
81334        rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
81335        goto abort_due_to_error;
81336      }
81337      if( v<pMem->u.i+1 ){
81338        v = pMem->u.i + 1;
81339      }
81340      pMem->u.i = v;
81341    }
81342#endif
81343    if( pC->useRandomRowid ){
81344      /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
81345      ** largest possible integer (9223372036854775807) then the database
81346      ** engine starts picking positive candidate ROWIDs at random until
81347      ** it finds one that is not previously used. */
81348      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
81349                             ** an AUTOINCREMENT table. */
81350      cnt = 0;
81351      do{
81352        sqlite3_randomness(sizeof(v), &v);
81353        v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
81354      }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
81355                                                 0, &res))==SQLITE_OK)
81356            && (res==0)
81357            && (++cnt<100));
81358      if( rc ) goto abort_due_to_error;
81359      if( res==0 ){
81360        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
81361        goto abort_due_to_error;
81362      }
81363      assert( v>0 );  /* EV: R-40812-03570 */
81364    }
81365    pC->deferredMoveto = 0;
81366    pC->cacheStatus = CACHE_STALE;
81367  }
81368  pOut->u.i = v;
81369  break;
81370}
81371
81372/* Opcode: Insert P1 P2 P3 P4 P5
81373** Synopsis: intkey=r[P3] data=r[P2]
81374**
81375** Write an entry into the table of cursor P1.  A new entry is
81376** created if it doesn't already exist or the data for an existing
81377** entry is overwritten.  The data is the value MEM_Blob stored in register
81378** number P2. The key is stored in register P3. The key must
81379** be a MEM_Int.
81380**
81381** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
81382** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
81383** then rowid is stored for subsequent return by the
81384** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
81385**
81386** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
81387** the last seek operation (OP_NotExists or OP_SeekRowid) was a success,
81388** then this
81389** operation will not attempt to find the appropriate row before doing
81390** the insert but will instead overwrite the row that the cursor is
81391** currently pointing to.  Presumably, the prior OP_NotExists or
81392** OP_SeekRowid opcode
81393** has already positioned the cursor correctly.  This is an optimization
81394** that boosts performance by avoiding redundant seeks.
81395**
81396** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
81397** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
81398** is part of an INSERT operation.  The difference is only important to
81399** the update hook.
81400**
81401** Parameter P4 may point to a Table structure, or may be NULL. If it is
81402** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
81403** following a successful insert.
81404**
81405** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
81406** allocated, then ownership of P2 is transferred to the pseudo-cursor
81407** and register P2 becomes ephemeral.  If the cursor is changed, the
81408** value of register P2 will then change.  Make sure this does not
81409** cause any problems.)
81410**
81411** This instruction only works on tables.  The equivalent instruction
81412** for indices is OP_IdxInsert.
81413*/
81414/* Opcode: InsertInt P1 P2 P3 P4 P5
81415** Synopsis:  intkey=P3 data=r[P2]
81416**
81417** This works exactly like OP_Insert except that the key is the
81418** integer value P3, not the value of the integer stored in register P3.
81419*/
81420case OP_Insert:
81421case OP_InsertInt: {
81422  Mem *pData;       /* MEM cell holding data for the record to be inserted */
81423  Mem *pKey;        /* MEM cell holding key  for the record */
81424  VdbeCursor *pC;   /* Cursor to table into which insert is written */
81425  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
81426  const char *zDb;  /* database name - used by the update hook */
81427  Table *pTab;      /* Table structure - used by update and pre-update hooks */
81428  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
81429  BtreePayload x;   /* Payload to be inserted */
81430
81431  op = 0;
81432  pData = &aMem[pOp->p2];
81433  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81434  assert( memIsValid(pData) );
81435  pC = p->apCsr[pOp->p1];
81436  assert( pC!=0 );
81437  assert( pC->eCurType==CURTYPE_BTREE );
81438  assert( pC->uc.pCursor!=0 );
81439  assert( pC->isTable );
81440  assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
81441  REGISTER_TRACE(pOp->p2, pData);
81442
81443  if( pOp->opcode==OP_Insert ){
81444    pKey = &aMem[pOp->p3];
81445    assert( pKey->flags & MEM_Int );
81446    assert( memIsValid(pKey) );
81447    REGISTER_TRACE(pOp->p3, pKey);
81448    x.nKey = pKey->u.i;
81449  }else{
81450    assert( pOp->opcode==OP_InsertInt );
81451    x.nKey = pOp->p3;
81452  }
81453
81454  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
81455    assert( pC->isTable );
81456    assert( pC->iDb>=0 );
81457    zDb = db->aDb[pC->iDb].zName;
81458    pTab = pOp->p4.pTab;
81459    assert( HasRowid(pTab) );
81460    op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
81461  }else{
81462    pTab = 0; /* Not needed.  Silence a comiler warning. */
81463    zDb = 0;  /* Not needed.  Silence a compiler warning. */
81464  }
81465
81466#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
81467  /* Invoke the pre-update hook, if any */
81468  if( db->xPreUpdateCallback
81469   && pOp->p4type==P4_TABLE
81470   && !(pOp->p5 & OPFLAG_ISUPDATE)
81471  ){
81472    sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey, pOp->p2);
81473  }
81474#endif
81475
81476  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
81477  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = x.nKey;
81478  if( pData->flags & MEM_Null ){
81479    x.pData = 0;
81480    x.nData = 0;
81481  }else{
81482    assert( pData->flags & (MEM_Blob|MEM_Str) );
81483    x.pData = pData->z;
81484    x.nData = pData->n;
81485  }
81486  seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
81487  if( pData->flags & MEM_Zero ){
81488    x.nZero = pData->u.nZero;
81489  }else{
81490    x.nZero = 0;
81491  }
81492  x.pKey = 0;
81493  rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
81494                          (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
81495  );
81496  pC->deferredMoveto = 0;
81497  pC->cacheStatus = CACHE_STALE;
81498
81499  /* Invoke the update-hook if required. */
81500  if( rc ) goto abort_due_to_error;
81501  if( db->xUpdateCallback && op ){
81502    db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, x.nKey);
81503  }
81504  break;
81505}
81506
81507/* Opcode: Delete P1 P2 P3 P4 P5
81508**
81509** Delete the record at which the P1 cursor is currently pointing.
81510**
81511** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
81512** the cursor will be left pointing at  either the next or the previous
81513** record in the table. If it is left pointing at the next record, then
81514** the next Next instruction will be a no-op. As a result, in this case
81515** it is ok to delete a record from within a Next loop. If
81516** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
81517** left in an undefined state.
81518**
81519** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
81520** delete one of several associated with deleting a table row and all its
81521** associated index entries.  Exactly one of those deletes is the "primary"
81522** delete.  The others are all on OPFLAG_FORDELETE cursors or else are
81523** marked with the AUXDELETE flag.
81524**
81525** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
81526** change count is incremented (otherwise not).
81527**
81528** P1 must not be pseudo-table.  It has to be a real table with
81529** multiple rows.
81530**
81531** If P4 is not NULL then it points to a Table struture. In this case either
81532** the update or pre-update hook, or both, may be invoked. The P1 cursor must
81533** have been positioned using OP_NotFound prior to invoking this opcode in
81534** this case. Specifically, if one is configured, the pre-update hook is
81535** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
81536** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
81537**
81538** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
81539** of the memory cell that contains the value that the rowid of the row will
81540** be set to by the update.
81541*/
81542case OP_Delete: {
81543  VdbeCursor *pC;
81544  const char *zDb;
81545  Table *pTab;
81546  int opflags;
81547
81548  opflags = pOp->p2;
81549  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81550  pC = p->apCsr[pOp->p1];
81551  assert( pC!=0 );
81552  assert( pC->eCurType==CURTYPE_BTREE );
81553  assert( pC->uc.pCursor!=0 );
81554  assert( pC->deferredMoveto==0 );
81555
81556#ifdef SQLITE_DEBUG
81557  if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
81558    /* If p5 is zero, the seek operation that positioned the cursor prior to
81559    ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
81560    ** the row that is being deleted */
81561    i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
81562    assert( pC->movetoTarget==iKey );
81563  }
81564#endif
81565
81566  /* If the update-hook or pre-update-hook will be invoked, set zDb to
81567  ** the name of the db to pass as to it. Also set local pTab to a copy
81568  ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
81569  ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
81570  ** VdbeCursor.movetoTarget to the current rowid.  */
81571  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
81572    assert( pC->iDb>=0 );
81573    assert( pOp->p4.pTab!=0 );
81574    zDb = db->aDb[pC->iDb].zName;
81575    pTab = pOp->p4.pTab;
81576    if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
81577      pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
81578    }
81579  }else{
81580    zDb = 0;   /* Not needed.  Silence a compiler warning. */
81581    pTab = 0;  /* Not needed.  Silence a compiler warning. */
81582  }
81583
81584#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
81585  /* Invoke the pre-update-hook if required. */
81586  if( db->xPreUpdateCallback && pOp->p4.pTab && HasRowid(pTab) ){
81587    assert( !(opflags & OPFLAG_ISUPDATE) || (aMem[pOp->p3].flags & MEM_Int) );
81588    sqlite3VdbePreUpdateHook(p, pC,
81589        (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
81590        zDb, pTab, pC->movetoTarget,
81591        pOp->p3
81592    );
81593  }
81594  if( opflags & OPFLAG_ISNOOP ) break;
81595#endif
81596
81597  /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
81598  assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
81599  assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
81600  assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
81601
81602#ifdef SQLITE_DEBUG
81603  if( p->pFrame==0 ){
81604    if( pC->isEphemeral==0
81605        && (pOp->p5 & OPFLAG_AUXDELETE)==0
81606        && (pC->wrFlag & OPFLAG_FORDELETE)==0
81607      ){
81608      nExtraDelete++;
81609    }
81610    if( pOp->p2 & OPFLAG_NCHANGE ){
81611      nExtraDelete--;
81612    }
81613  }
81614#endif
81615
81616  rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
81617  pC->cacheStatus = CACHE_STALE;
81618  if( rc ) goto abort_due_to_error;
81619
81620  /* Invoke the update-hook if required. */
81621  if( opflags & OPFLAG_NCHANGE ){
81622    p->nChange++;
81623    if( db->xUpdateCallback && HasRowid(pTab) ){
81624      db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
81625          pC->movetoTarget);
81626      assert( pC->iDb>=0 );
81627    }
81628  }
81629
81630  break;
81631}
81632/* Opcode: ResetCount * * * * *
81633**
81634** The value of the change counter is copied to the database handle
81635** change counter (returned by subsequent calls to sqlite3_changes()).
81636** Then the VMs internal change counter resets to 0.
81637** This is used by trigger programs.
81638*/
81639case OP_ResetCount: {
81640  sqlite3VdbeSetChanges(db, p->nChange);
81641  p->nChange = 0;
81642  break;
81643}
81644
81645/* Opcode: SorterCompare P1 P2 P3 P4
81646** Synopsis:  if key(P1)!=trim(r[P3],P4) goto P2
81647**
81648** P1 is a sorter cursor. This instruction compares a prefix of the
81649** record blob in register P3 against a prefix of the entry that
81650** the sorter cursor currently points to.  Only the first P4 fields
81651** of r[P3] and the sorter record are compared.
81652**
81653** If either P3 or the sorter contains a NULL in one of their significant
81654** fields (not counting the P4 fields at the end which are ignored) then
81655** the comparison is assumed to be equal.
81656**
81657** Fall through to next instruction if the two records compare equal to
81658** each other.  Jump to P2 if they are different.
81659*/
81660case OP_SorterCompare: {
81661  VdbeCursor *pC;
81662  int res;
81663  int nKeyCol;
81664
81665  pC = p->apCsr[pOp->p1];
81666  assert( isSorter(pC) );
81667  assert( pOp->p4type==P4_INT32 );
81668  pIn3 = &aMem[pOp->p3];
81669  nKeyCol = pOp->p4.i;
81670  res = 0;
81671  rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
81672  VdbeBranchTaken(res!=0,2);
81673  if( rc ) goto abort_due_to_error;
81674  if( res ) goto jump_to_p2;
81675  break;
81676};
81677
81678/* Opcode: SorterData P1 P2 P3 * *
81679** Synopsis: r[P2]=data
81680**
81681** Write into register P2 the current sorter data for sorter cursor P1.
81682** Then clear the column header cache on cursor P3.
81683**
81684** This opcode is normally use to move a record out of the sorter and into
81685** a register that is the source for a pseudo-table cursor created using
81686** OpenPseudo.  That pseudo-table cursor is the one that is identified by
81687** parameter P3.  Clearing the P3 column cache as part of this opcode saves
81688** us from having to issue a separate NullRow instruction to clear that cache.
81689*/
81690case OP_SorterData: {
81691  VdbeCursor *pC;
81692
81693  pOut = &aMem[pOp->p2];
81694  pC = p->apCsr[pOp->p1];
81695  assert( isSorter(pC) );
81696  rc = sqlite3VdbeSorterRowkey(pC, pOut);
81697  assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
81698  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81699  if( rc ) goto abort_due_to_error;
81700  p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
81701  break;
81702}
81703
81704/* Opcode: RowData P1 P2 * * *
81705** Synopsis: r[P2]=data
81706**
81707** Write into register P2 the complete row data for cursor P1.
81708** There is no interpretation of the data.
81709** It is just copied onto the P2 register exactly as
81710** it is found in the database file.
81711**
81712** If the P1 cursor must be pointing to a valid row (not a NULL row)
81713** of a real table, not a pseudo-table.
81714*/
81715/* Opcode: RowKey P1 P2 * * *
81716** Synopsis: r[P2]=key
81717**
81718** Write into register P2 the complete row key for cursor P1.
81719** There is no interpretation of the data.
81720** The key is copied onto the P2 register exactly as
81721** it is found in the database file.
81722**
81723** If the P1 cursor must be pointing to a valid row (not a NULL row)
81724** of a real table, not a pseudo-table.
81725*/
81726case OP_RowKey:
81727case OP_RowData: {
81728  VdbeCursor *pC;
81729  BtCursor *pCrsr;
81730  u32 n;
81731
81732  pOut = &aMem[pOp->p2];
81733  memAboutToChange(p, pOut);
81734
81735  /* Note that RowKey and RowData are really exactly the same instruction */
81736  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81737  pC = p->apCsr[pOp->p1];
81738  assert( pC!=0 );
81739  assert( pC->eCurType==CURTYPE_BTREE );
81740  assert( isSorter(pC)==0 );
81741  assert( pC->isTable || pOp->opcode!=OP_RowData );
81742  assert( pC->isTable==0 || pOp->opcode==OP_RowData );
81743  assert( pC->nullRow==0 );
81744  assert( pC->uc.pCursor!=0 );
81745  pCrsr = pC->uc.pCursor;
81746
81747  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
81748  ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
81749  ** that might invalidate the cursor.
81750  ** If this where not the case, on of the following assert()s
81751  ** would fail.  Should this ever change (because of changes in the code
81752  ** generator) then the fix would be to insert a call to
81753  ** sqlite3VdbeCursorMoveto().
81754  */
81755  assert( pC->deferredMoveto==0 );
81756  assert( sqlite3BtreeCursorIsValid(pCrsr) );
81757#if 0  /* Not required due to the previous to assert() statements */
81758  rc = sqlite3VdbeCursorMoveto(pC);
81759  if( rc!=SQLITE_OK ) goto abort_due_to_error;
81760#endif
81761
81762  n = sqlite3BtreePayloadSize(pCrsr);
81763  if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
81764    goto too_big;
81765  }
81766  testcase( n==0 );
81767  if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
81768    goto no_mem;
81769  }
81770  pOut->n = n;
81771  MemSetTypeFlag(pOut, MEM_Blob);
81772  if( pC->isTable==0 ){
81773    rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
81774  }else{
81775    rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
81776  }
81777  if( rc ) goto abort_due_to_error;
81778  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
81779  UPDATE_MAX_BLOBSIZE(pOut);
81780  REGISTER_TRACE(pOp->p2, pOut);
81781  break;
81782}
81783
81784/* Opcode: Rowid P1 P2 * * *
81785** Synopsis: r[P2]=rowid
81786**
81787** Store in register P2 an integer which is the key of the table entry that
81788** P1 is currently point to.
81789**
81790** P1 can be either an ordinary table or a virtual table.  There used to
81791** be a separate OP_VRowid opcode for use with virtual tables, but this
81792** one opcode now works for both table types.
81793*/
81794case OP_Rowid: {                 /* out2 */
81795  VdbeCursor *pC;
81796  i64 v;
81797  sqlite3_vtab *pVtab;
81798  const sqlite3_module *pModule;
81799
81800  pOut = out2Prerelease(p, pOp);
81801  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81802  pC = p->apCsr[pOp->p1];
81803  assert( pC!=0 );
81804  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
81805  if( pC->nullRow ){
81806    pOut->flags = MEM_Null;
81807    break;
81808  }else if( pC->deferredMoveto ){
81809    v = pC->movetoTarget;
81810#ifndef SQLITE_OMIT_VIRTUALTABLE
81811  }else if( pC->eCurType==CURTYPE_VTAB ){
81812    assert( pC->uc.pVCur!=0 );
81813    pVtab = pC->uc.pVCur->pVtab;
81814    pModule = pVtab->pModule;
81815    assert( pModule->xRowid );
81816    rc = pModule->xRowid(pC->uc.pVCur, &v);
81817    sqlite3VtabImportErrmsg(p, pVtab);
81818    if( rc ) goto abort_due_to_error;
81819#endif /* SQLITE_OMIT_VIRTUALTABLE */
81820  }else{
81821    assert( pC->eCurType==CURTYPE_BTREE );
81822    assert( pC->uc.pCursor!=0 );
81823    rc = sqlite3VdbeCursorRestore(pC);
81824    if( rc ) goto abort_due_to_error;
81825    if( pC->nullRow ){
81826      pOut->flags = MEM_Null;
81827      break;
81828    }
81829    v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
81830  }
81831  pOut->u.i = v;
81832  break;
81833}
81834
81835/* Opcode: NullRow P1 * * * *
81836**
81837** Move the cursor P1 to a null row.  Any OP_Column operations
81838** that occur while the cursor is on the null row will always
81839** write a NULL.
81840*/
81841case OP_NullRow: {
81842  VdbeCursor *pC;
81843
81844  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81845  pC = p->apCsr[pOp->p1];
81846  assert( pC!=0 );
81847  pC->nullRow = 1;
81848  pC->cacheStatus = CACHE_STALE;
81849  if( pC->eCurType==CURTYPE_BTREE ){
81850    assert( pC->uc.pCursor!=0 );
81851    sqlite3BtreeClearCursor(pC->uc.pCursor);
81852  }
81853  break;
81854}
81855
81856/* Opcode: Last P1 P2 P3 * *
81857**
81858** The next use of the Rowid or Column or Prev instruction for P1
81859** will refer to the last entry in the database table or index.
81860** If the table or index is empty and P2>0, then jump immediately to P2.
81861** If P2 is 0 or if the table or index is not empty, fall through
81862** to the following instruction.
81863**
81864** This opcode leaves the cursor configured to move in reverse order,
81865** from the end toward the beginning.  In other words, the cursor is
81866** configured to use Prev, not Next.
81867*/
81868case OP_Last: {        /* jump */
81869  VdbeCursor *pC;
81870  BtCursor *pCrsr;
81871  int res;
81872
81873  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81874  pC = p->apCsr[pOp->p1];
81875  assert( pC!=0 );
81876  assert( pC->eCurType==CURTYPE_BTREE );
81877  pCrsr = pC->uc.pCursor;
81878  res = 0;
81879  assert( pCrsr!=0 );
81880  rc = sqlite3BtreeLast(pCrsr, &res);
81881  pC->nullRow = (u8)res;
81882  pC->deferredMoveto = 0;
81883  pC->cacheStatus = CACHE_STALE;
81884  pC->seekResult = pOp->p3;
81885#ifdef SQLITE_DEBUG
81886  pC->seekOp = OP_Last;
81887#endif
81888  if( rc ) goto abort_due_to_error;
81889  if( pOp->p2>0 ){
81890    VdbeBranchTaken(res!=0,2);
81891    if( res ) goto jump_to_p2;
81892  }
81893  break;
81894}
81895
81896
81897/* Opcode: Sort P1 P2 * * *
81898**
81899** This opcode does exactly the same thing as OP_Rewind except that
81900** it increments an undocumented global variable used for testing.
81901**
81902** Sorting is accomplished by writing records into a sorting index,
81903** then rewinding that index and playing it back from beginning to
81904** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
81905** rewinding so that the global variable will be incremented and
81906** regression tests can determine whether or not the optimizer is
81907** correctly optimizing out sorts.
81908*/
81909case OP_SorterSort:    /* jump */
81910case OP_Sort: {        /* jump */
81911#ifdef SQLITE_TEST
81912  sqlite3_sort_count++;
81913  sqlite3_search_count--;
81914#endif
81915  p->aCounter[SQLITE_STMTSTATUS_SORT]++;
81916  /* Fall through into OP_Rewind */
81917}
81918/* Opcode: Rewind P1 P2 * * *
81919**
81920** The next use of the Rowid or Column or Next instruction for P1
81921** will refer to the first entry in the database table or index.
81922** If the table or index is empty, jump immediately to P2.
81923** If the table or index is not empty, fall through to the following
81924** instruction.
81925**
81926** This opcode leaves the cursor configured to move in forward order,
81927** from the beginning toward the end.  In other words, the cursor is
81928** configured to use Next, not Prev.
81929*/
81930case OP_Rewind: {        /* jump */
81931  VdbeCursor *pC;
81932  BtCursor *pCrsr;
81933  int res;
81934
81935  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81936  pC = p->apCsr[pOp->p1];
81937  assert( pC!=0 );
81938  assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
81939  res = 1;
81940#ifdef SQLITE_DEBUG
81941  pC->seekOp = OP_Rewind;
81942#endif
81943  if( isSorter(pC) ){
81944    rc = sqlite3VdbeSorterRewind(pC, &res);
81945  }else{
81946    assert( pC->eCurType==CURTYPE_BTREE );
81947    pCrsr = pC->uc.pCursor;
81948    assert( pCrsr );
81949    rc = sqlite3BtreeFirst(pCrsr, &res);
81950    pC->deferredMoveto = 0;
81951    pC->cacheStatus = CACHE_STALE;
81952  }
81953  if( rc ) goto abort_due_to_error;
81954  pC->nullRow = (u8)res;
81955  assert( pOp->p2>0 && pOp->p2<p->nOp );
81956  VdbeBranchTaken(res!=0,2);
81957  if( res ) goto jump_to_p2;
81958  break;
81959}
81960
81961/* Opcode: Next P1 P2 P3 P4 P5
81962**
81963** Advance cursor P1 so that it points to the next key/data pair in its
81964** table or index.  If there are no more key/value pairs then fall through
81965** to the following instruction.  But if the cursor advance was successful,
81966** jump immediately to P2.
81967**
81968** The Next opcode is only valid following an SeekGT, SeekGE, or
81969** OP_Rewind opcode used to position the cursor.  Next is not allowed
81970** to follow SeekLT, SeekLE, or OP_Last.
81971**
81972** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
81973** been opened prior to this opcode or the program will segfault.
81974**
81975** The P3 value is a hint to the btree implementation. If P3==1, that
81976** means P1 is an SQL index and that this instruction could have been
81977** omitted if that index had been unique.  P3 is usually 0.  P3 is
81978** always either 0 or 1.
81979**
81980** P4 is always of type P4_ADVANCE. The function pointer points to
81981** sqlite3BtreeNext().
81982**
81983** If P5 is positive and the jump is taken, then event counter
81984** number P5-1 in the prepared statement is incremented.
81985**
81986** See also: Prev, NextIfOpen
81987*/
81988/* Opcode: NextIfOpen P1 P2 P3 P4 P5
81989**
81990** This opcode works just like Next except that if cursor P1 is not
81991** open it behaves a no-op.
81992*/
81993/* Opcode: Prev P1 P2 P3 P4 P5
81994**
81995** Back up cursor P1 so that it points to the previous key/data pair in its
81996** table or index.  If there is no previous key/value pairs then fall through
81997** to the following instruction.  But if the cursor backup was successful,
81998** jump immediately to P2.
81999**
82000**
82001** The Prev opcode is only valid following an SeekLT, SeekLE, or
82002** OP_Last opcode used to position the cursor.  Prev is not allowed
82003** to follow SeekGT, SeekGE, or OP_Rewind.
82004**
82005** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
82006** not open then the behavior is undefined.
82007**
82008** The P3 value is a hint to the btree implementation. If P3==1, that
82009** means P1 is an SQL index and that this instruction could have been
82010** omitted if that index had been unique.  P3 is usually 0.  P3 is
82011** always either 0 or 1.
82012**
82013** P4 is always of type P4_ADVANCE. The function pointer points to
82014** sqlite3BtreePrevious().
82015**
82016** If P5 is positive and the jump is taken, then event counter
82017** number P5-1 in the prepared statement is incremented.
82018*/
82019/* Opcode: PrevIfOpen P1 P2 P3 P4 P5
82020**
82021** This opcode works just like Prev except that if cursor P1 is not
82022** open it behaves a no-op.
82023*/
82024case OP_SorterNext: {  /* jump */
82025  VdbeCursor *pC;
82026  int res;
82027
82028  pC = p->apCsr[pOp->p1];
82029  assert( isSorter(pC) );
82030  res = 0;
82031  rc = sqlite3VdbeSorterNext(db, pC, &res);
82032  goto next_tail;
82033case OP_PrevIfOpen:    /* jump */
82034case OP_NextIfOpen:    /* jump */
82035  if( p->apCsr[pOp->p1]==0 ) break;
82036  /* Fall through */
82037case OP_Prev:          /* jump */
82038case OP_Next:          /* jump */
82039  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82040  assert( pOp->p5<ArraySize(p->aCounter) );
82041  pC = p->apCsr[pOp->p1];
82042  res = pOp->p3;
82043  assert( pC!=0 );
82044  assert( pC->deferredMoveto==0 );
82045  assert( pC->eCurType==CURTYPE_BTREE );
82046  assert( res==0 || (res==1 && pC->isTable==0) );
82047  testcase( res==1 );
82048  assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
82049  assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
82050  assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
82051  assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
82052
82053  /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
82054  ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
82055  assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
82056       || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
82057       || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
82058  assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
82059       || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
82060       || pC->seekOp==OP_Last );
82061
82062  rc = pOp->p4.xAdvance(pC->uc.pCursor, &res);
82063next_tail:
82064  pC->cacheStatus = CACHE_STALE;
82065  VdbeBranchTaken(res==0,2);
82066  if( rc ) goto abort_due_to_error;
82067  if( res==0 ){
82068    pC->nullRow = 0;
82069    p->aCounter[pOp->p5]++;
82070#ifdef SQLITE_TEST
82071    sqlite3_search_count++;
82072#endif
82073    goto jump_to_p2_and_check_for_interrupt;
82074  }else{
82075    pC->nullRow = 1;
82076  }
82077  goto check_for_interrupt;
82078}
82079
82080/* Opcode: IdxInsert P1 P2 P3 * P5
82081** Synopsis: key=r[P2]
82082**
82083** Register P2 holds an SQL index key made using the
82084** MakeRecord instructions.  This opcode writes that key
82085** into the index P1.  Data for the entry is nil.
82086**
82087** P3 is a flag that provides a hint to the b-tree layer that this
82088** insert is likely to be an append.
82089**
82090** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
82091** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
82092** then the change counter is unchanged.
82093**
82094** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
82095** just done a seek to the spot where the new entry is to be inserted.
82096** This flag avoids doing an extra seek.
82097**
82098** This instruction only works for indices.  The equivalent instruction
82099** for tables is OP_Insert.
82100*/
82101case OP_SorterInsert:       /* in2 */
82102case OP_IdxInsert: {        /* in2 */
82103  VdbeCursor *pC;
82104  BtreePayload x;
82105
82106  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82107  pC = p->apCsr[pOp->p1];
82108  assert( pC!=0 );
82109  assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
82110  pIn2 = &aMem[pOp->p2];
82111  assert( pIn2->flags & MEM_Blob );
82112  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
82113  assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
82114  assert( pC->isTable==0 );
82115  rc = ExpandBlob(pIn2);
82116  if( rc ) goto abort_due_to_error;
82117  if( pOp->opcode==OP_SorterInsert ){
82118    rc = sqlite3VdbeSorterWrite(pC, pIn2);
82119  }else{
82120    x.nKey = pIn2->n;
82121    x.pKey = pIn2->z;
82122    x.nData = 0;
82123    x.nZero = 0;
82124    x.pData = 0;
82125    rc = sqlite3BtreeInsert(pC->uc.pCursor, &x, pOp->p3,
82126        ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
82127        );
82128    assert( pC->deferredMoveto==0 );
82129    pC->cacheStatus = CACHE_STALE;
82130  }
82131  if( rc) goto abort_due_to_error;
82132  break;
82133}
82134
82135/* Opcode: IdxDelete P1 P2 P3 * *
82136** Synopsis: key=r[P2@P3]
82137**
82138** The content of P3 registers starting at register P2 form
82139** an unpacked index key. This opcode removes that entry from the
82140** index opened by cursor P1.
82141*/
82142case OP_IdxDelete: {
82143  VdbeCursor *pC;
82144  BtCursor *pCrsr;
82145  int res;
82146  UnpackedRecord r;
82147
82148  assert( pOp->p3>0 );
82149  assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
82150  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82151  pC = p->apCsr[pOp->p1];
82152  assert( pC!=0 );
82153  assert( pC->eCurType==CURTYPE_BTREE );
82154  pCrsr = pC->uc.pCursor;
82155  assert( pCrsr!=0 );
82156  assert( pOp->p5==0 );
82157  r.pKeyInfo = pC->pKeyInfo;
82158  r.nField = (u16)pOp->p3;
82159  r.default_rc = 0;
82160  r.aMem = &aMem[pOp->p2];
82161  rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
82162  if( rc ) goto abort_due_to_error;
82163  if( res==0 ){
82164    rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
82165    if( rc ) goto abort_due_to_error;
82166  }
82167  assert( pC->deferredMoveto==0 );
82168  pC->cacheStatus = CACHE_STALE;
82169  break;
82170}
82171
82172/* Opcode: Seek P1 * P3 P4 *
82173** Synopsis:  Move P3 to P1.rowid
82174**
82175** P1 is an open index cursor and P3 is a cursor on the corresponding
82176** table.  This opcode does a deferred seek of the P3 table cursor
82177** to the row that corresponds to the current row of P1.
82178**
82179** This is a deferred seek.  Nothing actually happens until
82180** the cursor is used to read a record.  That way, if no reads
82181** occur, no unnecessary I/O happens.
82182**
82183** P4 may be an array of integers (type P4_INTARRAY) containing
82184** one entry for each column in the P3 table.  If array entry a(i)
82185** is non-zero, then reading column a(i)-1 from cursor P3 is
82186** equivalent to performing the deferred seek and then reading column i
82187** from P1.  This information is stored in P3 and used to redirect
82188** reads against P3 over to P1, thus possibly avoiding the need to
82189** seek and read cursor P3.
82190*/
82191/* Opcode: IdxRowid P1 P2 * * *
82192** Synopsis: r[P2]=rowid
82193**
82194** Write into register P2 an integer which is the last entry in the record at
82195** the end of the index key pointed to by cursor P1.  This integer should be
82196** the rowid of the table entry to which this index entry points.
82197**
82198** See also: Rowid, MakeRecord.
82199*/
82200case OP_Seek:
82201case OP_IdxRowid: {              /* out2 */
82202  VdbeCursor *pC;                /* The P1 index cursor */
82203  VdbeCursor *pTabCur;           /* The P2 table cursor (OP_Seek only) */
82204  i64 rowid;                     /* Rowid that P1 current points to */
82205
82206  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82207  pC = p->apCsr[pOp->p1];
82208  assert( pC!=0 );
82209  assert( pC->eCurType==CURTYPE_BTREE );
82210  assert( pC->uc.pCursor!=0 );
82211  assert( pC->isTable==0 );
82212  assert( pC->deferredMoveto==0 );
82213  assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
82214
82215  /* The IdxRowid and Seek opcodes are combined because of the commonality
82216  ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
82217  rc = sqlite3VdbeCursorRestore(pC);
82218
82219  /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
82220  ** out from under the cursor.  That will never happens for an IdxRowid
82221  ** or Seek opcode */
82222  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
82223
82224  if( !pC->nullRow ){
82225    rowid = 0;  /* Not needed.  Only used to silence a warning. */
82226    rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
82227    if( rc!=SQLITE_OK ){
82228      goto abort_due_to_error;
82229    }
82230    if( pOp->opcode==OP_Seek ){
82231      assert( pOp->p3>=0 && pOp->p3<p->nCursor );
82232      pTabCur = p->apCsr[pOp->p3];
82233      assert( pTabCur!=0 );
82234      assert( pTabCur->eCurType==CURTYPE_BTREE );
82235      assert( pTabCur->uc.pCursor!=0 );
82236      assert( pTabCur->isTable );
82237      pTabCur->nullRow = 0;
82238      pTabCur->movetoTarget = rowid;
82239      pTabCur->deferredMoveto = 1;
82240      assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
82241      pTabCur->aAltMap = pOp->p4.ai;
82242      pTabCur->pAltCursor = pC;
82243    }else{
82244      pOut = out2Prerelease(p, pOp);
82245      pOut->u.i = rowid;
82246      pOut->flags = MEM_Int;
82247    }
82248  }else{
82249    assert( pOp->opcode==OP_IdxRowid );
82250    sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
82251  }
82252  break;
82253}
82254
82255/* Opcode: IdxGE P1 P2 P3 P4 P5
82256** Synopsis: key=r[P3@P4]
82257**
82258** The P4 register values beginning with P3 form an unpacked index
82259** key that omits the PRIMARY KEY.  Compare this key value against the index
82260** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
82261** fields at the end.
82262**
82263** If the P1 index entry is greater than or equal to the key value
82264** then jump to P2.  Otherwise fall through to the next instruction.
82265*/
82266/* Opcode: IdxGT P1 P2 P3 P4 P5
82267** Synopsis: key=r[P3@P4]
82268**
82269** The P4 register values beginning with P3 form an unpacked index
82270** key that omits the PRIMARY KEY.  Compare this key value against the index
82271** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
82272** fields at the end.
82273**
82274** If the P1 index entry is greater than the key value
82275** then jump to P2.  Otherwise fall through to the next instruction.
82276*/
82277/* Opcode: IdxLT P1 P2 P3 P4 P5
82278** Synopsis: key=r[P3@P4]
82279**
82280** The P4 register values beginning with P3 form an unpacked index
82281** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
82282** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
82283** ROWID on the P1 index.
82284**
82285** If the P1 index entry is less than the key value then jump to P2.
82286** Otherwise fall through to the next instruction.
82287*/
82288/* Opcode: IdxLE P1 P2 P3 P4 P5
82289** Synopsis: key=r[P3@P4]
82290**
82291** The P4 register values beginning with P3 form an unpacked index
82292** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
82293** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
82294** ROWID on the P1 index.
82295**
82296** If the P1 index entry is less than or equal to the key value then jump
82297** to P2. Otherwise fall through to the next instruction.
82298*/
82299case OP_IdxLE:          /* jump */
82300case OP_IdxGT:          /* jump */
82301case OP_IdxLT:          /* jump */
82302case OP_IdxGE:  {       /* jump */
82303  VdbeCursor *pC;
82304  int res;
82305  UnpackedRecord r;
82306
82307  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82308  pC = p->apCsr[pOp->p1];
82309  assert( pC!=0 );
82310  assert( pC->isOrdered );
82311  assert( pC->eCurType==CURTYPE_BTREE );
82312  assert( pC->uc.pCursor!=0);
82313  assert( pC->deferredMoveto==0 );
82314  assert( pOp->p5==0 || pOp->p5==1 );
82315  assert( pOp->p4type==P4_INT32 );
82316  r.pKeyInfo = pC->pKeyInfo;
82317  r.nField = (u16)pOp->p4.i;
82318  if( pOp->opcode<OP_IdxLT ){
82319    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
82320    r.default_rc = -1;
82321  }else{
82322    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
82323    r.default_rc = 0;
82324  }
82325  r.aMem = &aMem[pOp->p3];
82326#ifdef SQLITE_DEBUG
82327  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
82328#endif
82329  res = 0;  /* Not needed.  Only used to silence a warning. */
82330  rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
82331  assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
82332  if( (pOp->opcode&1)==(OP_IdxLT&1) ){
82333    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
82334    res = -res;
82335  }else{
82336    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
82337    res++;
82338  }
82339  VdbeBranchTaken(res>0,2);
82340  if( rc ) goto abort_due_to_error;
82341  if( res>0 ) goto jump_to_p2;
82342  break;
82343}
82344
82345/* Opcode: Destroy P1 P2 P3 * *
82346**
82347** Delete an entire database table or index whose root page in the database
82348** file is given by P1.
82349**
82350** The table being destroyed is in the main database file if P3==0.  If
82351** P3==1 then the table to be clear is in the auxiliary database file
82352** that is used to store tables create using CREATE TEMPORARY TABLE.
82353**
82354** If AUTOVACUUM is enabled then it is possible that another root page
82355** might be moved into the newly deleted root page in order to keep all
82356** root pages contiguous at the beginning of the database.  The former
82357** value of the root page that moved - its value before the move occurred -
82358** is stored in register P2.  If no page
82359** movement was required (because the table being dropped was already
82360** the last one in the database) then a zero is stored in register P2.
82361** If AUTOVACUUM is disabled then a zero is stored in register P2.
82362**
82363** See also: Clear
82364*/
82365case OP_Destroy: {     /* out2 */
82366  int iMoved;
82367  int iDb;
82368
82369  assert( p->readOnly==0 );
82370  assert( pOp->p1>1 );
82371  pOut = out2Prerelease(p, pOp);
82372  pOut->flags = MEM_Null;
82373  if( db->nVdbeRead > db->nVDestroy+1 ){
82374    rc = SQLITE_LOCKED;
82375    p->errorAction = OE_Abort;
82376    goto abort_due_to_error;
82377  }else{
82378    iDb = pOp->p3;
82379    assert( DbMaskTest(p->btreeMask, iDb) );
82380    iMoved = 0;  /* Not needed.  Only to silence a warning. */
82381    rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
82382    pOut->flags = MEM_Int;
82383    pOut->u.i = iMoved;
82384    if( rc ) goto abort_due_to_error;
82385#ifndef SQLITE_OMIT_AUTOVACUUM
82386    if( iMoved!=0 ){
82387      sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
82388      /* All OP_Destroy operations occur on the same btree */
82389      assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
82390      resetSchemaOnFault = iDb+1;
82391    }
82392#endif
82393  }
82394  break;
82395}
82396
82397/* Opcode: Clear P1 P2 P3
82398**
82399** Delete all contents of the database table or index whose root page
82400** in the database file is given by P1.  But, unlike Destroy, do not
82401** remove the table or index from the database file.
82402**
82403** The table being clear is in the main database file if P2==0.  If
82404** P2==1 then the table to be clear is in the auxiliary database file
82405** that is used to store tables create using CREATE TEMPORARY TABLE.
82406**
82407** If the P3 value is non-zero, then the table referred to must be an
82408** intkey table (an SQL table, not an index). In this case the row change
82409** count is incremented by the number of rows in the table being cleared.
82410** If P3 is greater than zero, then the value stored in register P3 is
82411** also incremented by the number of rows in the table being cleared.
82412**
82413** See also: Destroy
82414*/
82415case OP_Clear: {
82416  int nChange;
82417
82418  nChange = 0;
82419  assert( p->readOnly==0 );
82420  assert( DbMaskTest(p->btreeMask, pOp->p2) );
82421  rc = sqlite3BtreeClearTable(
82422      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
82423  );
82424  if( pOp->p3 ){
82425    p->nChange += nChange;
82426    if( pOp->p3>0 ){
82427      assert( memIsValid(&aMem[pOp->p3]) );
82428      memAboutToChange(p, &aMem[pOp->p3]);
82429      aMem[pOp->p3].u.i += nChange;
82430    }
82431  }
82432  if( rc ) goto abort_due_to_error;
82433  break;
82434}
82435
82436/* Opcode: ResetSorter P1 * * * *
82437**
82438** Delete all contents from the ephemeral table or sorter
82439** that is open on cursor P1.
82440**
82441** This opcode only works for cursors used for sorting and
82442** opened with OP_OpenEphemeral or OP_SorterOpen.
82443*/
82444case OP_ResetSorter: {
82445  VdbeCursor *pC;
82446
82447  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82448  pC = p->apCsr[pOp->p1];
82449  assert( pC!=0 );
82450  if( isSorter(pC) ){
82451    sqlite3VdbeSorterReset(db, pC->uc.pSorter);
82452  }else{
82453    assert( pC->eCurType==CURTYPE_BTREE );
82454    assert( pC->isEphemeral );
82455    rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
82456    if( rc ) goto abort_due_to_error;
82457  }
82458  break;
82459}
82460
82461/* Opcode: CreateTable P1 P2 * * *
82462** Synopsis: r[P2]=root iDb=P1
82463**
82464** Allocate a new table in the main database file if P1==0 or in the
82465** auxiliary database file if P1==1 or in an attached database if
82466** P1>1.  Write the root page number of the new table into
82467** register P2
82468**
82469** The difference between a table and an index is this:  A table must
82470** have a 4-byte integer key and can have arbitrary data.  An index
82471** has an arbitrary key but no data.
82472**
82473** See also: CreateIndex
82474*/
82475/* Opcode: CreateIndex P1 P2 * * *
82476** Synopsis: r[P2]=root iDb=P1
82477**
82478** Allocate a new index in the main database file if P1==0 or in the
82479** auxiliary database file if P1==1 or in an attached database if
82480** P1>1.  Write the root page number of the new table into
82481** register P2.
82482**
82483** See documentation on OP_CreateTable for additional information.
82484*/
82485case OP_CreateIndex:            /* out2 */
82486case OP_CreateTable: {          /* out2 */
82487  int pgno;
82488  int flags;
82489  Db *pDb;
82490
82491  pOut = out2Prerelease(p, pOp);
82492  pgno = 0;
82493  assert( pOp->p1>=0 && pOp->p1<db->nDb );
82494  assert( DbMaskTest(p->btreeMask, pOp->p1) );
82495  assert( p->readOnly==0 );
82496  pDb = &db->aDb[pOp->p1];
82497  assert( pDb->pBt!=0 );
82498  if( pOp->opcode==OP_CreateTable ){
82499    /* flags = BTREE_INTKEY; */
82500    flags = BTREE_INTKEY;
82501  }else{
82502    flags = BTREE_BLOBKEY;
82503  }
82504  rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
82505  if( rc ) goto abort_due_to_error;
82506  pOut->u.i = pgno;
82507  break;
82508}
82509
82510/* Opcode: ParseSchema P1 * * P4 *
82511**
82512** Read and parse all entries from the SQLITE_MASTER table of database P1
82513** that match the WHERE clause P4.
82514**
82515** This opcode invokes the parser to create a new virtual machine,
82516** then runs the new virtual machine.  It is thus a re-entrant opcode.
82517*/
82518case OP_ParseSchema: {
82519  int iDb;
82520  const char *zMaster;
82521  char *zSql;
82522  InitData initData;
82523
82524  /* Any prepared statement that invokes this opcode will hold mutexes
82525  ** on every btree.  This is a prerequisite for invoking
82526  ** sqlite3InitCallback().
82527  */
82528#ifdef SQLITE_DEBUG
82529  for(iDb=0; iDb<db->nDb; iDb++){
82530    assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
82531  }
82532#endif
82533
82534  iDb = pOp->p1;
82535  assert( iDb>=0 && iDb<db->nDb );
82536  assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
82537  /* Used to be a conditional */ {
82538    zMaster = SCHEMA_TABLE(iDb);
82539    initData.db = db;
82540    initData.iDb = pOp->p1;
82541    initData.pzErrMsg = &p->zErrMsg;
82542    zSql = sqlite3MPrintf(db,
82543       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
82544       db->aDb[iDb].zName, zMaster, pOp->p4.z);
82545    if( zSql==0 ){
82546      rc = SQLITE_NOMEM_BKPT;
82547    }else{
82548      assert( db->init.busy==0 );
82549      db->init.busy = 1;
82550      initData.rc = SQLITE_OK;
82551      assert( !db->mallocFailed );
82552      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
82553      if( rc==SQLITE_OK ) rc = initData.rc;
82554      sqlite3DbFree(db, zSql);
82555      db->init.busy = 0;
82556    }
82557  }
82558  if( rc ){
82559    sqlite3ResetAllSchemasOfConnection(db);
82560    if( rc==SQLITE_NOMEM ){
82561      goto no_mem;
82562    }
82563    goto abort_due_to_error;
82564  }
82565  break;
82566}
82567
82568#if !defined(SQLITE_OMIT_ANALYZE)
82569/* Opcode: LoadAnalysis P1 * * * *
82570**
82571** Read the sqlite_stat1 table for database P1 and load the content
82572** of that table into the internal index hash table.  This will cause
82573** the analysis to be used when preparing all subsequent queries.
82574*/
82575case OP_LoadAnalysis: {
82576  assert( pOp->p1>=0 && pOp->p1<db->nDb );
82577  rc = sqlite3AnalysisLoad(db, pOp->p1);
82578  if( rc ) goto abort_due_to_error;
82579  break;
82580}
82581#endif /* !defined(SQLITE_OMIT_ANALYZE) */
82582
82583/* Opcode: DropTable P1 * * P4 *
82584**
82585** Remove the internal (in-memory) data structures that describe
82586** the table named P4 in database P1.  This is called after a table
82587** is dropped from disk (using the Destroy opcode) in order to keep
82588** the internal representation of the
82589** schema consistent with what is on disk.
82590*/
82591case OP_DropTable: {
82592  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
82593  break;
82594}
82595
82596/* Opcode: DropIndex P1 * * P4 *
82597**
82598** Remove the internal (in-memory) data structures that describe
82599** the index named P4 in database P1.  This is called after an index
82600** is dropped from disk (using the Destroy opcode)
82601** in order to keep the internal representation of the
82602** schema consistent with what is on disk.
82603*/
82604case OP_DropIndex: {
82605  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
82606  break;
82607}
82608
82609/* Opcode: DropTrigger P1 * * P4 *
82610**
82611** Remove the internal (in-memory) data structures that describe
82612** the trigger named P4 in database P1.  This is called after a trigger
82613** is dropped from disk (using the Destroy opcode) in order to keep
82614** the internal representation of the
82615** schema consistent with what is on disk.
82616*/
82617case OP_DropTrigger: {
82618  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
82619  break;
82620}
82621
82622
82623#ifndef SQLITE_OMIT_INTEGRITY_CHECK
82624/* Opcode: IntegrityCk P1 P2 P3 P4 P5
82625**
82626** Do an analysis of the currently open database.  Store in
82627** register P1 the text of an error message describing any problems.
82628** If no problems are found, store a NULL in register P1.
82629**
82630** The register P3 contains the maximum number of allowed errors.
82631** At most reg(P3) errors will be reported.
82632** In other words, the analysis stops as soon as reg(P1) errors are
82633** seen.  Reg(P1) is updated with the number of errors remaining.
82634**
82635** The root page numbers of all tables in the database are integers
82636** stored in P4_INTARRAY argument.
82637**
82638** If P5 is not zero, the check is done on the auxiliary database
82639** file, not the main database file.
82640**
82641** This opcode is used to implement the integrity_check pragma.
82642*/
82643case OP_IntegrityCk: {
82644  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
82645  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
82646  int nErr;       /* Number of errors reported */
82647  char *z;        /* Text of the error report */
82648  Mem *pnErr;     /* Register keeping track of errors remaining */
82649
82650  assert( p->bIsReader );
82651  nRoot = pOp->p2;
82652  aRoot = pOp->p4.ai;
82653  assert( nRoot>0 );
82654  assert( aRoot[nRoot]==0 );
82655  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
82656  pnErr = &aMem[pOp->p3];
82657  assert( (pnErr->flags & MEM_Int)!=0 );
82658  assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
82659  pIn1 = &aMem[pOp->p1];
82660  assert( pOp->p5<db->nDb );
82661  assert( DbMaskTest(p->btreeMask, pOp->p5) );
82662  z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
82663                                 (int)pnErr->u.i, &nErr);
82664  pnErr->u.i -= nErr;
82665  sqlite3VdbeMemSetNull(pIn1);
82666  if( nErr==0 ){
82667    assert( z==0 );
82668  }else if( z==0 ){
82669    goto no_mem;
82670  }else{
82671    sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
82672  }
82673  UPDATE_MAX_BLOBSIZE(pIn1);
82674  sqlite3VdbeChangeEncoding(pIn1, encoding);
82675  break;
82676}
82677#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
82678
82679/* Opcode: RowSetAdd P1 P2 * * *
82680** Synopsis:  rowset(P1)=r[P2]
82681**
82682** Insert the integer value held by register P2 into a boolean index
82683** held in register P1.
82684**
82685** An assertion fails if P2 is not an integer.
82686*/
82687case OP_RowSetAdd: {       /* in1, in2 */
82688  pIn1 = &aMem[pOp->p1];
82689  pIn2 = &aMem[pOp->p2];
82690  assert( (pIn2->flags & MEM_Int)!=0 );
82691  if( (pIn1->flags & MEM_RowSet)==0 ){
82692    sqlite3VdbeMemSetRowSet(pIn1);
82693    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
82694  }
82695  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
82696  break;
82697}
82698
82699/* Opcode: RowSetRead P1 P2 P3 * *
82700** Synopsis:  r[P3]=rowset(P1)
82701**
82702** Extract the smallest value from boolean index P1 and put that value into
82703** register P3.  Or, if boolean index P1 is initially empty, leave P3
82704** unchanged and jump to instruction P2.
82705*/
82706case OP_RowSetRead: {       /* jump, in1, out3 */
82707  i64 val;
82708
82709  pIn1 = &aMem[pOp->p1];
82710  if( (pIn1->flags & MEM_RowSet)==0
82711   || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
82712  ){
82713    /* The boolean index is empty */
82714    sqlite3VdbeMemSetNull(pIn1);
82715    VdbeBranchTaken(1,2);
82716    goto jump_to_p2_and_check_for_interrupt;
82717  }else{
82718    /* A value was pulled from the index */
82719    VdbeBranchTaken(0,2);
82720    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
82721  }
82722  goto check_for_interrupt;
82723}
82724
82725/* Opcode: RowSetTest P1 P2 P3 P4
82726** Synopsis: if r[P3] in rowset(P1) goto P2
82727**
82728** Register P3 is assumed to hold a 64-bit integer value. If register P1
82729** contains a RowSet object and that RowSet object contains
82730** the value held in P3, jump to register P2. Otherwise, insert the
82731** integer in P3 into the RowSet and continue on to the
82732** next opcode.
82733**
82734** The RowSet object is optimized for the case where successive sets
82735** of integers, where each set contains no duplicates. Each set
82736** of values is identified by a unique P4 value. The first set
82737** must have P4==0, the final set P4=-1.  P4 must be either -1 or
82738** non-negative.  For non-negative values of P4 only the lower 4
82739** bits are significant.
82740**
82741** This allows optimizations: (a) when P4==0 there is no need to test
82742** the rowset object for P3, as it is guaranteed not to contain it,
82743** (b) when P4==-1 there is no need to insert the value, as it will
82744** never be tested for, and (c) when a value that is part of set X is
82745** inserted, there is no need to search to see if the same value was
82746** previously inserted as part of set X (only if it was previously
82747** inserted as part of some other set).
82748*/
82749case OP_RowSetTest: {                     /* jump, in1, in3 */
82750  int iSet;
82751  int exists;
82752
82753  pIn1 = &aMem[pOp->p1];
82754  pIn3 = &aMem[pOp->p3];
82755  iSet = pOp->p4.i;
82756  assert( pIn3->flags&MEM_Int );
82757
82758  /* If there is anything other than a rowset object in memory cell P1,
82759  ** delete it now and initialize P1 with an empty rowset
82760  */
82761  if( (pIn1->flags & MEM_RowSet)==0 ){
82762    sqlite3VdbeMemSetRowSet(pIn1);
82763    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
82764  }
82765
82766  assert( pOp->p4type==P4_INT32 );
82767  assert( iSet==-1 || iSet>=0 );
82768  if( iSet ){
82769    exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
82770    VdbeBranchTaken(exists!=0,2);
82771    if( exists ) goto jump_to_p2;
82772  }
82773  if( iSet>=0 ){
82774    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
82775  }
82776  break;
82777}
82778
82779
82780#ifndef SQLITE_OMIT_TRIGGER
82781
82782/* Opcode: Program P1 P2 P3 P4 P5
82783**
82784** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
82785**
82786** P1 contains the address of the memory cell that contains the first memory
82787** cell in an array of values used as arguments to the sub-program. P2
82788** contains the address to jump to if the sub-program throws an IGNORE
82789** exception using the RAISE() function. Register P3 contains the address
82790** of a memory cell in this (the parent) VM that is used to allocate the
82791** memory required by the sub-vdbe at runtime.
82792**
82793** P4 is a pointer to the VM containing the trigger program.
82794**
82795** If P5 is non-zero, then recursive program invocation is enabled.
82796*/
82797case OP_Program: {        /* jump */
82798  int nMem;               /* Number of memory registers for sub-program */
82799  int nByte;              /* Bytes of runtime space required for sub-program */
82800  Mem *pRt;               /* Register to allocate runtime space */
82801  Mem *pMem;              /* Used to iterate through memory cells */
82802  Mem *pEnd;              /* Last memory cell in new array */
82803  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
82804  SubProgram *pProgram;   /* Sub-program to execute */
82805  void *t;                /* Token identifying trigger */
82806
82807  pProgram = pOp->p4.pProgram;
82808  pRt = &aMem[pOp->p3];
82809  assert( pProgram->nOp>0 );
82810
82811  /* If the p5 flag is clear, then recursive invocation of triggers is
82812  ** disabled for backwards compatibility (p5 is set if this sub-program
82813  ** is really a trigger, not a foreign key action, and the flag set
82814  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
82815  **
82816  ** It is recursive invocation of triggers, at the SQL level, that is
82817  ** disabled. In some cases a single trigger may generate more than one
82818  ** SubProgram (if the trigger may be executed with more than one different
82819  ** ON CONFLICT algorithm). SubProgram structures associated with a
82820  ** single trigger all have the same value for the SubProgram.token
82821  ** variable.  */
82822  if( pOp->p5 ){
82823    t = pProgram->token;
82824    for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
82825    if( pFrame ) break;
82826  }
82827
82828  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
82829    rc = SQLITE_ERROR;
82830    sqlite3VdbeError(p, "too many levels of trigger recursion");
82831    goto abort_due_to_error;
82832  }
82833
82834  /* Register pRt is used to store the memory required to save the state
82835  ** of the current program, and the memory required at runtime to execute
82836  ** the trigger program. If this trigger has been fired before, then pRt
82837  ** is already allocated. Otherwise, it must be initialized.  */
82838  if( (pRt->flags&MEM_Frame)==0 ){
82839    /* SubProgram.nMem is set to the number of memory cells used by the
82840    ** program stored in SubProgram.aOp. As well as these, one memory
82841    ** cell is required for each cursor used by the program. Set local
82842    ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
82843    */
82844    nMem = pProgram->nMem + pProgram->nCsr;
82845    assert( nMem>0 );
82846    if( pProgram->nCsr==0 ) nMem++;
82847    nByte = ROUND8(sizeof(VdbeFrame))
82848              + nMem * sizeof(Mem)
82849              + pProgram->nCsr * sizeof(VdbeCursor *)
82850              + pProgram->nOnce * sizeof(u8);
82851    pFrame = sqlite3DbMallocZero(db, nByte);
82852    if( !pFrame ){
82853      goto no_mem;
82854    }
82855    sqlite3VdbeMemRelease(pRt);
82856    pRt->flags = MEM_Frame;
82857    pRt->u.pFrame = pFrame;
82858
82859    pFrame->v = p;
82860    pFrame->nChildMem = nMem;
82861    pFrame->nChildCsr = pProgram->nCsr;
82862    pFrame->pc = (int)(pOp - aOp);
82863    pFrame->aMem = p->aMem;
82864    pFrame->nMem = p->nMem;
82865    pFrame->apCsr = p->apCsr;
82866    pFrame->nCursor = p->nCursor;
82867    pFrame->aOp = p->aOp;
82868    pFrame->nOp = p->nOp;
82869    pFrame->token = pProgram->token;
82870    pFrame->aOnceFlag = p->aOnceFlag;
82871    pFrame->nOnceFlag = p->nOnceFlag;
82872#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
82873    pFrame->anExec = p->anExec;
82874#endif
82875
82876    pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
82877    for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
82878      pMem->flags = MEM_Undefined;
82879      pMem->db = db;
82880    }
82881  }else{
82882    pFrame = pRt->u.pFrame;
82883    assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
82884        || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
82885    assert( pProgram->nCsr==pFrame->nChildCsr );
82886    assert( (int)(pOp - aOp)==pFrame->pc );
82887  }
82888
82889  p->nFrame++;
82890  pFrame->pParent = p->pFrame;
82891  pFrame->lastRowid = lastRowid;
82892  pFrame->nChange = p->nChange;
82893  pFrame->nDbChange = p->db->nChange;
82894  assert( pFrame->pAuxData==0 );
82895  pFrame->pAuxData = p->pAuxData;
82896  p->pAuxData = 0;
82897  p->nChange = 0;
82898  p->pFrame = pFrame;
82899  p->aMem = aMem = VdbeFrameMem(pFrame);
82900  p->nMem = pFrame->nChildMem;
82901  p->nCursor = (u16)pFrame->nChildCsr;
82902  p->apCsr = (VdbeCursor **)&aMem[p->nMem];
82903  p->aOp = aOp = pProgram->aOp;
82904  p->nOp = pProgram->nOp;
82905  p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
82906  p->nOnceFlag = pProgram->nOnce;
82907#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
82908  p->anExec = 0;
82909#endif
82910  pOp = &aOp[-1];
82911  memset(p->aOnceFlag, 0, p->nOnceFlag);
82912
82913  break;
82914}
82915
82916/* Opcode: Param P1 P2 * * *
82917**
82918** This opcode is only ever present in sub-programs called via the
82919** OP_Program instruction. Copy a value currently stored in a memory
82920** cell of the calling (parent) frame to cell P2 in the current frames
82921** address space. This is used by trigger programs to access the new.*
82922** and old.* values.
82923**
82924** The address of the cell in the parent frame is determined by adding
82925** the value of the P1 argument to the value of the P1 argument to the
82926** calling OP_Program instruction.
82927*/
82928case OP_Param: {           /* out2 */
82929  VdbeFrame *pFrame;
82930  Mem *pIn;
82931  pOut = out2Prerelease(p, pOp);
82932  pFrame = p->pFrame;
82933  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
82934  sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
82935  break;
82936}
82937
82938#endif /* #ifndef SQLITE_OMIT_TRIGGER */
82939
82940#ifndef SQLITE_OMIT_FOREIGN_KEY
82941/* Opcode: FkCounter P1 P2 * * *
82942** Synopsis: fkctr[P1]+=P2
82943**
82944** Increment a "constraint counter" by P2 (P2 may be negative or positive).
82945** If P1 is non-zero, the database constraint counter is incremented
82946** (deferred foreign key constraints). Otherwise, if P1 is zero, the
82947** statement counter is incremented (immediate foreign key constraints).
82948*/
82949case OP_FkCounter: {
82950  if( db->flags & SQLITE_DeferFKs ){
82951    db->nDeferredImmCons += pOp->p2;
82952  }else if( pOp->p1 ){
82953    db->nDeferredCons += pOp->p2;
82954  }else{
82955    p->nFkConstraint += pOp->p2;
82956  }
82957  break;
82958}
82959
82960/* Opcode: FkIfZero P1 P2 * * *
82961** Synopsis: if fkctr[P1]==0 goto P2
82962**
82963** This opcode tests if a foreign key constraint-counter is currently zero.
82964** If so, jump to instruction P2. Otherwise, fall through to the next
82965** instruction.
82966**
82967** If P1 is non-zero, then the jump is taken if the database constraint-counter
82968** is zero (the one that counts deferred constraint violations). If P1 is
82969** zero, the jump is taken if the statement constraint-counter is zero
82970** (immediate foreign key constraint violations).
82971*/
82972case OP_FkIfZero: {         /* jump */
82973  if( pOp->p1 ){
82974    VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
82975    if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
82976  }else{
82977    VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
82978    if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
82979  }
82980  break;
82981}
82982#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
82983
82984#ifndef SQLITE_OMIT_AUTOINCREMENT
82985/* Opcode: MemMax P1 P2 * * *
82986** Synopsis: r[P1]=max(r[P1],r[P2])
82987**
82988** P1 is a register in the root frame of this VM (the root frame is
82989** different from the current frame if this instruction is being executed
82990** within a sub-program). Set the value of register P1 to the maximum of
82991** its current value and the value in register P2.
82992**
82993** This instruction throws an error if the memory cell is not initially
82994** an integer.
82995*/
82996case OP_MemMax: {        /* in2 */
82997  VdbeFrame *pFrame;
82998  if( p->pFrame ){
82999    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
83000    pIn1 = &pFrame->aMem[pOp->p1];
83001  }else{
83002    pIn1 = &aMem[pOp->p1];
83003  }
83004  assert( memIsValid(pIn1) );
83005  sqlite3VdbeMemIntegerify(pIn1);
83006  pIn2 = &aMem[pOp->p2];
83007  sqlite3VdbeMemIntegerify(pIn2);
83008  if( pIn1->u.i<pIn2->u.i){
83009    pIn1->u.i = pIn2->u.i;
83010  }
83011  break;
83012}
83013#endif /* SQLITE_OMIT_AUTOINCREMENT */
83014
83015/* Opcode: IfPos P1 P2 P3 * *
83016** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
83017**
83018** Register P1 must contain an integer.
83019** If the value of register P1 is 1 or greater, subtract P3 from the
83020** value in P1 and jump to P2.
83021**
83022** If the initial value of register P1 is less than 1, then the
83023** value is unchanged and control passes through to the next instruction.
83024*/
83025case OP_IfPos: {        /* jump, in1 */
83026  pIn1 = &aMem[pOp->p1];
83027  assert( pIn1->flags&MEM_Int );
83028  VdbeBranchTaken( pIn1->u.i>0, 2);
83029  if( pIn1->u.i>0 ){
83030    pIn1->u.i -= pOp->p3;
83031    goto jump_to_p2;
83032  }
83033  break;
83034}
83035
83036/* Opcode: OffsetLimit P1 P2 P3 * *
83037** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
83038**
83039** This opcode performs a commonly used computation associated with
83040** LIMIT and OFFSET process.  r[P1] holds the limit counter.  r[P3]
83041** holds the offset counter.  The opcode computes the combined value
83042** of the LIMIT and OFFSET and stores that value in r[P2].  The r[P2]
83043** value computed is the total number of rows that will need to be
83044** visited in order to complete the query.
83045**
83046** If r[P3] is zero or negative, that means there is no OFFSET
83047** and r[P2] is set to be the value of the LIMIT, r[P1].
83048**
83049** if r[P1] is zero or negative, that means there is no LIMIT
83050** and r[P2] is set to -1.
83051**
83052** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
83053*/
83054case OP_OffsetLimit: {    /* in1, out2, in3 */
83055  pIn1 = &aMem[pOp->p1];
83056  pIn3 = &aMem[pOp->p3];
83057  pOut = out2Prerelease(p, pOp);
83058  assert( pIn1->flags & MEM_Int );
83059  assert( pIn3->flags & MEM_Int );
83060  pOut->u.i = pIn1->u.i<=0 ? -1 : pIn1->u.i+(pIn3->u.i>0?pIn3->u.i:0);
83061  break;
83062}
83063
83064/* Opcode: IfNotZero P1 P2 P3 * *
83065** Synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2
83066**
83067** Register P1 must contain an integer.  If the content of register P1 is
83068** initially nonzero, then subtract P3 from the value in register P1 and
83069** jump to P2.  If register P1 is initially zero, leave it unchanged
83070** and fall through.
83071*/
83072case OP_IfNotZero: {        /* jump, in1 */
83073  pIn1 = &aMem[pOp->p1];
83074  assert( pIn1->flags&MEM_Int );
83075  VdbeBranchTaken(pIn1->u.i<0, 2);
83076  if( pIn1->u.i ){
83077     pIn1->u.i -= pOp->p3;
83078     goto jump_to_p2;
83079  }
83080  break;
83081}
83082
83083/* Opcode: DecrJumpZero P1 P2 * * *
83084** Synopsis: if (--r[P1])==0 goto P2
83085**
83086** Register P1 must hold an integer.  Decrement the value in register P1
83087** then jump to P2 if the new value is exactly zero.
83088*/
83089case OP_DecrJumpZero: {      /* jump, in1 */
83090  pIn1 = &aMem[pOp->p1];
83091  assert( pIn1->flags&MEM_Int );
83092  pIn1->u.i--;
83093  VdbeBranchTaken(pIn1->u.i==0, 2);
83094  if( pIn1->u.i==0 ) goto jump_to_p2;
83095  break;
83096}
83097
83098
83099/* Opcode: AggStep0 * P2 P3 P4 P5
83100** Synopsis: accum=r[P3] step(r[P2@P5])
83101**
83102** Execute the step function for an aggregate.  The
83103** function has P5 arguments.   P4 is a pointer to the FuncDef
83104** structure that specifies the function.  Register P3 is the
83105** accumulator.
83106**
83107** The P5 arguments are taken from register P2 and its
83108** successors.
83109*/
83110/* Opcode: AggStep * P2 P3 P4 P5
83111** Synopsis: accum=r[P3] step(r[P2@P5])
83112**
83113** Execute the step function for an aggregate.  The
83114** function has P5 arguments.   P4 is a pointer to an sqlite3_context
83115** object that is used to run the function.  Register P3 is
83116** as the accumulator.
83117**
83118** The P5 arguments are taken from register P2 and its
83119** successors.
83120**
83121** This opcode is initially coded as OP_AggStep0.  On first evaluation,
83122** the FuncDef stored in P4 is converted into an sqlite3_context and
83123** the opcode is changed.  In this way, the initialization of the
83124** sqlite3_context only happens once, instead of on each call to the
83125** step function.
83126*/
83127case OP_AggStep0: {
83128  int n;
83129  sqlite3_context *pCtx;
83130
83131  assert( pOp->p4type==P4_FUNCDEF );
83132  n = pOp->p5;
83133  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
83134  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
83135  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
83136  pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
83137  if( pCtx==0 ) goto no_mem;
83138  pCtx->pMem = 0;
83139  pCtx->pFunc = pOp->p4.pFunc;
83140  pCtx->iOp = (int)(pOp - aOp);
83141  pCtx->pVdbe = p;
83142  pCtx->argc = n;
83143  pOp->p4type = P4_FUNCCTX;
83144  pOp->p4.pCtx = pCtx;
83145  pOp->opcode = OP_AggStep;
83146  /* Fall through into OP_AggStep */
83147}
83148case OP_AggStep: {
83149  int i;
83150  sqlite3_context *pCtx;
83151  Mem *pMem;
83152  Mem t;
83153
83154  assert( pOp->p4type==P4_FUNCCTX );
83155  pCtx = pOp->p4.pCtx;
83156  pMem = &aMem[pOp->p3];
83157
83158  /* If this function is inside of a trigger, the register array in aMem[]
83159  ** might change from one evaluation to the next.  The next block of code
83160  ** checks to see if the register array has changed, and if so it
83161  ** reinitializes the relavant parts of the sqlite3_context object */
83162  if( pCtx->pMem != pMem ){
83163    pCtx->pMem = pMem;
83164    for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
83165  }
83166
83167#ifdef SQLITE_DEBUG
83168  for(i=0; i<pCtx->argc; i++){
83169    assert( memIsValid(pCtx->argv[i]) );
83170    REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
83171  }
83172#endif
83173
83174  pMem->n++;
83175  sqlite3VdbeMemInit(&t, db, MEM_Null);
83176  pCtx->pOut = &t;
83177  pCtx->fErrorOrAux = 0;
83178  pCtx->skipFlag = 0;
83179  (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
83180  if( pCtx->fErrorOrAux ){
83181    if( pCtx->isError ){
83182      sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
83183      rc = pCtx->isError;
83184    }
83185    sqlite3VdbeMemRelease(&t);
83186    if( rc ) goto abort_due_to_error;
83187  }else{
83188    assert( t.flags==MEM_Null );
83189  }
83190  if( pCtx->skipFlag ){
83191    assert( pOp[-1].opcode==OP_CollSeq );
83192    i = pOp[-1].p1;
83193    if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
83194  }
83195  break;
83196}
83197
83198/* Opcode: AggFinal P1 P2 * P4 *
83199** Synopsis: accum=r[P1] N=P2
83200**
83201** Execute the finalizer function for an aggregate.  P1 is
83202** the memory location that is the accumulator for the aggregate.
83203**
83204** P2 is the number of arguments that the step function takes and
83205** P4 is a pointer to the FuncDef for this function.  The P2
83206** argument is not used by this opcode.  It is only there to disambiguate
83207** functions that can take varying numbers of arguments.  The
83208** P4 argument is only needed for the degenerate case where
83209** the step function was not previously called.
83210*/
83211case OP_AggFinal: {
83212  Mem *pMem;
83213  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
83214  pMem = &aMem[pOp->p1];
83215  assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
83216  rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
83217  if( rc ){
83218    sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
83219    goto abort_due_to_error;
83220  }
83221  sqlite3VdbeChangeEncoding(pMem, encoding);
83222  UPDATE_MAX_BLOBSIZE(pMem);
83223  if( sqlite3VdbeMemTooBig(pMem) ){
83224    goto too_big;
83225  }
83226  break;
83227}
83228
83229#ifndef SQLITE_OMIT_WAL
83230/* Opcode: Checkpoint P1 P2 P3 * *
83231**
83232** Checkpoint database P1. This is a no-op if P1 is not currently in
83233** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
83234** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns
83235** SQLITE_BUSY or not, respectively.  Write the number of pages in the
83236** WAL after the checkpoint into mem[P3+1] and the number of pages
83237** in the WAL that have been checkpointed after the checkpoint
83238** completes into mem[P3+2].  However on an error, mem[P3+1] and
83239** mem[P3+2] are initialized to -1.
83240*/
83241case OP_Checkpoint: {
83242  int i;                          /* Loop counter */
83243  int aRes[3];                    /* Results */
83244  Mem *pMem;                      /* Write results here */
83245
83246  assert( p->readOnly==0 );
83247  aRes[0] = 0;
83248  aRes[1] = aRes[2] = -1;
83249  assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
83250       || pOp->p2==SQLITE_CHECKPOINT_FULL
83251       || pOp->p2==SQLITE_CHECKPOINT_RESTART
83252       || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
83253  );
83254  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
83255  if( rc ){
83256    if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
83257    rc = SQLITE_OK;
83258    aRes[0] = 1;
83259  }
83260  for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
83261    sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
83262  }
83263  break;
83264};
83265#endif
83266
83267#ifndef SQLITE_OMIT_PRAGMA
83268/* Opcode: JournalMode P1 P2 P3 * *
83269**
83270** Change the journal mode of database P1 to P3. P3 must be one of the
83271** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
83272** modes (delete, truncate, persist, off and memory), this is a simple
83273** operation. No IO is required.
83274**
83275** If changing into or out of WAL mode the procedure is more complicated.
83276**
83277** Write a string containing the final journal-mode to register P2.
83278*/
83279case OP_JournalMode: {    /* out2 */
83280  Btree *pBt;                     /* Btree to change journal mode of */
83281  Pager *pPager;                  /* Pager associated with pBt */
83282  int eNew;                       /* New journal mode */
83283  int eOld;                       /* The old journal mode */
83284#ifndef SQLITE_OMIT_WAL
83285  const char *zFilename;          /* Name of database file for pPager */
83286#endif
83287
83288  pOut = out2Prerelease(p, pOp);
83289  eNew = pOp->p3;
83290  assert( eNew==PAGER_JOURNALMODE_DELETE
83291       || eNew==PAGER_JOURNALMODE_TRUNCATE
83292       || eNew==PAGER_JOURNALMODE_PERSIST
83293       || eNew==PAGER_JOURNALMODE_OFF
83294       || eNew==PAGER_JOURNALMODE_MEMORY
83295       || eNew==PAGER_JOURNALMODE_WAL
83296       || eNew==PAGER_JOURNALMODE_QUERY
83297  );
83298  assert( pOp->p1>=0 && pOp->p1<db->nDb );
83299  assert( p->readOnly==0 );
83300
83301  pBt = db->aDb[pOp->p1].pBt;
83302  pPager = sqlite3BtreePager(pBt);
83303  eOld = sqlite3PagerGetJournalMode(pPager);
83304  if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
83305  if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
83306
83307#ifndef SQLITE_OMIT_WAL
83308  zFilename = sqlite3PagerFilename(pPager, 1);
83309
83310  /* Do not allow a transition to journal_mode=WAL for a database
83311  ** in temporary storage or if the VFS does not support shared memory
83312  */
83313  if( eNew==PAGER_JOURNALMODE_WAL
83314   && (sqlite3Strlen30(zFilename)==0           /* Temp file */
83315       || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
83316  ){
83317    eNew = eOld;
83318  }
83319
83320  if( (eNew!=eOld)
83321   && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
83322  ){
83323    if( !db->autoCommit || db->nVdbeRead>1 ){
83324      rc = SQLITE_ERROR;
83325      sqlite3VdbeError(p,
83326          "cannot change %s wal mode from within a transaction",
83327          (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
83328      );
83329      goto abort_due_to_error;
83330    }else{
83331
83332      if( eOld==PAGER_JOURNALMODE_WAL ){
83333        /* If leaving WAL mode, close the log file. If successful, the call
83334        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
83335        ** file. An EXCLUSIVE lock may still be held on the database file
83336        ** after a successful return.
83337        */
83338        rc = sqlite3PagerCloseWal(pPager);
83339        if( rc==SQLITE_OK ){
83340          sqlite3PagerSetJournalMode(pPager, eNew);
83341        }
83342      }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
83343        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
83344        ** as an intermediate */
83345        sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
83346      }
83347
83348      /* Open a transaction on the database file. Regardless of the journal
83349      ** mode, this transaction always uses a rollback journal.
83350      */
83351      assert( sqlite3BtreeIsInTrans(pBt)==0 );
83352      if( rc==SQLITE_OK ){
83353        rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
83354      }
83355    }
83356  }
83357#endif /* ifndef SQLITE_OMIT_WAL */
83358
83359  if( rc ) eNew = eOld;
83360  eNew = sqlite3PagerSetJournalMode(pPager, eNew);
83361
83362  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
83363  pOut->z = (char *)sqlite3JournalModename(eNew);
83364  pOut->n = sqlite3Strlen30(pOut->z);
83365  pOut->enc = SQLITE_UTF8;
83366  sqlite3VdbeChangeEncoding(pOut, encoding);
83367  if( rc ) goto abort_due_to_error;
83368  break;
83369};
83370#endif /* SQLITE_OMIT_PRAGMA */
83371
83372#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
83373/* Opcode: Vacuum * * * * *
83374**
83375** Vacuum the entire database.  This opcode will cause other virtual
83376** machines to be created and run.  It may not be called from within
83377** a transaction.
83378*/
83379case OP_Vacuum: {
83380  assert( p->readOnly==0 );
83381  rc = sqlite3RunVacuum(&p->zErrMsg, db);
83382  if( rc ) goto abort_due_to_error;
83383  break;
83384}
83385#endif
83386
83387#if !defined(SQLITE_OMIT_AUTOVACUUM)
83388/* Opcode: IncrVacuum P1 P2 * * *
83389**
83390** Perform a single step of the incremental vacuum procedure on
83391** the P1 database. If the vacuum has finished, jump to instruction
83392** P2. Otherwise, fall through to the next instruction.
83393*/
83394case OP_IncrVacuum: {        /* jump */
83395  Btree *pBt;
83396
83397  assert( pOp->p1>=0 && pOp->p1<db->nDb );
83398  assert( DbMaskTest(p->btreeMask, pOp->p1) );
83399  assert( p->readOnly==0 );
83400  pBt = db->aDb[pOp->p1].pBt;
83401  rc = sqlite3BtreeIncrVacuum(pBt);
83402  VdbeBranchTaken(rc==SQLITE_DONE,2);
83403  if( rc ){
83404    if( rc!=SQLITE_DONE ) goto abort_due_to_error;
83405    rc = SQLITE_OK;
83406    goto jump_to_p2;
83407  }
83408  break;
83409}
83410#endif
83411
83412/* Opcode: Expire P1 * * * *
83413**
83414** Cause precompiled statements to expire.  When an expired statement
83415** is executed using sqlite3_step() it will either automatically
83416** reprepare itself (if it was originally created using sqlite3_prepare_v2())
83417** or it will fail with SQLITE_SCHEMA.
83418**
83419** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
83420** then only the currently executing statement is expired.
83421*/
83422case OP_Expire: {
83423  if( !pOp->p1 ){
83424    sqlite3ExpirePreparedStatements(db);
83425  }else{
83426    p->expired = 1;
83427  }
83428  break;
83429}
83430
83431#ifndef SQLITE_OMIT_SHARED_CACHE
83432/* Opcode: TableLock P1 P2 P3 P4 *
83433** Synopsis: iDb=P1 root=P2 write=P3
83434**
83435** Obtain a lock on a particular table. This instruction is only used when
83436** the shared-cache feature is enabled.
83437**
83438** P1 is the index of the database in sqlite3.aDb[] of the database
83439** on which the lock is acquired.  A readlock is obtained if P3==0 or
83440** a write lock if P3==1.
83441**
83442** P2 contains the root-page of the table to lock.
83443**
83444** P4 contains a pointer to the name of the table being locked. This is only
83445** used to generate an error message if the lock cannot be obtained.
83446*/
83447case OP_TableLock: {
83448  u8 isWriteLock = (u8)pOp->p3;
83449  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
83450    int p1 = pOp->p1;
83451    assert( p1>=0 && p1<db->nDb );
83452    assert( DbMaskTest(p->btreeMask, p1) );
83453    assert( isWriteLock==0 || isWriteLock==1 );
83454    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
83455    if( rc ){
83456      if( (rc&0xFF)==SQLITE_LOCKED ){
83457        const char *z = pOp->p4.z;
83458        sqlite3VdbeError(p, "database table is locked: %s", z);
83459      }
83460      goto abort_due_to_error;
83461    }
83462  }
83463  break;
83464}
83465#endif /* SQLITE_OMIT_SHARED_CACHE */
83466
83467#ifndef SQLITE_OMIT_VIRTUALTABLE
83468/* Opcode: VBegin * * * P4 *
83469**
83470** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
83471** xBegin method for that table.
83472**
83473** Also, whether or not P4 is set, check that this is not being called from
83474** within a callback to a virtual table xSync() method. If it is, the error
83475** code will be set to SQLITE_LOCKED.
83476*/
83477case OP_VBegin: {
83478  VTable *pVTab;
83479  pVTab = pOp->p4.pVtab;
83480  rc = sqlite3VtabBegin(db, pVTab);
83481  if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
83482  if( rc ) goto abort_due_to_error;
83483  break;
83484}
83485#endif /* SQLITE_OMIT_VIRTUALTABLE */
83486
83487#ifndef SQLITE_OMIT_VIRTUALTABLE
83488/* Opcode: VCreate P1 P2 * * *
83489**
83490** P2 is a register that holds the name of a virtual table in database
83491** P1. Call the xCreate method for that table.
83492*/
83493case OP_VCreate: {
83494  Mem sMem;          /* For storing the record being decoded */
83495  const char *zTab;  /* Name of the virtual table */
83496
83497  memset(&sMem, 0, sizeof(sMem));
83498  sMem.db = db;
83499  /* Because P2 is always a static string, it is impossible for the
83500  ** sqlite3VdbeMemCopy() to fail */
83501  assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
83502  assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
83503  rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
83504  assert( rc==SQLITE_OK );
83505  zTab = (const char*)sqlite3_value_text(&sMem);
83506  assert( zTab || db->mallocFailed );
83507  if( zTab ){
83508    rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
83509  }
83510  sqlite3VdbeMemRelease(&sMem);
83511  if( rc ) goto abort_due_to_error;
83512  break;
83513}
83514#endif /* SQLITE_OMIT_VIRTUALTABLE */
83515
83516#ifndef SQLITE_OMIT_VIRTUALTABLE
83517/* Opcode: VDestroy P1 * * P4 *
83518**
83519** P4 is the name of a virtual table in database P1.  Call the xDestroy method
83520** of that table.
83521*/
83522case OP_VDestroy: {
83523  db->nVDestroy++;
83524  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
83525  db->nVDestroy--;
83526  if( rc ) goto abort_due_to_error;
83527  break;
83528}
83529#endif /* SQLITE_OMIT_VIRTUALTABLE */
83530
83531#ifndef SQLITE_OMIT_VIRTUALTABLE
83532/* Opcode: VOpen P1 * * P4 *
83533**
83534** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
83535** P1 is a cursor number.  This opcode opens a cursor to the virtual
83536** table and stores that cursor in P1.
83537*/
83538case OP_VOpen: {
83539  VdbeCursor *pCur;
83540  sqlite3_vtab_cursor *pVCur;
83541  sqlite3_vtab *pVtab;
83542  const sqlite3_module *pModule;
83543
83544  assert( p->bIsReader );
83545  pCur = 0;
83546  pVCur = 0;
83547  pVtab = pOp->p4.pVtab->pVtab;
83548  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
83549    rc = SQLITE_LOCKED;
83550    goto abort_due_to_error;
83551  }
83552  pModule = pVtab->pModule;
83553  rc = pModule->xOpen(pVtab, &pVCur);
83554  sqlite3VtabImportErrmsg(p, pVtab);
83555  if( rc ) goto abort_due_to_error;
83556
83557  /* Initialize sqlite3_vtab_cursor base class */
83558  pVCur->pVtab = pVtab;
83559
83560  /* Initialize vdbe cursor object */
83561  pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
83562  if( pCur ){
83563    pCur->uc.pVCur = pVCur;
83564    pVtab->nRef++;
83565  }else{
83566    assert( db->mallocFailed );
83567    pModule->xClose(pVCur);
83568    goto no_mem;
83569  }
83570  break;
83571}
83572#endif /* SQLITE_OMIT_VIRTUALTABLE */
83573
83574#ifndef SQLITE_OMIT_VIRTUALTABLE
83575/* Opcode: VFilter P1 P2 P3 P4 *
83576** Synopsis: iplan=r[P3] zplan='P4'
83577**
83578** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
83579** the filtered result set is empty.
83580**
83581** P4 is either NULL or a string that was generated by the xBestIndex
83582** method of the module.  The interpretation of the P4 string is left
83583** to the module implementation.
83584**
83585** This opcode invokes the xFilter method on the virtual table specified
83586** by P1.  The integer query plan parameter to xFilter is stored in register
83587** P3. Register P3+1 stores the argc parameter to be passed to the
83588** xFilter method. Registers P3+2..P3+1+argc are the argc
83589** additional parameters which are passed to
83590** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
83591**
83592** A jump is made to P2 if the result set after filtering would be empty.
83593*/
83594case OP_VFilter: {   /* jump */
83595  int nArg;
83596  int iQuery;
83597  const sqlite3_module *pModule;
83598  Mem *pQuery;
83599  Mem *pArgc;
83600  sqlite3_vtab_cursor *pVCur;
83601  sqlite3_vtab *pVtab;
83602  VdbeCursor *pCur;
83603  int res;
83604  int i;
83605  Mem **apArg;
83606
83607  pQuery = &aMem[pOp->p3];
83608  pArgc = &pQuery[1];
83609  pCur = p->apCsr[pOp->p1];
83610  assert( memIsValid(pQuery) );
83611  REGISTER_TRACE(pOp->p3, pQuery);
83612  assert( pCur->eCurType==CURTYPE_VTAB );
83613  pVCur = pCur->uc.pVCur;
83614  pVtab = pVCur->pVtab;
83615  pModule = pVtab->pModule;
83616
83617  /* Grab the index number and argc parameters */
83618  assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
83619  nArg = (int)pArgc->u.i;
83620  iQuery = (int)pQuery->u.i;
83621
83622  /* Invoke the xFilter method */
83623  res = 0;
83624  apArg = p->apArg;
83625  for(i = 0; i<nArg; i++){
83626    apArg[i] = &pArgc[i+1];
83627  }
83628  rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
83629  sqlite3VtabImportErrmsg(p, pVtab);
83630  if( rc ) goto abort_due_to_error;
83631  res = pModule->xEof(pVCur);
83632  pCur->nullRow = 0;
83633  VdbeBranchTaken(res!=0,2);
83634  if( res ) goto jump_to_p2;
83635  break;
83636}
83637#endif /* SQLITE_OMIT_VIRTUALTABLE */
83638
83639#ifndef SQLITE_OMIT_VIRTUALTABLE
83640/* Opcode: VColumn P1 P2 P3 * *
83641** Synopsis: r[P3]=vcolumn(P2)
83642**
83643** Store the value of the P2-th column of
83644** the row of the virtual-table that the
83645** P1 cursor is pointing to into register P3.
83646*/
83647case OP_VColumn: {
83648  sqlite3_vtab *pVtab;
83649  const sqlite3_module *pModule;
83650  Mem *pDest;
83651  sqlite3_context sContext;
83652
83653  VdbeCursor *pCur = p->apCsr[pOp->p1];
83654  assert( pCur->eCurType==CURTYPE_VTAB );
83655  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
83656  pDest = &aMem[pOp->p3];
83657  memAboutToChange(p, pDest);
83658  if( pCur->nullRow ){
83659    sqlite3VdbeMemSetNull(pDest);
83660    break;
83661  }
83662  pVtab = pCur->uc.pVCur->pVtab;
83663  pModule = pVtab->pModule;
83664  assert( pModule->xColumn );
83665  memset(&sContext, 0, sizeof(sContext));
83666  sContext.pOut = pDest;
83667  MemSetTypeFlag(pDest, MEM_Null);
83668  rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
83669  sqlite3VtabImportErrmsg(p, pVtab);
83670  if( sContext.isError ){
83671    rc = sContext.isError;
83672  }
83673  sqlite3VdbeChangeEncoding(pDest, encoding);
83674  REGISTER_TRACE(pOp->p3, pDest);
83675  UPDATE_MAX_BLOBSIZE(pDest);
83676
83677  if( sqlite3VdbeMemTooBig(pDest) ){
83678    goto too_big;
83679  }
83680  if( rc ) goto abort_due_to_error;
83681  break;
83682}
83683#endif /* SQLITE_OMIT_VIRTUALTABLE */
83684
83685#ifndef SQLITE_OMIT_VIRTUALTABLE
83686/* Opcode: VNext P1 P2 * * *
83687**
83688** Advance virtual table P1 to the next row in its result set and
83689** jump to instruction P2.  Or, if the virtual table has reached
83690** the end of its result set, then fall through to the next instruction.
83691*/
83692case OP_VNext: {   /* jump */
83693  sqlite3_vtab *pVtab;
83694  const sqlite3_module *pModule;
83695  int res;
83696  VdbeCursor *pCur;
83697
83698  res = 0;
83699  pCur = p->apCsr[pOp->p1];
83700  assert( pCur->eCurType==CURTYPE_VTAB );
83701  if( pCur->nullRow ){
83702    break;
83703  }
83704  pVtab = pCur->uc.pVCur->pVtab;
83705  pModule = pVtab->pModule;
83706  assert( pModule->xNext );
83707
83708  /* Invoke the xNext() method of the module. There is no way for the
83709  ** underlying implementation to return an error if one occurs during
83710  ** xNext(). Instead, if an error occurs, true is returned (indicating that
83711  ** data is available) and the error code returned when xColumn or
83712  ** some other method is next invoked on the save virtual table cursor.
83713  */
83714  rc = pModule->xNext(pCur->uc.pVCur);
83715  sqlite3VtabImportErrmsg(p, pVtab);
83716  if( rc ) goto abort_due_to_error;
83717  res = pModule->xEof(pCur->uc.pVCur);
83718  VdbeBranchTaken(!res,2);
83719  if( !res ){
83720    /* If there is data, jump to P2 */
83721    goto jump_to_p2_and_check_for_interrupt;
83722  }
83723  goto check_for_interrupt;
83724}
83725#endif /* SQLITE_OMIT_VIRTUALTABLE */
83726
83727#ifndef SQLITE_OMIT_VIRTUALTABLE
83728/* Opcode: VRename P1 * * P4 *
83729**
83730** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
83731** This opcode invokes the corresponding xRename method. The value
83732** in register P1 is passed as the zName argument to the xRename method.
83733*/
83734case OP_VRename: {
83735  sqlite3_vtab *pVtab;
83736  Mem *pName;
83737
83738  pVtab = pOp->p4.pVtab->pVtab;
83739  pName = &aMem[pOp->p1];
83740  assert( pVtab->pModule->xRename );
83741  assert( memIsValid(pName) );
83742  assert( p->readOnly==0 );
83743  REGISTER_TRACE(pOp->p1, pName);
83744  assert( pName->flags & MEM_Str );
83745  testcase( pName->enc==SQLITE_UTF8 );
83746  testcase( pName->enc==SQLITE_UTF16BE );
83747  testcase( pName->enc==SQLITE_UTF16LE );
83748  rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
83749  if( rc ) goto abort_due_to_error;
83750  rc = pVtab->pModule->xRename(pVtab, pName->z);
83751  sqlite3VtabImportErrmsg(p, pVtab);
83752  p->expired = 0;
83753  if( rc ) goto abort_due_to_error;
83754  break;
83755}
83756#endif
83757
83758#ifndef SQLITE_OMIT_VIRTUALTABLE
83759/* Opcode: VUpdate P1 P2 P3 P4 P5
83760** Synopsis: data=r[P3@P2]
83761**
83762** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
83763** This opcode invokes the corresponding xUpdate method. P2 values
83764** are contiguous memory cells starting at P3 to pass to the xUpdate
83765** invocation. The value in register (P3+P2-1) corresponds to the
83766** p2th element of the argv array passed to xUpdate.
83767**
83768** The xUpdate method will do a DELETE or an INSERT or both.
83769** The argv[0] element (which corresponds to memory cell P3)
83770** is the rowid of a row to delete.  If argv[0] is NULL then no
83771** deletion occurs.  The argv[1] element is the rowid of the new
83772** row.  This can be NULL to have the virtual table select the new
83773** rowid for itself.  The subsequent elements in the array are
83774** the values of columns in the new row.
83775**
83776** If P2==1 then no insert is performed.  argv[0] is the rowid of
83777** a row to delete.
83778**
83779** P1 is a boolean flag. If it is set to true and the xUpdate call
83780** is successful, then the value returned by sqlite3_last_insert_rowid()
83781** is set to the value of the rowid for the row just inserted.
83782**
83783** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
83784** apply in the case of a constraint failure on an insert or update.
83785*/
83786case OP_VUpdate: {
83787  sqlite3_vtab *pVtab;
83788  const sqlite3_module *pModule;
83789  int nArg;
83790  int i;
83791  sqlite_int64 rowid;
83792  Mem **apArg;
83793  Mem *pX;
83794
83795  assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
83796       || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
83797  );
83798  assert( p->readOnly==0 );
83799  pVtab = pOp->p4.pVtab->pVtab;
83800  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
83801    rc = SQLITE_LOCKED;
83802    goto abort_due_to_error;
83803  }
83804  pModule = pVtab->pModule;
83805  nArg = pOp->p2;
83806  assert( pOp->p4type==P4_VTAB );
83807  if( ALWAYS(pModule->xUpdate) ){
83808    u8 vtabOnConflict = db->vtabOnConflict;
83809    apArg = p->apArg;
83810    pX = &aMem[pOp->p3];
83811    for(i=0; i<nArg; i++){
83812      assert( memIsValid(pX) );
83813      memAboutToChange(p, pX);
83814      apArg[i] = pX;
83815      pX++;
83816    }
83817    db->vtabOnConflict = pOp->p5;
83818    rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
83819    db->vtabOnConflict = vtabOnConflict;
83820    sqlite3VtabImportErrmsg(p, pVtab);
83821    if( rc==SQLITE_OK && pOp->p1 ){
83822      assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
83823      db->lastRowid = lastRowid = rowid;
83824    }
83825    if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
83826      if( pOp->p5==OE_Ignore ){
83827        rc = SQLITE_OK;
83828      }else{
83829        p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
83830      }
83831    }else{
83832      p->nChange++;
83833    }
83834    if( rc ) goto abort_due_to_error;
83835  }
83836  break;
83837}
83838#endif /* SQLITE_OMIT_VIRTUALTABLE */
83839
83840#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
83841/* Opcode: Pagecount P1 P2 * * *
83842**
83843** Write the current number of pages in database P1 to memory cell P2.
83844*/
83845case OP_Pagecount: {            /* out2 */
83846  pOut = out2Prerelease(p, pOp);
83847  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
83848  break;
83849}
83850#endif
83851
83852
83853#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
83854/* Opcode: MaxPgcnt P1 P2 P3 * *
83855**
83856** Try to set the maximum page count for database P1 to the value in P3.
83857** Do not let the maximum page count fall below the current page count and
83858** do not change the maximum page count value if P3==0.
83859**
83860** Store the maximum page count after the change in register P2.
83861*/
83862case OP_MaxPgcnt: {            /* out2 */
83863  unsigned int newMax;
83864  Btree *pBt;
83865
83866  pOut = out2Prerelease(p, pOp);
83867  pBt = db->aDb[pOp->p1].pBt;
83868  newMax = 0;
83869  if( pOp->p3 ){
83870    newMax = sqlite3BtreeLastPage(pBt);
83871    if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
83872  }
83873  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
83874  break;
83875}
83876#endif
83877
83878
83879/* Opcode: Init * P2 * P4 *
83880** Synopsis:  Start at P2
83881**
83882** Programs contain a single instance of this opcode as the very first
83883** opcode.
83884**
83885** If tracing is enabled (by the sqlite3_trace()) interface, then
83886** the UTF-8 string contained in P4 is emitted on the trace callback.
83887** Or if P4 is blank, use the string returned by sqlite3_sql().
83888**
83889** If P2 is not zero, jump to instruction P2.
83890*/
83891case OP_Init: {          /* jump */
83892  char *zTrace;
83893
83894  /* If the P4 argument is not NULL, then it must be an SQL comment string.
83895  ** The "--" string is broken up to prevent false-positives with srcck1.c.
83896  **
83897  ** This assert() provides evidence for:
83898  ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
83899  ** would have been returned by the legacy sqlite3_trace() interface by
83900  ** using the X argument when X begins with "--" and invoking
83901  ** sqlite3_expanded_sql(P) otherwise.
83902  */
83903  assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
83904
83905#ifndef SQLITE_OMIT_TRACE
83906  if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
83907   && !p->doingRerun
83908   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
83909  ){
83910#ifndef SQLITE_OMIT_DEPRECATED
83911    if( db->mTrace & SQLITE_TRACE_LEGACY ){
83912      void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
83913      char *z = sqlite3VdbeExpandSql(p, zTrace);
83914      x(db->pTraceArg, z);
83915      sqlite3_free(z);
83916    }else
83917#endif
83918    {
83919      (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
83920    }
83921  }
83922#ifdef SQLITE_USE_FCNTL_TRACE
83923  zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
83924  if( zTrace ){
83925    int i;
83926    for(i=0; i<db->nDb; i++){
83927      if( DbMaskTest(p->btreeMask, i)==0 ) continue;
83928      sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
83929    }
83930  }
83931#endif /* SQLITE_USE_FCNTL_TRACE */
83932#ifdef SQLITE_DEBUG
83933  if( (db->flags & SQLITE_SqlTrace)!=0
83934   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
83935  ){
83936    sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
83937  }
83938#endif /* SQLITE_DEBUG */
83939#endif /* SQLITE_OMIT_TRACE */
83940  if( pOp->p2 ) goto jump_to_p2;
83941  break;
83942}
83943
83944#ifdef SQLITE_ENABLE_CURSOR_HINTS
83945/* Opcode: CursorHint P1 * * P4 *
83946**
83947** Provide a hint to cursor P1 that it only needs to return rows that
83948** satisfy the Expr in P4.  TK_REGISTER terms in the P4 expression refer
83949** to values currently held in registers.  TK_COLUMN terms in the P4
83950** expression refer to columns in the b-tree to which cursor P1 is pointing.
83951*/
83952case OP_CursorHint: {
83953  VdbeCursor *pC;
83954
83955  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83956  assert( pOp->p4type==P4_EXPR );
83957  pC = p->apCsr[pOp->p1];
83958  if( pC ){
83959    assert( pC->eCurType==CURTYPE_BTREE );
83960    sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
83961                           pOp->p4.pExpr, aMem);
83962  }
83963  break;
83964}
83965#endif /* SQLITE_ENABLE_CURSOR_HINTS */
83966
83967/* Opcode: Noop * * * * *
83968**
83969** Do nothing.  This instruction is often useful as a jump
83970** destination.
83971*/
83972/*
83973** The magic Explain opcode are only inserted when explain==2 (which
83974** is to say when the EXPLAIN QUERY PLAN syntax is used.)
83975** This opcode records information from the optimizer.  It is the
83976** the same as a no-op.  This opcodesnever appears in a real VM program.
83977*/
83978default: {          /* This is really OP_Noop and OP_Explain */
83979  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
83980  break;
83981}
83982
83983/*****************************************************************************
83984** The cases of the switch statement above this line should all be indented
83985** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
83986** readability.  From this point on down, the normal indentation rules are
83987** restored.
83988*****************************************************************************/
83989    }
83990
83991#ifdef VDBE_PROFILE
83992    {
83993      u64 endTime = sqlite3Hwtime();
83994      if( endTime>start ) pOrigOp->cycles += endTime - start;
83995      pOrigOp->cnt++;
83996    }
83997#endif
83998
83999    /* The following code adds nothing to the actual functionality
84000    ** of the program.  It is only here for testing and debugging.
84001    ** On the other hand, it does burn CPU cycles every time through
84002    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
84003    */
84004#ifndef NDEBUG
84005    assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
84006
84007#ifdef SQLITE_DEBUG
84008    if( db->flags & SQLITE_VdbeTrace ){
84009      u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
84010      if( rc!=0 ) printf("rc=%d\n",rc);
84011      if( opProperty & (OPFLG_OUT2) ){
84012        registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
84013      }
84014      if( opProperty & OPFLG_OUT3 ){
84015        registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
84016      }
84017    }
84018#endif  /* SQLITE_DEBUG */
84019#endif  /* NDEBUG */
84020  }  /* The end of the for(;;) loop the loops through opcodes */
84021
84022  /* If we reach this point, it means that execution is finished with
84023  ** an error of some kind.
84024  */
84025abort_due_to_error:
84026  if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
84027  assert( rc );
84028  if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
84029    sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
84030  }
84031  p->rc = rc;
84032  sqlite3SystemError(db, rc);
84033  testcase( sqlite3GlobalConfig.xLog!=0 );
84034  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
84035                   (int)(pOp - aOp), p->zSql, p->zErrMsg);
84036  sqlite3VdbeHalt(p);
84037  if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
84038  rc = SQLITE_ERROR;
84039  if( resetSchemaOnFault>0 ){
84040    sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
84041  }
84042
84043  /* This is the only way out of this procedure.  We have to
84044  ** release the mutexes on btrees that were acquired at the
84045  ** top. */
84046vdbe_return:
84047  db->lastRowid = lastRowid;
84048  testcase( nVmStep>0 );
84049  p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
84050  sqlite3VdbeLeave(p);
84051  assert( rc!=SQLITE_OK || nExtraDelete==0
84052       || sqlite3_strlike("DELETE%",p->zSql,0)!=0
84053  );
84054  return rc;
84055
84056  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
84057  ** is encountered.
84058  */
84059too_big:
84060  sqlite3VdbeError(p, "string or blob too big");
84061  rc = SQLITE_TOOBIG;
84062  goto abort_due_to_error;
84063
84064  /* Jump to here if a malloc() fails.
84065  */
84066no_mem:
84067  sqlite3OomFault(db);
84068  sqlite3VdbeError(p, "out of memory");
84069  rc = SQLITE_NOMEM_BKPT;
84070  goto abort_due_to_error;
84071
84072  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
84073  ** flag.
84074  */
84075abort_due_to_interrupt:
84076  assert( db->u1.isInterrupted );
84077  rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
84078  p->rc = rc;
84079  sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
84080  goto abort_due_to_error;
84081}
84082
84083
84084/************** End of vdbe.c ************************************************/
84085/************** Begin file vdbeblob.c ****************************************/
84086/*
84087** 2007 May 1
84088**
84089** The author disclaims copyright to this source code.  In place of
84090** a legal notice, here is a blessing:
84091**
84092**    May you do good and not evil.
84093**    May you find forgiveness for yourself and forgive others.
84094**    May you share freely, never taking more than you give.
84095**
84096*************************************************************************
84097**
84098** This file contains code used to implement incremental BLOB I/O.
84099*/
84100
84101/* #include "sqliteInt.h" */
84102/* #include "vdbeInt.h" */
84103
84104#ifndef SQLITE_OMIT_INCRBLOB
84105
84106/*
84107** Valid sqlite3_blob* handles point to Incrblob structures.
84108*/
84109typedef struct Incrblob Incrblob;
84110struct Incrblob {
84111  int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
84112  int nByte;              /* Size of open blob, in bytes */
84113  int iOffset;            /* Byte offset of blob in cursor data */
84114  int iCol;               /* Table column this handle is open on */
84115  BtCursor *pCsr;         /* Cursor pointing at blob row */
84116  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
84117  sqlite3 *db;            /* The associated database */
84118  char *zDb;              /* Database name */
84119  Table *pTab;            /* Table object */
84120};
84121
84122
84123/*
84124** This function is used by both blob_open() and blob_reopen(). It seeks
84125** the b-tree cursor associated with blob handle p to point to row iRow.
84126** If successful, SQLITE_OK is returned and subsequent calls to
84127** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
84128**
84129** If an error occurs, or if the specified row does not exist or does not
84130** contain a value of type TEXT or BLOB in the column nominated when the
84131** blob handle was opened, then an error code is returned and *pzErr may
84132** be set to point to a buffer containing an error message. It is the
84133** responsibility of the caller to free the error message buffer using
84134** sqlite3DbFree().
84135**
84136** If an error does occur, then the b-tree cursor is closed. All subsequent
84137** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
84138** immediately return SQLITE_ABORT.
84139*/
84140static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
84141  int rc;                         /* Error code */
84142  char *zErr = 0;                 /* Error message */
84143  Vdbe *v = (Vdbe *)p->pStmt;
84144
84145  /* Set the value of the SQL statements only variable to integer iRow.
84146  ** This is done directly instead of using sqlite3_bind_int64() to avoid
84147  ** triggering asserts related to mutexes.
84148  */
84149  assert( v->aVar[0].flags&MEM_Int );
84150  v->aVar[0].u.i = iRow;
84151
84152  rc = sqlite3_step(p->pStmt);
84153  if( rc==SQLITE_ROW ){
84154    VdbeCursor *pC = v->apCsr[0];
84155    u32 type = pC->aType[p->iCol];
84156    if( type<12 ){
84157      zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
84158          type==0?"null": type==7?"real": "integer"
84159      );
84160      rc = SQLITE_ERROR;
84161      sqlite3_finalize(p->pStmt);
84162      p->pStmt = 0;
84163    }else{
84164      p->iOffset = pC->aType[p->iCol + pC->nField];
84165      p->nByte = sqlite3VdbeSerialTypeLen(type);
84166      p->pCsr =  pC->uc.pCursor;
84167      sqlite3BtreeIncrblobCursor(p->pCsr);
84168    }
84169  }
84170
84171  if( rc==SQLITE_ROW ){
84172    rc = SQLITE_OK;
84173  }else if( p->pStmt ){
84174    rc = sqlite3_finalize(p->pStmt);
84175    p->pStmt = 0;
84176    if( rc==SQLITE_OK ){
84177      zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
84178      rc = SQLITE_ERROR;
84179    }else{
84180      zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
84181    }
84182  }
84183
84184  assert( rc!=SQLITE_OK || zErr==0 );
84185  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
84186
84187  *pzErr = zErr;
84188  return rc;
84189}
84190
84191/*
84192** Open a blob handle.
84193*/
84194SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
84195  sqlite3* db,            /* The database connection */
84196  const char *zDb,        /* The attached database containing the blob */
84197  const char *zTable,     /* The table containing the blob */
84198  const char *zColumn,    /* The column containing the blob */
84199  sqlite_int64 iRow,      /* The row containing the glob */
84200  int flags,              /* True -> read/write access, false -> read-only */
84201  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
84202){
84203  int nAttempt = 0;
84204  int iCol;               /* Index of zColumn in row-record */
84205  int rc = SQLITE_OK;
84206  char *zErr = 0;
84207  Table *pTab;
84208  Parse *pParse = 0;
84209  Incrblob *pBlob = 0;
84210
84211#ifdef SQLITE_ENABLE_API_ARMOR
84212  if( ppBlob==0 ){
84213    return SQLITE_MISUSE_BKPT;
84214  }
84215#endif
84216  *ppBlob = 0;
84217#ifdef SQLITE_ENABLE_API_ARMOR
84218  if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
84219    return SQLITE_MISUSE_BKPT;
84220  }
84221#endif
84222  flags = !!flags;                /* flags = (flags ? 1 : 0); */
84223
84224  sqlite3_mutex_enter(db->mutex);
84225
84226  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
84227  if( !pBlob ) goto blob_open_out;
84228  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
84229  if( !pParse ) goto blob_open_out;
84230
84231  do {
84232    memset(pParse, 0, sizeof(Parse));
84233    pParse->db = db;
84234    sqlite3DbFree(db, zErr);
84235    zErr = 0;
84236
84237    sqlite3BtreeEnterAll(db);
84238    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
84239    if( pTab && IsVirtual(pTab) ){
84240      pTab = 0;
84241      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
84242    }
84243    if( pTab && !HasRowid(pTab) ){
84244      pTab = 0;
84245      sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
84246    }
84247#ifndef SQLITE_OMIT_VIEW
84248    if( pTab && pTab->pSelect ){
84249      pTab = 0;
84250      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
84251    }
84252#endif
84253    if( !pTab ){
84254      if( pParse->zErrMsg ){
84255        sqlite3DbFree(db, zErr);
84256        zErr = pParse->zErrMsg;
84257        pParse->zErrMsg = 0;
84258      }
84259      rc = SQLITE_ERROR;
84260      sqlite3BtreeLeaveAll(db);
84261      goto blob_open_out;
84262    }
84263    pBlob->pTab = pTab;
84264    pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zName;
84265
84266    /* Now search pTab for the exact column. */
84267    for(iCol=0; iCol<pTab->nCol; iCol++) {
84268      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
84269        break;
84270      }
84271    }
84272    if( iCol==pTab->nCol ){
84273      sqlite3DbFree(db, zErr);
84274      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
84275      rc = SQLITE_ERROR;
84276      sqlite3BtreeLeaveAll(db);
84277      goto blob_open_out;
84278    }
84279
84280    /* If the value is being opened for writing, check that the
84281    ** column is not indexed, and that it is not part of a foreign key.
84282    ** It is against the rules to open a column to which either of these
84283    ** descriptions applies for writing.  */
84284    if( flags ){
84285      const char *zFault = 0;
84286      Index *pIdx;
84287#ifndef SQLITE_OMIT_FOREIGN_KEY
84288      if( db->flags&SQLITE_ForeignKeys ){
84289        /* Check that the column is not part of an FK child key definition. It
84290        ** is not necessary to check if it is part of a parent key, as parent
84291        ** key columns must be indexed. The check below will pick up this
84292        ** case.  */
84293        FKey *pFKey;
84294        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
84295          int j;
84296          for(j=0; j<pFKey->nCol; j++){
84297            if( pFKey->aCol[j].iFrom==iCol ){
84298              zFault = "foreign key";
84299            }
84300          }
84301        }
84302      }
84303#endif
84304      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84305        int j;
84306        for(j=0; j<pIdx->nKeyCol; j++){
84307          /* FIXME: Be smarter about indexes that use expressions */
84308          if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
84309            zFault = "indexed";
84310          }
84311        }
84312      }
84313      if( zFault ){
84314        sqlite3DbFree(db, zErr);
84315        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
84316        rc = SQLITE_ERROR;
84317        sqlite3BtreeLeaveAll(db);
84318        goto blob_open_out;
84319      }
84320    }
84321
84322    pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
84323    assert( pBlob->pStmt || db->mallocFailed );
84324    if( pBlob->pStmt ){
84325
84326      /* This VDBE program seeks a btree cursor to the identified
84327      ** db/table/row entry. The reason for using a vdbe program instead
84328      ** of writing code to use the b-tree layer directly is that the
84329      ** vdbe program will take advantage of the various transaction,
84330      ** locking and error handling infrastructure built into the vdbe.
84331      **
84332      ** After seeking the cursor, the vdbe executes an OP_ResultRow.
84333      ** Code external to the Vdbe then "borrows" the b-tree cursor and
84334      ** uses it to implement the blob_read(), blob_write() and
84335      ** blob_bytes() functions.
84336      **
84337      ** The sqlite3_blob_close() function finalizes the vdbe program,
84338      ** which closes the b-tree cursor and (possibly) commits the
84339      ** transaction.
84340      */
84341      static const int iLn = VDBE_OFFSET_LINENO(2);
84342      static const VdbeOpList openBlob[] = {
84343        {OP_TableLock,      0, 0, 0},  /* 0: Acquire a read or write lock */
84344        {OP_OpenRead,       0, 0, 0},  /* 1: Open a cursor */
84345        {OP_Variable,       1, 1, 0},  /* 2: Move ?1 into reg[1] */
84346        {OP_NotExists,      0, 7, 1},  /* 3: Seek the cursor */
84347        {OP_Column,         0, 0, 1},  /* 4  */
84348        {OP_ResultRow,      1, 0, 0},  /* 5  */
84349        {OP_Goto,           0, 2, 0},  /* 6  */
84350        {OP_Close,          0, 0, 0},  /* 7  */
84351        {OP_Halt,           0, 0, 0},  /* 8  */
84352      };
84353      Vdbe *v = (Vdbe *)pBlob->pStmt;
84354      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84355      VdbeOp *aOp;
84356
84357      sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
84358                           pTab->pSchema->schema_cookie,
84359                           pTab->pSchema->iGeneration);
84360      sqlite3VdbeChangeP5(v, 1);
84361      aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
84362
84363      /* Make sure a mutex is held on the table to be accessed */
84364      sqlite3VdbeUsesBtree(v, iDb);
84365
84366      if( db->mallocFailed==0 ){
84367        assert( aOp!=0 );
84368        /* Configure the OP_TableLock instruction */
84369#ifdef SQLITE_OMIT_SHARED_CACHE
84370        aOp[0].opcode = OP_Noop;
84371#else
84372        aOp[0].p1 = iDb;
84373        aOp[0].p2 = pTab->tnum;
84374        aOp[0].p3 = flags;
84375        sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
84376      }
84377      if( db->mallocFailed==0 ){
84378#endif
84379
84380        /* Remove either the OP_OpenWrite or OpenRead. Set the P2
84381        ** parameter of the other to pTab->tnum.  */
84382        if( flags ) aOp[1].opcode = OP_OpenWrite;
84383        aOp[1].p2 = pTab->tnum;
84384        aOp[1].p3 = iDb;
84385
84386        /* Configure the number of columns. Configure the cursor to
84387        ** think that the table has one more column than it really
84388        ** does. An OP_Column to retrieve this imaginary column will
84389        ** always return an SQL NULL. This is useful because it means
84390        ** we can invoke OP_Column to fill in the vdbe cursors type
84391        ** and offset cache without causing any IO.
84392        */
84393        aOp[1].p4type = P4_INT32;
84394        aOp[1].p4.i = pTab->nCol+1;
84395        aOp[4].p2 = pTab->nCol;
84396
84397        pParse->nVar = 1;
84398        pParse->nMem = 1;
84399        pParse->nTab = 1;
84400        sqlite3VdbeMakeReady(v, pParse);
84401      }
84402    }
84403
84404    pBlob->flags = flags;
84405    pBlob->iCol = iCol;
84406    pBlob->db = db;
84407    sqlite3BtreeLeaveAll(db);
84408    if( db->mallocFailed ){
84409      goto blob_open_out;
84410    }
84411    sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
84412    rc = blobSeekToRow(pBlob, iRow, &zErr);
84413  } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
84414
84415blob_open_out:
84416  if( rc==SQLITE_OK && db->mallocFailed==0 ){
84417    *ppBlob = (sqlite3_blob *)pBlob;
84418  }else{
84419    if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
84420    sqlite3DbFree(db, pBlob);
84421  }
84422  sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
84423  sqlite3DbFree(db, zErr);
84424  sqlite3ParserReset(pParse);
84425  sqlite3StackFree(db, pParse);
84426  rc = sqlite3ApiExit(db, rc);
84427  sqlite3_mutex_leave(db->mutex);
84428  return rc;
84429}
84430
84431/*
84432** Close a blob handle that was previously created using
84433** sqlite3_blob_open().
84434*/
84435SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *pBlob){
84436  Incrblob *p = (Incrblob *)pBlob;
84437  int rc;
84438  sqlite3 *db;
84439
84440  if( p ){
84441    db = p->db;
84442    sqlite3_mutex_enter(db->mutex);
84443    rc = sqlite3_finalize(p->pStmt);
84444    sqlite3DbFree(db, p);
84445    sqlite3_mutex_leave(db->mutex);
84446  }else{
84447    rc = SQLITE_OK;
84448  }
84449  return rc;
84450}
84451
84452/*
84453** Perform a read or write operation on a blob
84454*/
84455static int blobReadWrite(
84456  sqlite3_blob *pBlob,
84457  void *z,
84458  int n,
84459  int iOffset,
84460  int (*xCall)(BtCursor*, u32, u32, void*)
84461){
84462  int rc;
84463  Incrblob *p = (Incrblob *)pBlob;
84464  Vdbe *v;
84465  sqlite3 *db;
84466
84467  if( p==0 ) return SQLITE_MISUSE_BKPT;
84468  db = p->db;
84469  sqlite3_mutex_enter(db->mutex);
84470  v = (Vdbe*)p->pStmt;
84471
84472  if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
84473    /* Request is out of range. Return a transient error. */
84474    rc = SQLITE_ERROR;
84475  }else if( v==0 ){
84476    /* If there is no statement handle, then the blob-handle has
84477    ** already been invalidated. Return SQLITE_ABORT in this case.
84478    */
84479    rc = SQLITE_ABORT;
84480  }else{
84481    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
84482    ** returned, clean-up the statement handle.
84483    */
84484    assert( db == v->db );
84485    sqlite3BtreeEnterCursor(p->pCsr);
84486
84487#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
84488    if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
84489      /* If a pre-update hook is registered and this is a write cursor,
84490      ** invoke it here.
84491      **
84492      ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
84493      ** operation should really be an SQLITE_UPDATE. This is probably
84494      ** incorrect, but is convenient because at this point the new.* values
84495      ** are not easily obtainable. And for the sessions module, an
84496      ** SQLITE_UPDATE where the PK columns do not change is handled in the
84497      ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
84498      ** slightly more efficient). Since you cannot write to a PK column
84499      ** using the incremental-blob API, this works. For the sessions module
84500      ** anyhow.
84501      */
84502      sqlite3_int64 iKey;
84503      iKey = sqlite3BtreeIntegerKey(p->pCsr);
84504      sqlite3VdbePreUpdateHook(
84505          v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
84506      );
84507    }
84508#endif
84509
84510    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
84511    sqlite3BtreeLeaveCursor(p->pCsr);
84512    if( rc==SQLITE_ABORT ){
84513      sqlite3VdbeFinalize(v);
84514      p->pStmt = 0;
84515    }else{
84516      v->rc = rc;
84517    }
84518  }
84519  sqlite3Error(db, rc);
84520  rc = sqlite3ApiExit(db, rc);
84521  sqlite3_mutex_leave(db->mutex);
84522  return rc;
84523}
84524
84525/*
84526** Read data from a blob handle.
84527*/
84528SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
84529  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
84530}
84531
84532/*
84533** Write data to a blob handle.
84534*/
84535SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
84536  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
84537}
84538
84539/*
84540** Query a blob handle for the size of the data.
84541**
84542** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
84543** so no mutex is required for access.
84544*/
84545SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *pBlob){
84546  Incrblob *p = (Incrblob *)pBlob;
84547  return (p && p->pStmt) ? p->nByte : 0;
84548}
84549
84550/*
84551** Move an existing blob handle to point to a different row of the same
84552** database table.
84553**
84554** If an error occurs, or if the specified row does not exist or does not
84555** contain a blob or text value, then an error code is returned and the
84556** database handle error code and message set. If this happens, then all
84557** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
84558** immediately return SQLITE_ABORT.
84559*/
84560SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
84561  int rc;
84562  Incrblob *p = (Incrblob *)pBlob;
84563  sqlite3 *db;
84564
84565  if( p==0 ) return SQLITE_MISUSE_BKPT;
84566  db = p->db;
84567  sqlite3_mutex_enter(db->mutex);
84568
84569  if( p->pStmt==0 ){
84570    /* If there is no statement handle, then the blob-handle has
84571    ** already been invalidated. Return SQLITE_ABORT in this case.
84572    */
84573    rc = SQLITE_ABORT;
84574  }else{
84575    char *zErr;
84576    rc = blobSeekToRow(p, iRow, &zErr);
84577    if( rc!=SQLITE_OK ){
84578      sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
84579      sqlite3DbFree(db, zErr);
84580    }
84581    assert( rc!=SQLITE_SCHEMA );
84582  }
84583
84584  rc = sqlite3ApiExit(db, rc);
84585  assert( rc==SQLITE_OK || p->pStmt==0 );
84586  sqlite3_mutex_leave(db->mutex);
84587  return rc;
84588}
84589
84590#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
84591
84592/************** End of vdbeblob.c ********************************************/
84593/************** Begin file vdbesort.c ****************************************/
84594/*
84595** 2011-07-09
84596**
84597** The author disclaims copyright to this source code.  In place of
84598** a legal notice, here is a blessing:
84599**
84600**    May you do good and not evil.
84601**    May you find forgiveness for yourself and forgive others.
84602**    May you share freely, never taking more than you give.
84603**
84604*************************************************************************
84605** This file contains code for the VdbeSorter object, used in concert with
84606** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
84607** or by SELECT statements with ORDER BY clauses that cannot be satisfied
84608** using indexes and without LIMIT clauses.
84609**
84610** The VdbeSorter object implements a multi-threaded external merge sort
84611** algorithm that is efficient even if the number of elements being sorted
84612** exceeds the available memory.
84613**
84614** Here is the (internal, non-API) interface between this module and the
84615** rest of the SQLite system:
84616**
84617**    sqlite3VdbeSorterInit()       Create a new VdbeSorter object.
84618**
84619**    sqlite3VdbeSorterWrite()      Add a single new row to the VdbeSorter
84620**                                  object.  The row is a binary blob in the
84621**                                  OP_MakeRecord format that contains both
84622**                                  the ORDER BY key columns and result columns
84623**                                  in the case of a SELECT w/ ORDER BY, or
84624**                                  the complete record for an index entry
84625**                                  in the case of a CREATE INDEX.
84626**
84627**    sqlite3VdbeSorterRewind()     Sort all content previously added.
84628**                                  Position the read cursor on the
84629**                                  first sorted element.
84630**
84631**    sqlite3VdbeSorterNext()       Advance the read cursor to the next sorted
84632**                                  element.
84633**
84634**    sqlite3VdbeSorterRowkey()     Return the complete binary blob for the
84635**                                  row currently under the read cursor.
84636**
84637**    sqlite3VdbeSorterCompare()    Compare the binary blob for the row
84638**                                  currently under the read cursor against
84639**                                  another binary blob X and report if
84640**                                  X is strictly less than the read cursor.
84641**                                  Used to enforce uniqueness in a
84642**                                  CREATE UNIQUE INDEX statement.
84643**
84644**    sqlite3VdbeSorterClose()      Close the VdbeSorter object and reclaim
84645**                                  all resources.
84646**
84647**    sqlite3VdbeSorterReset()      Refurbish the VdbeSorter for reuse.  This
84648**                                  is like Close() followed by Init() only
84649**                                  much faster.
84650**
84651** The interfaces above must be called in a particular order.  Write() can
84652** only occur in between Init()/Reset() and Rewind().  Next(), Rowkey(), and
84653** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
84654**
84655**   Init()
84656**   for each record: Write()
84657**   Rewind()
84658**     Rowkey()/Compare()
84659**   Next()
84660**   Close()
84661**
84662** Algorithm:
84663**
84664** Records passed to the sorter via calls to Write() are initially held
84665** unsorted in main memory. Assuming the amount of memory used never exceeds
84666** a threshold, when Rewind() is called the set of records is sorted using
84667** an in-memory merge sort. In this case, no temporary files are required
84668** and subsequent calls to Rowkey(), Next() and Compare() read records
84669** directly from main memory.
84670**
84671** If the amount of space used to store records in main memory exceeds the
84672** threshold, then the set of records currently in memory are sorted and
84673** written to a temporary file in "Packed Memory Array" (PMA) format.
84674** A PMA created at this point is known as a "level-0 PMA". Higher levels
84675** of PMAs may be created by merging existing PMAs together - for example
84676** merging two or more level-0 PMAs together creates a level-1 PMA.
84677**
84678** The threshold for the amount of main memory to use before flushing
84679** records to a PMA is roughly the same as the limit configured for the
84680** page-cache of the main database. Specifically, the threshold is set to
84681** the value returned by "PRAGMA main.page_size" multipled by
84682** that returned by "PRAGMA main.cache_size", in bytes.
84683**
84684** If the sorter is running in single-threaded mode, then all PMAs generated
84685** are appended to a single temporary file. Or, if the sorter is running in
84686** multi-threaded mode then up to (N+1) temporary files may be opened, where
84687** N is the configured number of worker threads. In this case, instead of
84688** sorting the records and writing the PMA to a temporary file itself, the
84689** calling thread usually launches a worker thread to do so. Except, if
84690** there are already N worker threads running, the main thread does the work
84691** itself.
84692**
84693** The sorter is running in multi-threaded mode if (a) the library was built
84694** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
84695** than zero, and (b) worker threads have been enabled at runtime by calling
84696** "PRAGMA threads=N" with some value of N greater than 0.
84697**
84698** When Rewind() is called, any data remaining in memory is flushed to a
84699** final PMA. So at this point the data is stored in some number of sorted
84700** PMAs within temporary files on disk.
84701**
84702** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
84703** sorter is running in single-threaded mode, then these PMAs are merged
84704** incrementally as keys are retreived from the sorter by the VDBE.  The
84705** MergeEngine object, described in further detail below, performs this
84706** merge.
84707**
84708** Or, if running in multi-threaded mode, then a background thread is
84709** launched to merge the existing PMAs. Once the background thread has
84710** merged T bytes of data into a single sorted PMA, the main thread
84711** begins reading keys from that PMA while the background thread proceeds
84712** with merging the next T bytes of data. And so on.
84713**
84714** Parameter T is set to half the value of the memory threshold used
84715** by Write() above to determine when to create a new PMA.
84716**
84717** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
84718** Rewind() is called, then a hierarchy of incremental-merges is used.
84719** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
84720** disk are merged together. Then T bytes of data from the second set, and
84721** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
84722** PMAs at a time. This done is to improve locality.
84723**
84724** If running in multi-threaded mode and there are more than
84725** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
84726** than one background thread may be created. Specifically, there may be
84727** one background thread for each temporary file on disk, and one background
84728** thread to merge the output of each of the others to a single PMA for
84729** the main thread to read from.
84730*/
84731/* #include "sqliteInt.h" */
84732/* #include "vdbeInt.h" */
84733
84734/*
84735** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
84736** messages to stderr that may be helpful in understanding the performance
84737** characteristics of the sorter in multi-threaded mode.
84738*/
84739#if 0
84740# define SQLITE_DEBUG_SORTER_THREADS 1
84741#endif
84742
84743/*
84744** Hard-coded maximum amount of data to accumulate in memory before flushing
84745** to a level 0 PMA. The purpose of this limit is to prevent various integer
84746** overflows. 512MiB.
84747*/
84748#define SQLITE_MAX_PMASZ    (1<<29)
84749
84750/*
84751** Private objects used by the sorter
84752*/
84753typedef struct MergeEngine MergeEngine;     /* Merge PMAs together */
84754typedef struct PmaReader PmaReader;         /* Incrementally read one PMA */
84755typedef struct PmaWriter PmaWriter;         /* Incrementally write one PMA */
84756typedef struct SorterRecord SorterRecord;   /* A record being sorted */
84757typedef struct SortSubtask SortSubtask;     /* A sub-task in the sort process */
84758typedef struct SorterFile SorterFile;       /* Temporary file object wrapper */
84759typedef struct SorterList SorterList;       /* In-memory list of records */
84760typedef struct IncrMerger IncrMerger;       /* Read & merge multiple PMAs */
84761
84762/*
84763** A container for a temp file handle and the current amount of data
84764** stored in the file.
84765*/
84766struct SorterFile {
84767  sqlite3_file *pFd;              /* File handle */
84768  i64 iEof;                       /* Bytes of data stored in pFd */
84769};
84770
84771/*
84772** An in-memory list of objects to be sorted.
84773**
84774** If aMemory==0 then each object is allocated separately and the objects
84775** are connected using SorterRecord.u.pNext.  If aMemory!=0 then all objects
84776** are stored in the aMemory[] bulk memory, one right after the other, and
84777** are connected using SorterRecord.u.iNext.
84778*/
84779struct SorterList {
84780  SorterRecord *pList;            /* Linked list of records */
84781  u8 *aMemory;                    /* If non-NULL, bulk memory to hold pList */
84782  int szPMA;                      /* Size of pList as PMA in bytes */
84783};
84784
84785/*
84786** The MergeEngine object is used to combine two or more smaller PMAs into
84787** one big PMA using a merge operation.  Separate PMAs all need to be
84788** combined into one big PMA in order to be able to step through the sorted
84789** records in order.
84790**
84791** The aReadr[] array contains a PmaReader object for each of the PMAs being
84792** merged.  An aReadr[] object either points to a valid key or else is at EOF.
84793** ("EOF" means "End Of File".  When aReadr[] is at EOF there is no more data.)
84794** For the purposes of the paragraphs below, we assume that the array is
84795** actually N elements in size, where N is the smallest power of 2 greater
84796** to or equal to the number of PMAs being merged. The extra aReadr[] elements
84797** are treated as if they are empty (always at EOF).
84798**
84799** The aTree[] array is also N elements in size. The value of N is stored in
84800** the MergeEngine.nTree variable.
84801**
84802** The final (N/2) elements of aTree[] contain the results of comparing
84803** pairs of PMA keys together. Element i contains the result of
84804** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
84805** aTree element is set to the index of it.
84806**
84807** For the purposes of this comparison, EOF is considered greater than any
84808** other key value. If the keys are equal (only possible with two EOF
84809** values), it doesn't matter which index is stored.
84810**
84811** The (N/4) elements of aTree[] that precede the final (N/2) described
84812** above contains the index of the smallest of each block of 4 PmaReaders
84813** And so on. So that aTree[1] contains the index of the PmaReader that
84814** currently points to the smallest key value. aTree[0] is unused.
84815**
84816** Example:
84817**
84818**     aReadr[0] -> Banana
84819**     aReadr[1] -> Feijoa
84820**     aReadr[2] -> Elderberry
84821**     aReadr[3] -> Currant
84822**     aReadr[4] -> Grapefruit
84823**     aReadr[5] -> Apple
84824**     aReadr[6] -> Durian
84825**     aReadr[7] -> EOF
84826**
84827**     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
84828**
84829** The current element is "Apple" (the value of the key indicated by
84830** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
84831** be advanced to the next key in its segment. Say the next key is
84832** "Eggplant":
84833**
84834**     aReadr[5] -> Eggplant
84835**
84836** The contents of aTree[] are updated first by comparing the new PmaReader
84837** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
84838** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
84839** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
84840** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
84841** so the value written into element 1 of the array is 0. As follows:
84842**
84843**     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
84844**
84845** In other words, each time we advance to the next sorter element, log2(N)
84846** key comparison operations are required, where N is the number of segments
84847** being merged (rounded up to the next power of 2).
84848*/
84849struct MergeEngine {
84850  int nTree;                 /* Used size of aTree/aReadr (power of 2) */
84851  SortSubtask *pTask;        /* Used by this thread only */
84852  int *aTree;                /* Current state of incremental merge */
84853  PmaReader *aReadr;         /* Array of PmaReaders to merge data from */
84854};
84855
84856/*
84857** This object represents a single thread of control in a sort operation.
84858** Exactly VdbeSorter.nTask instances of this object are allocated
84859** as part of each VdbeSorter object. Instances are never allocated any
84860** other way. VdbeSorter.nTask is set to the number of worker threads allowed
84861** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread).  Thus for
84862** single-threaded operation, there is exactly one instance of this object
84863** and for multi-threaded operation there are two or more instances.
84864**
84865** Essentially, this structure contains all those fields of the VdbeSorter
84866** structure for which each thread requires a separate instance. For example,
84867** each thread requries its own UnpackedRecord object to unpack records in
84868** as part of comparison operations.
84869**
84870** Before a background thread is launched, variable bDone is set to 0. Then,
84871** right before it exits, the thread itself sets bDone to 1. This is used for
84872** two purposes:
84873**
84874**   1. When flushing the contents of memory to a level-0 PMA on disk, to
84875**      attempt to select a SortSubtask for which there is not already an
84876**      active background thread (since doing so causes the main thread
84877**      to block until it finishes).
84878**
84879**   2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
84880**      to sqlite3ThreadJoin() is likely to block. Cases that are likely to
84881**      block provoke debugging output.
84882**
84883** In both cases, the effects of the main thread seeing (bDone==0) even
84884** after the thread has finished are not dire. So we don't worry about
84885** memory barriers and such here.
84886*/
84887typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
84888struct SortSubtask {
84889  SQLiteThread *pThread;          /* Background thread, if any */
84890  int bDone;                      /* Set if thread is finished but not joined */
84891  VdbeSorter *pSorter;            /* Sorter that owns this sub-task */
84892  UnpackedRecord *pUnpacked;      /* Space to unpack a record */
84893  SorterList list;                /* List for thread to write to a PMA */
84894  int nPMA;                       /* Number of PMAs currently in file */
84895  SorterCompare xCompare;         /* Compare function to use */
84896  SorterFile file;                /* Temp file for level-0 PMAs */
84897  SorterFile file2;               /* Space for other PMAs */
84898};
84899
84900
84901/*
84902** Main sorter structure. A single instance of this is allocated for each
84903** sorter cursor created by the VDBE.
84904**
84905** mxKeysize:
84906**   As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
84907**   this variable is updated so as to be set to the size on disk of the
84908**   largest record in the sorter.
84909*/
84910struct VdbeSorter {
84911  int mnPmaSize;                  /* Minimum PMA size, in bytes */
84912  int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
84913  int mxKeysize;                  /* Largest serialized key seen so far */
84914  int pgsz;                       /* Main database page size */
84915  PmaReader *pReader;             /* Readr data from here after Rewind() */
84916  MergeEngine *pMerger;           /* Or here, if bUseThreads==0 */
84917  sqlite3 *db;                    /* Database connection */
84918  KeyInfo *pKeyInfo;              /* How to compare records */
84919  UnpackedRecord *pUnpacked;      /* Used by VdbeSorterCompare() */
84920  SorterList list;                /* List of in-memory records */
84921  int iMemory;                    /* Offset of free space in list.aMemory */
84922  int nMemory;                    /* Size of list.aMemory allocation in bytes */
84923  u8 bUsePMA;                     /* True if one or more PMAs created */
84924  u8 bUseThreads;                 /* True to use background threads */
84925  u8 iPrev;                       /* Previous thread used to flush PMA */
84926  u8 nTask;                       /* Size of aTask[] array */
84927  u8 typeMask;
84928  SortSubtask aTask[1];           /* One or more subtasks */
84929};
84930
84931#define SORTER_TYPE_INTEGER 0x01
84932#define SORTER_TYPE_TEXT    0x02
84933
84934/*
84935** An instance of the following object is used to read records out of a
84936** PMA, in sorted order.  The next key to be read is cached in nKey/aKey.
84937** aKey might point into aMap or into aBuffer.  If neither of those locations
84938** contain a contiguous representation of the key, then aAlloc is allocated
84939** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
84940**
84941** pFd==0 at EOF.
84942*/
84943struct PmaReader {
84944  i64 iReadOff;               /* Current read offset */
84945  i64 iEof;                   /* 1 byte past EOF for this PmaReader */
84946  int nAlloc;                 /* Bytes of space at aAlloc */
84947  int nKey;                   /* Number of bytes in key */
84948  sqlite3_file *pFd;          /* File handle we are reading from */
84949  u8 *aAlloc;                 /* Space for aKey if aBuffer and pMap wont work */
84950  u8 *aKey;                   /* Pointer to current key */
84951  u8 *aBuffer;                /* Current read buffer */
84952  int nBuffer;                /* Size of read buffer in bytes */
84953  u8 *aMap;                   /* Pointer to mapping of entire file */
84954  IncrMerger *pIncr;          /* Incremental merger */
84955};
84956
84957/*
84958** Normally, a PmaReader object iterates through an existing PMA stored
84959** within a temp file. However, if the PmaReader.pIncr variable points to
84960** an object of the following type, it may be used to iterate/merge through
84961** multiple PMAs simultaneously.
84962**
84963** There are two types of IncrMerger object - single (bUseThread==0) and
84964** multi-threaded (bUseThread==1).
84965**
84966** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
84967** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
84968** size. When the IncrMerger is initialized, it reads enough data from
84969** pMerger to populate aFile[0]. It then sets variables within the
84970** corresponding PmaReader object to read from that file and kicks off
84971** a background thread to populate aFile[1] with the next mxSz bytes of
84972** sorted record data from pMerger.
84973**
84974** When the PmaReader reaches the end of aFile[0], it blocks until the
84975** background thread has finished populating aFile[1]. It then exchanges
84976** the contents of the aFile[0] and aFile[1] variables within this structure,
84977** sets the PmaReader fields to read from the new aFile[0] and kicks off
84978** another background thread to populate the new aFile[1]. And so on, until
84979** the contents of pMerger are exhausted.
84980**
84981** A single-threaded IncrMerger does not open any temporary files of its
84982** own. Instead, it has exclusive access to mxSz bytes of space beginning
84983** at offset iStartOff of file pTask->file2. And instead of using a
84984** background thread to prepare data for the PmaReader, with a single
84985** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
84986** keys from pMerger by the calling thread whenever the PmaReader runs out
84987** of data.
84988*/
84989struct IncrMerger {
84990  SortSubtask *pTask;             /* Task that owns this merger */
84991  MergeEngine *pMerger;           /* Merge engine thread reads data from */
84992  i64 iStartOff;                  /* Offset to start writing file at */
84993  int mxSz;                       /* Maximum bytes of data to store */
84994  int bEof;                       /* Set to true when merge is finished */
84995  int bUseThread;                 /* True to use a bg thread for this object */
84996  SorterFile aFile[2];            /* aFile[0] for reading, [1] for writing */
84997};
84998
84999/*
85000** An instance of this object is used for writing a PMA.
85001**
85002** The PMA is written one record at a time.  Each record is of an arbitrary
85003** size.  But I/O is more efficient if it occurs in page-sized blocks where
85004** each block is aligned on a page boundary.  This object caches writes to
85005** the PMA so that aligned, page-size blocks are written.
85006*/
85007struct PmaWriter {
85008  int eFWErr;                     /* Non-zero if in an error state */
85009  u8 *aBuffer;                    /* Pointer to write buffer */
85010  int nBuffer;                    /* Size of write buffer in bytes */
85011  int iBufStart;                  /* First byte of buffer to write */
85012  int iBufEnd;                    /* Last byte of buffer to write */
85013  i64 iWriteOff;                  /* Offset of start of buffer in file */
85014  sqlite3_file *pFd;              /* File handle to write to */
85015};
85016
85017/*
85018** This object is the header on a single record while that record is being
85019** held in memory and prior to being written out as part of a PMA.
85020**
85021** How the linked list is connected depends on how memory is being managed
85022** by this module. If using a separate allocation for each in-memory record
85023** (VdbeSorter.list.aMemory==0), then the list is always connected using the
85024** SorterRecord.u.pNext pointers.
85025**
85026** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
85027** then while records are being accumulated the list is linked using the
85028** SorterRecord.u.iNext offset. This is because the aMemory[] array may
85029** be sqlite3Realloc()ed while records are being accumulated. Once the VM
85030** has finished passing records to the sorter, or when the in-memory buffer
85031** is full, the list is sorted. As part of the sorting process, it is
85032** converted to use the SorterRecord.u.pNext pointers. See function
85033** vdbeSorterSort() for details.
85034*/
85035struct SorterRecord {
85036  int nVal;                       /* Size of the record in bytes */
85037  union {
85038    SorterRecord *pNext;          /* Pointer to next record in list */
85039    int iNext;                    /* Offset within aMemory of next record */
85040  } u;
85041  /* The data for the record immediately follows this header */
85042};
85043
85044/* Return a pointer to the buffer containing the record data for SorterRecord
85045** object p. Should be used as if:
85046**
85047**   void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
85048*/
85049#define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
85050
85051
85052/* Maximum number of PMAs that a single MergeEngine can merge */
85053#define SORTER_MAX_MERGE_COUNT 16
85054
85055static int vdbeIncrSwap(IncrMerger*);
85056static void vdbeIncrFree(IncrMerger *);
85057
85058/*
85059** Free all memory belonging to the PmaReader object passed as the
85060** argument. All structure fields are set to zero before returning.
85061*/
85062static void vdbePmaReaderClear(PmaReader *pReadr){
85063  sqlite3_free(pReadr->aAlloc);
85064  sqlite3_free(pReadr->aBuffer);
85065  if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
85066  vdbeIncrFree(pReadr->pIncr);
85067  memset(pReadr, 0, sizeof(PmaReader));
85068}
85069
85070/*
85071** Read the next nByte bytes of data from the PMA p.
85072** If successful, set *ppOut to point to a buffer containing the data
85073** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
85074** error code.
85075**
85076** The buffer returned in *ppOut is only valid until the
85077** next call to this function.
85078*/
85079static int vdbePmaReadBlob(
85080  PmaReader *p,                   /* PmaReader from which to take the blob */
85081  int nByte,                      /* Bytes of data to read */
85082  u8 **ppOut                      /* OUT: Pointer to buffer containing data */
85083){
85084  int iBuf;                       /* Offset within buffer to read from */
85085  int nAvail;                     /* Bytes of data available in buffer */
85086
85087  if( p->aMap ){
85088    *ppOut = &p->aMap[p->iReadOff];
85089    p->iReadOff += nByte;
85090    return SQLITE_OK;
85091  }
85092
85093  assert( p->aBuffer );
85094
85095  /* If there is no more data to be read from the buffer, read the next
85096  ** p->nBuffer bytes of data from the file into it. Or, if there are less
85097  ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
85098  iBuf = p->iReadOff % p->nBuffer;
85099  if( iBuf==0 ){
85100    int nRead;                    /* Bytes to read from disk */
85101    int rc;                       /* sqlite3OsRead() return code */
85102
85103    /* Determine how many bytes of data to read. */
85104    if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
85105      nRead = p->nBuffer;
85106    }else{
85107      nRead = (int)(p->iEof - p->iReadOff);
85108    }
85109    assert( nRead>0 );
85110
85111    /* Readr data from the file. Return early if an error occurs. */
85112    rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
85113    assert( rc!=SQLITE_IOERR_SHORT_READ );
85114    if( rc!=SQLITE_OK ) return rc;
85115  }
85116  nAvail = p->nBuffer - iBuf;
85117
85118  if( nByte<=nAvail ){
85119    /* The requested data is available in the in-memory buffer. In this
85120    ** case there is no need to make a copy of the data, just return a
85121    ** pointer into the buffer to the caller.  */
85122    *ppOut = &p->aBuffer[iBuf];
85123    p->iReadOff += nByte;
85124  }else{
85125    /* The requested data is not all available in the in-memory buffer.
85126    ** In this case, allocate space at p->aAlloc[] to copy the requested
85127    ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
85128    int nRem;                     /* Bytes remaining to copy */
85129
85130    /* Extend the p->aAlloc[] allocation if required. */
85131    if( p->nAlloc<nByte ){
85132      u8 *aNew;
85133      int nNew = MAX(128, p->nAlloc*2);
85134      while( nByte>nNew ) nNew = nNew*2;
85135      aNew = sqlite3Realloc(p->aAlloc, nNew);
85136      if( !aNew ) return SQLITE_NOMEM_BKPT;
85137      p->nAlloc = nNew;
85138      p->aAlloc = aNew;
85139    }
85140
85141    /* Copy as much data as is available in the buffer into the start of
85142    ** p->aAlloc[].  */
85143    memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
85144    p->iReadOff += nAvail;
85145    nRem = nByte - nAvail;
85146
85147    /* The following loop copies up to p->nBuffer bytes per iteration into
85148    ** the p->aAlloc[] buffer.  */
85149    while( nRem>0 ){
85150      int rc;                     /* vdbePmaReadBlob() return code */
85151      int nCopy;                  /* Number of bytes to copy */
85152      u8 *aNext;                  /* Pointer to buffer to copy data from */
85153
85154      nCopy = nRem;
85155      if( nRem>p->nBuffer ) nCopy = p->nBuffer;
85156      rc = vdbePmaReadBlob(p, nCopy, &aNext);
85157      if( rc!=SQLITE_OK ) return rc;
85158      assert( aNext!=p->aAlloc );
85159      memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
85160      nRem -= nCopy;
85161    }
85162
85163    *ppOut = p->aAlloc;
85164  }
85165
85166  return SQLITE_OK;
85167}
85168
85169/*
85170** Read a varint from the stream of data accessed by p. Set *pnOut to
85171** the value read.
85172*/
85173static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
85174  int iBuf;
85175
85176  if( p->aMap ){
85177    p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
85178  }else{
85179    iBuf = p->iReadOff % p->nBuffer;
85180    if( iBuf && (p->nBuffer-iBuf)>=9 ){
85181      p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
85182    }else{
85183      u8 aVarint[16], *a;
85184      int i = 0, rc;
85185      do{
85186        rc = vdbePmaReadBlob(p, 1, &a);
85187        if( rc ) return rc;
85188        aVarint[(i++)&0xf] = a[0];
85189      }while( (a[0]&0x80)!=0 );
85190      sqlite3GetVarint(aVarint, pnOut);
85191    }
85192  }
85193
85194  return SQLITE_OK;
85195}
85196
85197/*
85198** Attempt to memory map file pFile. If successful, set *pp to point to the
85199** new mapping and return SQLITE_OK. If the mapping is not attempted
85200** (because the file is too large or the VFS layer is configured not to use
85201** mmap), return SQLITE_OK and set *pp to NULL.
85202**
85203** Or, if an error occurs, return an SQLite error code. The final value of
85204** *pp is undefined in this case.
85205*/
85206static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
85207  int rc = SQLITE_OK;
85208  if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
85209    sqlite3_file *pFd = pFile->pFd;
85210    if( pFd->pMethods->iVersion>=3 ){
85211      rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
85212      testcase( rc!=SQLITE_OK );
85213    }
85214  }
85215  return rc;
85216}
85217
85218/*
85219** Attach PmaReader pReadr to file pFile (if it is not already attached to
85220** that file) and seek it to offset iOff within the file.  Return SQLITE_OK
85221** if successful, or an SQLite error code if an error occurs.
85222*/
85223static int vdbePmaReaderSeek(
85224  SortSubtask *pTask,             /* Task context */
85225  PmaReader *pReadr,              /* Reader whose cursor is to be moved */
85226  SorterFile *pFile,              /* Sorter file to read from */
85227  i64 iOff                        /* Offset in pFile */
85228){
85229  int rc = SQLITE_OK;
85230
85231  assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
85232
85233  if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
85234  if( pReadr->aMap ){
85235    sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
85236    pReadr->aMap = 0;
85237  }
85238  pReadr->iReadOff = iOff;
85239  pReadr->iEof = pFile->iEof;
85240  pReadr->pFd = pFile->pFd;
85241
85242  rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
85243  if( rc==SQLITE_OK && pReadr->aMap==0 ){
85244    int pgsz = pTask->pSorter->pgsz;
85245    int iBuf = pReadr->iReadOff % pgsz;
85246    if( pReadr->aBuffer==0 ){
85247      pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
85248      if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
85249      pReadr->nBuffer = pgsz;
85250    }
85251    if( rc==SQLITE_OK && iBuf ){
85252      int nRead = pgsz - iBuf;
85253      if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
85254        nRead = (int)(pReadr->iEof - pReadr->iReadOff);
85255      }
85256      rc = sqlite3OsRead(
85257          pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
85258      );
85259      testcase( rc!=SQLITE_OK );
85260    }
85261  }
85262
85263  return rc;
85264}
85265
85266/*
85267** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
85268** no error occurs, or an SQLite error code if one does.
85269*/
85270static int vdbePmaReaderNext(PmaReader *pReadr){
85271  int rc = SQLITE_OK;             /* Return Code */
85272  u64 nRec = 0;                   /* Size of record in bytes */
85273
85274
85275  if( pReadr->iReadOff>=pReadr->iEof ){
85276    IncrMerger *pIncr = pReadr->pIncr;
85277    int bEof = 1;
85278    if( pIncr ){
85279      rc = vdbeIncrSwap(pIncr);
85280      if( rc==SQLITE_OK && pIncr->bEof==0 ){
85281        rc = vdbePmaReaderSeek(
85282            pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
85283        );
85284        bEof = 0;
85285      }
85286    }
85287
85288    if( bEof ){
85289      /* This is an EOF condition */
85290      vdbePmaReaderClear(pReadr);
85291      testcase( rc!=SQLITE_OK );
85292      return rc;
85293    }
85294  }
85295
85296  if( rc==SQLITE_OK ){
85297    rc = vdbePmaReadVarint(pReadr, &nRec);
85298  }
85299  if( rc==SQLITE_OK ){
85300    pReadr->nKey = (int)nRec;
85301    rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
85302    testcase( rc!=SQLITE_OK );
85303  }
85304
85305  return rc;
85306}
85307
85308/*
85309** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
85310** starting at offset iStart and ending at offset iEof-1. This function
85311** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
85312** PMA is empty).
85313**
85314** If the pnByte parameter is NULL, then it is assumed that the file
85315** contains a single PMA, and that that PMA omits the initial length varint.
85316*/
85317static int vdbePmaReaderInit(
85318  SortSubtask *pTask,             /* Task context */
85319  SorterFile *pFile,              /* Sorter file to read from */
85320  i64 iStart,                     /* Start offset in pFile */
85321  PmaReader *pReadr,              /* PmaReader to populate */
85322  i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
85323){
85324  int rc;
85325
85326  assert( pFile->iEof>iStart );
85327  assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
85328  assert( pReadr->aBuffer==0 );
85329  assert( pReadr->aMap==0 );
85330
85331  rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
85332  if( rc==SQLITE_OK ){
85333    u64 nByte = 0;                 /* Size of PMA in bytes */
85334    rc = vdbePmaReadVarint(pReadr, &nByte);
85335    pReadr->iEof = pReadr->iReadOff + nByte;
85336    *pnByte += nByte;
85337  }
85338
85339  if( rc==SQLITE_OK ){
85340    rc = vdbePmaReaderNext(pReadr);
85341  }
85342  return rc;
85343}
85344
85345/*
85346** A version of vdbeSorterCompare() that assumes that it has already been
85347** determined that the first field of key1 is equal to the first field of
85348** key2.
85349*/
85350static int vdbeSorterCompareTail(
85351  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
85352  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
85353  const void *pKey1, int nKey1,   /* Left side of comparison */
85354  const void *pKey2, int nKey2    /* Right side of comparison */
85355){
85356  UnpackedRecord *r2 = pTask->pUnpacked;
85357  if( *pbKey2Cached==0 ){
85358    sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
85359    *pbKey2Cached = 1;
85360  }
85361  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
85362}
85363
85364/*
85365** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
85366** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
85367** used by the comparison. Return the result of the comparison.
85368**
85369** If IN/OUT parameter *pbKey2Cached is true when this function is called,
85370** it is assumed that (pTask->pUnpacked) contains the unpacked version
85371** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
85372** version of key2 and *pbKey2Cached set to true before returning.
85373**
85374** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
85375** to SQLITE_NOMEM.
85376*/
85377static int vdbeSorterCompare(
85378  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
85379  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
85380  const void *pKey1, int nKey1,   /* Left side of comparison */
85381  const void *pKey2, int nKey2    /* Right side of comparison */
85382){
85383  UnpackedRecord *r2 = pTask->pUnpacked;
85384  if( !*pbKey2Cached ){
85385    sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
85386    *pbKey2Cached = 1;
85387  }
85388  return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
85389}
85390
85391/*
85392** A specially optimized version of vdbeSorterCompare() that assumes that
85393** the first field of each key is a TEXT value and that the collation
85394** sequence to compare them with is BINARY.
85395*/
85396static int vdbeSorterCompareText(
85397  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
85398  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
85399  const void *pKey1, int nKey1,   /* Left side of comparison */
85400  const void *pKey2, int nKey2    /* Right side of comparison */
85401){
85402  const u8 * const p1 = (const u8 * const)pKey1;
85403  const u8 * const p2 = (const u8 * const)pKey2;
85404  const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
85405  const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
85406
85407  int n1;
85408  int n2;
85409  int res;
85410
85411  getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2;
85412  getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2;
85413  res = memcmp(v1, v2, MIN(n1, n2));
85414  if( res==0 ){
85415    res = n1 - n2;
85416  }
85417
85418  if( res==0 ){
85419    if( pTask->pSorter->pKeyInfo->nField>1 ){
85420      res = vdbeSorterCompareTail(
85421          pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
85422      );
85423    }
85424  }else{
85425    if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
85426      res = res * -1;
85427    }
85428  }
85429
85430  return res;
85431}
85432
85433/*
85434** A specially optimized version of vdbeSorterCompare() that assumes that
85435** the first field of each key is an INTEGER value.
85436*/
85437static int vdbeSorterCompareInt(
85438  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
85439  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
85440  const void *pKey1, int nKey1,   /* Left side of comparison */
85441  const void *pKey2, int nKey2    /* Right side of comparison */
85442){
85443  const u8 * const p1 = (const u8 * const)pKey1;
85444  const u8 * const p2 = (const u8 * const)pKey2;
85445  const int s1 = p1[1];                 /* Left hand serial type */
85446  const int s2 = p2[1];                 /* Right hand serial type */
85447  const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
85448  const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
85449  int res;                              /* Return value */
85450
85451  assert( (s1>0 && s1<7) || s1==8 || s1==9 );
85452  assert( (s2>0 && s2<7) || s2==8 || s2==9 );
85453
85454  if( s1>7 && s2>7 ){
85455    res = s1 - s2;
85456  }else{
85457    if( s1==s2 ){
85458      if( (*v1 ^ *v2) & 0x80 ){
85459        /* The two values have different signs */
85460        res = (*v1 & 0x80) ? -1 : +1;
85461      }else{
85462        /* The two values have the same sign. Compare using memcmp(). */
85463        static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 };
85464        int i;
85465        res = 0;
85466        for(i=0; i<aLen[s1]; i++){
85467          if( (res = v1[i] - v2[i]) ) break;
85468        }
85469      }
85470    }else{
85471      if( s2>7 ){
85472        res = +1;
85473      }else if( s1>7 ){
85474        res = -1;
85475      }else{
85476        res = s1 - s2;
85477      }
85478      assert( res!=0 );
85479
85480      if( res>0 ){
85481        if( *v1 & 0x80 ) res = -1;
85482      }else{
85483        if( *v2 & 0x80 ) res = +1;
85484      }
85485    }
85486  }
85487
85488  if( res==0 ){
85489    if( pTask->pSorter->pKeyInfo->nField>1 ){
85490      res = vdbeSorterCompareTail(
85491          pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
85492      );
85493    }
85494  }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
85495    res = res * -1;
85496  }
85497
85498  return res;
85499}
85500
85501/*
85502** Initialize the temporary index cursor just opened as a sorter cursor.
85503**
85504** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
85505** to determine the number of fields that should be compared from the
85506** records being sorted. However, if the value passed as argument nField
85507** is non-zero and the sorter is able to guarantee a stable sort, nField
85508** is used instead. This is used when sorting records for a CREATE INDEX
85509** statement. In this case, keys are always delivered to the sorter in
85510** order of the primary key, which happens to be make up the final part
85511** of the records being sorted. So if the sort is stable, there is never
85512** any reason to compare PK fields and they can be ignored for a small
85513** performance boost.
85514**
85515** The sorter can guarantee a stable sort when running in single-threaded
85516** mode, but not in multi-threaded mode.
85517**
85518** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
85519*/
85520SQLITE_PRIVATE int sqlite3VdbeSorterInit(
85521  sqlite3 *db,                    /* Database connection (for malloc()) */
85522  int nField,                     /* Number of key fields in each record */
85523  VdbeCursor *pCsr                /* Cursor that holds the new sorter */
85524){
85525  int pgsz;                       /* Page size of main database */
85526  int i;                          /* Used to iterate through aTask[] */
85527  VdbeSorter *pSorter;            /* The new sorter */
85528  KeyInfo *pKeyInfo;              /* Copy of pCsr->pKeyInfo with db==0 */
85529  int szKeyInfo;                  /* Size of pCsr->pKeyInfo in bytes */
85530  int sz;                         /* Size of pSorter in bytes */
85531  int rc = SQLITE_OK;
85532#if SQLITE_MAX_WORKER_THREADS==0
85533# define nWorker 0
85534#else
85535  int nWorker;
85536#endif
85537
85538  /* Initialize the upper limit on the number of worker threads */
85539#if SQLITE_MAX_WORKER_THREADS>0
85540  if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
85541    nWorker = 0;
85542  }else{
85543    nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
85544  }
85545#endif
85546
85547  /* Do not allow the total number of threads (main thread + all workers)
85548  ** to exceed the maximum merge count */
85549#if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
85550  if( nWorker>=SORTER_MAX_MERGE_COUNT ){
85551    nWorker = SORTER_MAX_MERGE_COUNT-1;
85552  }
85553#endif
85554
85555  assert( pCsr->pKeyInfo && pCsr->pBt==0 );
85556  assert( pCsr->eCurType==CURTYPE_SORTER );
85557  szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
85558  sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
85559
85560  pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
85561  pCsr->uc.pSorter = pSorter;
85562  if( pSorter==0 ){
85563    rc = SQLITE_NOMEM_BKPT;
85564  }else{
85565    pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
85566    memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
85567    pKeyInfo->db = 0;
85568    if( nField && nWorker==0 ){
85569      pKeyInfo->nXField += (pKeyInfo->nField - nField);
85570      pKeyInfo->nField = nField;
85571    }
85572    pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
85573    pSorter->nTask = nWorker + 1;
85574    pSorter->iPrev = (u8)(nWorker - 1);
85575    pSorter->bUseThreads = (pSorter->nTask>1);
85576    pSorter->db = db;
85577    for(i=0; i<pSorter->nTask; i++){
85578      SortSubtask *pTask = &pSorter->aTask[i];
85579      pTask->pSorter = pSorter;
85580    }
85581
85582    if( !sqlite3TempInMemory(db) ){
85583      i64 mxCache;                /* Cache size in bytes*/
85584      u32 szPma = sqlite3GlobalConfig.szPma;
85585      pSorter->mnPmaSize = szPma * pgsz;
85586
85587      mxCache = db->aDb[0].pSchema->cache_size;
85588      if( mxCache<0 ){
85589        /* A negative cache-size value C indicates that the cache is abs(C)
85590        ** KiB in size.  */
85591        mxCache = mxCache * -1024;
85592      }else{
85593        mxCache = mxCache * pgsz;
85594      }
85595      mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
85596      pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
85597
85598      /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
85599      ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
85600      ** large heap allocations.
85601      */
85602      if( sqlite3GlobalConfig.pScratch==0 ){
85603        assert( pSorter->iMemory==0 );
85604        pSorter->nMemory = pgsz;
85605        pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
85606        if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
85607      }
85608    }
85609
85610    if( (pKeyInfo->nField+pKeyInfo->nXField)<13
85611     && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
85612    ){
85613      pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
85614    }
85615  }
85616
85617  return rc;
85618}
85619#undef nWorker   /* Defined at the top of this function */
85620
85621/*
85622** Free the list of sorted records starting at pRecord.
85623*/
85624static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
85625  SorterRecord *p;
85626  SorterRecord *pNext;
85627  for(p=pRecord; p; p=pNext){
85628    pNext = p->u.pNext;
85629    sqlite3DbFree(db, p);
85630  }
85631}
85632
85633/*
85634** Free all resources owned by the object indicated by argument pTask. All
85635** fields of *pTask are zeroed before returning.
85636*/
85637static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
85638  sqlite3DbFree(db, pTask->pUnpacked);
85639#if SQLITE_MAX_WORKER_THREADS>0
85640  /* pTask->list.aMemory can only be non-zero if it was handed memory
85641  ** from the main thread.  That only occurs SQLITE_MAX_WORKER_THREADS>0 */
85642  if( pTask->list.aMemory ){
85643    sqlite3_free(pTask->list.aMemory);
85644  }else
85645#endif
85646  {
85647    assert( pTask->list.aMemory==0 );
85648    vdbeSorterRecordFree(0, pTask->list.pList);
85649  }
85650  if( pTask->file.pFd ){
85651    sqlite3OsCloseFree(pTask->file.pFd);
85652  }
85653  if( pTask->file2.pFd ){
85654    sqlite3OsCloseFree(pTask->file2.pFd);
85655  }
85656  memset(pTask, 0, sizeof(SortSubtask));
85657}
85658
85659#ifdef SQLITE_DEBUG_SORTER_THREADS
85660static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
85661  i64 t;
85662  int iTask = (pTask - pTask->pSorter->aTask);
85663  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85664  fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
85665}
85666static void vdbeSorterRewindDebug(const char *zEvent){
85667  i64 t;
85668  sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
85669  fprintf(stderr, "%lld:X %s\n", t, zEvent);
85670}
85671static void vdbeSorterPopulateDebug(
85672  SortSubtask *pTask,
85673  const char *zEvent
85674){
85675  i64 t;
85676  int iTask = (pTask - pTask->pSorter->aTask);
85677  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85678  fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
85679}
85680static void vdbeSorterBlockDebug(
85681  SortSubtask *pTask,
85682  int bBlocked,
85683  const char *zEvent
85684){
85685  if( bBlocked ){
85686    i64 t;
85687    sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85688    fprintf(stderr, "%lld:main %s\n", t, zEvent);
85689  }
85690}
85691#else
85692# define vdbeSorterWorkDebug(x,y)
85693# define vdbeSorterRewindDebug(y)
85694# define vdbeSorterPopulateDebug(x,y)
85695# define vdbeSorterBlockDebug(x,y,z)
85696#endif
85697
85698#if SQLITE_MAX_WORKER_THREADS>0
85699/*
85700** Join thread pTask->thread.
85701*/
85702static int vdbeSorterJoinThread(SortSubtask *pTask){
85703  int rc = SQLITE_OK;
85704  if( pTask->pThread ){
85705#ifdef SQLITE_DEBUG_SORTER_THREADS
85706    int bDone = pTask->bDone;
85707#endif
85708    void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
85709    vdbeSorterBlockDebug(pTask, !bDone, "enter");
85710    (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
85711    vdbeSorterBlockDebug(pTask, !bDone, "exit");
85712    rc = SQLITE_PTR_TO_INT(pRet);
85713    assert( pTask->bDone==1 );
85714    pTask->bDone = 0;
85715    pTask->pThread = 0;
85716  }
85717  return rc;
85718}
85719
85720/*
85721** Launch a background thread to run xTask(pIn).
85722*/
85723static int vdbeSorterCreateThread(
85724  SortSubtask *pTask,             /* Thread will use this task object */
85725  void *(*xTask)(void*),          /* Routine to run in a separate thread */
85726  void *pIn                       /* Argument passed into xTask() */
85727){
85728  assert( pTask->pThread==0 && pTask->bDone==0 );
85729  return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
85730}
85731
85732/*
85733** Join all outstanding threads launched by SorterWrite() to create
85734** level-0 PMAs.
85735*/
85736static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
85737  int rc = rcin;
85738  int i;
85739
85740  /* This function is always called by the main user thread.
85741  **
85742  ** If this function is being called after SorterRewind() has been called,
85743  ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
85744  ** is currently attempt to join one of the other threads. To avoid a race
85745  ** condition where this thread also attempts to join the same object, join
85746  ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
85747  for(i=pSorter->nTask-1; i>=0; i--){
85748    SortSubtask *pTask = &pSorter->aTask[i];
85749    int rc2 = vdbeSorterJoinThread(pTask);
85750    if( rc==SQLITE_OK ) rc = rc2;
85751  }
85752  return rc;
85753}
85754#else
85755# define vdbeSorterJoinAll(x,rcin) (rcin)
85756# define vdbeSorterJoinThread(pTask) SQLITE_OK
85757#endif
85758
85759/*
85760** Allocate a new MergeEngine object capable of handling up to
85761** nReader PmaReader inputs.
85762**
85763** nReader is automatically rounded up to the next power of two.
85764** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
85765*/
85766static MergeEngine *vdbeMergeEngineNew(int nReader){
85767  int N = 2;                      /* Smallest power of two >= nReader */
85768  int nByte;                      /* Total bytes of space to allocate */
85769  MergeEngine *pNew;              /* Pointer to allocated object to return */
85770
85771  assert( nReader<=SORTER_MAX_MERGE_COUNT );
85772
85773  while( N<nReader ) N += N;
85774  nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
85775
85776  pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
85777  if( pNew ){
85778    pNew->nTree = N;
85779    pNew->pTask = 0;
85780    pNew->aReadr = (PmaReader*)&pNew[1];
85781    pNew->aTree = (int*)&pNew->aReadr[N];
85782  }
85783  return pNew;
85784}
85785
85786/*
85787** Free the MergeEngine object passed as the only argument.
85788*/
85789static void vdbeMergeEngineFree(MergeEngine *pMerger){
85790  int i;
85791  if( pMerger ){
85792    for(i=0; i<pMerger->nTree; i++){
85793      vdbePmaReaderClear(&pMerger->aReadr[i]);
85794    }
85795  }
85796  sqlite3_free(pMerger);
85797}
85798
85799/*
85800** Free all resources associated with the IncrMerger object indicated by
85801** the first argument.
85802*/
85803static void vdbeIncrFree(IncrMerger *pIncr){
85804  if( pIncr ){
85805#if SQLITE_MAX_WORKER_THREADS>0
85806    if( pIncr->bUseThread ){
85807      vdbeSorterJoinThread(pIncr->pTask);
85808      if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
85809      if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
85810    }
85811#endif
85812    vdbeMergeEngineFree(pIncr->pMerger);
85813    sqlite3_free(pIncr);
85814  }
85815}
85816
85817/*
85818** Reset a sorting cursor back to its original empty state.
85819*/
85820SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
85821  int i;
85822  (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
85823  assert( pSorter->bUseThreads || pSorter->pReader==0 );
85824#if SQLITE_MAX_WORKER_THREADS>0
85825  if( pSorter->pReader ){
85826    vdbePmaReaderClear(pSorter->pReader);
85827    sqlite3DbFree(db, pSorter->pReader);
85828    pSorter->pReader = 0;
85829  }
85830#endif
85831  vdbeMergeEngineFree(pSorter->pMerger);
85832  pSorter->pMerger = 0;
85833  for(i=0; i<pSorter->nTask; i++){
85834    SortSubtask *pTask = &pSorter->aTask[i];
85835    vdbeSortSubtaskCleanup(db, pTask);
85836    pTask->pSorter = pSorter;
85837  }
85838  if( pSorter->list.aMemory==0 ){
85839    vdbeSorterRecordFree(0, pSorter->list.pList);
85840  }
85841  pSorter->list.pList = 0;
85842  pSorter->list.szPMA = 0;
85843  pSorter->bUsePMA = 0;
85844  pSorter->iMemory = 0;
85845  pSorter->mxKeysize = 0;
85846  sqlite3DbFree(db, pSorter->pUnpacked);
85847  pSorter->pUnpacked = 0;
85848}
85849
85850/*
85851** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
85852*/
85853SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
85854  VdbeSorter *pSorter;
85855  assert( pCsr->eCurType==CURTYPE_SORTER );
85856  pSorter = pCsr->uc.pSorter;
85857  if( pSorter ){
85858    sqlite3VdbeSorterReset(db, pSorter);
85859    sqlite3_free(pSorter->list.aMemory);
85860    sqlite3DbFree(db, pSorter);
85861    pCsr->uc.pSorter = 0;
85862  }
85863}
85864
85865#if SQLITE_MAX_MMAP_SIZE>0
85866/*
85867** The first argument is a file-handle open on a temporary file. The file
85868** is guaranteed to be nByte bytes or smaller in size. This function
85869** attempts to extend the file to nByte bytes in size and to ensure that
85870** the VFS has memory mapped it.
85871**
85872** Whether or not the file does end up memory mapped of course depends on
85873** the specific VFS implementation.
85874*/
85875static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
85876  if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
85877    void *p = 0;
85878    int chunksize = 4*1024;
85879    sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
85880    sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
85881    sqlite3OsFetch(pFd, 0, (int)nByte, &p);
85882    sqlite3OsUnfetch(pFd, 0, p);
85883  }
85884}
85885#else
85886# define vdbeSorterExtendFile(x,y,z)
85887#endif
85888
85889/*
85890** Allocate space for a file-handle and open a temporary file. If successful,
85891** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
85892** Otherwise, set *ppFd to 0 and return an SQLite error code.
85893*/
85894static int vdbeSorterOpenTempFile(
85895  sqlite3 *db,                    /* Database handle doing sort */
85896  i64 nExtend,                    /* Attempt to extend file to this size */
85897  sqlite3_file **ppFd
85898){
85899  int rc;
85900  if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
85901  rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
85902      SQLITE_OPEN_TEMP_JOURNAL |
85903      SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
85904      SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &rc
85905  );
85906  if( rc==SQLITE_OK ){
85907    i64 max = SQLITE_MAX_MMAP_SIZE;
85908    sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
85909    if( nExtend>0 ){
85910      vdbeSorterExtendFile(db, *ppFd, nExtend);
85911    }
85912  }
85913  return rc;
85914}
85915
85916/*
85917** If it has not already been allocated, allocate the UnpackedRecord
85918** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
85919** if no allocation was required), or SQLITE_NOMEM otherwise.
85920*/
85921static int vdbeSortAllocUnpacked(SortSubtask *pTask){
85922  if( pTask->pUnpacked==0 ){
85923    char *pFree;
85924    pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
85925        pTask->pSorter->pKeyInfo, 0, 0, &pFree
85926    );
85927    assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
85928    if( pFree==0 ) return SQLITE_NOMEM_BKPT;
85929    pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
85930    pTask->pUnpacked->errCode = 0;
85931  }
85932  return SQLITE_OK;
85933}
85934
85935
85936/*
85937** Merge the two sorted lists p1 and p2 into a single list.
85938*/
85939static SorterRecord *vdbeSorterMerge(
85940  SortSubtask *pTask,             /* Calling thread context */
85941  SorterRecord *p1,               /* First list to merge */
85942  SorterRecord *p2                /* Second list to merge */
85943){
85944  SorterRecord *pFinal = 0;
85945  SorterRecord **pp = &pFinal;
85946  int bCached = 0;
85947
85948  assert( p1!=0 && p2!=0 );
85949  for(;;){
85950    int res;
85951    res = pTask->xCompare(
85952        pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
85953    );
85954
85955    if( res<=0 ){
85956      *pp = p1;
85957      pp = &p1->u.pNext;
85958      p1 = p1->u.pNext;
85959      if( p1==0 ){
85960        *pp = p2;
85961        break;
85962      }
85963    }else{
85964      *pp = p2;
85965      pp = &p2->u.pNext;
85966      p2 = p2->u.pNext;
85967      bCached = 0;
85968      if( p2==0 ){
85969        *pp = p1;
85970        break;
85971      }
85972    }
85973  }
85974  return pFinal;
85975}
85976
85977/*
85978** Return the SorterCompare function to compare values collected by the
85979** sorter object passed as the only argument.
85980*/
85981static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
85982  if( p->typeMask==SORTER_TYPE_INTEGER ){
85983    return vdbeSorterCompareInt;
85984  }else if( p->typeMask==SORTER_TYPE_TEXT ){
85985    return vdbeSorterCompareText;
85986  }
85987  return vdbeSorterCompare;
85988}
85989
85990/*
85991** Sort the linked list of records headed at pTask->pList. Return
85992** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
85993** an error occurs.
85994*/
85995static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
85996  int i;
85997  SorterRecord **aSlot;
85998  SorterRecord *p;
85999  int rc;
86000
86001  rc = vdbeSortAllocUnpacked(pTask);
86002  if( rc!=SQLITE_OK ) return rc;
86003
86004  p = pList->pList;
86005  pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
86006
86007  aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
86008  if( !aSlot ){
86009    return SQLITE_NOMEM_BKPT;
86010  }
86011
86012  while( p ){
86013    SorterRecord *pNext;
86014    if( pList->aMemory ){
86015      if( (u8*)p==pList->aMemory ){
86016        pNext = 0;
86017      }else{
86018        assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
86019        pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
86020      }
86021    }else{
86022      pNext = p->u.pNext;
86023    }
86024
86025    p->u.pNext = 0;
86026    for(i=0; aSlot[i]; i++){
86027      p = vdbeSorterMerge(pTask, p, aSlot[i]);
86028      aSlot[i] = 0;
86029    }
86030    aSlot[i] = p;
86031    p = pNext;
86032  }
86033
86034  p = 0;
86035  for(i=0; i<64; i++){
86036    if( aSlot[i]==0 ) continue;
86037    p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
86038  }
86039  pList->pList = p;
86040
86041  sqlite3_free(aSlot);
86042  assert( pTask->pUnpacked->errCode==SQLITE_OK
86043       || pTask->pUnpacked->errCode==SQLITE_NOMEM
86044  );
86045  return pTask->pUnpacked->errCode;
86046}
86047
86048/*
86049** Initialize a PMA-writer object.
86050*/
86051static void vdbePmaWriterInit(
86052  sqlite3_file *pFd,              /* File handle to write to */
86053  PmaWriter *p,                   /* Object to populate */
86054  int nBuf,                       /* Buffer size */
86055  i64 iStart                      /* Offset of pFd to begin writing at */
86056){
86057  memset(p, 0, sizeof(PmaWriter));
86058  p->aBuffer = (u8*)sqlite3Malloc(nBuf);
86059  if( !p->aBuffer ){
86060    p->eFWErr = SQLITE_NOMEM_BKPT;
86061  }else{
86062    p->iBufEnd = p->iBufStart = (iStart % nBuf);
86063    p->iWriteOff = iStart - p->iBufStart;
86064    p->nBuffer = nBuf;
86065    p->pFd = pFd;
86066  }
86067}
86068
86069/*
86070** Write nData bytes of data to the PMA. Return SQLITE_OK
86071** if successful, or an SQLite error code if an error occurs.
86072*/
86073static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
86074  int nRem = nData;
86075  while( nRem>0 && p->eFWErr==0 ){
86076    int nCopy = nRem;
86077    if( nCopy>(p->nBuffer - p->iBufEnd) ){
86078      nCopy = p->nBuffer - p->iBufEnd;
86079    }
86080
86081    memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
86082    p->iBufEnd += nCopy;
86083    if( p->iBufEnd==p->nBuffer ){
86084      p->eFWErr = sqlite3OsWrite(p->pFd,
86085          &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
86086          p->iWriteOff + p->iBufStart
86087      );
86088      p->iBufStart = p->iBufEnd = 0;
86089      p->iWriteOff += p->nBuffer;
86090    }
86091    assert( p->iBufEnd<p->nBuffer );
86092
86093    nRem -= nCopy;
86094  }
86095}
86096
86097/*
86098** Flush any buffered data to disk and clean up the PMA-writer object.
86099** The results of using the PMA-writer after this call are undefined.
86100** Return SQLITE_OK if flushing the buffered data succeeds or is not
86101** required. Otherwise, return an SQLite error code.
86102**
86103** Before returning, set *piEof to the offset immediately following the
86104** last byte written to the file.
86105*/
86106static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
86107  int rc;
86108  if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
86109    p->eFWErr = sqlite3OsWrite(p->pFd,
86110        &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
86111        p->iWriteOff + p->iBufStart
86112    );
86113  }
86114  *piEof = (p->iWriteOff + p->iBufEnd);
86115  sqlite3_free(p->aBuffer);
86116  rc = p->eFWErr;
86117  memset(p, 0, sizeof(PmaWriter));
86118  return rc;
86119}
86120
86121/*
86122** Write value iVal encoded as a varint to the PMA. Return
86123** SQLITE_OK if successful, or an SQLite error code if an error occurs.
86124*/
86125static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
86126  int nByte;
86127  u8 aByte[10];
86128  nByte = sqlite3PutVarint(aByte, iVal);
86129  vdbePmaWriteBlob(p, aByte, nByte);
86130}
86131
86132/*
86133** Write the current contents of in-memory linked-list pList to a level-0
86134** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
86135** successful, or an SQLite error code otherwise.
86136**
86137** The format of a PMA is:
86138**
86139**     * A varint. This varint contains the total number of bytes of content
86140**       in the PMA (not including the varint itself).
86141**
86142**     * One or more records packed end-to-end in order of ascending keys.
86143**       Each record consists of a varint followed by a blob of data (the
86144**       key). The varint is the number of bytes in the blob of data.
86145*/
86146static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
86147  sqlite3 *db = pTask->pSorter->db;
86148  int rc = SQLITE_OK;             /* Return code */
86149  PmaWriter writer;               /* Object used to write to the file */
86150
86151#ifdef SQLITE_DEBUG
86152  /* Set iSz to the expected size of file pTask->file after writing the PMA.
86153  ** This is used by an assert() statement at the end of this function.  */
86154  i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
86155#endif
86156
86157  vdbeSorterWorkDebug(pTask, "enter");
86158  memset(&writer, 0, sizeof(PmaWriter));
86159  assert( pList->szPMA>0 );
86160
86161  /* If the first temporary PMA file has not been opened, open it now. */
86162  if( pTask->file.pFd==0 ){
86163    rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
86164    assert( rc!=SQLITE_OK || pTask->file.pFd );
86165    assert( pTask->file.iEof==0 );
86166    assert( pTask->nPMA==0 );
86167  }
86168
86169  /* Try to get the file to memory map */
86170  if( rc==SQLITE_OK ){
86171    vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
86172  }
86173
86174  /* Sort the list */
86175  if( rc==SQLITE_OK ){
86176    rc = vdbeSorterSort(pTask, pList);
86177  }
86178
86179  if( rc==SQLITE_OK ){
86180    SorterRecord *p;
86181    SorterRecord *pNext = 0;
86182
86183    vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
86184                      pTask->file.iEof);
86185    pTask->nPMA++;
86186    vdbePmaWriteVarint(&writer, pList->szPMA);
86187    for(p=pList->pList; p; p=pNext){
86188      pNext = p->u.pNext;
86189      vdbePmaWriteVarint(&writer, p->nVal);
86190      vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
86191      if( pList->aMemory==0 ) sqlite3_free(p);
86192    }
86193    pList->pList = p;
86194    rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
86195  }
86196
86197  vdbeSorterWorkDebug(pTask, "exit");
86198  assert( rc!=SQLITE_OK || pList->pList==0 );
86199  assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
86200  return rc;
86201}
86202
86203/*
86204** Advance the MergeEngine to its next entry.
86205** Set *pbEof to true there is no next entry because
86206** the MergeEngine has reached the end of all its inputs.
86207**
86208** Return SQLITE_OK if successful or an error code if an error occurs.
86209*/
86210static int vdbeMergeEngineStep(
86211  MergeEngine *pMerger,      /* The merge engine to advance to the next row */
86212  int *pbEof                 /* Set TRUE at EOF.  Set false for more content */
86213){
86214  int rc;
86215  int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
86216  SortSubtask *pTask = pMerger->pTask;
86217
86218  /* Advance the current PmaReader */
86219  rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
86220
86221  /* Update contents of aTree[] */
86222  if( rc==SQLITE_OK ){
86223    int i;                      /* Index of aTree[] to recalculate */
86224    PmaReader *pReadr1;         /* First PmaReader to compare */
86225    PmaReader *pReadr2;         /* Second PmaReader to compare */
86226    int bCached = 0;
86227
86228    /* Find the first two PmaReaders to compare. The one that was just
86229    ** advanced (iPrev) and the one next to it in the array.  */
86230    pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
86231    pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
86232
86233    for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
86234      /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
86235      int iRes;
86236      if( pReadr1->pFd==0 ){
86237        iRes = +1;
86238      }else if( pReadr2->pFd==0 ){
86239        iRes = -1;
86240      }else{
86241        iRes = pTask->xCompare(pTask, &bCached,
86242            pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
86243        );
86244      }
86245
86246      /* If pReadr1 contained the smaller value, set aTree[i] to its index.
86247      ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
86248      ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
86249      ** pKey2 to point to the record belonging to pReadr2.
86250      **
86251      ** Alternatively, if pReadr2 contains the smaller of the two values,
86252      ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
86253      ** was actually called above, then pTask->pUnpacked now contains
86254      ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
86255      ** vdbeSorterCompare() from decoding pReadr2 again.
86256      **
86257      ** If the two values were equal, then the value from the oldest
86258      ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
86259      ** is sorted from oldest to newest, so pReadr1 contains older values
86260      ** than pReadr2 iff (pReadr1<pReadr2).  */
86261      if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
86262        pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
86263        pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
86264        bCached = 0;
86265      }else{
86266        if( pReadr1->pFd ) bCached = 0;
86267        pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
86268        pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
86269      }
86270    }
86271    *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
86272  }
86273
86274  return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
86275}
86276
86277#if SQLITE_MAX_WORKER_THREADS>0
86278/*
86279** The main routine for background threads that write level-0 PMAs.
86280*/
86281static void *vdbeSorterFlushThread(void *pCtx){
86282  SortSubtask *pTask = (SortSubtask*)pCtx;
86283  int rc;                         /* Return code */
86284  assert( pTask->bDone==0 );
86285  rc = vdbeSorterListToPMA(pTask, &pTask->list);
86286  pTask->bDone = 1;
86287  return SQLITE_INT_TO_PTR(rc);
86288}
86289#endif /* SQLITE_MAX_WORKER_THREADS>0 */
86290
86291/*
86292** Flush the current contents of VdbeSorter.list to a new PMA, possibly
86293** using a background thread.
86294*/
86295static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
86296#if SQLITE_MAX_WORKER_THREADS==0
86297  pSorter->bUsePMA = 1;
86298  return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
86299#else
86300  int rc = SQLITE_OK;
86301  int i;
86302  SortSubtask *pTask = 0;    /* Thread context used to create new PMA */
86303  int nWorker = (pSorter->nTask-1);
86304
86305  /* Set the flag to indicate that at least one PMA has been written.
86306  ** Or will be, anyhow.  */
86307  pSorter->bUsePMA = 1;
86308
86309  /* Select a sub-task to sort and flush the current list of in-memory
86310  ** records to disk. If the sorter is running in multi-threaded mode,
86311  ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
86312  ** the background thread from a sub-tasks previous turn is still running,
86313  ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
86314  ** fall back to using the final sub-task. The first (pSorter->nTask-1)
86315  ** sub-tasks are prefered as they use background threads - the final
86316  ** sub-task uses the main thread. */
86317  for(i=0; i<nWorker; i++){
86318    int iTest = (pSorter->iPrev + i + 1) % nWorker;
86319    pTask = &pSorter->aTask[iTest];
86320    if( pTask->bDone ){
86321      rc = vdbeSorterJoinThread(pTask);
86322    }
86323    if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
86324  }
86325
86326  if( rc==SQLITE_OK ){
86327    if( i==nWorker ){
86328      /* Use the foreground thread for this operation */
86329      rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
86330    }else{
86331      /* Launch a background thread for this operation */
86332      u8 *aMem = pTask->list.aMemory;
86333      void *pCtx = (void*)pTask;
86334
86335      assert( pTask->pThread==0 && pTask->bDone==0 );
86336      assert( pTask->list.pList==0 );
86337      assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
86338
86339      pSorter->iPrev = (u8)(pTask - pSorter->aTask);
86340      pTask->list = pSorter->list;
86341      pSorter->list.pList = 0;
86342      pSorter->list.szPMA = 0;
86343      if( aMem ){
86344        pSorter->list.aMemory = aMem;
86345        pSorter->nMemory = sqlite3MallocSize(aMem);
86346      }else if( pSorter->list.aMemory ){
86347        pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
86348        if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
86349      }
86350
86351      rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
86352    }
86353  }
86354
86355  return rc;
86356#endif /* SQLITE_MAX_WORKER_THREADS!=0 */
86357}
86358
86359/*
86360** Add a record to the sorter.
86361*/
86362SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
86363  const VdbeCursor *pCsr,         /* Sorter cursor */
86364  Mem *pVal                       /* Memory cell containing record */
86365){
86366  VdbeSorter *pSorter;
86367  int rc = SQLITE_OK;             /* Return Code */
86368  SorterRecord *pNew;             /* New list element */
86369  int bFlush;                     /* True to flush contents of memory to PMA */
86370  int nReq;                       /* Bytes of memory required */
86371  int nPMA;                       /* Bytes of PMA space required */
86372  int t;                          /* serial type of first record field */
86373
86374  assert( pCsr->eCurType==CURTYPE_SORTER );
86375  pSorter = pCsr->uc.pSorter;
86376  getVarint32((const u8*)&pVal->z[1], t);
86377  if( t>0 && t<10 && t!=7 ){
86378    pSorter->typeMask &= SORTER_TYPE_INTEGER;
86379  }else if( t>10 && (t & 0x01) ){
86380    pSorter->typeMask &= SORTER_TYPE_TEXT;
86381  }else{
86382    pSorter->typeMask = 0;
86383  }
86384
86385  assert( pSorter );
86386
86387  /* Figure out whether or not the current contents of memory should be
86388  ** flushed to a PMA before continuing. If so, do so.
86389  **
86390  ** If using the single large allocation mode (pSorter->aMemory!=0), then
86391  ** flush the contents of memory to a new PMA if (a) at least one value is
86392  ** already in memory and (b) the new value will not fit in memory.
86393  **
86394  ** Or, if using separate allocations for each record, flush the contents
86395  ** of memory to a PMA if either of the following are true:
86396  **
86397  **   * The total memory allocated for the in-memory list is greater
86398  **     than (page-size * cache-size), or
86399  **
86400  **   * The total memory allocated for the in-memory list is greater
86401  **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
86402  */
86403  nReq = pVal->n + sizeof(SorterRecord);
86404  nPMA = pVal->n + sqlite3VarintLen(pVal->n);
86405  if( pSorter->mxPmaSize ){
86406    if( pSorter->list.aMemory ){
86407      bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
86408    }else{
86409      bFlush = (
86410          (pSorter->list.szPMA > pSorter->mxPmaSize)
86411       || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
86412      );
86413    }
86414    if( bFlush ){
86415      rc = vdbeSorterFlushPMA(pSorter);
86416      pSorter->list.szPMA = 0;
86417      pSorter->iMemory = 0;
86418      assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
86419    }
86420  }
86421
86422  pSorter->list.szPMA += nPMA;
86423  if( nPMA>pSorter->mxKeysize ){
86424    pSorter->mxKeysize = nPMA;
86425  }
86426
86427  if( pSorter->list.aMemory ){
86428    int nMin = pSorter->iMemory + nReq;
86429
86430    if( nMin>pSorter->nMemory ){
86431      u8 *aNew;
86432      int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
86433      int nNew = pSorter->nMemory * 2;
86434      while( nNew < nMin ) nNew = nNew*2;
86435      if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
86436      if( nNew < nMin ) nNew = nMin;
86437
86438      aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
86439      if( !aNew ) return SQLITE_NOMEM_BKPT;
86440      pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
86441      pSorter->list.aMemory = aNew;
86442      pSorter->nMemory = nNew;
86443    }
86444
86445    pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
86446    pSorter->iMemory += ROUND8(nReq);
86447    if( pSorter->list.pList ){
86448      pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
86449    }
86450  }else{
86451    pNew = (SorterRecord *)sqlite3Malloc(nReq);
86452    if( pNew==0 ){
86453      return SQLITE_NOMEM_BKPT;
86454    }
86455    pNew->u.pNext = pSorter->list.pList;
86456  }
86457
86458  memcpy(SRVAL(pNew), pVal->z, pVal->n);
86459  pNew->nVal = pVal->n;
86460  pSorter->list.pList = pNew;
86461
86462  return rc;
86463}
86464
86465/*
86466** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
86467** of the data stored in aFile[1] is the same as that used by regular PMAs,
86468** except that the number-of-bytes varint is omitted from the start.
86469*/
86470static int vdbeIncrPopulate(IncrMerger *pIncr){
86471  int rc = SQLITE_OK;
86472  int rc2;
86473  i64 iStart = pIncr->iStartOff;
86474  SorterFile *pOut = &pIncr->aFile[1];
86475  SortSubtask *pTask = pIncr->pTask;
86476  MergeEngine *pMerger = pIncr->pMerger;
86477  PmaWriter writer;
86478  assert( pIncr->bEof==0 );
86479
86480  vdbeSorterPopulateDebug(pTask, "enter");
86481
86482  vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
86483  while( rc==SQLITE_OK ){
86484    int dummy;
86485    PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
86486    int nKey = pReader->nKey;
86487    i64 iEof = writer.iWriteOff + writer.iBufEnd;
86488
86489    /* Check if the output file is full or if the input has been exhausted.
86490    ** In either case exit the loop. */
86491    if( pReader->pFd==0 ) break;
86492    if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
86493
86494    /* Write the next key to the output. */
86495    vdbePmaWriteVarint(&writer, nKey);
86496    vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
86497    assert( pIncr->pMerger->pTask==pTask );
86498    rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
86499  }
86500
86501  rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
86502  if( rc==SQLITE_OK ) rc = rc2;
86503  vdbeSorterPopulateDebug(pTask, "exit");
86504  return rc;
86505}
86506
86507#if SQLITE_MAX_WORKER_THREADS>0
86508/*
86509** The main routine for background threads that populate aFile[1] of
86510** multi-threaded IncrMerger objects.
86511*/
86512static void *vdbeIncrPopulateThread(void *pCtx){
86513  IncrMerger *pIncr = (IncrMerger*)pCtx;
86514  void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
86515  pIncr->pTask->bDone = 1;
86516  return pRet;
86517}
86518
86519/*
86520** Launch a background thread to populate aFile[1] of pIncr.
86521*/
86522static int vdbeIncrBgPopulate(IncrMerger *pIncr){
86523  void *p = (void*)pIncr;
86524  assert( pIncr->bUseThread );
86525  return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
86526}
86527#endif
86528
86529/*
86530** This function is called when the PmaReader corresponding to pIncr has
86531** finished reading the contents of aFile[0]. Its purpose is to "refill"
86532** aFile[0] such that the PmaReader should start rereading it from the
86533** beginning.
86534**
86535** For single-threaded objects, this is accomplished by literally reading
86536** keys from pIncr->pMerger and repopulating aFile[0].
86537**
86538** For multi-threaded objects, all that is required is to wait until the
86539** background thread is finished (if it is not already) and then swap
86540** aFile[0] and aFile[1] in place. If the contents of pMerger have not
86541** been exhausted, this function also launches a new background thread
86542** to populate the new aFile[1].
86543**
86544** SQLITE_OK is returned on success, or an SQLite error code otherwise.
86545*/
86546static int vdbeIncrSwap(IncrMerger *pIncr){
86547  int rc = SQLITE_OK;
86548
86549#if SQLITE_MAX_WORKER_THREADS>0
86550  if( pIncr->bUseThread ){
86551    rc = vdbeSorterJoinThread(pIncr->pTask);
86552
86553    if( rc==SQLITE_OK ){
86554      SorterFile f0 = pIncr->aFile[0];
86555      pIncr->aFile[0] = pIncr->aFile[1];
86556      pIncr->aFile[1] = f0;
86557    }
86558
86559    if( rc==SQLITE_OK ){
86560      if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
86561        pIncr->bEof = 1;
86562      }else{
86563        rc = vdbeIncrBgPopulate(pIncr);
86564      }
86565    }
86566  }else
86567#endif
86568  {
86569    rc = vdbeIncrPopulate(pIncr);
86570    pIncr->aFile[0] = pIncr->aFile[1];
86571    if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
86572      pIncr->bEof = 1;
86573    }
86574  }
86575
86576  return rc;
86577}
86578
86579/*
86580** Allocate and return a new IncrMerger object to read data from pMerger.
86581**
86582** If an OOM condition is encountered, return NULL. In this case free the
86583** pMerger argument before returning.
86584*/
86585static int vdbeIncrMergerNew(
86586  SortSubtask *pTask,     /* The thread that will be using the new IncrMerger */
86587  MergeEngine *pMerger,   /* The MergeEngine that the IncrMerger will control */
86588  IncrMerger **ppOut      /* Write the new IncrMerger here */
86589){
86590  int rc = SQLITE_OK;
86591  IncrMerger *pIncr = *ppOut = (IncrMerger*)
86592       (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
86593  if( pIncr ){
86594    pIncr->pMerger = pMerger;
86595    pIncr->pTask = pTask;
86596    pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
86597    pTask->file2.iEof += pIncr->mxSz;
86598  }else{
86599    vdbeMergeEngineFree(pMerger);
86600    rc = SQLITE_NOMEM_BKPT;
86601  }
86602  return rc;
86603}
86604
86605#if SQLITE_MAX_WORKER_THREADS>0
86606/*
86607** Set the "use-threads" flag on object pIncr.
86608*/
86609static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
86610  pIncr->bUseThread = 1;
86611  pIncr->pTask->file2.iEof -= pIncr->mxSz;
86612}
86613#endif /* SQLITE_MAX_WORKER_THREADS>0 */
86614
86615
86616
86617/*
86618** Recompute pMerger->aTree[iOut] by comparing the next keys on the
86619** two PmaReaders that feed that entry.  Neither of the PmaReaders
86620** are advanced.  This routine merely does the comparison.
86621*/
86622static void vdbeMergeEngineCompare(
86623  MergeEngine *pMerger,  /* Merge engine containing PmaReaders to compare */
86624  int iOut               /* Store the result in pMerger->aTree[iOut] */
86625){
86626  int i1;
86627  int i2;
86628  int iRes;
86629  PmaReader *p1;
86630  PmaReader *p2;
86631
86632  assert( iOut<pMerger->nTree && iOut>0 );
86633
86634  if( iOut>=(pMerger->nTree/2) ){
86635    i1 = (iOut - pMerger->nTree/2) * 2;
86636    i2 = i1 + 1;
86637  }else{
86638    i1 = pMerger->aTree[iOut*2];
86639    i2 = pMerger->aTree[iOut*2+1];
86640  }
86641
86642  p1 = &pMerger->aReadr[i1];
86643  p2 = &pMerger->aReadr[i2];
86644
86645  if( p1->pFd==0 ){
86646    iRes = i2;
86647  }else if( p2->pFd==0 ){
86648    iRes = i1;
86649  }else{
86650    SortSubtask *pTask = pMerger->pTask;
86651    int bCached = 0;
86652    int res;
86653    assert( pTask->pUnpacked!=0 );  /* from vdbeSortSubtaskMain() */
86654    res = pTask->xCompare(
86655        pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
86656    );
86657    if( res<=0 ){
86658      iRes = i1;
86659    }else{
86660      iRes = i2;
86661    }
86662  }
86663
86664  pMerger->aTree[iOut] = iRes;
86665}
86666
86667/*
86668** Allowed values for the eMode parameter to vdbeMergeEngineInit()
86669** and vdbePmaReaderIncrMergeInit().
86670**
86671** Only INCRINIT_NORMAL is valid in single-threaded builds (when
86672** SQLITE_MAX_WORKER_THREADS==0).  The other values are only used
86673** when there exists one or more separate worker threads.
86674*/
86675#define INCRINIT_NORMAL 0
86676#define INCRINIT_TASK   1
86677#define INCRINIT_ROOT   2
86678
86679/*
86680** Forward reference required as the vdbeIncrMergeInit() and
86681** vdbePmaReaderIncrInit() routines are called mutually recursively when
86682** building a merge tree.
86683*/
86684static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
86685
86686/*
86687** Initialize the MergeEngine object passed as the second argument. Once this
86688** function returns, the first key of merged data may be read from the
86689** MergeEngine object in the usual fashion.
86690**
86691** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
86692** objects attached to the PmaReader objects that the merger reads from have
86693** already been populated, but that they have not yet populated aFile[0] and
86694** set the PmaReader objects up to read from it. In this case all that is
86695** required is to call vdbePmaReaderNext() on each PmaReader to point it at
86696** its first key.
86697**
86698** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
86699** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
86700** to pMerger.
86701**
86702** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
86703*/
86704static int vdbeMergeEngineInit(
86705  SortSubtask *pTask,             /* Thread that will run pMerger */
86706  MergeEngine *pMerger,           /* MergeEngine to initialize */
86707  int eMode                       /* One of the INCRINIT_XXX constants */
86708){
86709  int rc = SQLITE_OK;             /* Return code */
86710  int i;                          /* For looping over PmaReader objects */
86711  int nTree = pMerger->nTree;
86712
86713  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
86714  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
86715
86716  /* Verify that the MergeEngine is assigned to a single thread */
86717  assert( pMerger->pTask==0 );
86718  pMerger->pTask = pTask;
86719
86720  for(i=0; i<nTree; i++){
86721    if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
86722      /* PmaReaders should be normally initialized in order, as if they are
86723      ** reading from the same temp file this makes for more linear file IO.
86724      ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
86725      ** in use it will block the vdbePmaReaderNext() call while it uses
86726      ** the main thread to fill its buffer. So calling PmaReaderNext()
86727      ** on this PmaReader before any of the multi-threaded PmaReaders takes
86728      ** better advantage of multi-processor hardware. */
86729      rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
86730    }else{
86731      rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
86732    }
86733    if( rc!=SQLITE_OK ) return rc;
86734  }
86735
86736  for(i=pMerger->nTree-1; i>0; i--){
86737    vdbeMergeEngineCompare(pMerger, i);
86738  }
86739  return pTask->pUnpacked->errCode;
86740}
86741
86742/*
86743** The PmaReader passed as the first argument is guaranteed to be an
86744** incremental-reader (pReadr->pIncr!=0). This function serves to open
86745** and/or initialize the temp file related fields of the IncrMerge
86746** object at (pReadr->pIncr).
86747**
86748** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
86749** in the sub-tree headed by pReadr are also initialized. Data is then
86750** loaded into the buffers belonging to pReadr and it is set to point to
86751** the first key in its range.
86752**
86753** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
86754** to be a multi-threaded PmaReader and this function is being called in a
86755** background thread. In this case all PmaReaders in the sub-tree are
86756** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
86757** pReadr is populated. However, pReadr itself is not set up to point
86758** to its first key. A call to vdbePmaReaderNext() is still required to do
86759** that.
86760**
86761** The reason this function does not call vdbePmaReaderNext() immediately
86762** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
86763** to block on thread (pTask->thread) before accessing aFile[1]. But, since
86764** this entire function is being run by thread (pTask->thread), that will
86765** lead to the current background thread attempting to join itself.
86766**
86767** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
86768** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
86769** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
86770** In this case vdbePmaReaderNext() is called on all child PmaReaders and
86771** the current PmaReader set to point to the first key in its range.
86772**
86773** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
86774*/
86775static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
86776  int rc = SQLITE_OK;
86777  IncrMerger *pIncr = pReadr->pIncr;
86778  SortSubtask *pTask = pIncr->pTask;
86779  sqlite3 *db = pTask->pSorter->db;
86780
86781  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
86782  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
86783
86784  rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
86785
86786  /* Set up the required files for pIncr. A multi-theaded IncrMerge object
86787  ** requires two temp files to itself, whereas a single-threaded object
86788  ** only requires a region of pTask->file2. */
86789  if( rc==SQLITE_OK ){
86790    int mxSz = pIncr->mxSz;
86791#if SQLITE_MAX_WORKER_THREADS>0
86792    if( pIncr->bUseThread ){
86793      rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
86794      if( rc==SQLITE_OK ){
86795        rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
86796      }
86797    }else
86798#endif
86799    /*if( !pIncr->bUseThread )*/{
86800      if( pTask->file2.pFd==0 ){
86801        assert( pTask->file2.iEof>0 );
86802        rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
86803        pTask->file2.iEof = 0;
86804      }
86805      if( rc==SQLITE_OK ){
86806        pIncr->aFile[1].pFd = pTask->file2.pFd;
86807        pIncr->iStartOff = pTask->file2.iEof;
86808        pTask->file2.iEof += mxSz;
86809      }
86810    }
86811  }
86812
86813#if SQLITE_MAX_WORKER_THREADS>0
86814  if( rc==SQLITE_OK && pIncr->bUseThread ){
86815    /* Use the current thread to populate aFile[1], even though this
86816    ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
86817    ** then this function is already running in background thread
86818    ** pIncr->pTask->thread.
86819    **
86820    ** If this is the INCRINIT_ROOT object, then it is running in the
86821    ** main VDBE thread. But that is Ok, as that thread cannot return
86822    ** control to the VDBE or proceed with anything useful until the
86823    ** first results are ready from this merger object anyway.
86824    */
86825    assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
86826    rc = vdbeIncrPopulate(pIncr);
86827  }
86828#endif
86829
86830  if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
86831    rc = vdbePmaReaderNext(pReadr);
86832  }
86833
86834  return rc;
86835}
86836
86837#if SQLITE_MAX_WORKER_THREADS>0
86838/*
86839** The main routine for vdbePmaReaderIncrMergeInit() operations run in
86840** background threads.
86841*/
86842static void *vdbePmaReaderBgIncrInit(void *pCtx){
86843  PmaReader *pReader = (PmaReader*)pCtx;
86844  void *pRet = SQLITE_INT_TO_PTR(
86845                  vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
86846               );
86847  pReader->pIncr->pTask->bDone = 1;
86848  return pRet;
86849}
86850#endif
86851
86852/*
86853** If the PmaReader passed as the first argument is not an incremental-reader
86854** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
86855** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
86856** this routine to initialize the incremental merge.
86857**
86858** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
86859** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
86860** Or, if the IncrMerger is single threaded, the same function is called
86861** using the current thread.
86862*/
86863static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
86864  IncrMerger *pIncr = pReadr->pIncr;   /* Incremental merger */
86865  int rc = SQLITE_OK;                  /* Return code */
86866  if( pIncr ){
86867#if SQLITE_MAX_WORKER_THREADS>0
86868    assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
86869    if( pIncr->bUseThread ){
86870      void *pCtx = (void*)pReadr;
86871      rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
86872    }else
86873#endif
86874    {
86875      rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
86876    }
86877  }
86878  return rc;
86879}
86880
86881/*
86882** Allocate a new MergeEngine object to merge the contents of nPMA level-0
86883** PMAs from pTask->file. If no error occurs, set *ppOut to point to
86884** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
86885** to NULL and return an SQLite error code.
86886**
86887** When this function is called, *piOffset is set to the offset of the
86888** first PMA to read from pTask->file. Assuming no error occurs, it is
86889** set to the offset immediately following the last byte of the last
86890** PMA before returning. If an error does occur, then the final value of
86891** *piOffset is undefined.
86892*/
86893static int vdbeMergeEngineLevel0(
86894  SortSubtask *pTask,             /* Sorter task to read from */
86895  int nPMA,                       /* Number of PMAs to read */
86896  i64 *piOffset,                  /* IN/OUT: Readr offset in pTask->file */
86897  MergeEngine **ppOut             /* OUT: New merge-engine */
86898){
86899  MergeEngine *pNew;              /* Merge engine to return */
86900  i64 iOff = *piOffset;
86901  int i;
86902  int rc = SQLITE_OK;
86903
86904  *ppOut = pNew = vdbeMergeEngineNew(nPMA);
86905  if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
86906
86907  for(i=0; i<nPMA && rc==SQLITE_OK; i++){
86908    i64 nDummy = 0;
86909    PmaReader *pReadr = &pNew->aReadr[i];
86910    rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
86911    iOff = pReadr->iEof;
86912  }
86913
86914  if( rc!=SQLITE_OK ){
86915    vdbeMergeEngineFree(pNew);
86916    *ppOut = 0;
86917  }
86918  *piOffset = iOff;
86919  return rc;
86920}
86921
86922/*
86923** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
86924** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
86925**
86926** i.e.
86927**
86928**   nPMA<=16    -> TreeDepth() == 0
86929**   nPMA<=256   -> TreeDepth() == 1
86930**   nPMA<=65536 -> TreeDepth() == 2
86931*/
86932static int vdbeSorterTreeDepth(int nPMA){
86933  int nDepth = 0;
86934  i64 nDiv = SORTER_MAX_MERGE_COUNT;
86935  while( nDiv < (i64)nPMA ){
86936    nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
86937    nDepth++;
86938  }
86939  return nDepth;
86940}
86941
86942/*
86943** pRoot is the root of an incremental merge-tree with depth nDepth (according
86944** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
86945** tree, counting from zero. This function adds pLeaf to the tree.
86946**
86947** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
86948** code is returned and pLeaf is freed.
86949*/
86950static int vdbeSorterAddToTree(
86951  SortSubtask *pTask,             /* Task context */
86952  int nDepth,                     /* Depth of tree according to TreeDepth() */
86953  int iSeq,                       /* Sequence number of leaf within tree */
86954  MergeEngine *pRoot,             /* Root of tree */
86955  MergeEngine *pLeaf              /* Leaf to add to tree */
86956){
86957  int rc = SQLITE_OK;
86958  int nDiv = 1;
86959  int i;
86960  MergeEngine *p = pRoot;
86961  IncrMerger *pIncr;
86962
86963  rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
86964
86965  for(i=1; i<nDepth; i++){
86966    nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
86967  }
86968
86969  for(i=1; i<nDepth && rc==SQLITE_OK; i++){
86970    int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
86971    PmaReader *pReadr = &p->aReadr[iIter];
86972
86973    if( pReadr->pIncr==0 ){
86974      MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
86975      if( pNew==0 ){
86976        rc = SQLITE_NOMEM_BKPT;
86977      }else{
86978        rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
86979      }
86980    }
86981    if( rc==SQLITE_OK ){
86982      p = pReadr->pIncr->pMerger;
86983      nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
86984    }
86985  }
86986
86987  if( rc==SQLITE_OK ){
86988    p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
86989  }else{
86990    vdbeIncrFree(pIncr);
86991  }
86992  return rc;
86993}
86994
86995/*
86996** This function is called as part of a SorterRewind() operation on a sorter
86997** that has already written two or more level-0 PMAs to one or more temp
86998** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
86999** can be used to incrementally merge all PMAs on disk.
87000**
87001** If successful, SQLITE_OK is returned and *ppOut set to point to the
87002** MergeEngine object at the root of the tree before returning. Or, if an
87003** error occurs, an SQLite error code is returned and the final value
87004** of *ppOut is undefined.
87005*/
87006static int vdbeSorterMergeTreeBuild(
87007  VdbeSorter *pSorter,       /* The VDBE cursor that implements the sort */
87008  MergeEngine **ppOut        /* Write the MergeEngine here */
87009){
87010  MergeEngine *pMain = 0;
87011  int rc = SQLITE_OK;
87012  int iTask;
87013
87014#if SQLITE_MAX_WORKER_THREADS>0
87015  /* If the sorter uses more than one task, then create the top-level
87016  ** MergeEngine here. This MergeEngine will read data from exactly
87017  ** one PmaReader per sub-task.  */
87018  assert( pSorter->bUseThreads || pSorter->nTask==1 );
87019  if( pSorter->nTask>1 ){
87020    pMain = vdbeMergeEngineNew(pSorter->nTask);
87021    if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
87022  }
87023#endif
87024
87025  for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
87026    SortSubtask *pTask = &pSorter->aTask[iTask];
87027    assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
87028    if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
87029      MergeEngine *pRoot = 0;     /* Root node of tree for this task */
87030      int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
87031      i64 iReadOff = 0;
87032
87033      if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
87034        rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
87035      }else{
87036        int i;
87037        int iSeq = 0;
87038        pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
87039        if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
87040        for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
87041          MergeEngine *pMerger = 0; /* New level-0 PMA merger */
87042          int nReader;              /* Number of level-0 PMAs to merge */
87043
87044          nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
87045          rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
87046          if( rc==SQLITE_OK ){
87047            rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
87048          }
87049        }
87050      }
87051
87052      if( rc==SQLITE_OK ){
87053#if SQLITE_MAX_WORKER_THREADS>0
87054        if( pMain!=0 ){
87055          rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
87056        }else
87057#endif
87058        {
87059          assert( pMain==0 );
87060          pMain = pRoot;
87061        }
87062      }else{
87063        vdbeMergeEngineFree(pRoot);
87064      }
87065    }
87066  }
87067
87068  if( rc!=SQLITE_OK ){
87069    vdbeMergeEngineFree(pMain);
87070    pMain = 0;
87071  }
87072  *ppOut = pMain;
87073  return rc;
87074}
87075
87076/*
87077** This function is called as part of an sqlite3VdbeSorterRewind() operation
87078** on a sorter that has written two or more PMAs to temporary files. It sets
87079** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
87080** (for multi-threaded sorters) so that it can be used to iterate through
87081** all records stored in the sorter.
87082**
87083** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
87084*/
87085static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
87086  int rc;                         /* Return code */
87087  SortSubtask *pTask0 = &pSorter->aTask[0];
87088  MergeEngine *pMain = 0;
87089#if SQLITE_MAX_WORKER_THREADS
87090  sqlite3 *db = pTask0->pSorter->db;
87091  int i;
87092  SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
87093  for(i=0; i<pSorter->nTask; i++){
87094    pSorter->aTask[i].xCompare = xCompare;
87095  }
87096#endif
87097
87098  rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
87099  if( rc==SQLITE_OK ){
87100#if SQLITE_MAX_WORKER_THREADS
87101    assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
87102    if( pSorter->bUseThreads ){
87103      int iTask;
87104      PmaReader *pReadr = 0;
87105      SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
87106      rc = vdbeSortAllocUnpacked(pLast);
87107      if( rc==SQLITE_OK ){
87108        pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
87109        pSorter->pReader = pReadr;
87110        if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
87111      }
87112      if( rc==SQLITE_OK ){
87113        rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
87114        if( rc==SQLITE_OK ){
87115          vdbeIncrMergerSetThreads(pReadr->pIncr);
87116          for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
87117            IncrMerger *pIncr;
87118            if( (pIncr = pMain->aReadr[iTask].pIncr) ){
87119              vdbeIncrMergerSetThreads(pIncr);
87120              assert( pIncr->pTask!=pLast );
87121            }
87122          }
87123          for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
87124            /* Check that:
87125            **
87126            **   a) The incremental merge object is configured to use the
87127            **      right task, and
87128            **   b) If it is using task (nTask-1), it is configured to run
87129            **      in single-threaded mode. This is important, as the
87130            **      root merge (INCRINIT_ROOT) will be using the same task
87131            **      object.
87132            */
87133            PmaReader *p = &pMain->aReadr[iTask];
87134            assert( p->pIncr==0 || (
87135                (p->pIncr->pTask==&pSorter->aTask[iTask])             /* a */
87136             && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0)  /* b */
87137            ));
87138            rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
87139          }
87140        }
87141        pMain = 0;
87142      }
87143      if( rc==SQLITE_OK ){
87144        rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
87145      }
87146    }else
87147#endif
87148    {
87149      rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
87150      pSorter->pMerger = pMain;
87151      pMain = 0;
87152    }
87153  }
87154
87155  if( rc!=SQLITE_OK ){
87156    vdbeMergeEngineFree(pMain);
87157  }
87158  return rc;
87159}
87160
87161
87162/*
87163** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
87164** this function is called to prepare for iterating through the records
87165** in sorted order.
87166*/
87167SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
87168  VdbeSorter *pSorter;
87169  int rc = SQLITE_OK;             /* Return code */
87170
87171  assert( pCsr->eCurType==CURTYPE_SORTER );
87172  pSorter = pCsr->uc.pSorter;
87173  assert( pSorter );
87174
87175  /* If no data has been written to disk, then do not do so now. Instead,
87176  ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
87177  ** from the in-memory list.  */
87178  if( pSorter->bUsePMA==0 ){
87179    if( pSorter->list.pList ){
87180      *pbEof = 0;
87181      rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
87182    }else{
87183      *pbEof = 1;
87184    }
87185    return rc;
87186  }
87187
87188  /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
87189  ** function flushes the contents of memory to disk, it immediately always
87190  ** creates a new list consisting of a single key immediately afterwards.
87191  ** So the list is never empty at this point.  */
87192  assert( pSorter->list.pList );
87193  rc = vdbeSorterFlushPMA(pSorter);
87194
87195  /* Join all threads */
87196  rc = vdbeSorterJoinAll(pSorter, rc);
87197
87198  vdbeSorterRewindDebug("rewind");
87199
87200  /* Assuming no errors have occurred, set up a merger structure to
87201  ** incrementally read and merge all remaining PMAs.  */
87202  assert( pSorter->pReader==0 );
87203  if( rc==SQLITE_OK ){
87204    rc = vdbeSorterSetupMerge(pSorter);
87205    *pbEof = 0;
87206  }
87207
87208  vdbeSorterRewindDebug("rewinddone");
87209  return rc;
87210}
87211
87212/*
87213** Advance to the next element in the sorter.
87214*/
87215SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
87216  VdbeSorter *pSorter;
87217  int rc;                         /* Return code */
87218
87219  assert( pCsr->eCurType==CURTYPE_SORTER );
87220  pSorter = pCsr->uc.pSorter;
87221  assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
87222  if( pSorter->bUsePMA ){
87223    assert( pSorter->pReader==0 || pSorter->pMerger==0 );
87224    assert( pSorter->bUseThreads==0 || pSorter->pReader );
87225    assert( pSorter->bUseThreads==1 || pSorter->pMerger );
87226#if SQLITE_MAX_WORKER_THREADS>0
87227    if( pSorter->bUseThreads ){
87228      rc = vdbePmaReaderNext(pSorter->pReader);
87229      *pbEof = (pSorter->pReader->pFd==0);
87230    }else
87231#endif
87232    /*if( !pSorter->bUseThreads )*/ {
87233      assert( pSorter->pMerger!=0 );
87234      assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
87235      rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
87236    }
87237  }else{
87238    SorterRecord *pFree = pSorter->list.pList;
87239    pSorter->list.pList = pFree->u.pNext;
87240    pFree->u.pNext = 0;
87241    if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
87242    *pbEof = !pSorter->list.pList;
87243    rc = SQLITE_OK;
87244  }
87245  return rc;
87246}
87247
87248/*
87249** Return a pointer to a buffer owned by the sorter that contains the
87250** current key.
87251*/
87252static void *vdbeSorterRowkey(
87253  const VdbeSorter *pSorter,      /* Sorter object */
87254  int *pnKey                      /* OUT: Size of current key in bytes */
87255){
87256  void *pKey;
87257  if( pSorter->bUsePMA ){
87258    PmaReader *pReader;
87259#if SQLITE_MAX_WORKER_THREADS>0
87260    if( pSorter->bUseThreads ){
87261      pReader = pSorter->pReader;
87262    }else
87263#endif
87264    /*if( !pSorter->bUseThreads )*/{
87265      pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
87266    }
87267    *pnKey = pReader->nKey;
87268    pKey = pReader->aKey;
87269  }else{
87270    *pnKey = pSorter->list.pList->nVal;
87271    pKey = SRVAL(pSorter->list.pList);
87272  }
87273  return pKey;
87274}
87275
87276/*
87277** Copy the current sorter key into the memory cell pOut.
87278*/
87279SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
87280  VdbeSorter *pSorter;
87281  void *pKey; int nKey;           /* Sorter key to copy into pOut */
87282
87283  assert( pCsr->eCurType==CURTYPE_SORTER );
87284  pSorter = pCsr->uc.pSorter;
87285  pKey = vdbeSorterRowkey(pSorter, &nKey);
87286  if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
87287    return SQLITE_NOMEM_BKPT;
87288  }
87289  pOut->n = nKey;
87290  MemSetTypeFlag(pOut, MEM_Blob);
87291  memcpy(pOut->z, pKey, nKey);
87292
87293  return SQLITE_OK;
87294}
87295
87296/*
87297** Compare the key in memory cell pVal with the key that the sorter cursor
87298** passed as the first argument currently points to. For the purposes of
87299** the comparison, ignore the rowid field at the end of each record.
87300**
87301** If the sorter cursor key contains any NULL values, consider it to be
87302** less than pVal. Even if pVal also contains NULL values.
87303**
87304** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
87305** Otherwise, set *pRes to a negative, zero or positive value if the
87306** key in pVal is smaller than, equal to or larger than the current sorter
87307** key.
87308**
87309** This routine forms the core of the OP_SorterCompare opcode, which in
87310** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
87311*/
87312SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
87313  const VdbeCursor *pCsr,         /* Sorter cursor */
87314  Mem *pVal,                      /* Value to compare to current sorter key */
87315  int nKeyCol,                    /* Compare this many columns */
87316  int *pRes                       /* OUT: Result of comparison */
87317){
87318  VdbeSorter *pSorter;
87319  UnpackedRecord *r2;
87320  KeyInfo *pKeyInfo;
87321  int i;
87322  void *pKey; int nKey;           /* Sorter key to compare pVal with */
87323
87324  assert( pCsr->eCurType==CURTYPE_SORTER );
87325  pSorter = pCsr->uc.pSorter;
87326  r2 = pSorter->pUnpacked;
87327  pKeyInfo = pCsr->pKeyInfo;
87328  if( r2==0 ){
87329    char *p;
87330    r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
87331    assert( pSorter->pUnpacked==(UnpackedRecord*)p );
87332    if( r2==0 ) return SQLITE_NOMEM_BKPT;
87333    r2->nField = nKeyCol;
87334  }
87335  assert( r2->nField==nKeyCol );
87336
87337  pKey = vdbeSorterRowkey(pSorter, &nKey);
87338  sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
87339  for(i=0; i<nKeyCol; i++){
87340    if( r2->aMem[i].flags & MEM_Null ){
87341      *pRes = -1;
87342      return SQLITE_OK;
87343    }
87344  }
87345
87346  *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
87347  return SQLITE_OK;
87348}
87349
87350/************** End of vdbesort.c ********************************************/
87351/************** Begin file memjournal.c **************************************/
87352/*
87353** 2008 October 7
87354**
87355** The author disclaims copyright to this source code.  In place of
87356** a legal notice, here is a blessing:
87357**
87358**    May you do good and not evil.
87359**    May you find forgiveness for yourself and forgive others.
87360**    May you share freely, never taking more than you give.
87361**
87362*************************************************************************
87363**
87364** This file contains code use to implement an in-memory rollback journal.
87365** The in-memory rollback journal is used to journal transactions for
87366** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
87367**
87368** Update:  The in-memory journal is also used to temporarily cache
87369** smaller journals that are not critical for power-loss recovery.
87370** For example, statement journals that are not too big will be held
87371** entirely in memory, thus reducing the number of file I/O calls, and
87372** more importantly, reducing temporary file creation events.  If these
87373** journals become too large for memory, they are spilled to disk.  But
87374** in the common case, they are usually small and no file I/O needs to
87375** occur.
87376*/
87377/* #include "sqliteInt.h" */
87378
87379/* Forward references to internal structures */
87380typedef struct MemJournal MemJournal;
87381typedef struct FilePoint FilePoint;
87382typedef struct FileChunk FileChunk;
87383
87384/*
87385** The rollback journal is composed of a linked list of these structures.
87386**
87387** The zChunk array is always at least 8 bytes in size - usually much more.
87388** Its actual size is stored in the MemJournal.nChunkSize variable.
87389*/
87390struct FileChunk {
87391  FileChunk *pNext;               /* Next chunk in the journal */
87392  u8 zChunk[8];                   /* Content of this chunk */
87393};
87394
87395/*
87396** By default, allocate this many bytes of memory for each FileChunk object.
87397*/
87398#define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
87399
87400/*
87401** For chunk size nChunkSize, return the number of bytes that should
87402** be allocated for each FileChunk structure.
87403*/
87404#define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
87405
87406/*
87407** An instance of this object serves as a cursor into the rollback journal.
87408** The cursor can be either for reading or writing.
87409*/
87410struct FilePoint {
87411  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
87412  FileChunk *pChunk;              /* Specific chunk into which cursor points */
87413};
87414
87415/*
87416** This structure is a subclass of sqlite3_file. Each open memory-journal
87417** is an instance of this class.
87418*/
87419struct MemJournal {
87420  const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
87421  int nChunkSize;                 /* In-memory chunk-size */
87422
87423  int nSpill;                     /* Bytes of data before flushing */
87424  int nSize;                      /* Bytes of data currently in memory */
87425  FileChunk *pFirst;              /* Head of in-memory chunk-list */
87426  FilePoint endpoint;             /* Pointer to the end of the file */
87427  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
87428
87429  int flags;                      /* xOpen flags */
87430  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
87431  const char *zJournal;           /* Name of the journal file */
87432};
87433
87434/*
87435** Read data from the in-memory journal file.  This is the implementation
87436** of the sqlite3_vfs.xRead method.
87437*/
87438static int memjrnlRead(
87439  sqlite3_file *pJfd,    /* The journal file from which to read */
87440  void *zBuf,            /* Put the results here */
87441  int iAmt,              /* Number of bytes to read */
87442  sqlite_int64 iOfst     /* Begin reading at this offset */
87443){
87444  MemJournal *p = (MemJournal *)pJfd;
87445  u8 *zOut = zBuf;
87446  int nRead = iAmt;
87447  int iChunkOffset;
87448  FileChunk *pChunk;
87449
87450#ifdef SQLITE_ENABLE_ATOMIC_WRITE
87451  if( (iAmt+iOfst)>p->endpoint.iOffset ){
87452    return SQLITE_IOERR_SHORT_READ;
87453  }
87454#endif
87455
87456  assert( (iAmt+iOfst)<=p->endpoint.iOffset );
87457  assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
87458  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
87459    sqlite3_int64 iOff = 0;
87460    for(pChunk=p->pFirst;
87461        ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
87462        pChunk=pChunk->pNext
87463    ){
87464      iOff += p->nChunkSize;
87465    }
87466  }else{
87467    pChunk = p->readpoint.pChunk;
87468    assert( pChunk!=0 );
87469  }
87470
87471  iChunkOffset = (int)(iOfst%p->nChunkSize);
87472  do {
87473    int iSpace = p->nChunkSize - iChunkOffset;
87474    int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
87475    memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
87476    zOut += nCopy;
87477    nRead -= iSpace;
87478    iChunkOffset = 0;
87479  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
87480  p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
87481  p->readpoint.pChunk = pChunk;
87482
87483  return SQLITE_OK;
87484}
87485
87486/*
87487** Free the list of FileChunk structures headed at MemJournal.pFirst.
87488*/
87489static void memjrnlFreeChunks(MemJournal *p){
87490  FileChunk *pIter;
87491  FileChunk *pNext;
87492  for(pIter=p->pFirst; pIter; pIter=pNext){
87493    pNext = pIter->pNext;
87494    sqlite3_free(pIter);
87495  }
87496  p->pFirst = 0;
87497}
87498
87499/*
87500** Flush the contents of memory to a real file on disk.
87501*/
87502static int memjrnlCreateFile(MemJournal *p){
87503  int rc;
87504  sqlite3_file *pReal = (sqlite3_file*)p;
87505  MemJournal copy = *p;
87506
87507  memset(p, 0, sizeof(MemJournal));
87508  rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
87509  if( rc==SQLITE_OK ){
87510    int nChunk = copy.nChunkSize;
87511    i64 iOff = 0;
87512    FileChunk *pIter;
87513    for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
87514      if( iOff + nChunk > copy.endpoint.iOffset ){
87515        nChunk = copy.endpoint.iOffset - iOff;
87516      }
87517      rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
87518      if( rc ) break;
87519      iOff += nChunk;
87520    }
87521    if( rc==SQLITE_OK ){
87522      /* No error has occurred. Free the in-memory buffers. */
87523      memjrnlFreeChunks(&copy);
87524    }
87525  }
87526  if( rc!=SQLITE_OK ){
87527    /* If an error occurred while creating or writing to the file, restore
87528    ** the original before returning. This way, SQLite uses the in-memory
87529    ** journal data to roll back changes made to the internal page-cache
87530    ** before this function was called.  */
87531    sqlite3OsClose(pReal);
87532    *p = copy;
87533  }
87534  return rc;
87535}
87536
87537
87538/*
87539** Write data to the file.
87540*/
87541static int memjrnlWrite(
87542  sqlite3_file *pJfd,    /* The journal file into which to write */
87543  const void *zBuf,      /* Take data to be written from here */
87544  int iAmt,              /* Number of bytes to write */
87545  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
87546){
87547  MemJournal *p = (MemJournal *)pJfd;
87548  int nWrite = iAmt;
87549  u8 *zWrite = (u8 *)zBuf;
87550
87551  /* If the file should be created now, create it and write the new data
87552  ** into the file on disk. */
87553  if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
87554    int rc = memjrnlCreateFile(p);
87555    if( rc==SQLITE_OK ){
87556      rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
87557    }
87558    return rc;
87559  }
87560
87561  /* If the contents of this write should be stored in memory */
87562  else{
87563    /* An in-memory journal file should only ever be appended to. Random
87564    ** access writes are not required. The only exception to this is when
87565    ** the in-memory journal is being used by a connection using the
87566    ** atomic-write optimization. In this case the first 28 bytes of the
87567    ** journal file may be written as part of committing the transaction. */
87568    assert( iOfst==p->endpoint.iOffset || iOfst==0 );
87569#ifdef SQLITE_ENABLE_ATOMIC_WRITE
87570    if( iOfst==0 && p->pFirst ){
87571      assert( p->nChunkSize>iAmt );
87572      memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
87573    }else
87574#else
87575    assert( iOfst>0 || p->pFirst==0 );
87576#endif
87577    {
87578      while( nWrite>0 ){
87579        FileChunk *pChunk = p->endpoint.pChunk;
87580        int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
87581        int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
87582
87583        if( iChunkOffset==0 ){
87584          /* New chunk is required to extend the file. */
87585          FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
87586          if( !pNew ){
87587            return SQLITE_IOERR_NOMEM_BKPT;
87588          }
87589          pNew->pNext = 0;
87590          if( pChunk ){
87591            assert( p->pFirst );
87592            pChunk->pNext = pNew;
87593          }else{
87594            assert( !p->pFirst );
87595            p->pFirst = pNew;
87596          }
87597          p->endpoint.pChunk = pNew;
87598        }
87599
87600        memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
87601        zWrite += iSpace;
87602        nWrite -= iSpace;
87603        p->endpoint.iOffset += iSpace;
87604      }
87605      p->nSize = iAmt + iOfst;
87606    }
87607  }
87608
87609  return SQLITE_OK;
87610}
87611
87612/*
87613** Truncate the file.
87614**
87615** If the journal file is already on disk, truncate it there. Or, if it
87616** is still in main memory but is being truncated to zero bytes in size,
87617** ignore
87618*/
87619static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
87620  MemJournal *p = (MemJournal *)pJfd;
87621  if( ALWAYS(size==0) ){
87622    memjrnlFreeChunks(p);
87623    p->nSize = 0;
87624    p->endpoint.pChunk = 0;
87625    p->endpoint.iOffset = 0;
87626    p->readpoint.pChunk = 0;
87627    p->readpoint.iOffset = 0;
87628  }
87629  return SQLITE_OK;
87630}
87631
87632/*
87633** Close the file.
87634*/
87635static int memjrnlClose(sqlite3_file *pJfd){
87636  MemJournal *p = (MemJournal *)pJfd;
87637  memjrnlFreeChunks(p);
87638  return SQLITE_OK;
87639}
87640
87641/*
87642** Sync the file.
87643**
87644** If the real file has been created, call its xSync method. Otherwise,
87645** syncing an in-memory journal is a no-op.
87646*/
87647static int memjrnlSync(sqlite3_file *pJfd, int flags){
87648  UNUSED_PARAMETER2(pJfd, flags);
87649  return SQLITE_OK;
87650}
87651
87652/*
87653** Query the size of the file in bytes.
87654*/
87655static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
87656  MemJournal *p = (MemJournal *)pJfd;
87657  *pSize = (sqlite_int64) p->endpoint.iOffset;
87658  return SQLITE_OK;
87659}
87660
87661/*
87662** Table of methods for MemJournal sqlite3_file object.
87663*/
87664static const struct sqlite3_io_methods MemJournalMethods = {
87665  1,                /* iVersion */
87666  memjrnlClose,     /* xClose */
87667  memjrnlRead,      /* xRead */
87668  memjrnlWrite,     /* xWrite */
87669  memjrnlTruncate,  /* xTruncate */
87670  memjrnlSync,      /* xSync */
87671  memjrnlFileSize,  /* xFileSize */
87672  0,                /* xLock */
87673  0,                /* xUnlock */
87674  0,                /* xCheckReservedLock */
87675  0,                /* xFileControl */
87676  0,                /* xSectorSize */
87677  0,                /* xDeviceCharacteristics */
87678  0,                /* xShmMap */
87679  0,                /* xShmLock */
87680  0,                /* xShmBarrier */
87681  0,                /* xShmUnmap */
87682  0,                /* xFetch */
87683  0                 /* xUnfetch */
87684};
87685
87686/*
87687** Open a journal file.
87688**
87689** The behaviour of the journal file depends on the value of parameter
87690** nSpill. If nSpill is 0, then the journal file is always create and
87691** accessed using the underlying VFS. If nSpill is less than zero, then
87692** all content is always stored in main-memory. Finally, if nSpill is a
87693** positive value, then the journal file is initially created in-memory
87694** but may be flushed to disk later on. In this case the journal file is
87695** flushed to disk either when it grows larger than nSpill bytes in size,
87696** or when sqlite3JournalCreate() is called.
87697*/
87698SQLITE_PRIVATE int sqlite3JournalOpen(
87699  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
87700  const char *zName,         /* Name of the journal file */
87701  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
87702  int flags,                 /* Opening flags */
87703  int nSpill                 /* Bytes buffered before opening the file */
87704){
87705  MemJournal *p = (MemJournal*)pJfd;
87706
87707  /* Zero the file-handle object. If nSpill was passed zero, initialize
87708  ** it using the sqlite3OsOpen() function of the underlying VFS. In this
87709  ** case none of the code in this module is executed as a result of calls
87710  ** made on the journal file-handle.  */
87711  memset(p, 0, sizeof(MemJournal));
87712  if( nSpill==0 ){
87713    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
87714  }
87715
87716  if( nSpill>0 ){
87717    p->nChunkSize = nSpill;
87718  }else{
87719    p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
87720    assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
87721  }
87722
87723  p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
87724  p->nSpill = nSpill;
87725  p->flags = flags;
87726  p->zJournal = zName;
87727  p->pVfs = pVfs;
87728  return SQLITE_OK;
87729}
87730
87731/*
87732** Open an in-memory journal file.
87733*/
87734SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
87735  sqlite3JournalOpen(0, 0, pJfd, 0, -1);
87736}
87737
87738#ifdef SQLITE_ENABLE_ATOMIC_WRITE
87739/*
87740** If the argument p points to a MemJournal structure that is not an
87741** in-memory-only journal file (i.e. is one that was opened with a +ve
87742** nSpill parameter), and the underlying file has not yet been created,
87743** create it now.
87744*/
87745SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
87746  int rc = SQLITE_OK;
87747  if( p->pMethods==&MemJournalMethods && ((MemJournal*)p)->nSpill>0 ){
87748    rc = memjrnlCreateFile((MemJournal*)p);
87749  }
87750  return rc;
87751}
87752#endif
87753
87754/*
87755** The file-handle passed as the only argument is open on a journal file.
87756** Return true if this "journal file" is currently stored in heap memory,
87757** or false otherwise.
87758*/
87759SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
87760  return p->pMethods==&MemJournalMethods;
87761}
87762
87763/*
87764** Return the number of bytes required to store a JournalFile that uses vfs
87765** pVfs to create the underlying on-disk files.
87766*/
87767SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
87768  return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
87769}
87770
87771/************** End of memjournal.c ******************************************/
87772/************** Begin file walker.c ******************************************/
87773/*
87774** 2008 August 16
87775**
87776** The author disclaims copyright to this source code.  In place of
87777** a legal notice, here is a blessing:
87778**
87779**    May you do good and not evil.
87780**    May you find forgiveness for yourself and forgive others.
87781**    May you share freely, never taking more than you give.
87782**
87783*************************************************************************
87784** This file contains routines used for walking the parser tree for
87785** an SQL statement.
87786*/
87787/* #include "sqliteInt.h" */
87788/* #include <stdlib.h> */
87789/* #include <string.h> */
87790
87791
87792/*
87793** Walk an expression tree.  Invoke the callback once for each node
87794** of the expression, while descending.  (In other words, the callback
87795** is invoked before visiting children.)
87796**
87797** The return value from the callback should be one of the WRC_*
87798** constants to specify how to proceed with the walk.
87799**
87800**    WRC_Continue      Continue descending down the tree.
87801**
87802**    WRC_Prune         Do not descend into child nodes.  But allow
87803**                      the walk to continue with sibling nodes.
87804**
87805**    WRC_Abort         Do no more callbacks.  Unwind the stack and
87806**                      return the top-level walk call.
87807**
87808** The return value from this routine is WRC_Abort to abandon the tree walk
87809** and WRC_Continue to continue.
87810*/
87811static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
87812  int rc;
87813  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
87814  testcase( ExprHasProperty(pExpr, EP_Reduced) );
87815  rc = pWalker->xExprCallback(pWalker, pExpr);
87816  if( rc==WRC_Continue
87817              && !ExprHasProperty(pExpr,EP_TokenOnly) ){
87818    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
87819    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
87820    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
87821      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
87822    }else{
87823      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
87824    }
87825  }
87826  return rc & WRC_Abort;
87827}
87828SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
87829  return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
87830}
87831
87832/*
87833** Call sqlite3WalkExpr() for every expression in list p or until
87834** an abort request is seen.
87835*/
87836SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
87837  int i;
87838  struct ExprList_item *pItem;
87839  if( p ){
87840    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
87841      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
87842    }
87843  }
87844  return WRC_Continue;
87845}
87846
87847/*
87848** Walk all expressions associated with SELECT statement p.  Do
87849** not invoke the SELECT callback on p, but do (of course) invoke
87850** any expr callbacks and SELECT callbacks that come from subqueries.
87851** Return WRC_Abort or WRC_Continue.
87852*/
87853SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
87854  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
87855  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
87856  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
87857  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
87858  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
87859  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
87860  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
87861  return WRC_Continue;
87862}
87863
87864/*
87865** Walk the parse trees associated with all subqueries in the
87866** FROM clause of SELECT statement p.  Do not invoke the select
87867** callback on p, but do invoke it on each FROM clause subquery
87868** and on any subqueries further down in the tree.  Return
87869** WRC_Abort or WRC_Continue;
87870*/
87871SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
87872  SrcList *pSrc;
87873  int i;
87874  struct SrcList_item *pItem;
87875
87876  pSrc = p->pSrc;
87877  if( ALWAYS(pSrc) ){
87878    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
87879      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
87880        return WRC_Abort;
87881      }
87882      if( pItem->fg.isTabFunc
87883       && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
87884      ){
87885        return WRC_Abort;
87886      }
87887    }
87888  }
87889  return WRC_Continue;
87890}
87891
87892/*
87893** Call sqlite3WalkExpr() for every expression in Select statement p.
87894** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
87895** on the compound select chain, p->pPrior.
87896**
87897** If it is not NULL, the xSelectCallback() callback is invoked before
87898** the walk of the expressions and FROM clause. The xSelectCallback2()
87899** method, if it is not NULL, is invoked following the walk of the
87900** expressions and FROM clause.
87901**
87902** Return WRC_Continue under normal conditions.  Return WRC_Abort if
87903** there is an abort request.
87904**
87905** If the Walker does not have an xSelectCallback() then this routine
87906** is a no-op returning WRC_Continue.
87907*/
87908SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
87909  int rc;
87910  if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
87911    return WRC_Continue;
87912  }
87913  rc = WRC_Continue;
87914  pWalker->walkerDepth++;
87915  while( p ){
87916    if( pWalker->xSelectCallback ){
87917       rc = pWalker->xSelectCallback(pWalker, p);
87918       if( rc ) break;
87919    }
87920    if( sqlite3WalkSelectExpr(pWalker, p)
87921     || sqlite3WalkSelectFrom(pWalker, p)
87922    ){
87923      pWalker->walkerDepth--;
87924      return WRC_Abort;
87925    }
87926    if( pWalker->xSelectCallback2 ){
87927      pWalker->xSelectCallback2(pWalker, p);
87928    }
87929    p = p->pPrior;
87930  }
87931  pWalker->walkerDepth--;
87932  return rc & WRC_Abort;
87933}
87934
87935/************** End of walker.c **********************************************/
87936/************** Begin file resolve.c *****************************************/
87937/*
87938** 2008 August 18
87939**
87940** The author disclaims copyright to this source code.  In place of
87941** a legal notice, here is a blessing:
87942**
87943**    May you do good and not evil.
87944**    May you find forgiveness for yourself and forgive others.
87945**    May you share freely, never taking more than you give.
87946**
87947*************************************************************************
87948**
87949** This file contains routines used for walking the parser tree and
87950** resolve all identifiers by associating them with a particular
87951** table and column.
87952*/
87953/* #include "sqliteInt.h" */
87954/* #include <stdlib.h> */
87955/* #include <string.h> */
87956
87957/*
87958** Walk the expression tree pExpr and increase the aggregate function
87959** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
87960** This needs to occur when copying a TK_AGG_FUNCTION node from an
87961** outer query into an inner subquery.
87962**
87963** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
87964** is a helper function - a callback for the tree walker.
87965*/
87966static int incrAggDepth(Walker *pWalker, Expr *pExpr){
87967  if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
87968  return WRC_Continue;
87969}
87970static void incrAggFunctionDepth(Expr *pExpr, int N){
87971  if( N>0 ){
87972    Walker w;
87973    memset(&w, 0, sizeof(w));
87974    w.xExprCallback = incrAggDepth;
87975    w.u.n = N;
87976    sqlite3WalkExpr(&w, pExpr);
87977  }
87978}
87979
87980/*
87981** Turn the pExpr expression into an alias for the iCol-th column of the
87982** result set in pEList.
87983**
87984** If the reference is followed by a COLLATE operator, then make sure
87985** the COLLATE operator is preserved.  For example:
87986**
87987**     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
87988**
87989** Should be transformed into:
87990**
87991**     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
87992**
87993** The nSubquery parameter specifies how many levels of subquery the
87994** alias is removed from the original expression.  The usual value is
87995** zero but it might be more if the alias is contained within a subquery
87996** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
87997** structures must be increased by the nSubquery amount.
87998*/
87999static void resolveAlias(
88000  Parse *pParse,         /* Parsing context */
88001  ExprList *pEList,      /* A result set */
88002  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
88003  Expr *pExpr,           /* Transform this into an alias to the result set */
88004  const char *zType,     /* "GROUP" or "ORDER" or "" */
88005  int nSubquery          /* Number of subqueries that the label is moving */
88006){
88007  Expr *pOrig;           /* The iCol-th column of the result set */
88008  Expr *pDup;            /* Copy of pOrig */
88009  sqlite3 *db;           /* The database connection */
88010
88011  assert( iCol>=0 && iCol<pEList->nExpr );
88012  pOrig = pEList->a[iCol].pExpr;
88013  assert( pOrig!=0 );
88014  db = pParse->db;
88015  pDup = sqlite3ExprDup(db, pOrig, 0);
88016  if( pDup==0 ) return;
88017  if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
88018  if( pExpr->op==TK_COLLATE ){
88019    pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
88020  }
88021  ExprSetProperty(pDup, EP_Alias);
88022
88023  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
88024  ** prevents ExprDelete() from deleting the Expr structure itself,
88025  ** allowing it to be repopulated by the memcpy() on the following line.
88026  ** The pExpr->u.zToken might point into memory that will be freed by the
88027  ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
88028  ** make a copy of the token before doing the sqlite3DbFree().
88029  */
88030  ExprSetProperty(pExpr, EP_Static);
88031  sqlite3ExprDelete(db, pExpr);
88032  memcpy(pExpr, pDup, sizeof(*pExpr));
88033  if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
88034    assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
88035    pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
88036    pExpr->flags |= EP_MemToken;
88037  }
88038  sqlite3DbFree(db, pDup);
88039}
88040
88041
88042/*
88043** Return TRUE if the name zCol occurs anywhere in the USING clause.
88044**
88045** Return FALSE if the USING clause is NULL or if it does not contain
88046** zCol.
88047*/
88048static int nameInUsingClause(IdList *pUsing, const char *zCol){
88049  if( pUsing ){
88050    int k;
88051    for(k=0; k<pUsing->nId; k++){
88052      if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
88053    }
88054  }
88055  return 0;
88056}
88057
88058/*
88059** Subqueries stores the original database, table and column names for their
88060** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
88061** Check to see if the zSpan given to this routine matches the zDb, zTab,
88062** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
88063** match anything.
88064*/
88065SQLITE_PRIVATE int sqlite3MatchSpanName(
88066  const char *zSpan,
88067  const char *zCol,
88068  const char *zTab,
88069  const char *zDb
88070){
88071  int n;
88072  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
88073  if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
88074    return 0;
88075  }
88076  zSpan += n+1;
88077  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
88078  if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
88079    return 0;
88080  }
88081  zSpan += n+1;
88082  if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
88083    return 0;
88084  }
88085  return 1;
88086}
88087
88088/*
88089** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
88090** that name in the set of source tables in pSrcList and make the pExpr
88091** expression node refer back to that source column.  The following changes
88092** are made to pExpr:
88093**
88094**    pExpr->iDb           Set the index in db->aDb[] of the database X
88095**                         (even if X is implied).
88096**    pExpr->iTable        Set to the cursor number for the table obtained
88097**                         from pSrcList.
88098**    pExpr->pTab          Points to the Table structure of X.Y (even if
88099**                         X and/or Y are implied.)
88100**    pExpr->iColumn       Set to the column number within the table.
88101**    pExpr->op            Set to TK_COLUMN.
88102**    pExpr->pLeft         Any expression this points to is deleted
88103**    pExpr->pRight        Any expression this points to is deleted.
88104**
88105** The zDb variable is the name of the database (the "X").  This value may be
88106** NULL meaning that name is of the form Y.Z or Z.  Any available database
88107** can be used.  The zTable variable is the name of the table (the "Y").  This
88108** value can be NULL if zDb is also NULL.  If zTable is NULL it
88109** means that the form of the name is Z and that columns from any table
88110** can be used.
88111**
88112** If the name cannot be resolved unambiguously, leave an error message
88113** in pParse and return WRC_Abort.  Return WRC_Prune on success.
88114*/
88115static int lookupName(
88116  Parse *pParse,       /* The parsing context */
88117  const char *zDb,     /* Name of the database containing table, or NULL */
88118  const char *zTab,    /* Name of table containing column, or NULL */
88119  const char *zCol,    /* Name of the column. */
88120  NameContext *pNC,    /* The name context used to resolve the name */
88121  Expr *pExpr          /* Make this EXPR node point to the selected column */
88122){
88123  int i, j;                         /* Loop counters */
88124  int cnt = 0;                      /* Number of matching column names */
88125  int cntTab = 0;                   /* Number of matching table names */
88126  int nSubquery = 0;                /* How many levels of subquery */
88127  sqlite3 *db = pParse->db;         /* The database connection */
88128  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
88129  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
88130  NameContext *pTopNC = pNC;        /* First namecontext in the list */
88131  Schema *pSchema = 0;              /* Schema of the expression */
88132  int isTrigger = 0;                /* True if resolved to a trigger column */
88133  Table *pTab = 0;                  /* Table hold the row */
88134  Column *pCol;                     /* A column of pTab */
88135
88136  assert( pNC );     /* the name context cannot be NULL. */
88137  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
88138  assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
88139
88140  /* Initialize the node to no-match */
88141  pExpr->iTable = -1;
88142  pExpr->pTab = 0;
88143  ExprSetVVAProperty(pExpr, EP_NoReduce);
88144
88145  /* Translate the schema name in zDb into a pointer to the corresponding
88146  ** schema.  If not found, pSchema will remain NULL and nothing will match
88147  ** resulting in an appropriate error message toward the end of this routine
88148  */
88149  if( zDb ){
88150    testcase( pNC->ncFlags & NC_PartIdx );
88151    testcase( pNC->ncFlags & NC_IsCheck );
88152    if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
88153      /* Silently ignore database qualifiers inside CHECK constraints and
88154      ** partial indices.  Do not raise errors because that might break
88155      ** legacy and because it does not hurt anything to just ignore the
88156      ** database name. */
88157      zDb = 0;
88158    }else{
88159      for(i=0; i<db->nDb; i++){
88160        assert( db->aDb[i].zName );
88161        if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
88162          pSchema = db->aDb[i].pSchema;
88163          break;
88164        }
88165      }
88166    }
88167  }
88168
88169  /* Start at the inner-most context and move outward until a match is found */
88170  while( pNC && cnt==0 ){
88171    ExprList *pEList;
88172    SrcList *pSrcList = pNC->pSrcList;
88173
88174    if( pSrcList ){
88175      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
88176        pTab = pItem->pTab;
88177        assert( pTab!=0 && pTab->zName!=0 );
88178        assert( pTab->nCol>0 );
88179        if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
88180          int hit = 0;
88181          pEList = pItem->pSelect->pEList;
88182          for(j=0; j<pEList->nExpr; j++){
88183            if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
88184              cnt++;
88185              cntTab = 2;
88186              pMatch = pItem;
88187              pExpr->iColumn = j;
88188              hit = 1;
88189            }
88190          }
88191          if( hit || zTab==0 ) continue;
88192        }
88193        if( zDb && pTab->pSchema!=pSchema ){
88194          continue;
88195        }
88196        if( zTab ){
88197          const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
88198          assert( zTabName!=0 );
88199          if( sqlite3StrICmp(zTabName, zTab)!=0 ){
88200            continue;
88201          }
88202        }
88203        if( 0==(cntTab++) ){
88204          pMatch = pItem;
88205        }
88206        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
88207          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
88208            /* If there has been exactly one prior match and this match
88209            ** is for the right-hand table of a NATURAL JOIN or is in a
88210            ** USING clause, then skip this match.
88211            */
88212            if( cnt==1 ){
88213              if( pItem->fg.jointype & JT_NATURAL ) continue;
88214              if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
88215            }
88216            cnt++;
88217            pMatch = pItem;
88218            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
88219            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
88220            break;
88221          }
88222        }
88223      }
88224      if( pMatch ){
88225        pExpr->iTable = pMatch->iCursor;
88226        pExpr->pTab = pMatch->pTab;
88227        /* RIGHT JOIN not (yet) supported */
88228        assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
88229        if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
88230          ExprSetProperty(pExpr, EP_CanBeNull);
88231        }
88232        pSchema = pExpr->pTab->pSchema;
88233      }
88234    } /* if( pSrcList ) */
88235
88236#ifndef SQLITE_OMIT_TRIGGER
88237    /* If we have not already resolved the name, then maybe
88238    ** it is a new.* or old.* trigger argument reference
88239    */
88240    if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
88241      int op = pParse->eTriggerOp;
88242      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
88243      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
88244        pExpr->iTable = 1;
88245        pTab = pParse->pTriggerTab;
88246      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
88247        pExpr->iTable = 0;
88248        pTab = pParse->pTriggerTab;
88249      }else{
88250        pTab = 0;
88251      }
88252
88253      if( pTab ){
88254        int iCol;
88255        pSchema = pTab->pSchema;
88256        cntTab++;
88257        for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
88258          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
88259            if( iCol==pTab->iPKey ){
88260              iCol = -1;
88261            }
88262            break;
88263          }
88264        }
88265        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
88266          /* IMP: R-51414-32910 */
88267          iCol = -1;
88268        }
88269        if( iCol<pTab->nCol ){
88270          cnt++;
88271          if( iCol<0 ){
88272            pExpr->affinity = SQLITE_AFF_INTEGER;
88273          }else if( pExpr->iTable==0 ){
88274            testcase( iCol==31 );
88275            testcase( iCol==32 );
88276            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
88277          }else{
88278            testcase( iCol==31 );
88279            testcase( iCol==32 );
88280            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
88281          }
88282          pExpr->iColumn = (i16)iCol;
88283          pExpr->pTab = pTab;
88284          isTrigger = 1;
88285        }
88286      }
88287    }
88288#endif /* !defined(SQLITE_OMIT_TRIGGER) */
88289
88290    /*
88291    ** Perhaps the name is a reference to the ROWID
88292    */
88293    if( cnt==0
88294     && cntTab==1
88295     && pMatch
88296     && (pNC->ncFlags & NC_IdxExpr)==0
88297     && sqlite3IsRowid(zCol)
88298     && VisibleRowid(pMatch->pTab)
88299    ){
88300      cnt = 1;
88301      pExpr->iColumn = -1;
88302      pExpr->affinity = SQLITE_AFF_INTEGER;
88303    }
88304
88305    /*
88306    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
88307    ** might refer to an result-set alias.  This happens, for example, when
88308    ** we are resolving names in the WHERE clause of the following command:
88309    **
88310    **     SELECT a+b AS x FROM table WHERE x<10;
88311    **
88312    ** In cases like this, replace pExpr with a copy of the expression that
88313    ** forms the result set entry ("a+b" in the example) and return immediately.
88314    ** Note that the expression in the result set should have already been
88315    ** resolved by the time the WHERE clause is resolved.
88316    **
88317    ** The ability to use an output result-set column in the WHERE, GROUP BY,
88318    ** or HAVING clauses, or as part of a larger expression in the ORDER BY
88319    ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
88320    ** is supported for backwards compatibility only. Hence, we issue a warning
88321    ** on sqlite3_log() whenever the capability is used.
88322    */
88323    if( (pEList = pNC->pEList)!=0
88324     && zTab==0
88325     && cnt==0
88326    ){
88327      for(j=0; j<pEList->nExpr; j++){
88328        char *zAs = pEList->a[j].zName;
88329        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
88330          Expr *pOrig;
88331          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
88332          assert( pExpr->x.pList==0 );
88333          assert( pExpr->x.pSelect==0 );
88334          pOrig = pEList->a[j].pExpr;
88335          if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
88336            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
88337            return WRC_Abort;
88338          }
88339          resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
88340          cnt = 1;
88341          pMatch = 0;
88342          assert( zTab==0 && zDb==0 );
88343          goto lookupname_end;
88344        }
88345      }
88346    }
88347
88348    /* Advance to the next name context.  The loop will exit when either
88349    ** we have a match (cnt>0) or when we run out of name contexts.
88350    */
88351    if( cnt==0 ){
88352      pNC = pNC->pNext;
88353      nSubquery++;
88354    }
88355  }
88356
88357  /*
88358  ** If X and Y are NULL (in other words if only the column name Z is
88359  ** supplied) and the value of Z is enclosed in double-quotes, then
88360  ** Z is a string literal if it doesn't match any column names.  In that
88361  ** case, we need to return right away and not make any changes to
88362  ** pExpr.
88363  **
88364  ** Because no reference was made to outer contexts, the pNC->nRef
88365  ** fields are not changed in any context.
88366  */
88367  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
88368    pExpr->op = TK_STRING;
88369    pExpr->pTab = 0;
88370    return WRC_Prune;
88371  }
88372
88373  /*
88374  ** cnt==0 means there was not match.  cnt>1 means there were two or
88375  ** more matches.  Either way, we have an error.
88376  */
88377  if( cnt!=1 ){
88378    const char *zErr;
88379    zErr = cnt==0 ? "no such column" : "ambiguous column name";
88380    if( zDb ){
88381      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
88382    }else if( zTab ){
88383      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
88384    }else{
88385      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
88386    }
88387    pParse->checkSchema = 1;
88388    pTopNC->nErr++;
88389  }
88390
88391  /* If a column from a table in pSrcList is referenced, then record
88392  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
88393  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
88394  ** column number is greater than the number of bits in the bitmask
88395  ** then set the high-order bit of the bitmask.
88396  */
88397  if( pExpr->iColumn>=0 && pMatch!=0 ){
88398    int n = pExpr->iColumn;
88399    testcase( n==BMS-1 );
88400    if( n>=BMS ){
88401      n = BMS-1;
88402    }
88403    assert( pMatch->iCursor==pExpr->iTable );
88404    pMatch->colUsed |= ((Bitmask)1)<<n;
88405  }
88406
88407  /* Clean up and return
88408  */
88409  sqlite3ExprDelete(db, pExpr->pLeft);
88410  pExpr->pLeft = 0;
88411  sqlite3ExprDelete(db, pExpr->pRight);
88412  pExpr->pRight = 0;
88413  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
88414lookupname_end:
88415  if( cnt==1 ){
88416    assert( pNC!=0 );
88417    if( !ExprHasProperty(pExpr, EP_Alias) ){
88418      sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
88419    }
88420    /* Increment the nRef value on all name contexts from TopNC up to
88421    ** the point where the name matched. */
88422    for(;;){
88423      assert( pTopNC!=0 );
88424      pTopNC->nRef++;
88425      if( pTopNC==pNC ) break;
88426      pTopNC = pTopNC->pNext;
88427    }
88428    return WRC_Prune;
88429  } else {
88430    return WRC_Abort;
88431  }
88432}
88433
88434/*
88435** Allocate and return a pointer to an expression to load the column iCol
88436** from datasource iSrc in SrcList pSrc.
88437*/
88438SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
88439  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
88440  if( p ){
88441    struct SrcList_item *pItem = &pSrc->a[iSrc];
88442    p->pTab = pItem->pTab;
88443    p->iTable = pItem->iCursor;
88444    if( p->pTab->iPKey==iCol ){
88445      p->iColumn = -1;
88446    }else{
88447      p->iColumn = (ynVar)iCol;
88448      testcase( iCol==BMS );
88449      testcase( iCol==BMS-1 );
88450      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
88451    }
88452    ExprSetProperty(p, EP_Resolved);
88453  }
88454  return p;
88455}
88456
88457/*
88458** Report an error that an expression is not valid for some set of
88459** pNC->ncFlags values determined by validMask.
88460*/
88461static void notValid(
88462  Parse *pParse,       /* Leave error message here */
88463  NameContext *pNC,    /* The name context */
88464  const char *zMsg,    /* Type of error */
88465  int validMask        /* Set of contexts for which prohibited */
88466){
88467  assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
88468  if( (pNC->ncFlags & validMask)!=0 ){
88469    const char *zIn = "partial index WHERE clauses";
88470    if( pNC->ncFlags & NC_IdxExpr )      zIn = "index expressions";
88471#ifndef SQLITE_OMIT_CHECK
88472    else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
88473#endif
88474    sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
88475  }
88476}
88477
88478/*
88479** Expression p should encode a floating point value between 1.0 and 0.0.
88480** Return 1024 times this value.  Or return -1 if p is not a floating point
88481** value between 1.0 and 0.0.
88482*/
88483static int exprProbability(Expr *p){
88484  double r = -1.0;
88485  if( p->op!=TK_FLOAT ) return -1;
88486  sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
88487  assert( r>=0.0 );
88488  if( r>1.0 ) return -1;
88489  return (int)(r*134217728.0);
88490}
88491
88492/*
88493** This routine is callback for sqlite3WalkExpr().
88494**
88495** Resolve symbolic names into TK_COLUMN operators for the current
88496** node in the expression tree.  Return 0 to continue the search down
88497** the tree or 2 to abort the tree walk.
88498**
88499** This routine also does error checking and name resolution for
88500** function names.  The operator for aggregate functions is changed
88501** to TK_AGG_FUNCTION.
88502*/
88503static int resolveExprStep(Walker *pWalker, Expr *pExpr){
88504  NameContext *pNC;
88505  Parse *pParse;
88506
88507  pNC = pWalker->u.pNC;
88508  assert( pNC!=0 );
88509  pParse = pNC->pParse;
88510  assert( pParse==pWalker->pParse );
88511
88512  if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
88513  ExprSetProperty(pExpr, EP_Resolved);
88514#ifndef NDEBUG
88515  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
88516    SrcList *pSrcList = pNC->pSrcList;
88517    int i;
88518    for(i=0; i<pNC->pSrcList->nSrc; i++){
88519      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
88520    }
88521  }
88522#endif
88523  switch( pExpr->op ){
88524
88525#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
88526    /* The special operator TK_ROW means use the rowid for the first
88527    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
88528    ** clause processing on UPDATE and DELETE statements.
88529    */
88530    case TK_ROW: {
88531      SrcList *pSrcList = pNC->pSrcList;
88532      struct SrcList_item *pItem;
88533      assert( pSrcList && pSrcList->nSrc==1 );
88534      pItem = pSrcList->a;
88535      pExpr->op = TK_COLUMN;
88536      pExpr->pTab = pItem->pTab;
88537      pExpr->iTable = pItem->iCursor;
88538      pExpr->iColumn = -1;
88539      pExpr->affinity = SQLITE_AFF_INTEGER;
88540      break;
88541    }
88542#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
88543          && !defined(SQLITE_OMIT_SUBQUERY) */
88544
88545    /* A lone identifier is the name of a column.
88546    */
88547    case TK_ID: {
88548      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
88549    }
88550
88551    /* A table name and column name:     ID.ID
88552    ** Or a database, table and column:  ID.ID.ID
88553    */
88554    case TK_DOT: {
88555      const char *zColumn;
88556      const char *zTable;
88557      const char *zDb;
88558      Expr *pRight;
88559
88560      /* if( pSrcList==0 ) break; */
88561      notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
88562      /*notValid(pParse, pNC, "the \".\" operator", NC_PartIdx|NC_IsCheck, 1);*/
88563      pRight = pExpr->pRight;
88564      if( pRight->op==TK_ID ){
88565        zDb = 0;
88566        zTable = pExpr->pLeft->u.zToken;
88567        zColumn = pRight->u.zToken;
88568      }else{
88569        assert( pRight->op==TK_DOT );
88570        zDb = pExpr->pLeft->u.zToken;
88571        zTable = pRight->pLeft->u.zToken;
88572        zColumn = pRight->pRight->u.zToken;
88573      }
88574      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
88575    }
88576
88577    /* Resolve function names
88578    */
88579    case TK_FUNCTION: {
88580      ExprList *pList = pExpr->x.pList;    /* The argument list */
88581      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
88582      int no_such_func = 0;       /* True if no such function exists */
88583      int wrong_num_args = 0;     /* True if wrong number of arguments */
88584      int is_agg = 0;             /* True if is an aggregate function */
88585      int auth;                   /* Authorization to use the function */
88586      int nId;                    /* Number of characters in function name */
88587      const char *zId;            /* The function name. */
88588      FuncDef *pDef;              /* Information about the function */
88589      u8 enc = ENC(pParse->db);   /* The database encoding */
88590
88591      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
88592      notValid(pParse, pNC, "functions", NC_PartIdx);
88593      zId = pExpr->u.zToken;
88594      nId = sqlite3Strlen30(zId);
88595      pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
88596      if( pDef==0 ){
88597        pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
88598        if( pDef==0 ){
88599          no_such_func = 1;
88600        }else{
88601          wrong_num_args = 1;
88602        }
88603      }else{
88604        is_agg = pDef->xFinalize!=0;
88605        if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
88606          ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
88607          if( n==2 ){
88608            pExpr->iTable = exprProbability(pList->a[1].pExpr);
88609            if( pExpr->iTable<0 ){
88610              sqlite3ErrorMsg(pParse,
88611                "second argument to likelihood() must be a "
88612                "constant between 0.0 and 1.0");
88613              pNC->nErr++;
88614            }
88615          }else{
88616            /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
88617            ** equivalent to likelihood(X, 0.0625).
88618            ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
88619            ** short-hand for likelihood(X,0.0625).
88620            ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
88621            ** for likelihood(X,0.9375).
88622            ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
88623            ** to likelihood(X,0.9375). */
88624            /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
88625            pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
88626          }
88627        }
88628#ifndef SQLITE_OMIT_AUTHORIZATION
88629        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
88630        if( auth!=SQLITE_OK ){
88631          if( auth==SQLITE_DENY ){
88632            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
88633                                    pDef->zName);
88634            pNC->nErr++;
88635          }
88636          pExpr->op = TK_NULL;
88637          return WRC_Prune;
88638        }
88639#endif
88640        if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
88641          /* For the purposes of the EP_ConstFunc flag, date and time
88642          ** functions and other functions that change slowly are considered
88643          ** constant because they are constant for the duration of one query */
88644          ExprSetProperty(pExpr,EP_ConstFunc);
88645        }
88646        if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
88647          /* Date/time functions that use 'now', and other functions like
88648          ** sqlite_version() that might change over time cannot be used
88649          ** in an index. */
88650          notValid(pParse, pNC, "non-deterministic functions", NC_IdxExpr);
88651        }
88652      }
88653      if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
88654        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
88655        pNC->nErr++;
88656        is_agg = 0;
88657      }else if( no_such_func && pParse->db->init.busy==0
88658#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
88659                && pParse->explain==0
88660#endif
88661      ){
88662        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
88663        pNC->nErr++;
88664      }else if( wrong_num_args ){
88665        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
88666             nId, zId);
88667        pNC->nErr++;
88668      }
88669      if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
88670      sqlite3WalkExprList(pWalker, pList);
88671      if( is_agg ){
88672        NameContext *pNC2 = pNC;
88673        pExpr->op = TK_AGG_FUNCTION;
88674        pExpr->op2 = 0;
88675        while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
88676          pExpr->op2++;
88677          pNC2 = pNC2->pNext;
88678        }
88679        assert( pDef!=0 );
88680        if( pNC2 ){
88681          assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
88682          testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
88683          pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
88684
88685        }
88686        pNC->ncFlags |= NC_AllowAgg;
88687      }
88688      /* FIX ME:  Compute pExpr->affinity based on the expected return
88689      ** type of the function
88690      */
88691      return WRC_Prune;
88692    }
88693#ifndef SQLITE_OMIT_SUBQUERY
88694    case TK_SELECT:
88695    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
88696#endif
88697    case TK_IN: {
88698      testcase( pExpr->op==TK_IN );
88699      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
88700        int nRef = pNC->nRef;
88701        notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
88702        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
88703        assert( pNC->nRef>=nRef );
88704        if( nRef!=pNC->nRef ){
88705          ExprSetProperty(pExpr, EP_VarSelect);
88706          pNC->ncFlags |= NC_VarSelect;
88707        }
88708      }
88709      break;
88710    }
88711    case TK_VARIABLE: {
88712      notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
88713      break;
88714    }
88715  }
88716  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
88717}
88718
88719/*
88720** pEList is a list of expressions which are really the result set of the
88721** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
88722** This routine checks to see if pE is a simple identifier which corresponds
88723** to the AS-name of one of the terms of the expression list.  If it is,
88724** this routine return an integer between 1 and N where N is the number of
88725** elements in pEList, corresponding to the matching entry.  If there is
88726** no match, or if pE is not a simple identifier, then this routine
88727** return 0.
88728**
88729** pEList has been resolved.  pE has not.
88730*/
88731static int resolveAsName(
88732  Parse *pParse,     /* Parsing context for error messages */
88733  ExprList *pEList,  /* List of expressions to scan */
88734  Expr *pE           /* Expression we are trying to match */
88735){
88736  int i;             /* Loop counter */
88737
88738  UNUSED_PARAMETER(pParse);
88739
88740  if( pE->op==TK_ID ){
88741    char *zCol = pE->u.zToken;
88742    for(i=0; i<pEList->nExpr; i++){
88743      char *zAs = pEList->a[i].zName;
88744      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
88745        return i+1;
88746      }
88747    }
88748  }
88749  return 0;
88750}
88751
88752/*
88753** pE is a pointer to an expression which is a single term in the
88754** ORDER BY of a compound SELECT.  The expression has not been
88755** name resolved.
88756**
88757** At the point this routine is called, we already know that the
88758** ORDER BY term is not an integer index into the result set.  That
88759** case is handled by the calling routine.
88760**
88761** Attempt to match pE against result set columns in the left-most
88762** SELECT statement.  Return the index i of the matching column,
88763** as an indication to the caller that it should sort by the i-th column.
88764** The left-most column is 1.  In other words, the value returned is the
88765** same integer value that would be used in the SQL statement to indicate
88766** the column.
88767**
88768** If there is no match, return 0.  Return -1 if an error occurs.
88769*/
88770static int resolveOrderByTermToExprList(
88771  Parse *pParse,     /* Parsing context for error messages */
88772  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
88773  Expr *pE           /* The specific ORDER BY term */
88774){
88775  int i;             /* Loop counter */
88776  ExprList *pEList;  /* The columns of the result set */
88777  NameContext nc;    /* Name context for resolving pE */
88778  sqlite3 *db;       /* Database connection */
88779  int rc;            /* Return code from subprocedures */
88780  u8 savedSuppErr;   /* Saved value of db->suppressErr */
88781
88782  assert( sqlite3ExprIsInteger(pE, &i)==0 );
88783  pEList = pSelect->pEList;
88784
88785  /* Resolve all names in the ORDER BY term expression
88786  */
88787  memset(&nc, 0, sizeof(nc));
88788  nc.pParse = pParse;
88789  nc.pSrcList = pSelect->pSrc;
88790  nc.pEList = pEList;
88791  nc.ncFlags = NC_AllowAgg;
88792  nc.nErr = 0;
88793  db = pParse->db;
88794  savedSuppErr = db->suppressErr;
88795  db->suppressErr = 1;
88796  rc = sqlite3ResolveExprNames(&nc, pE);
88797  db->suppressErr = savedSuppErr;
88798  if( rc ) return 0;
88799
88800  /* Try to match the ORDER BY expression against an expression
88801  ** in the result set.  Return an 1-based index of the matching
88802  ** result-set entry.
88803  */
88804  for(i=0; i<pEList->nExpr; i++){
88805    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
88806      return i+1;
88807    }
88808  }
88809
88810  /* If no match, return 0. */
88811  return 0;
88812}
88813
88814/*
88815** Generate an ORDER BY or GROUP BY term out-of-range error.
88816*/
88817static void resolveOutOfRangeError(
88818  Parse *pParse,         /* The error context into which to write the error */
88819  const char *zType,     /* "ORDER" or "GROUP" */
88820  int i,                 /* The index (1-based) of the term out of range */
88821  int mx                 /* Largest permissible value of i */
88822){
88823  sqlite3ErrorMsg(pParse,
88824    "%r %s BY term out of range - should be "
88825    "between 1 and %d", i, zType, mx);
88826}
88827
88828/*
88829** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
88830** each term of the ORDER BY clause is a constant integer between 1
88831** and N where N is the number of columns in the compound SELECT.
88832**
88833** ORDER BY terms that are already an integer between 1 and N are
88834** unmodified.  ORDER BY terms that are integers outside the range of
88835** 1 through N generate an error.  ORDER BY terms that are expressions
88836** are matched against result set expressions of compound SELECT
88837** beginning with the left-most SELECT and working toward the right.
88838** At the first match, the ORDER BY expression is transformed into
88839** the integer column number.
88840**
88841** Return the number of errors seen.
88842*/
88843static int resolveCompoundOrderBy(
88844  Parse *pParse,        /* Parsing context.  Leave error messages here */
88845  Select *pSelect       /* The SELECT statement containing the ORDER BY */
88846){
88847  int i;
88848  ExprList *pOrderBy;
88849  ExprList *pEList;
88850  sqlite3 *db;
88851  int moreToDo = 1;
88852
88853  pOrderBy = pSelect->pOrderBy;
88854  if( pOrderBy==0 ) return 0;
88855  db = pParse->db;
88856#if SQLITE_MAX_COLUMN
88857  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
88858    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
88859    return 1;
88860  }
88861#endif
88862  for(i=0; i<pOrderBy->nExpr; i++){
88863    pOrderBy->a[i].done = 0;
88864  }
88865  pSelect->pNext = 0;
88866  while( pSelect->pPrior ){
88867    pSelect->pPrior->pNext = pSelect;
88868    pSelect = pSelect->pPrior;
88869  }
88870  while( pSelect && moreToDo ){
88871    struct ExprList_item *pItem;
88872    moreToDo = 0;
88873    pEList = pSelect->pEList;
88874    assert( pEList!=0 );
88875    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
88876      int iCol = -1;
88877      Expr *pE, *pDup;
88878      if( pItem->done ) continue;
88879      pE = sqlite3ExprSkipCollate(pItem->pExpr);
88880      if( sqlite3ExprIsInteger(pE, &iCol) ){
88881        if( iCol<=0 || iCol>pEList->nExpr ){
88882          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
88883          return 1;
88884        }
88885      }else{
88886        iCol = resolveAsName(pParse, pEList, pE);
88887        if( iCol==0 ){
88888          pDup = sqlite3ExprDup(db, pE, 0);
88889          if( !db->mallocFailed ){
88890            assert(pDup);
88891            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
88892          }
88893          sqlite3ExprDelete(db, pDup);
88894        }
88895      }
88896      if( iCol>0 ){
88897        /* Convert the ORDER BY term into an integer column number iCol,
88898        ** taking care to preserve the COLLATE clause if it exists */
88899        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
88900        if( pNew==0 ) return 1;
88901        pNew->flags |= EP_IntValue;
88902        pNew->u.iValue = iCol;
88903        if( pItem->pExpr==pE ){
88904          pItem->pExpr = pNew;
88905        }else{
88906          Expr *pParent = pItem->pExpr;
88907          assert( pParent->op==TK_COLLATE );
88908          while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
88909          assert( pParent->pLeft==pE );
88910          pParent->pLeft = pNew;
88911        }
88912        sqlite3ExprDelete(db, pE);
88913        pItem->u.x.iOrderByCol = (u16)iCol;
88914        pItem->done = 1;
88915      }else{
88916        moreToDo = 1;
88917      }
88918    }
88919    pSelect = pSelect->pNext;
88920  }
88921  for(i=0; i<pOrderBy->nExpr; i++){
88922    if( pOrderBy->a[i].done==0 ){
88923      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
88924            "column in the result set", i+1);
88925      return 1;
88926    }
88927  }
88928  return 0;
88929}
88930
88931/*
88932** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
88933** the SELECT statement pSelect.  If any term is reference to a
88934** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
88935** field) then convert that term into a copy of the corresponding result set
88936** column.
88937**
88938** If any errors are detected, add an error message to pParse and
88939** return non-zero.  Return zero if no errors are seen.
88940*/
88941SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
88942  Parse *pParse,        /* Parsing context.  Leave error messages here */
88943  Select *pSelect,      /* The SELECT statement containing the clause */
88944  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
88945  const char *zType     /* "ORDER" or "GROUP" */
88946){
88947  int i;
88948  sqlite3 *db = pParse->db;
88949  ExprList *pEList;
88950  struct ExprList_item *pItem;
88951
88952  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
88953#if SQLITE_MAX_COLUMN
88954  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
88955    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
88956    return 1;
88957  }
88958#endif
88959  pEList = pSelect->pEList;
88960  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
88961  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
88962    if( pItem->u.x.iOrderByCol ){
88963      if( pItem->u.x.iOrderByCol>pEList->nExpr ){
88964        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
88965        return 1;
88966      }
88967      resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
88968                   zType,0);
88969    }
88970  }
88971  return 0;
88972}
88973
88974/*
88975** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
88976** The Name context of the SELECT statement is pNC.  zType is either
88977** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
88978**
88979** This routine resolves each term of the clause into an expression.
88980** If the order-by term is an integer I between 1 and N (where N is the
88981** number of columns in the result set of the SELECT) then the expression
88982** in the resolution is a copy of the I-th result-set expression.  If
88983** the order-by term is an identifier that corresponds to the AS-name of
88984** a result-set expression, then the term resolves to a copy of the
88985** result-set expression.  Otherwise, the expression is resolved in
88986** the usual way - using sqlite3ResolveExprNames().
88987**
88988** This routine returns the number of errors.  If errors occur, then
88989** an appropriate error message might be left in pParse.  (OOM errors
88990** excepted.)
88991*/
88992static int resolveOrderGroupBy(
88993  NameContext *pNC,     /* The name context of the SELECT statement */
88994  Select *pSelect,      /* The SELECT statement holding pOrderBy */
88995  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
88996  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
88997){
88998  int i, j;                      /* Loop counters */
88999  int iCol;                      /* Column number */
89000  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
89001  Parse *pParse;                 /* Parsing context */
89002  int nResult;                   /* Number of terms in the result set */
89003
89004  if( pOrderBy==0 ) return 0;
89005  nResult = pSelect->pEList->nExpr;
89006  pParse = pNC->pParse;
89007  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
89008    Expr *pE = pItem->pExpr;
89009    Expr *pE2 = sqlite3ExprSkipCollate(pE);
89010    if( zType[0]!='G' ){
89011      iCol = resolveAsName(pParse, pSelect->pEList, pE2);
89012      if( iCol>0 ){
89013        /* If an AS-name match is found, mark this ORDER BY column as being
89014        ** a copy of the iCol-th result-set column.  The subsequent call to
89015        ** sqlite3ResolveOrderGroupBy() will convert the expression to a
89016        ** copy of the iCol-th result-set expression. */
89017        pItem->u.x.iOrderByCol = (u16)iCol;
89018        continue;
89019      }
89020    }
89021    if( sqlite3ExprIsInteger(pE2, &iCol) ){
89022      /* The ORDER BY term is an integer constant.  Again, set the column
89023      ** number so that sqlite3ResolveOrderGroupBy() will convert the
89024      ** order-by term to a copy of the result-set expression */
89025      if( iCol<1 || iCol>0xffff ){
89026        resolveOutOfRangeError(pParse, zType, i+1, nResult);
89027        return 1;
89028      }
89029      pItem->u.x.iOrderByCol = (u16)iCol;
89030      continue;
89031    }
89032
89033    /* Otherwise, treat the ORDER BY term as an ordinary expression */
89034    pItem->u.x.iOrderByCol = 0;
89035    if( sqlite3ResolveExprNames(pNC, pE) ){
89036      return 1;
89037    }
89038    for(j=0; j<pSelect->pEList->nExpr; j++){
89039      if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
89040        pItem->u.x.iOrderByCol = j+1;
89041      }
89042    }
89043  }
89044  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
89045}
89046
89047/*
89048** Resolve names in the SELECT statement p and all of its descendants.
89049*/
89050static int resolveSelectStep(Walker *pWalker, Select *p){
89051  NameContext *pOuterNC;  /* Context that contains this SELECT */
89052  NameContext sNC;        /* Name context of this SELECT */
89053  int isCompound;         /* True if p is a compound select */
89054  int nCompound;          /* Number of compound terms processed so far */
89055  Parse *pParse;          /* Parsing context */
89056  int i;                  /* Loop counter */
89057  ExprList *pGroupBy;     /* The GROUP BY clause */
89058  Select *pLeftmost;      /* Left-most of SELECT of a compound */
89059  sqlite3 *db;            /* Database connection */
89060
89061
89062  assert( p!=0 );
89063  if( p->selFlags & SF_Resolved ){
89064    return WRC_Prune;
89065  }
89066  pOuterNC = pWalker->u.pNC;
89067  pParse = pWalker->pParse;
89068  db = pParse->db;
89069
89070  /* Normally sqlite3SelectExpand() will be called first and will have
89071  ** already expanded this SELECT.  However, if this is a subquery within
89072  ** an expression, sqlite3ResolveExprNames() will be called without a
89073  ** prior call to sqlite3SelectExpand().  When that happens, let
89074  ** sqlite3SelectPrep() do all of the processing for this SELECT.
89075  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
89076  ** this routine in the correct order.
89077  */
89078  if( (p->selFlags & SF_Expanded)==0 ){
89079    sqlite3SelectPrep(pParse, p, pOuterNC);
89080    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
89081  }
89082
89083  isCompound = p->pPrior!=0;
89084  nCompound = 0;
89085  pLeftmost = p;
89086  while( p ){
89087    assert( (p->selFlags & SF_Expanded)!=0 );
89088    assert( (p->selFlags & SF_Resolved)==0 );
89089    p->selFlags |= SF_Resolved;
89090
89091    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
89092    ** are not allowed to refer to any names, so pass an empty NameContext.
89093    */
89094    memset(&sNC, 0, sizeof(sNC));
89095    sNC.pParse = pParse;
89096    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
89097        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
89098      return WRC_Abort;
89099    }
89100
89101    /* If the SF_Converted flags is set, then this Select object was
89102    ** was created by the convertCompoundSelectToSubquery() function.
89103    ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
89104    ** as if it were part of the sub-query, not the parent. This block
89105    ** moves the pOrderBy down to the sub-query. It will be moved back
89106    ** after the names have been resolved.  */
89107    if( p->selFlags & SF_Converted ){
89108      Select *pSub = p->pSrc->a[0].pSelect;
89109      assert( p->pSrc->nSrc==1 && p->pOrderBy );
89110      assert( pSub->pPrior && pSub->pOrderBy==0 );
89111      pSub->pOrderBy = p->pOrderBy;
89112      p->pOrderBy = 0;
89113    }
89114
89115    /* Recursively resolve names in all subqueries
89116    */
89117    for(i=0; i<p->pSrc->nSrc; i++){
89118      struct SrcList_item *pItem = &p->pSrc->a[i];
89119      if( pItem->pSelect ){
89120        NameContext *pNC;         /* Used to iterate name contexts */
89121        int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
89122        const char *zSavedContext = pParse->zAuthContext;
89123
89124        /* Count the total number of references to pOuterNC and all of its
89125        ** parent contexts. After resolving references to expressions in
89126        ** pItem->pSelect, check if this value has changed. If so, then
89127        ** SELECT statement pItem->pSelect must be correlated. Set the
89128        ** pItem->fg.isCorrelated flag if this is the case. */
89129        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
89130
89131        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
89132        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
89133        pParse->zAuthContext = zSavedContext;
89134        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
89135
89136        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
89137        assert( pItem->fg.isCorrelated==0 && nRef<=0 );
89138        pItem->fg.isCorrelated = (nRef!=0);
89139      }
89140    }
89141
89142    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
89143    ** resolve the result-set expression list.
89144    */
89145    sNC.ncFlags = NC_AllowAgg;
89146    sNC.pSrcList = p->pSrc;
89147    sNC.pNext = pOuterNC;
89148
89149    /* Resolve names in the result set. */
89150    if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
89151
89152    /* If there are no aggregate functions in the result-set, and no GROUP BY
89153    ** expression, do not allow aggregates in any of the other expressions.
89154    */
89155    assert( (p->selFlags & SF_Aggregate)==0 );
89156    pGroupBy = p->pGroupBy;
89157    if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
89158      assert( NC_MinMaxAgg==SF_MinMaxAgg );
89159      p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
89160    }else{
89161      sNC.ncFlags &= ~NC_AllowAgg;
89162    }
89163
89164    /* If a HAVING clause is present, then there must be a GROUP BY clause.
89165    */
89166    if( p->pHaving && !pGroupBy ){
89167      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
89168      return WRC_Abort;
89169    }
89170
89171    /* Add the output column list to the name-context before parsing the
89172    ** other expressions in the SELECT statement. This is so that
89173    ** expressions in the WHERE clause (etc.) can refer to expressions by
89174    ** aliases in the result set.
89175    **
89176    ** Minor point: If this is the case, then the expression will be
89177    ** re-evaluated for each reference to it.
89178    */
89179    sNC.pEList = p->pEList;
89180    if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
89181    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
89182
89183    /* Resolve names in table-valued-function arguments */
89184    for(i=0; i<p->pSrc->nSrc; i++){
89185      struct SrcList_item *pItem = &p->pSrc->a[i];
89186      if( pItem->fg.isTabFunc
89187       && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
89188      ){
89189        return WRC_Abort;
89190      }
89191    }
89192
89193    /* The ORDER BY and GROUP BY clauses may not refer to terms in
89194    ** outer queries
89195    */
89196    sNC.pNext = 0;
89197    sNC.ncFlags |= NC_AllowAgg;
89198
89199    /* If this is a converted compound query, move the ORDER BY clause from
89200    ** the sub-query back to the parent query. At this point each term
89201    ** within the ORDER BY clause has been transformed to an integer value.
89202    ** These integers will be replaced by copies of the corresponding result
89203    ** set expressions by the call to resolveOrderGroupBy() below.  */
89204    if( p->selFlags & SF_Converted ){
89205      Select *pSub = p->pSrc->a[0].pSelect;
89206      p->pOrderBy = pSub->pOrderBy;
89207      pSub->pOrderBy = 0;
89208    }
89209
89210    /* Process the ORDER BY clause for singleton SELECT statements.
89211    ** The ORDER BY clause for compounds SELECT statements is handled
89212    ** below, after all of the result-sets for all of the elements of
89213    ** the compound have been resolved.
89214    **
89215    ** If there is an ORDER BY clause on a term of a compound-select other
89216    ** than the right-most term, then that is a syntax error.  But the error
89217    ** is not detected until much later, and so we need to go ahead and
89218    ** resolve those symbols on the incorrect ORDER BY for consistency.
89219    */
89220    if( isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
89221     && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
89222    ){
89223      return WRC_Abort;
89224    }
89225    if( db->mallocFailed ){
89226      return WRC_Abort;
89227    }
89228
89229    /* Resolve the GROUP BY clause.  At the same time, make sure
89230    ** the GROUP BY clause does not contain aggregate functions.
89231    */
89232    if( pGroupBy ){
89233      struct ExprList_item *pItem;
89234
89235      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
89236        return WRC_Abort;
89237      }
89238      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
89239        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
89240          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
89241              "the GROUP BY clause");
89242          return WRC_Abort;
89243        }
89244      }
89245    }
89246
89247    /* If this is part of a compound SELECT, check that it has the right
89248    ** number of expressions in the select list. */
89249    if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
89250      sqlite3SelectWrongNumTermsError(pParse, p->pNext);
89251      return WRC_Abort;
89252    }
89253
89254    /* Advance to the next term of the compound
89255    */
89256    p = p->pPrior;
89257    nCompound++;
89258  }
89259
89260  /* Resolve the ORDER BY on a compound SELECT after all terms of
89261  ** the compound have been resolved.
89262  */
89263  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
89264    return WRC_Abort;
89265  }
89266
89267  return WRC_Prune;
89268}
89269
89270/*
89271** This routine walks an expression tree and resolves references to
89272** table columns and result-set columns.  At the same time, do error
89273** checking on function usage and set a flag if any aggregate functions
89274** are seen.
89275**
89276** To resolve table columns references we look for nodes (or subtrees) of the
89277** form X.Y.Z or Y.Z or just Z where
89278**
89279**      X:   The name of a database.  Ex:  "main" or "temp" or
89280**           the symbolic name assigned to an ATTACH-ed database.
89281**
89282**      Y:   The name of a table in a FROM clause.  Or in a trigger
89283**           one of the special names "old" or "new".
89284**
89285**      Z:   The name of a column in table Y.
89286**
89287** The node at the root of the subtree is modified as follows:
89288**
89289**    Expr.op        Changed to TK_COLUMN
89290**    Expr.pTab      Points to the Table object for X.Y
89291**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
89292**    Expr.iTable    The VDBE cursor number for X.Y
89293**
89294**
89295** To resolve result-set references, look for expression nodes of the
89296** form Z (with no X and Y prefix) where the Z matches the right-hand
89297** size of an AS clause in the result-set of a SELECT.  The Z expression
89298** is replaced by a copy of the left-hand side of the result-set expression.
89299** Table-name and function resolution occurs on the substituted expression
89300** tree.  For example, in:
89301**
89302**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
89303**
89304** The "x" term of the order by is replaced by "a+b" to render:
89305**
89306**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
89307**
89308** Function calls are checked to make sure that the function is
89309** defined and that the correct number of arguments are specified.
89310** If the function is an aggregate function, then the NC_HasAgg flag is
89311** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
89312** If an expression contains aggregate functions then the EP_Agg
89313** property on the expression is set.
89314**
89315** An error message is left in pParse if anything is amiss.  The number
89316** if errors is returned.
89317*/
89318SQLITE_PRIVATE int sqlite3ResolveExprNames(
89319  NameContext *pNC,       /* Namespace to resolve expressions in. */
89320  Expr *pExpr             /* The expression to be analyzed. */
89321){
89322  u16 savedHasAgg;
89323  Walker w;
89324
89325  if( pExpr==0 ) return 0;
89326#if SQLITE_MAX_EXPR_DEPTH>0
89327  {
89328    Parse *pParse = pNC->pParse;
89329    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
89330      return 1;
89331    }
89332    pParse->nHeight += pExpr->nHeight;
89333  }
89334#endif
89335  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
89336  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
89337  w.pParse = pNC->pParse;
89338  w.xExprCallback = resolveExprStep;
89339  w.xSelectCallback = resolveSelectStep;
89340  w.xSelectCallback2 = 0;
89341  w.walkerDepth = 0;
89342  w.eCode = 0;
89343  w.u.pNC = pNC;
89344  sqlite3WalkExpr(&w, pExpr);
89345#if SQLITE_MAX_EXPR_DEPTH>0
89346  pNC->pParse->nHeight -= pExpr->nHeight;
89347#endif
89348  if( pNC->nErr>0 || w.pParse->nErr>0 ){
89349    ExprSetProperty(pExpr, EP_Error);
89350  }
89351  if( pNC->ncFlags & NC_HasAgg ){
89352    ExprSetProperty(pExpr, EP_Agg);
89353  }
89354  pNC->ncFlags |= savedHasAgg;
89355  return ExprHasProperty(pExpr, EP_Error);
89356}
89357
89358/*
89359** Resolve all names for all expression in an expression list.  This is
89360** just like sqlite3ResolveExprNames() except that it works for an expression
89361** list rather than a single expression.
89362*/
89363SQLITE_PRIVATE int sqlite3ResolveExprListNames(
89364  NameContext *pNC,       /* Namespace to resolve expressions in. */
89365  ExprList *pList         /* The expression list to be analyzed. */
89366){
89367  int i;
89368  if( pList ){
89369    for(i=0; i<pList->nExpr; i++){
89370      if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
89371    }
89372  }
89373  return WRC_Continue;
89374}
89375
89376/*
89377** Resolve all names in all expressions of a SELECT and in all
89378** decendents of the SELECT, including compounds off of p->pPrior,
89379** subqueries in expressions, and subqueries used as FROM clause
89380** terms.
89381**
89382** See sqlite3ResolveExprNames() for a description of the kinds of
89383** transformations that occur.
89384**
89385** All SELECT statements should have been expanded using
89386** sqlite3SelectExpand() prior to invoking this routine.
89387*/
89388SQLITE_PRIVATE void sqlite3ResolveSelectNames(
89389  Parse *pParse,         /* The parser context */
89390  Select *p,             /* The SELECT statement being coded. */
89391  NameContext *pOuterNC  /* Name context for parent SELECT statement */
89392){
89393  Walker w;
89394
89395  assert( p!=0 );
89396  memset(&w, 0, sizeof(w));
89397  w.xExprCallback = resolveExprStep;
89398  w.xSelectCallback = resolveSelectStep;
89399  w.pParse = pParse;
89400  w.u.pNC = pOuterNC;
89401  sqlite3WalkSelect(&w, p);
89402}
89403
89404/*
89405** Resolve names in expressions that can only reference a single table:
89406**
89407**    *   CHECK constraints
89408**    *   WHERE clauses on partial indices
89409**
89410** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
89411** is set to -1 and the Expr.iColumn value is set to the column number.
89412**
89413** Any errors cause an error message to be set in pParse.
89414*/
89415SQLITE_PRIVATE void sqlite3ResolveSelfReference(
89416  Parse *pParse,      /* Parsing context */
89417  Table *pTab,        /* The table being referenced */
89418  int type,           /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
89419  Expr *pExpr,        /* Expression to resolve.  May be NULL. */
89420  ExprList *pList     /* Expression list to resolve.  May be NUL. */
89421){
89422  SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
89423  NameContext sNC;                /* Name context for pParse->pNewTable */
89424
89425  assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
89426  memset(&sNC, 0, sizeof(sNC));
89427  memset(&sSrc, 0, sizeof(sSrc));
89428  sSrc.nSrc = 1;
89429  sSrc.a[0].zName = pTab->zName;
89430  sSrc.a[0].pTab = pTab;
89431  sSrc.a[0].iCursor = -1;
89432  sNC.pParse = pParse;
89433  sNC.pSrcList = &sSrc;
89434  sNC.ncFlags = type;
89435  if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
89436  if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
89437}
89438
89439/************** End of resolve.c *********************************************/
89440/************** Begin file expr.c ********************************************/
89441/*
89442** 2001 September 15
89443**
89444** The author disclaims copyright to this source code.  In place of
89445** a legal notice, here is a blessing:
89446**
89447**    May you do good and not evil.
89448**    May you find forgiveness for yourself and forgive others.
89449**    May you share freely, never taking more than you give.
89450**
89451*************************************************************************
89452** This file contains routines used for analyzing expressions and
89453** for generating VDBE code that evaluates expressions in SQLite.
89454*/
89455/* #include "sqliteInt.h" */
89456
89457/*
89458** Return the 'affinity' of the expression pExpr if any.
89459**
89460** If pExpr is a column, a reference to a column via an 'AS' alias,
89461** or a sub-select with a column as the return value, then the
89462** affinity of that column is returned. Otherwise, 0x00 is returned,
89463** indicating no affinity for the expression.
89464**
89465** i.e. the WHERE clause expressions in the following statements all
89466** have an affinity:
89467**
89468** CREATE TABLE t1(a);
89469** SELECT * FROM t1 WHERE a;
89470** SELECT a AS b FROM t1 WHERE b;
89471** SELECT * FROM t1 WHERE (select a from t1);
89472*/
89473SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
89474  int op;
89475  pExpr = sqlite3ExprSkipCollate(pExpr);
89476  if( pExpr->flags & EP_Generic ) return 0;
89477  op = pExpr->op;
89478  if( op==TK_SELECT ){
89479    assert( pExpr->flags&EP_xIsSelect );
89480    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
89481  }
89482#ifndef SQLITE_OMIT_CAST
89483  if( op==TK_CAST ){
89484    assert( !ExprHasProperty(pExpr, EP_IntValue) );
89485    return sqlite3AffinityType(pExpr->u.zToken, 0);
89486  }
89487#endif
89488  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
89489   && pExpr->pTab!=0
89490  ){
89491    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
89492    ** a TK_COLUMN but was previously evaluated and cached in a register */
89493    int j = pExpr->iColumn;
89494    if( j<0 ) return SQLITE_AFF_INTEGER;
89495    assert( pExpr->pTab && j<pExpr->pTab->nCol );
89496    return pExpr->pTab->aCol[j].affinity;
89497  }
89498  return pExpr->affinity;
89499}
89500
89501/*
89502** Set the collating sequence for expression pExpr to be the collating
89503** sequence named by pToken.   Return a pointer to a new Expr node that
89504** implements the COLLATE operator.
89505**
89506** If a memory allocation error occurs, that fact is recorded in pParse->db
89507** and the pExpr parameter is returned unchanged.
89508*/
89509SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
89510  Parse *pParse,           /* Parsing context */
89511  Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
89512  const Token *pCollName,  /* Name of collating sequence */
89513  int dequote              /* True to dequote pCollName */
89514){
89515  if( pCollName->n>0 ){
89516    Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
89517    if( pNew ){
89518      pNew->pLeft = pExpr;
89519      pNew->flags |= EP_Collate|EP_Skip;
89520      pExpr = pNew;
89521    }
89522  }
89523  return pExpr;
89524}
89525SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
89526  Token s;
89527  assert( zC!=0 );
89528  sqlite3TokenInit(&s, (char*)zC);
89529  return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
89530}
89531
89532/*
89533** Skip over any TK_COLLATE operators and any unlikely()
89534** or likelihood() function at the root of an expression.
89535*/
89536SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
89537  while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
89538    if( ExprHasProperty(pExpr, EP_Unlikely) ){
89539      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
89540      assert( pExpr->x.pList->nExpr>0 );
89541      assert( pExpr->op==TK_FUNCTION );
89542      pExpr = pExpr->x.pList->a[0].pExpr;
89543    }else{
89544      assert( pExpr->op==TK_COLLATE );
89545      pExpr = pExpr->pLeft;
89546    }
89547  }
89548  return pExpr;
89549}
89550
89551/*
89552** Return the collation sequence for the expression pExpr. If
89553** there is no defined collating sequence, return NULL.
89554**
89555** The collating sequence might be determined by a COLLATE operator
89556** or by the presence of a column with a defined collating sequence.
89557** COLLATE operators take first precedence.  Left operands take
89558** precedence over right operands.
89559*/
89560SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
89561  sqlite3 *db = pParse->db;
89562  CollSeq *pColl = 0;
89563  Expr *p = pExpr;
89564  while( p ){
89565    int op = p->op;
89566    if( p->flags & EP_Generic ) break;
89567    if( op==TK_CAST || op==TK_UPLUS ){
89568      p = p->pLeft;
89569      continue;
89570    }
89571    if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
89572      pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
89573      break;
89574    }
89575    if( (op==TK_AGG_COLUMN || op==TK_COLUMN
89576          || op==TK_REGISTER || op==TK_TRIGGER)
89577     && p->pTab!=0
89578    ){
89579      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
89580      ** a TK_COLUMN but was previously evaluated and cached in a register */
89581      int j = p->iColumn;
89582      if( j>=0 ){
89583        const char *zColl = p->pTab->aCol[j].zColl;
89584        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
89585      }
89586      break;
89587    }
89588    if( p->flags & EP_Collate ){
89589      if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
89590        p = p->pLeft;
89591      }else{
89592        Expr *pNext  = p->pRight;
89593        /* The Expr.x union is never used at the same time as Expr.pRight */
89594        assert( p->x.pList==0 || p->pRight==0 );
89595        /* p->flags holds EP_Collate and p->pLeft->flags does not.  And
89596        ** p->x.pSelect cannot.  So if p->x.pLeft exists, it must hold at
89597        ** least one EP_Collate. Thus the following two ALWAYS. */
89598        if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
89599          int i;
89600          for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
89601            if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
89602              pNext = p->x.pList->a[i].pExpr;
89603              break;
89604            }
89605          }
89606        }
89607        p = pNext;
89608      }
89609    }else{
89610      break;
89611    }
89612  }
89613  if( sqlite3CheckCollSeq(pParse, pColl) ){
89614    pColl = 0;
89615  }
89616  return pColl;
89617}
89618
89619/*
89620** pExpr is an operand of a comparison operator.  aff2 is the
89621** type affinity of the other operand.  This routine returns the
89622** type affinity that should be used for the comparison operator.
89623*/
89624SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
89625  char aff1 = sqlite3ExprAffinity(pExpr);
89626  if( aff1 && aff2 ){
89627    /* Both sides of the comparison are columns. If one has numeric
89628    ** affinity, use that. Otherwise use no affinity.
89629    */
89630    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
89631      return SQLITE_AFF_NUMERIC;
89632    }else{
89633      return SQLITE_AFF_BLOB;
89634    }
89635  }else if( !aff1 && !aff2 ){
89636    /* Neither side of the comparison is a column.  Compare the
89637    ** results directly.
89638    */
89639    return SQLITE_AFF_BLOB;
89640  }else{
89641    /* One side is a column, the other is not. Use the columns affinity. */
89642    assert( aff1==0 || aff2==0 );
89643    return (aff1 + aff2);
89644  }
89645}
89646
89647/*
89648** pExpr is a comparison operator.  Return the type affinity that should
89649** be applied to both operands prior to doing the comparison.
89650*/
89651static char comparisonAffinity(Expr *pExpr){
89652  char aff;
89653  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
89654          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
89655          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
89656  assert( pExpr->pLeft );
89657  aff = sqlite3ExprAffinity(pExpr->pLeft);
89658  if( pExpr->pRight ){
89659    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
89660  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
89661    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
89662  }else if( !aff ){
89663    aff = SQLITE_AFF_BLOB;
89664  }
89665  return aff;
89666}
89667
89668/*
89669** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
89670** idx_affinity is the affinity of an indexed column. Return true
89671** if the index with affinity idx_affinity may be used to implement
89672** the comparison in pExpr.
89673*/
89674SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
89675  char aff = comparisonAffinity(pExpr);
89676  switch( aff ){
89677    case SQLITE_AFF_BLOB:
89678      return 1;
89679    case SQLITE_AFF_TEXT:
89680      return idx_affinity==SQLITE_AFF_TEXT;
89681    default:
89682      return sqlite3IsNumericAffinity(idx_affinity);
89683  }
89684}
89685
89686/*
89687** Return the P5 value that should be used for a binary comparison
89688** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
89689*/
89690static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
89691  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
89692  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
89693  return aff;
89694}
89695
89696/*
89697** Return a pointer to the collation sequence that should be used by
89698** a binary comparison operator comparing pLeft and pRight.
89699**
89700** If the left hand expression has a collating sequence type, then it is
89701** used. Otherwise the collation sequence for the right hand expression
89702** is used, or the default (BINARY) if neither expression has a collating
89703** type.
89704**
89705** Argument pRight (but not pLeft) may be a null pointer. In this case,
89706** it is not considered.
89707*/
89708SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
89709  Parse *pParse,
89710  Expr *pLeft,
89711  Expr *pRight
89712){
89713  CollSeq *pColl;
89714  assert( pLeft );
89715  if( pLeft->flags & EP_Collate ){
89716    pColl = sqlite3ExprCollSeq(pParse, pLeft);
89717  }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
89718    pColl = sqlite3ExprCollSeq(pParse, pRight);
89719  }else{
89720    pColl = sqlite3ExprCollSeq(pParse, pLeft);
89721    if( !pColl ){
89722      pColl = sqlite3ExprCollSeq(pParse, pRight);
89723    }
89724  }
89725  return pColl;
89726}
89727
89728/*
89729** Generate code for a comparison operator.
89730*/
89731static int codeCompare(
89732  Parse *pParse,    /* The parsing (and code generating) context */
89733  Expr *pLeft,      /* The left operand */
89734  Expr *pRight,     /* The right operand */
89735  int opcode,       /* The comparison opcode */
89736  int in1, int in2, /* Register holding operands */
89737  int dest,         /* Jump here if true.  */
89738  int jumpIfNull    /* If true, jump if either operand is NULL */
89739){
89740  int p5;
89741  int addr;
89742  CollSeq *p4;
89743
89744  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
89745  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
89746  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
89747                           (void*)p4, P4_COLLSEQ);
89748  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
89749  return addr;
89750}
89751
89752#if SQLITE_MAX_EXPR_DEPTH>0
89753/*
89754** Check that argument nHeight is less than or equal to the maximum
89755** expression depth allowed. If it is not, leave an error message in
89756** pParse.
89757*/
89758SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
89759  int rc = SQLITE_OK;
89760  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
89761  if( nHeight>mxHeight ){
89762    sqlite3ErrorMsg(pParse,
89763       "Expression tree is too large (maximum depth %d)", mxHeight
89764    );
89765    rc = SQLITE_ERROR;
89766  }
89767  return rc;
89768}
89769
89770/* The following three functions, heightOfExpr(), heightOfExprList()
89771** and heightOfSelect(), are used to determine the maximum height
89772** of any expression tree referenced by the structure passed as the
89773** first argument.
89774**
89775** If this maximum height is greater than the current value pointed
89776** to by pnHeight, the second parameter, then set *pnHeight to that
89777** value.
89778*/
89779static void heightOfExpr(Expr *p, int *pnHeight){
89780  if( p ){
89781    if( p->nHeight>*pnHeight ){
89782      *pnHeight = p->nHeight;
89783    }
89784  }
89785}
89786static void heightOfExprList(ExprList *p, int *pnHeight){
89787  if( p ){
89788    int i;
89789    for(i=0; i<p->nExpr; i++){
89790      heightOfExpr(p->a[i].pExpr, pnHeight);
89791    }
89792  }
89793}
89794static void heightOfSelect(Select *p, int *pnHeight){
89795  if( p ){
89796    heightOfExpr(p->pWhere, pnHeight);
89797    heightOfExpr(p->pHaving, pnHeight);
89798    heightOfExpr(p->pLimit, pnHeight);
89799    heightOfExpr(p->pOffset, pnHeight);
89800    heightOfExprList(p->pEList, pnHeight);
89801    heightOfExprList(p->pGroupBy, pnHeight);
89802    heightOfExprList(p->pOrderBy, pnHeight);
89803    heightOfSelect(p->pPrior, pnHeight);
89804  }
89805}
89806
89807/*
89808** Set the Expr.nHeight variable in the structure passed as an
89809** argument. An expression with no children, Expr.pList or
89810** Expr.pSelect member has a height of 1. Any other expression
89811** has a height equal to the maximum height of any other
89812** referenced Expr plus one.
89813**
89814** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
89815** if appropriate.
89816*/
89817static void exprSetHeight(Expr *p){
89818  int nHeight = 0;
89819  heightOfExpr(p->pLeft, &nHeight);
89820  heightOfExpr(p->pRight, &nHeight);
89821  if( ExprHasProperty(p, EP_xIsSelect) ){
89822    heightOfSelect(p->x.pSelect, &nHeight);
89823  }else if( p->x.pList ){
89824    heightOfExprList(p->x.pList, &nHeight);
89825    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
89826  }
89827  p->nHeight = nHeight + 1;
89828}
89829
89830/*
89831** Set the Expr.nHeight variable using the exprSetHeight() function. If
89832** the height is greater than the maximum allowed expression depth,
89833** leave an error in pParse.
89834**
89835** Also propagate all EP_Propagate flags from the Expr.x.pList into
89836** Expr.flags.
89837*/
89838SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
89839  if( pParse->nErr ) return;
89840  exprSetHeight(p);
89841  sqlite3ExprCheckHeight(pParse, p->nHeight);
89842}
89843
89844/*
89845** Return the maximum height of any expression tree referenced
89846** by the select statement passed as an argument.
89847*/
89848SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
89849  int nHeight = 0;
89850  heightOfSelect(p, &nHeight);
89851  return nHeight;
89852}
89853#else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
89854/*
89855** Propagate all EP_Propagate flags from the Expr.x.pList into
89856** Expr.flags.
89857*/
89858SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
89859  if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
89860    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
89861  }
89862}
89863#define exprSetHeight(y)
89864#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
89865
89866/*
89867** This routine is the core allocator for Expr nodes.
89868**
89869** Construct a new expression node and return a pointer to it.  Memory
89870** for this node and for the pToken argument is a single allocation
89871** obtained from sqlite3DbMalloc().  The calling function
89872** is responsible for making sure the node eventually gets freed.
89873**
89874** If dequote is true, then the token (if it exists) is dequoted.
89875** If dequote is false, no dequoting is performed.  The deQuote
89876** parameter is ignored if pToken is NULL or if the token does not
89877** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
89878** then the EP_DblQuoted flag is set on the expression node.
89879**
89880** Special case:  If op==TK_INTEGER and pToken points to a string that
89881** can be translated into a 32-bit integer, then the token is not
89882** stored in u.zToken.  Instead, the integer values is written
89883** into u.iValue and the EP_IntValue flag is set.  No extra storage
89884** is allocated to hold the integer text and the dequote flag is ignored.
89885*/
89886SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
89887  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
89888  int op,                 /* Expression opcode */
89889  const Token *pToken,    /* Token argument.  Might be NULL */
89890  int dequote             /* True to dequote */
89891){
89892  Expr *pNew;
89893  int nExtra = 0;
89894  int iValue = 0;
89895
89896  assert( db!=0 );
89897  if( pToken ){
89898    if( op!=TK_INTEGER || pToken->z==0
89899          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
89900      nExtra = pToken->n+1;
89901      assert( iValue>=0 );
89902    }
89903  }
89904  pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
89905  if( pNew ){
89906    memset(pNew, 0, sizeof(Expr));
89907    pNew->op = (u8)op;
89908    pNew->iAgg = -1;
89909    if( pToken ){
89910      if( nExtra==0 ){
89911        pNew->flags |= EP_IntValue;
89912        pNew->u.iValue = iValue;
89913      }else{
89914        pNew->u.zToken = (char*)&pNew[1];
89915        assert( pToken->z!=0 || pToken->n==0 );
89916        if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
89917        pNew->u.zToken[pToken->n] = 0;
89918        if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
89919          if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
89920          sqlite3Dequote(pNew->u.zToken);
89921        }
89922      }
89923    }
89924#if SQLITE_MAX_EXPR_DEPTH>0
89925    pNew->nHeight = 1;
89926#endif
89927  }
89928  return pNew;
89929}
89930
89931/*
89932** Allocate a new expression node from a zero-terminated token that has
89933** already been dequoted.
89934*/
89935SQLITE_PRIVATE Expr *sqlite3Expr(
89936  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
89937  int op,                 /* Expression opcode */
89938  const char *zToken      /* Token argument.  Might be NULL */
89939){
89940  Token x;
89941  x.z = zToken;
89942  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
89943  return sqlite3ExprAlloc(db, op, &x, 0);
89944}
89945
89946/*
89947** Attach subtrees pLeft and pRight to the Expr node pRoot.
89948**
89949** If pRoot==NULL that means that a memory allocation error has occurred.
89950** In that case, delete the subtrees pLeft and pRight.
89951*/
89952SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
89953  sqlite3 *db,
89954  Expr *pRoot,
89955  Expr *pLeft,
89956  Expr *pRight
89957){
89958  if( pRoot==0 ){
89959    assert( db->mallocFailed );
89960    sqlite3ExprDelete(db, pLeft);
89961    sqlite3ExprDelete(db, pRight);
89962  }else{
89963    if( pRight ){
89964      pRoot->pRight = pRight;
89965      pRoot->flags |= EP_Propagate & pRight->flags;
89966    }
89967    if( pLeft ){
89968      pRoot->pLeft = pLeft;
89969      pRoot->flags |= EP_Propagate & pLeft->flags;
89970    }
89971    exprSetHeight(pRoot);
89972  }
89973}
89974
89975/*
89976** Allocate an Expr node which joins as many as two subtrees.
89977**
89978** One or both of the subtrees can be NULL.  Return a pointer to the new
89979** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
89980** free the subtrees and return NULL.
89981*/
89982SQLITE_PRIVATE Expr *sqlite3PExpr(
89983  Parse *pParse,          /* Parsing context */
89984  int op,                 /* Expression opcode */
89985  Expr *pLeft,            /* Left operand */
89986  Expr *pRight,           /* Right operand */
89987  const Token *pToken     /* Argument token */
89988){
89989  Expr *p;
89990  if( op==TK_AND && pParse->nErr==0 ){
89991    /* Take advantage of short-circuit false optimization for AND */
89992    p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
89993  }else{
89994    p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1);
89995    sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
89996  }
89997  if( p ) {
89998    sqlite3ExprCheckHeight(pParse, p->nHeight);
89999  }
90000  return p;
90001}
90002
90003/*
90004** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due
90005** do a memory allocation failure) then delete the pSelect object.
90006*/
90007SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
90008  if( pExpr ){
90009    pExpr->x.pSelect = pSelect;
90010    ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
90011    sqlite3ExprSetHeightAndFlags(pParse, pExpr);
90012  }else{
90013    assert( pParse->db->mallocFailed );
90014    sqlite3SelectDelete(pParse->db, pSelect);
90015  }
90016}
90017
90018
90019/*
90020** If the expression is always either TRUE or FALSE (respectively),
90021** then return 1.  If one cannot determine the truth value of the
90022** expression at compile-time return 0.
90023**
90024** This is an optimization.  If is OK to return 0 here even if
90025** the expression really is always false or false (a false negative).
90026** But it is a bug to return 1 if the expression might have different
90027** boolean values in different circumstances (a false positive.)
90028**
90029** Note that if the expression is part of conditional for a
90030** LEFT JOIN, then we cannot determine at compile-time whether or not
90031** is it true or false, so always return 0.
90032*/
90033static int exprAlwaysTrue(Expr *p){
90034  int v = 0;
90035  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
90036  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
90037  return v!=0;
90038}
90039static int exprAlwaysFalse(Expr *p){
90040  int v = 0;
90041  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
90042  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
90043  return v==0;
90044}
90045
90046/*
90047** Join two expressions using an AND operator.  If either expression is
90048** NULL, then just return the other expression.
90049**
90050** If one side or the other of the AND is known to be false, then instead
90051** of returning an AND expression, just return a constant expression with
90052** a value of false.
90053*/
90054SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
90055  if( pLeft==0 ){
90056    return pRight;
90057  }else if( pRight==0 ){
90058    return pLeft;
90059  }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
90060    sqlite3ExprDelete(db, pLeft);
90061    sqlite3ExprDelete(db, pRight);
90062    return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
90063  }else{
90064    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
90065    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
90066    return pNew;
90067  }
90068}
90069
90070/*
90071** Construct a new expression node for a function with multiple
90072** arguments.
90073*/
90074SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
90075  Expr *pNew;
90076  sqlite3 *db = pParse->db;
90077  assert( pToken );
90078  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
90079  if( pNew==0 ){
90080    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
90081    return 0;
90082  }
90083  pNew->x.pList = pList;
90084  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
90085  sqlite3ExprSetHeightAndFlags(pParse, pNew);
90086  return pNew;
90087}
90088
90089/*
90090** Assign a variable number to an expression that encodes a wildcard
90091** in the original SQL statement.
90092**
90093** Wildcards consisting of a single "?" are assigned the next sequential
90094** variable number.
90095**
90096** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
90097** sure "nnn" is not too be to avoid a denial of service attack when
90098** the SQL statement comes from an external source.
90099**
90100** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
90101** as the previous instance of the same wildcard.  Or if this is the first
90102** instance of the wildcard, the next sequential variable number is
90103** assigned.
90104*/
90105SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
90106  sqlite3 *db = pParse->db;
90107  const char *z;
90108
90109  if( pExpr==0 ) return;
90110  assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
90111  z = pExpr->u.zToken;
90112  assert( z!=0 );
90113  assert( z[0]!=0 );
90114  if( z[1]==0 ){
90115    /* Wildcard of the form "?".  Assign the next variable number */
90116    assert( z[0]=='?' );
90117    pExpr->iColumn = (ynVar)(++pParse->nVar);
90118  }else{
90119    ynVar x = 0;
90120    u32 n = sqlite3Strlen30(z);
90121    if( z[0]=='?' ){
90122      /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
90123      ** use it as the variable number */
90124      i64 i;
90125      int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
90126      pExpr->iColumn = x = (ynVar)i;
90127      testcase( i==0 );
90128      testcase( i==1 );
90129      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
90130      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
90131      if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
90132        sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
90133            db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
90134        x = 0;
90135      }
90136      if( i>pParse->nVar ){
90137        pParse->nVar = (int)i;
90138      }
90139    }else{
90140      /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
90141      ** number as the prior appearance of the same name, or if the name
90142      ** has never appeared before, reuse the same variable number
90143      */
90144      ynVar i;
90145      for(i=0; i<pParse->nzVar; i++){
90146        if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
90147          pExpr->iColumn = x = (ynVar)i+1;
90148          break;
90149        }
90150      }
90151      if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
90152    }
90153    if( x>0 ){
90154      if( x>pParse->nzVar ){
90155        char **a;
90156        a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
90157        if( a==0 ){
90158          assert( db->mallocFailed ); /* Error reported through mallocFailed */
90159          return;
90160        }
90161        pParse->azVar = a;
90162        memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
90163        pParse->nzVar = x;
90164      }
90165      if( z[0]!='?' || pParse->azVar[x-1]==0 ){
90166        sqlite3DbFree(db, pParse->azVar[x-1]);
90167        pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
90168      }
90169    }
90170  }
90171  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
90172    sqlite3ErrorMsg(pParse, "too many SQL variables");
90173  }
90174}
90175
90176/*
90177** Recursively delete an expression tree.
90178*/
90179static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
90180  assert( p!=0 );
90181  /* Sanity check: Assert that the IntValue is non-negative if it exists */
90182  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
90183  if( !ExprHasProperty(p, EP_TokenOnly) ){
90184    /* The Expr.x union is never used at the same time as Expr.pRight */
90185    assert( p->x.pList==0 || p->pRight==0 );
90186    sqlite3ExprDelete(db, p->pLeft);
90187    sqlite3ExprDelete(db, p->pRight);
90188    if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
90189    if( ExprHasProperty(p, EP_xIsSelect) ){
90190      sqlite3SelectDelete(db, p->x.pSelect);
90191    }else{
90192      sqlite3ExprListDelete(db, p->x.pList);
90193    }
90194  }
90195  if( !ExprHasProperty(p, EP_Static) ){
90196    sqlite3DbFree(db, p);
90197  }
90198}
90199SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
90200  if( p ) sqlite3ExprDeleteNN(db, p);
90201}
90202
90203/*
90204** Return the number of bytes allocated for the expression structure
90205** passed as the first argument. This is always one of EXPR_FULLSIZE,
90206** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
90207*/
90208static int exprStructSize(Expr *p){
90209  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
90210  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
90211  return EXPR_FULLSIZE;
90212}
90213
90214/*
90215** The dupedExpr*Size() routines each return the number of bytes required
90216** to store a copy of an expression or expression tree.  They differ in
90217** how much of the tree is measured.
90218**
90219**     dupedExprStructSize()     Size of only the Expr structure
90220**     dupedExprNodeSize()       Size of Expr + space for token
90221**     dupedExprSize()           Expr + token + subtree components
90222**
90223***************************************************************************
90224**
90225** The dupedExprStructSize() function returns two values OR-ed together:
90226** (1) the space required for a copy of the Expr structure only and
90227** (2) the EP_xxx flags that indicate what the structure size should be.
90228** The return values is always one of:
90229**
90230**      EXPR_FULLSIZE
90231**      EXPR_REDUCEDSIZE   | EP_Reduced
90232**      EXPR_TOKENONLYSIZE | EP_TokenOnly
90233**
90234** The size of the structure can be found by masking the return value
90235** of this routine with 0xfff.  The flags can be found by masking the
90236** return value with EP_Reduced|EP_TokenOnly.
90237**
90238** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
90239** (unreduced) Expr objects as they or originally constructed by the parser.
90240** During expression analysis, extra information is computed and moved into
90241** later parts of teh Expr object and that extra information might get chopped
90242** off if the expression is reduced.  Note also that it does not work to
90243** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
90244** to reduce a pristine expression tree from the parser.  The implementation
90245** of dupedExprStructSize() contain multiple assert() statements that attempt
90246** to enforce this constraint.
90247*/
90248static int dupedExprStructSize(Expr *p, int flags){
90249  int nSize;
90250  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
90251  assert( EXPR_FULLSIZE<=0xfff );
90252  assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
90253  if( 0==flags ){
90254    nSize = EXPR_FULLSIZE;
90255  }else{
90256    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
90257    assert( !ExprHasProperty(p, EP_FromJoin) );
90258    assert( !ExprHasProperty(p, EP_MemToken) );
90259    assert( !ExprHasProperty(p, EP_NoReduce) );
90260    if( p->pLeft || p->x.pList ){
90261      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
90262    }else{
90263      assert( p->pRight==0 );
90264      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
90265    }
90266  }
90267  return nSize;
90268}
90269
90270/*
90271** This function returns the space in bytes required to store the copy
90272** of the Expr structure and a copy of the Expr.u.zToken string (if that
90273** string is defined.)
90274*/
90275static int dupedExprNodeSize(Expr *p, int flags){
90276  int nByte = dupedExprStructSize(p, flags) & 0xfff;
90277  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
90278    nByte += sqlite3Strlen30(p->u.zToken)+1;
90279  }
90280  return ROUND8(nByte);
90281}
90282
90283/*
90284** Return the number of bytes required to create a duplicate of the
90285** expression passed as the first argument. The second argument is a
90286** mask containing EXPRDUP_XXX flags.
90287**
90288** The value returned includes space to create a copy of the Expr struct
90289** itself and the buffer referred to by Expr.u.zToken, if any.
90290**
90291** If the EXPRDUP_REDUCE flag is set, then the return value includes
90292** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
90293** and Expr.pRight variables (but not for any structures pointed to or
90294** descended from the Expr.x.pList or Expr.x.pSelect variables).
90295*/
90296static int dupedExprSize(Expr *p, int flags){
90297  int nByte = 0;
90298  if( p ){
90299    nByte = dupedExprNodeSize(p, flags);
90300    if( flags&EXPRDUP_REDUCE ){
90301      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
90302    }
90303  }
90304  return nByte;
90305}
90306
90307/*
90308** This function is similar to sqlite3ExprDup(), except that if pzBuffer
90309** is not NULL then *pzBuffer is assumed to point to a buffer large enough
90310** to store the copy of expression p, the copies of p->u.zToken
90311** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
90312** if any. Before returning, *pzBuffer is set to the first byte past the
90313** portion of the buffer copied into by this function.
90314*/
90315static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
90316  Expr *pNew;           /* Value to return */
90317  u8 *zAlloc;           /* Memory space from which to build Expr object */
90318  u32 staticFlag;       /* EP_Static if space not obtained from malloc */
90319
90320  assert( db!=0 );
90321  assert( p );
90322  assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
90323  assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
90324
90325  /* Figure out where to write the new Expr structure. */
90326  if( pzBuffer ){
90327    zAlloc = *pzBuffer;
90328    staticFlag = EP_Static;
90329  }else{
90330    zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
90331    staticFlag = 0;
90332  }
90333  pNew = (Expr *)zAlloc;
90334
90335  if( pNew ){
90336    /* Set nNewSize to the size allocated for the structure pointed to
90337    ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
90338    ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
90339    ** by the copy of the p->u.zToken string (if any).
90340    */
90341    const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
90342    const int nNewSize = nStructSize & 0xfff;
90343    int nToken;
90344    if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
90345      nToken = sqlite3Strlen30(p->u.zToken) + 1;
90346    }else{
90347      nToken = 0;
90348    }
90349    if( dupFlags ){
90350      assert( ExprHasProperty(p, EP_Reduced)==0 );
90351      memcpy(zAlloc, p, nNewSize);
90352    }else{
90353      u32 nSize = (u32)exprStructSize(p);
90354      memcpy(zAlloc, p, nSize);
90355      if( nSize<EXPR_FULLSIZE ){
90356        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
90357      }
90358    }
90359
90360    /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
90361    pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
90362    pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
90363    pNew->flags |= staticFlag;
90364
90365    /* Copy the p->u.zToken string, if any. */
90366    if( nToken ){
90367      char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
90368      memcpy(zToken, p->u.zToken, nToken);
90369    }
90370
90371    if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
90372      /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
90373      if( ExprHasProperty(p, EP_xIsSelect) ){
90374        pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
90375      }else{
90376        pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
90377      }
90378    }
90379
90380    /* Fill in pNew->pLeft and pNew->pRight. */
90381    if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
90382      zAlloc += dupedExprNodeSize(p, dupFlags);
90383      if( ExprHasProperty(pNew, EP_Reduced) ){
90384        pNew->pLeft = p->pLeft ?
90385                      exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
90386        pNew->pRight = p->pRight ?
90387                       exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
90388      }
90389      if( pzBuffer ){
90390        *pzBuffer = zAlloc;
90391      }
90392    }else{
90393      if( !ExprHasProperty(p, EP_TokenOnly) ){
90394        pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
90395        pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
90396      }
90397    }
90398  }
90399  return pNew;
90400}
90401
90402/*
90403** Create and return a deep copy of the object passed as the second
90404** argument. If an OOM condition is encountered, NULL is returned
90405** and the db->mallocFailed flag set.
90406*/
90407#ifndef SQLITE_OMIT_CTE
90408static With *withDup(sqlite3 *db, With *p){
90409  With *pRet = 0;
90410  if( p ){
90411    int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
90412    pRet = sqlite3DbMallocZero(db, nByte);
90413    if( pRet ){
90414      int i;
90415      pRet->nCte = p->nCte;
90416      for(i=0; i<p->nCte; i++){
90417        pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
90418        pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
90419        pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
90420      }
90421    }
90422  }
90423  return pRet;
90424}
90425#else
90426# define withDup(x,y) 0
90427#endif
90428
90429/*
90430** The following group of routines make deep copies of expressions,
90431** expression lists, ID lists, and select statements.  The copies can
90432** be deleted (by being passed to their respective ...Delete() routines)
90433** without effecting the originals.
90434**
90435** The expression list, ID, and source lists return by sqlite3ExprListDup(),
90436** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
90437** by subsequent calls to sqlite*ListAppend() routines.
90438**
90439** Any tables that the SrcList might point to are not duplicated.
90440**
90441** The flags parameter contains a combination of the EXPRDUP_XXX flags.
90442** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
90443** truncated version of the usual Expr structure that will be stored as
90444** part of the in-memory representation of the database schema.
90445*/
90446SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
90447  assert( flags==0 || flags==EXPRDUP_REDUCE );
90448  return p ? exprDup(db, p, flags, 0) : 0;
90449}
90450SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
90451  ExprList *pNew;
90452  struct ExprList_item *pItem, *pOldItem;
90453  int i;
90454  assert( db!=0 );
90455  if( p==0 ) return 0;
90456  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
90457  if( pNew==0 ) return 0;
90458  pNew->nExpr = i = p->nExpr;
90459  if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
90460  pNew->a = pItem = sqlite3DbMallocRawNN(db,  i*sizeof(p->a[0]) );
90461  if( pItem==0 ){
90462    sqlite3DbFree(db, pNew);
90463    return 0;
90464  }
90465  pOldItem = p->a;
90466  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
90467    Expr *pOldExpr = pOldItem->pExpr;
90468    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
90469    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
90470    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
90471    pItem->sortOrder = pOldItem->sortOrder;
90472    pItem->done = 0;
90473    pItem->bSpanIsTab = pOldItem->bSpanIsTab;
90474    pItem->u = pOldItem->u;
90475  }
90476  return pNew;
90477}
90478
90479/*
90480** If cursors, triggers, views and subqueries are all omitted from
90481** the build, then none of the following routines, except for
90482** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
90483** called with a NULL argument.
90484*/
90485#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
90486 || !defined(SQLITE_OMIT_SUBQUERY)
90487SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
90488  SrcList *pNew;
90489  int i;
90490  int nByte;
90491  assert( db!=0 );
90492  if( p==0 ) return 0;
90493  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
90494  pNew = sqlite3DbMallocRawNN(db, nByte );
90495  if( pNew==0 ) return 0;
90496  pNew->nSrc = pNew->nAlloc = p->nSrc;
90497  for(i=0; i<p->nSrc; i++){
90498    struct SrcList_item *pNewItem = &pNew->a[i];
90499    struct SrcList_item *pOldItem = &p->a[i];
90500    Table *pTab;
90501    pNewItem->pSchema = pOldItem->pSchema;
90502    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
90503    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
90504    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
90505    pNewItem->fg = pOldItem->fg;
90506    pNewItem->iCursor = pOldItem->iCursor;
90507    pNewItem->addrFillSub = pOldItem->addrFillSub;
90508    pNewItem->regReturn = pOldItem->regReturn;
90509    if( pNewItem->fg.isIndexedBy ){
90510      pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
90511    }
90512    pNewItem->pIBIndex = pOldItem->pIBIndex;
90513    if( pNewItem->fg.isTabFunc ){
90514      pNewItem->u1.pFuncArg =
90515          sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
90516    }
90517    pTab = pNewItem->pTab = pOldItem->pTab;
90518    if( pTab ){
90519      pTab->nRef++;
90520    }
90521    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
90522    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
90523    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
90524    pNewItem->colUsed = pOldItem->colUsed;
90525  }
90526  return pNew;
90527}
90528SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
90529  IdList *pNew;
90530  int i;
90531  assert( db!=0 );
90532  if( p==0 ) return 0;
90533  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
90534  if( pNew==0 ) return 0;
90535  pNew->nId = p->nId;
90536  pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
90537  if( pNew->a==0 ){
90538    sqlite3DbFree(db, pNew);
90539    return 0;
90540  }
90541  /* Note that because the size of the allocation for p->a[] is not
90542  ** necessarily a power of two, sqlite3IdListAppend() may not be called
90543  ** on the duplicate created by this function. */
90544  for(i=0; i<p->nId; i++){
90545    struct IdList_item *pNewItem = &pNew->a[i];
90546    struct IdList_item *pOldItem = &p->a[i];
90547    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
90548    pNewItem->idx = pOldItem->idx;
90549  }
90550  return pNew;
90551}
90552SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
90553  Select *pNew, *pPrior;
90554  assert( db!=0 );
90555  if( p==0 ) return 0;
90556  pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
90557  if( pNew==0 ) return 0;
90558  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
90559  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
90560  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
90561  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
90562  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
90563  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
90564  pNew->op = p->op;
90565  pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
90566  if( pPrior ) pPrior->pNext = pNew;
90567  pNew->pNext = 0;
90568  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
90569  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
90570  pNew->iLimit = 0;
90571  pNew->iOffset = 0;
90572  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
90573  pNew->addrOpenEphm[0] = -1;
90574  pNew->addrOpenEphm[1] = -1;
90575  pNew->nSelectRow = p->nSelectRow;
90576  pNew->pWith = withDup(db, p->pWith);
90577  sqlite3SelectSetName(pNew, p->zSelName);
90578  return pNew;
90579}
90580#else
90581SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
90582  assert( p==0 );
90583  return 0;
90584}
90585#endif
90586
90587
90588/*
90589** Add a new element to the end of an expression list.  If pList is
90590** initially NULL, then create a new expression list.
90591**
90592** If a memory allocation error occurs, the entire list is freed and
90593** NULL is returned.  If non-NULL is returned, then it is guaranteed
90594** that the new entry was successfully appended.
90595*/
90596SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
90597  Parse *pParse,          /* Parsing context */
90598  ExprList *pList,        /* List to which to append. Might be NULL */
90599  Expr *pExpr             /* Expression to be appended. Might be NULL */
90600){
90601  sqlite3 *db = pParse->db;
90602  assert( db!=0 );
90603  if( pList==0 ){
90604    pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
90605    if( pList==0 ){
90606      goto no_mem;
90607    }
90608    pList->nExpr = 0;
90609    pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0]));
90610    if( pList->a==0 ) goto no_mem;
90611  }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
90612    struct ExprList_item *a;
90613    assert( pList->nExpr>0 );
90614    a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
90615    if( a==0 ){
90616      goto no_mem;
90617    }
90618    pList->a = a;
90619  }
90620  assert( pList->a!=0 );
90621  if( 1 ){
90622    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
90623    memset(pItem, 0, sizeof(*pItem));
90624    pItem->pExpr = pExpr;
90625  }
90626  return pList;
90627
90628no_mem:
90629  /* Avoid leaking memory if malloc has failed. */
90630  sqlite3ExprDelete(db, pExpr);
90631  sqlite3ExprListDelete(db, pList);
90632  return 0;
90633}
90634
90635/*
90636** Set the sort order for the last element on the given ExprList.
90637*/
90638SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
90639  if( p==0 ) return;
90640  assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
90641  assert( p->nExpr>0 );
90642  if( iSortOrder<0 ){
90643    assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
90644    return;
90645  }
90646  p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
90647}
90648
90649/*
90650** Set the ExprList.a[].zName element of the most recently added item
90651** on the expression list.
90652**
90653** pList might be NULL following an OOM error.  But pName should never be
90654** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
90655** is set.
90656*/
90657SQLITE_PRIVATE void sqlite3ExprListSetName(
90658  Parse *pParse,          /* Parsing context */
90659  ExprList *pList,        /* List to which to add the span. */
90660  Token *pName,           /* Name to be added */
90661  int dequote             /* True to cause the name to be dequoted */
90662){
90663  assert( pList!=0 || pParse->db->mallocFailed!=0 );
90664  if( pList ){
90665    struct ExprList_item *pItem;
90666    assert( pList->nExpr>0 );
90667    pItem = &pList->a[pList->nExpr-1];
90668    assert( pItem->zName==0 );
90669    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
90670    if( dequote ) sqlite3Dequote(pItem->zName);
90671  }
90672}
90673
90674/*
90675** Set the ExprList.a[].zSpan element of the most recently added item
90676** on the expression list.
90677**
90678** pList might be NULL following an OOM error.  But pSpan should never be
90679** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
90680** is set.
90681*/
90682SQLITE_PRIVATE void sqlite3ExprListSetSpan(
90683  Parse *pParse,          /* Parsing context */
90684  ExprList *pList,        /* List to which to add the span. */
90685  ExprSpan *pSpan         /* The span to be added */
90686){
90687  sqlite3 *db = pParse->db;
90688  assert( pList!=0 || db->mallocFailed!=0 );
90689  if( pList ){
90690    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
90691    assert( pList->nExpr>0 );
90692    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
90693    sqlite3DbFree(db, pItem->zSpan);
90694    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
90695                                    (int)(pSpan->zEnd - pSpan->zStart));
90696  }
90697}
90698
90699/*
90700** If the expression list pEList contains more than iLimit elements,
90701** leave an error message in pParse.
90702*/
90703SQLITE_PRIVATE void sqlite3ExprListCheckLength(
90704  Parse *pParse,
90705  ExprList *pEList,
90706  const char *zObject
90707){
90708  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
90709  testcase( pEList && pEList->nExpr==mx );
90710  testcase( pEList && pEList->nExpr==mx+1 );
90711  if( pEList && pEList->nExpr>mx ){
90712    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
90713  }
90714}
90715
90716/*
90717** Delete an entire expression list.
90718*/
90719static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
90720  int i;
90721  struct ExprList_item *pItem;
90722  assert( pList->a!=0 || pList->nExpr==0 );
90723  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
90724    sqlite3ExprDelete(db, pItem->pExpr);
90725    sqlite3DbFree(db, pItem->zName);
90726    sqlite3DbFree(db, pItem->zSpan);
90727  }
90728  sqlite3DbFree(db, pList->a);
90729  sqlite3DbFree(db, pList);
90730}
90731SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
90732  if( pList ) exprListDeleteNN(db, pList);
90733}
90734
90735/*
90736** Return the bitwise-OR of all Expr.flags fields in the given
90737** ExprList.
90738*/
90739SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
90740  int i;
90741  u32 m = 0;
90742  if( pList ){
90743    for(i=0; i<pList->nExpr; i++){
90744       Expr *pExpr = pList->a[i].pExpr;
90745       assert( pExpr!=0 );
90746       m |= pExpr->flags;
90747    }
90748  }
90749  return m;
90750}
90751
90752/*
90753** These routines are Walker callbacks used to check expressions to
90754** see if they are "constant" for some definition of constant.  The
90755** Walker.eCode value determines the type of "constant" we are looking
90756** for.
90757**
90758** These callback routines are used to implement the following:
90759**
90760**     sqlite3ExprIsConstant()                  pWalker->eCode==1
90761**     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
90762**     sqlite3ExprIsTableConstant()             pWalker->eCode==3
90763**     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
90764**
90765** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
90766** is found to not be a constant.
90767**
90768** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
90769** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
90770** an existing schema and 4 when processing a new statement.  A bound
90771** parameter raises an error for new statements, but is silently converted
90772** to NULL for existing schemas.  This allows sqlite_master tables that
90773** contain a bound parameter because they were generated by older versions
90774** of SQLite to be parsed by newer versions of SQLite without raising a
90775** malformed schema error.
90776*/
90777static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
90778
90779  /* If pWalker->eCode is 2 then any term of the expression that comes from
90780  ** the ON or USING clauses of a left join disqualifies the expression
90781  ** from being considered constant. */
90782  if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
90783    pWalker->eCode = 0;
90784    return WRC_Abort;
90785  }
90786
90787  switch( pExpr->op ){
90788    /* Consider functions to be constant if all their arguments are constant
90789    ** and either pWalker->eCode==4 or 5 or the function has the
90790    ** SQLITE_FUNC_CONST flag. */
90791    case TK_FUNCTION:
90792      if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
90793        return WRC_Continue;
90794      }else{
90795        pWalker->eCode = 0;
90796        return WRC_Abort;
90797      }
90798    case TK_ID:
90799    case TK_COLUMN:
90800    case TK_AGG_FUNCTION:
90801    case TK_AGG_COLUMN:
90802      testcase( pExpr->op==TK_ID );
90803      testcase( pExpr->op==TK_COLUMN );
90804      testcase( pExpr->op==TK_AGG_FUNCTION );
90805      testcase( pExpr->op==TK_AGG_COLUMN );
90806      if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
90807        return WRC_Continue;
90808      }else{
90809        pWalker->eCode = 0;
90810        return WRC_Abort;
90811      }
90812    case TK_VARIABLE:
90813      if( pWalker->eCode==5 ){
90814        /* Silently convert bound parameters that appear inside of CREATE
90815        ** statements into a NULL when parsing the CREATE statement text out
90816        ** of the sqlite_master table */
90817        pExpr->op = TK_NULL;
90818      }else if( pWalker->eCode==4 ){
90819        /* A bound parameter in a CREATE statement that originates from
90820        ** sqlite3_prepare() causes an error */
90821        pWalker->eCode = 0;
90822        return WRC_Abort;
90823      }
90824      /* Fall through */
90825    default:
90826      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
90827      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
90828      return WRC_Continue;
90829  }
90830}
90831static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
90832  UNUSED_PARAMETER(NotUsed);
90833  pWalker->eCode = 0;
90834  return WRC_Abort;
90835}
90836static int exprIsConst(Expr *p, int initFlag, int iCur){
90837  Walker w;
90838  memset(&w, 0, sizeof(w));
90839  w.eCode = initFlag;
90840  w.xExprCallback = exprNodeIsConstant;
90841  w.xSelectCallback = selectNodeIsConstant;
90842  w.u.iCur = iCur;
90843  sqlite3WalkExpr(&w, p);
90844  return w.eCode;
90845}
90846
90847/*
90848** Walk an expression tree.  Return non-zero if the expression is constant
90849** and 0 if it involves variables or function calls.
90850**
90851** For the purposes of this function, a double-quoted string (ex: "abc")
90852** is considered a variable but a single-quoted string (ex: 'abc') is
90853** a constant.
90854*/
90855SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
90856  return exprIsConst(p, 1, 0);
90857}
90858
90859/*
90860** Walk an expression tree.  Return non-zero if the expression is constant
90861** that does no originate from the ON or USING clauses of a join.
90862** Return 0 if it involves variables or function calls or terms from
90863** an ON or USING clause.
90864*/
90865SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
90866  return exprIsConst(p, 2, 0);
90867}
90868
90869/*
90870** Walk an expression tree.  Return non-zero if the expression is constant
90871** for any single row of the table with cursor iCur.  In other words, the
90872** expression must not refer to any non-deterministic function nor any
90873** table other than iCur.
90874*/
90875SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
90876  return exprIsConst(p, 3, iCur);
90877}
90878
90879/*
90880** Walk an expression tree.  Return non-zero if the expression is constant
90881** or a function call with constant arguments.  Return and 0 if there
90882** are any variables.
90883**
90884** For the purposes of this function, a double-quoted string (ex: "abc")
90885** is considered a variable but a single-quoted string (ex: 'abc') is
90886** a constant.
90887*/
90888SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
90889  assert( isInit==0 || isInit==1 );
90890  return exprIsConst(p, 4+isInit, 0);
90891}
90892
90893#ifdef SQLITE_ENABLE_CURSOR_HINTS
90894/*
90895** Walk an expression tree.  Return 1 if the expression contains a
90896** subquery of some kind.  Return 0 if there are no subqueries.
90897*/
90898SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
90899  Walker w;
90900  memset(&w, 0, sizeof(w));
90901  w.eCode = 1;
90902  w.xExprCallback = sqlite3ExprWalkNoop;
90903  w.xSelectCallback = selectNodeIsConstant;
90904  sqlite3WalkExpr(&w, p);
90905  return w.eCode==0;
90906}
90907#endif
90908
90909/*
90910** If the expression p codes a constant integer that is small enough
90911** to fit in a 32-bit integer, return 1 and put the value of the integer
90912** in *pValue.  If the expression is not an integer or if it is too big
90913** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
90914*/
90915SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
90916  int rc = 0;
90917
90918  /* If an expression is an integer literal that fits in a signed 32-bit
90919  ** integer, then the EP_IntValue flag will have already been set */
90920  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
90921           || sqlite3GetInt32(p->u.zToken, &rc)==0 );
90922
90923  if( p->flags & EP_IntValue ){
90924    *pValue = p->u.iValue;
90925    return 1;
90926  }
90927  switch( p->op ){
90928    case TK_UPLUS: {
90929      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
90930      break;
90931    }
90932    case TK_UMINUS: {
90933      int v;
90934      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
90935        assert( v!=(-2147483647-1) );
90936        *pValue = -v;
90937        rc = 1;
90938      }
90939      break;
90940    }
90941    default: break;
90942  }
90943  return rc;
90944}
90945
90946/*
90947** Return FALSE if there is no chance that the expression can be NULL.
90948**
90949** If the expression might be NULL or if the expression is too complex
90950** to tell return TRUE.
90951**
90952** This routine is used as an optimization, to skip OP_IsNull opcodes
90953** when we know that a value cannot be NULL.  Hence, a false positive
90954** (returning TRUE when in fact the expression can never be NULL) might
90955** be a small performance hit but is otherwise harmless.  On the other
90956** hand, a false negative (returning FALSE when the result could be NULL)
90957** will likely result in an incorrect answer.  So when in doubt, return
90958** TRUE.
90959*/
90960SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
90961  u8 op;
90962  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
90963  op = p->op;
90964  if( op==TK_REGISTER ) op = p->op2;
90965  switch( op ){
90966    case TK_INTEGER:
90967    case TK_STRING:
90968    case TK_FLOAT:
90969    case TK_BLOB:
90970      return 0;
90971    case TK_COLUMN:
90972      assert( p->pTab!=0 );
90973      return ExprHasProperty(p, EP_CanBeNull) ||
90974             (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
90975    default:
90976      return 1;
90977  }
90978}
90979
90980/*
90981** Return TRUE if the given expression is a constant which would be
90982** unchanged by OP_Affinity with the affinity given in the second
90983** argument.
90984**
90985** This routine is used to determine if the OP_Affinity operation
90986** can be omitted.  When in doubt return FALSE.  A false negative
90987** is harmless.  A false positive, however, can result in the wrong
90988** answer.
90989*/
90990SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
90991  u8 op;
90992  if( aff==SQLITE_AFF_BLOB ) return 1;
90993  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
90994  op = p->op;
90995  if( op==TK_REGISTER ) op = p->op2;
90996  switch( op ){
90997    case TK_INTEGER: {
90998      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
90999    }
91000    case TK_FLOAT: {
91001      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
91002    }
91003    case TK_STRING: {
91004      return aff==SQLITE_AFF_TEXT;
91005    }
91006    case TK_BLOB: {
91007      return 1;
91008    }
91009    case TK_COLUMN: {
91010      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
91011      return p->iColumn<0
91012          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
91013    }
91014    default: {
91015      return 0;
91016    }
91017  }
91018}
91019
91020/*
91021** Return TRUE if the given string is a row-id column name.
91022*/
91023SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
91024  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
91025  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
91026  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
91027  return 0;
91028}
91029
91030/*
91031** pX is the RHS of an IN operator.  If pX is a SELECT statement
91032** that can be simplified to a direct table access, then return
91033** a pointer to the SELECT statement.  If pX is not a SELECT statement,
91034** or if the SELECT statement needs to be manifested into a transient
91035** table, then return NULL.
91036*/
91037#ifndef SQLITE_OMIT_SUBQUERY
91038static Select *isCandidateForInOpt(Expr *pX){
91039  Select *p;
91040  SrcList *pSrc;
91041  ExprList *pEList;
91042  Expr *pRes;
91043  Table *pTab;
91044  if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */
91045  if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
91046  p = pX->x.pSelect;
91047  if( p->pPrior ) return 0;              /* Not a compound SELECT */
91048  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
91049    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
91050    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
91051    return 0; /* No DISTINCT keyword and no aggregate functions */
91052  }
91053  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
91054  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
91055  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
91056  if( p->pWhere ) return 0;              /* Has no WHERE clause */
91057  pSrc = p->pSrc;
91058  assert( pSrc!=0 );
91059  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
91060  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
91061  pTab = pSrc->a[0].pTab;
91062  assert( pTab!=0 );
91063  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
91064  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
91065  pEList = p->pEList;
91066  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
91067  pRes = pEList->a[0].pExpr;
91068  if( pRes->op!=TK_COLUMN ) return 0;    /* Result is a column */
91069  assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */
91070  return p;
91071}
91072#endif /* SQLITE_OMIT_SUBQUERY */
91073
91074/*
91075** Code an OP_Once instruction and allocate space for its flag. Return the
91076** address of the new instruction.
91077*/
91078SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
91079  Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
91080  return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
91081}
91082
91083/*
91084** Generate code that checks the left-most column of index table iCur to see if
91085** it contains any NULL entries.  Cause the register at regHasNull to be set
91086** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
91087** to be set to NULL if iCur contains one or more NULL values.
91088*/
91089static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
91090  int addr1;
91091  sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
91092  addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
91093  sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
91094  sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
91095  VdbeComment((v, "first_entry_in(%d)", iCur));
91096  sqlite3VdbeJumpHere(v, addr1);
91097}
91098
91099
91100#ifndef SQLITE_OMIT_SUBQUERY
91101/*
91102** The argument is an IN operator with a list (not a subquery) on the
91103** right-hand side.  Return TRUE if that list is constant.
91104*/
91105static int sqlite3InRhsIsConstant(Expr *pIn){
91106  Expr *pLHS;
91107  int res;
91108  assert( !ExprHasProperty(pIn, EP_xIsSelect) );
91109  pLHS = pIn->pLeft;
91110  pIn->pLeft = 0;
91111  res = sqlite3ExprIsConstant(pIn);
91112  pIn->pLeft = pLHS;
91113  return res;
91114}
91115#endif
91116
91117/*
91118** This function is used by the implementation of the IN (...) operator.
91119** The pX parameter is the expression on the RHS of the IN operator, which
91120** might be either a list of expressions or a subquery.
91121**
91122** The job of this routine is to find or create a b-tree object that can
91123** be used either to test for membership in the RHS set or to iterate through
91124** all members of the RHS set, skipping duplicates.
91125**
91126** A cursor is opened on the b-tree object that is the RHS of the IN operator
91127** and pX->iTable is set to the index of that cursor.
91128**
91129** The returned value of this function indicates the b-tree type, as follows:
91130**
91131**   IN_INDEX_ROWID      - The cursor was opened on a database table.
91132**   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
91133**   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
91134**   IN_INDEX_EPH        - The cursor was opened on a specially created and
91135**                         populated epheremal table.
91136**   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
91137**                         implemented as a sequence of comparisons.
91138**
91139** An existing b-tree might be used if the RHS expression pX is a simple
91140** subquery such as:
91141**
91142**     SELECT <column> FROM <table>
91143**
91144** If the RHS of the IN operator is a list or a more complex subquery, then
91145** an ephemeral table might need to be generated from the RHS and then
91146** pX->iTable made to point to the ephemeral table instead of an
91147** existing table.
91148**
91149** The inFlags parameter must contain exactly one of the bits
91150** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP.  If inFlags contains
91151** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
91152** fast membership test.  When the IN_INDEX_LOOP bit is set, the
91153** IN index will be used to loop over all values of the RHS of the
91154** IN operator.
91155**
91156** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
91157** through the set members) then the b-tree must not contain duplicates.
91158** An epheremal table must be used unless the selected <column> is guaranteed
91159** to be unique - either because it is an INTEGER PRIMARY KEY or it
91160** has a UNIQUE constraint or UNIQUE index.
91161**
91162** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
91163** for fast set membership tests) then an epheremal table must
91164** be used unless <column> is an INTEGER PRIMARY KEY or an index can
91165** be found with <column> as its left-most column.
91166**
91167** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
91168** if the RHS of the IN operator is a list (not a subquery) then this
91169** routine might decide that creating an ephemeral b-tree for membership
91170** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
91171** calling routine should implement the IN operator using a sequence
91172** of Eq or Ne comparison operations.
91173**
91174** When the b-tree is being used for membership tests, the calling function
91175** might need to know whether or not the RHS side of the IN operator
91176** contains a NULL.  If prRhsHasNull is not a NULL pointer and
91177** if there is any chance that the (...) might contain a NULL value at
91178** runtime, then a register is allocated and the register number written
91179** to *prRhsHasNull. If there is no chance that the (...) contains a
91180** NULL value, then *prRhsHasNull is left unchanged.
91181**
91182** If a register is allocated and its location stored in *prRhsHasNull, then
91183** the value in that register will be NULL if the b-tree contains one or more
91184** NULL values, and it will be some non-NULL value if the b-tree contains no
91185** NULL values.
91186*/
91187#ifndef SQLITE_OMIT_SUBQUERY
91188SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
91189  Select *p;                            /* SELECT to the right of IN operator */
91190  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
91191  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
91192  int mustBeUnique;                     /* True if RHS must be unique */
91193  Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
91194
91195  assert( pX->op==TK_IN );
91196  mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
91197
91198  /* Check to see if an existing table or index can be used to
91199  ** satisfy the query.  This is preferable to generating a new
91200  ** ephemeral table.
91201  */
91202  if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
91203    sqlite3 *db = pParse->db;              /* Database connection */
91204    Table *pTab;                           /* Table <table>. */
91205    Expr *pExpr;                           /* Expression <column> */
91206    i16 iCol;                              /* Index of column <column> */
91207    i16 iDb;                               /* Database idx for pTab */
91208
91209    assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
91210    assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
91211    assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
91212    pTab = p->pSrc->a[0].pTab;
91213    pExpr = p->pEList->a[0].pExpr;
91214    iCol = (i16)pExpr->iColumn;
91215
91216    /* Code an OP_Transaction and OP_TableLock for <table>. */
91217    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
91218    sqlite3CodeVerifySchema(pParse, iDb);
91219    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
91220
91221    /* This function is only called from two places. In both cases the vdbe
91222    ** has already been allocated. So assume sqlite3GetVdbe() is always
91223    ** successful here.
91224    */
91225    assert(v);
91226    if( iCol<0 ){
91227      int iAddr = sqlite3CodeOnce(pParse);
91228      VdbeCoverage(v);
91229
91230      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
91231      eType = IN_INDEX_ROWID;
91232
91233      sqlite3VdbeJumpHere(v, iAddr);
91234    }else{
91235      Index *pIdx;                         /* Iterator variable */
91236
91237      /* The collation sequence used by the comparison. If an index is to
91238      ** be used in place of a temp-table, it must be ordered according
91239      ** to this collation sequence.  */
91240      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
91241
91242      /* Check that the affinity that will be used to perform the
91243      ** comparison is the same as the affinity of the column. If
91244      ** it is not, it is not possible to use any index.
91245      */
91246      int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
91247
91248      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
91249        if( (pIdx->aiColumn[0]==iCol)
91250         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
91251         && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
91252        ){
91253          int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
91254          sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
91255          sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
91256          VdbeComment((v, "%s", pIdx->zName));
91257          assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
91258          eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
91259
91260          if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
91261#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
91262            const i64 sOne = 1;
91263            sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
91264                iTab, 0, 0, (u8*)&sOne, P4_INT64);
91265#endif
91266            *prRhsHasNull = ++pParse->nMem;
91267            sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
91268          }
91269          sqlite3VdbeJumpHere(v, iAddr);
91270        }
91271      }
91272    }
91273  }
91274
91275  /* If no preexisting index is available for the IN clause
91276  ** and IN_INDEX_NOOP is an allowed reply
91277  ** and the RHS of the IN operator is a list, not a subquery
91278  ** and the RHS is not constant or has two or fewer terms,
91279  ** then it is not worth creating an ephemeral table to evaluate
91280  ** the IN operator so return IN_INDEX_NOOP.
91281  */
91282  if( eType==0
91283   && (inFlags & IN_INDEX_NOOP_OK)
91284   && !ExprHasProperty(pX, EP_xIsSelect)
91285   && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
91286  ){
91287    eType = IN_INDEX_NOOP;
91288  }
91289
91290
91291  if( eType==0 ){
91292    /* Could not find an existing table or index to use as the RHS b-tree.
91293    ** We will have to generate an ephemeral table to do the job.
91294    */
91295    u32 savedNQueryLoop = pParse->nQueryLoop;
91296    int rMayHaveNull = 0;
91297    eType = IN_INDEX_EPH;
91298    if( inFlags & IN_INDEX_LOOP ){
91299      pParse->nQueryLoop = 0;
91300      if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
91301        eType = IN_INDEX_ROWID;
91302      }
91303    }else if( prRhsHasNull ){
91304      *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
91305    }
91306    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
91307    pParse->nQueryLoop = savedNQueryLoop;
91308  }else{
91309    pX->iTable = iTab;
91310  }
91311  return eType;
91312}
91313#endif
91314
91315/*
91316** Generate code for scalar subqueries used as a subquery expression, EXISTS,
91317** or IN operators.  Examples:
91318**
91319**     (SELECT a FROM b)          -- subquery
91320**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
91321**     x IN (4,5,11)              -- IN operator with list on right-hand side
91322**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
91323**
91324** The pExpr parameter describes the expression that contains the IN
91325** operator or subquery.
91326**
91327** If parameter isRowid is non-zero, then expression pExpr is guaranteed
91328** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
91329** to some integer key column of a table B-Tree. In this case, use an
91330** intkey B-Tree to store the set of IN(...) values instead of the usual
91331** (slower) variable length keys B-Tree.
91332**
91333** If rMayHaveNull is non-zero, that means that the operation is an IN
91334** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
91335** All this routine does is initialize the register given by rMayHaveNull
91336** to NULL.  Calling routines will take care of changing this register
91337** value to non-NULL if the RHS is NULL-free.
91338**
91339** For a SELECT or EXISTS operator, return the register that holds the
91340** result.  For IN operators or if an error occurs, the return value is 0.
91341*/
91342#ifndef SQLITE_OMIT_SUBQUERY
91343SQLITE_PRIVATE int sqlite3CodeSubselect(
91344  Parse *pParse,          /* Parsing context */
91345  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
91346  int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
91347  int isRowid             /* If true, LHS of IN operator is a rowid */
91348){
91349  int jmpIfDynamic = -1;                      /* One-time test address */
91350  int rReg = 0;                           /* Register storing resulting */
91351  Vdbe *v = sqlite3GetVdbe(pParse);
91352  if( NEVER(v==0) ) return 0;
91353  sqlite3ExprCachePush(pParse);
91354
91355  /* This code must be run in its entirety every time it is encountered
91356  ** if any of the following is true:
91357  **
91358  **    *  The right-hand side is a correlated subquery
91359  **    *  The right-hand side is an expression list containing variables
91360  **    *  We are inside a trigger
91361  **
91362  ** If all of the above are false, then we can run this code just once
91363  ** save the results, and reuse the same result on subsequent invocations.
91364  */
91365  if( !ExprHasProperty(pExpr, EP_VarSelect) ){
91366    jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
91367  }
91368
91369#ifndef SQLITE_OMIT_EXPLAIN
91370  if( pParse->explain==2 ){
91371    char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
91372        jmpIfDynamic>=0?"":"CORRELATED ",
91373        pExpr->op==TK_IN?"LIST":"SCALAR",
91374        pParse->iNextSelectId
91375    );
91376    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
91377  }
91378#endif
91379
91380  switch( pExpr->op ){
91381    case TK_IN: {
91382      char affinity;              /* Affinity of the LHS of the IN */
91383      int addr;                   /* Address of OP_OpenEphemeral instruction */
91384      Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
91385      KeyInfo *pKeyInfo = 0;      /* Key information */
91386
91387      affinity = sqlite3ExprAffinity(pLeft);
91388
91389      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
91390      ** expression it is handled the same way.  An ephemeral table is
91391      ** filled with single-field index keys representing the results
91392      ** from the SELECT or the <exprlist>.
91393      **
91394      ** If the 'x' expression is a column value, or the SELECT...
91395      ** statement returns a column value, then the affinity of that
91396      ** column is used to build the index keys. If both 'x' and the
91397      ** SELECT... statement are columns, then numeric affinity is used
91398      ** if either column has NUMERIC or INTEGER affinity. If neither
91399      ** 'x' nor the SELECT... statement are columns, then numeric affinity
91400      ** is used.
91401      */
91402      pExpr->iTable = pParse->nTab++;
91403      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
91404      pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
91405
91406      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
91407        /* Case 1:     expr IN (SELECT ...)
91408        **
91409        ** Generate code to write the results of the select into the temporary
91410        ** table allocated and opened above.
91411        */
91412        Select *pSelect = pExpr->x.pSelect;
91413        SelectDest dest;
91414        ExprList *pEList;
91415
91416        assert( !isRowid );
91417        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
91418        dest.affSdst = (u8)affinity;
91419        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
91420        pSelect->iLimit = 0;
91421        testcase( pSelect->selFlags & SF_Distinct );
91422        testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
91423        if( sqlite3Select(pParse, pSelect, &dest) ){
91424          sqlite3KeyInfoUnref(pKeyInfo);
91425          return 0;
91426        }
91427        pEList = pSelect->pEList;
91428        assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
91429        assert( pEList!=0 );
91430        assert( pEList->nExpr>0 );
91431        assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
91432        pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
91433                                                         pEList->a[0].pExpr);
91434      }else if( ALWAYS(pExpr->x.pList!=0) ){
91435        /* Case 2:     expr IN (exprlist)
91436        **
91437        ** For each expression, build an index key from the evaluation and
91438        ** store it in the temporary table. If <expr> is a column, then use
91439        ** that columns affinity when building index keys. If <expr> is not
91440        ** a column, use numeric affinity.
91441        */
91442        int i;
91443        ExprList *pList = pExpr->x.pList;
91444        struct ExprList_item *pItem;
91445        int r1, r2, r3;
91446
91447        if( !affinity ){
91448          affinity = SQLITE_AFF_BLOB;
91449        }
91450        if( pKeyInfo ){
91451          assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
91452          pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
91453        }
91454
91455        /* Loop through each expression in <exprlist>. */
91456        r1 = sqlite3GetTempReg(pParse);
91457        r2 = sqlite3GetTempReg(pParse);
91458        if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
91459        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
91460          Expr *pE2 = pItem->pExpr;
91461          int iValToIns;
91462
91463          /* If the expression is not constant then we will need to
91464          ** disable the test that was generated above that makes sure
91465          ** this code only executes once.  Because for a non-constant
91466          ** expression we need to rerun this code each time.
91467          */
91468          if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
91469            sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
91470            jmpIfDynamic = -1;
91471          }
91472
91473          /* Evaluate the expression and insert it into the temp table */
91474          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
91475            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
91476          }else{
91477            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
91478            if( isRowid ){
91479              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
91480                                sqlite3VdbeCurrentAddr(v)+2);
91481              VdbeCoverage(v);
91482              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
91483            }else{
91484              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
91485              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
91486              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
91487            }
91488          }
91489        }
91490        sqlite3ReleaseTempReg(pParse, r1);
91491        sqlite3ReleaseTempReg(pParse, r2);
91492      }
91493      if( pKeyInfo ){
91494        sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
91495      }
91496      break;
91497    }
91498
91499    case TK_EXISTS:
91500    case TK_SELECT:
91501    default: {
91502      /* If this has to be a scalar SELECT.  Generate code to put the
91503      ** value of this select in a memory cell and record the number
91504      ** of the memory cell in iColumn.  If this is an EXISTS, write
91505      ** an integer 0 (not exists) or 1 (exists) into a memory cell
91506      ** and record that memory cell in iColumn.
91507      */
91508      Select *pSel;                         /* SELECT statement to encode */
91509      SelectDest dest;                      /* How to deal with SELECt result */
91510
91511      testcase( pExpr->op==TK_EXISTS );
91512      testcase( pExpr->op==TK_SELECT );
91513      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
91514
91515      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
91516      pSel = pExpr->x.pSelect;
91517      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
91518      if( pExpr->op==TK_SELECT ){
91519        dest.eDest = SRT_Mem;
91520        dest.iSdst = dest.iSDParm;
91521        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
91522        VdbeComment((v, "Init subquery result"));
91523      }else{
91524        dest.eDest = SRT_Exists;
91525        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
91526        VdbeComment((v, "Init EXISTS result"));
91527      }
91528      sqlite3ExprDelete(pParse->db, pSel->pLimit);
91529      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
91530                                  &sqlite3IntTokens[1]);
91531      pSel->iLimit = 0;
91532      pSel->selFlags &= ~SF_MultiValue;
91533      if( sqlite3Select(pParse, pSel, &dest) ){
91534        return 0;
91535      }
91536      rReg = dest.iSDParm;
91537      ExprSetVVAProperty(pExpr, EP_NoReduce);
91538      break;
91539    }
91540  }
91541
91542  if( rHasNullFlag ){
91543    sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
91544  }
91545
91546  if( jmpIfDynamic>=0 ){
91547    sqlite3VdbeJumpHere(v, jmpIfDynamic);
91548  }
91549  sqlite3ExprCachePop(pParse);
91550
91551  return rReg;
91552}
91553#endif /* SQLITE_OMIT_SUBQUERY */
91554
91555#ifndef SQLITE_OMIT_SUBQUERY
91556/*
91557** Generate code for an IN expression.
91558**
91559**      x IN (SELECT ...)
91560**      x IN (value, value, ...)
91561**
91562** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
91563** is an array of zero or more values.  The expression is true if the LHS is
91564** contained within the RHS.  The value of the expression is unknown (NULL)
91565** if the LHS is NULL or if the LHS is not contained within the RHS and the
91566** RHS contains one or more NULL values.
91567**
91568** This routine generates code that jumps to destIfFalse if the LHS is not
91569** contained within the RHS.  If due to NULLs we cannot determine if the LHS
91570** is contained in the RHS then jump to destIfNull.  If the LHS is contained
91571** within the RHS then fall through.
91572*/
91573static void sqlite3ExprCodeIN(
91574  Parse *pParse,        /* Parsing and code generating context */
91575  Expr *pExpr,          /* The IN expression */
91576  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
91577  int destIfNull        /* Jump here if the results are unknown due to NULLs */
91578){
91579  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
91580  char affinity;        /* Comparison affinity to use */
91581  int eType;            /* Type of the RHS */
91582  int r1;               /* Temporary use register */
91583  Vdbe *v;              /* Statement under construction */
91584
91585  /* Compute the RHS.   After this step, the table with cursor
91586  ** pExpr->iTable will contains the values that make up the RHS.
91587  */
91588  v = pParse->pVdbe;
91589  assert( v!=0 );       /* OOM detected prior to this routine */
91590  VdbeNoopComment((v, "begin IN expr"));
91591  eType = sqlite3FindInIndex(pParse, pExpr,
91592                             IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
91593                             destIfFalse==destIfNull ? 0 : &rRhsHasNull);
91594
91595  /* Figure out the affinity to use to create a key from the results
91596  ** of the expression. affinityStr stores a static string suitable for
91597  ** P4 of OP_MakeRecord.
91598  */
91599  affinity = comparisonAffinity(pExpr);
91600
91601  /* Code the LHS, the <expr> from "<expr> IN (...)".
91602  */
91603  sqlite3ExprCachePush(pParse);
91604  r1 = sqlite3GetTempReg(pParse);
91605  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
91606
91607  /* If sqlite3FindInIndex() did not find or create an index that is
91608  ** suitable for evaluating the IN operator, then evaluate using a
91609  ** sequence of comparisons.
91610  */
91611  if( eType==IN_INDEX_NOOP ){
91612    ExprList *pList = pExpr->x.pList;
91613    CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
91614    int labelOk = sqlite3VdbeMakeLabel(v);
91615    int r2, regToFree;
91616    int regCkNull = 0;
91617    int ii;
91618    assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
91619    if( destIfNull!=destIfFalse ){
91620      regCkNull = sqlite3GetTempReg(pParse);
91621      sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
91622    }
91623    for(ii=0; ii<pList->nExpr; ii++){
91624      r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
91625      if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
91626        sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
91627      }
91628      if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
91629        sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
91630                          (void*)pColl, P4_COLLSEQ);
91631        VdbeCoverageIf(v, ii<pList->nExpr-1);
91632        VdbeCoverageIf(v, ii==pList->nExpr-1);
91633        sqlite3VdbeChangeP5(v, affinity);
91634      }else{
91635        assert( destIfNull==destIfFalse );
91636        sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
91637                          (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
91638        sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
91639      }
91640      sqlite3ReleaseTempReg(pParse, regToFree);
91641    }
91642    if( regCkNull ){
91643      sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
91644      sqlite3VdbeGoto(v, destIfFalse);
91645    }
91646    sqlite3VdbeResolveLabel(v, labelOk);
91647    sqlite3ReleaseTempReg(pParse, regCkNull);
91648  }else{
91649
91650    /* If the LHS is NULL, then the result is either false or NULL depending
91651    ** on whether the RHS is empty or not, respectively.
91652    */
91653    if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
91654      if( destIfNull==destIfFalse ){
91655        /* Shortcut for the common case where the false and NULL outcomes are
91656        ** the same. */
91657        sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
91658      }else{
91659        int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
91660        sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
91661        VdbeCoverage(v);
91662        sqlite3VdbeGoto(v, destIfNull);
91663        sqlite3VdbeJumpHere(v, addr1);
91664      }
91665    }
91666
91667    if( eType==IN_INDEX_ROWID ){
91668      /* In this case, the RHS is the ROWID of table b-tree
91669      */
91670      sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, r1);
91671      VdbeCoverage(v);
91672    }else{
91673      /* In this case, the RHS is an index b-tree.
91674      */
91675      sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
91676
91677      /* If the set membership test fails, then the result of the
91678      ** "x IN (...)" expression must be either 0 or NULL. If the set
91679      ** contains no NULL values, then the result is 0. If the set
91680      ** contains one or more NULL values, then the result of the
91681      ** expression is also NULL.
91682      */
91683      assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
91684      if( rRhsHasNull==0 ){
91685        /* This branch runs if it is known at compile time that the RHS
91686        ** cannot contain NULL values. This happens as the result
91687        ** of a "NOT NULL" constraint in the database schema.
91688        **
91689        ** Also run this branch if NULL is equivalent to FALSE
91690        ** for this particular IN operator.
91691        */
91692        sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
91693        VdbeCoverage(v);
91694      }else{
91695        /* In this branch, the RHS of the IN might contain a NULL and
91696        ** the presence of a NULL on the RHS makes a difference in the
91697        ** outcome.
91698        */
91699        int addr1;
91700
91701        /* First check to see if the LHS is contained in the RHS.  If so,
91702        ** then the answer is TRUE the presence of NULLs in the RHS does
91703        ** not matter.  If the LHS is not contained in the RHS, then the
91704        ** answer is NULL if the RHS contains NULLs and the answer is
91705        ** FALSE if the RHS is NULL-free.
91706        */
91707        addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
91708        VdbeCoverage(v);
91709        sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
91710        VdbeCoverage(v);
91711        sqlite3VdbeGoto(v, destIfFalse);
91712        sqlite3VdbeJumpHere(v, addr1);
91713      }
91714    }
91715  }
91716  sqlite3ReleaseTempReg(pParse, r1);
91717  sqlite3ExprCachePop(pParse);
91718  VdbeComment((v, "end IN expr"));
91719}
91720#endif /* SQLITE_OMIT_SUBQUERY */
91721
91722#ifndef SQLITE_OMIT_FLOATING_POINT
91723/*
91724** Generate an instruction that will put the floating point
91725** value described by z[0..n-1] into register iMem.
91726**
91727** The z[] string will probably not be zero-terminated.  But the
91728** z[n] character is guaranteed to be something that does not look
91729** like the continuation of the number.
91730*/
91731static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
91732  if( ALWAYS(z!=0) ){
91733    double value;
91734    sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
91735    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
91736    if( negateFlag ) value = -value;
91737    sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
91738  }
91739}
91740#endif
91741
91742
91743/*
91744** Generate an instruction that will put the integer describe by
91745** text z[0..n-1] into register iMem.
91746**
91747** Expr.u.zToken is always UTF8 and zero-terminated.
91748*/
91749static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
91750  Vdbe *v = pParse->pVdbe;
91751  if( pExpr->flags & EP_IntValue ){
91752    int i = pExpr->u.iValue;
91753    assert( i>=0 );
91754    if( negFlag ) i = -i;
91755    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
91756  }else{
91757    int c;
91758    i64 value;
91759    const char *z = pExpr->u.zToken;
91760    assert( z!=0 );
91761    c = sqlite3DecOrHexToI64(z, &value);
91762    if( c==0 || (c==2 && negFlag) ){
91763      if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
91764      sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
91765    }else{
91766#ifdef SQLITE_OMIT_FLOATING_POINT
91767      sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
91768#else
91769#ifndef SQLITE_OMIT_HEX_INTEGER
91770      if( sqlite3_strnicmp(z,"0x",2)==0 ){
91771        sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
91772      }else
91773#endif
91774      {
91775        codeReal(v, z, negFlag, iMem);
91776      }
91777#endif
91778    }
91779  }
91780}
91781
91782#if defined(SQLITE_DEBUG)
91783/*
91784** Verify the consistency of the column cache
91785*/
91786static int cacheIsValid(Parse *pParse){
91787  int i, n;
91788  for(i=n=0; i<SQLITE_N_COLCACHE; i++){
91789    if( pParse->aColCache[i].iReg>0 ) n++;
91790  }
91791  return n==pParse->nColCache;
91792}
91793#endif
91794
91795/*
91796** Clear a cache entry.
91797*/
91798static void cacheEntryClear(Parse *pParse, struct yColCache *p){
91799  if( p->tempReg ){
91800    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
91801      pParse->aTempReg[pParse->nTempReg++] = p->iReg;
91802    }
91803    p->tempReg = 0;
91804  }
91805  p->iReg = 0;
91806  pParse->nColCache--;
91807  assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
91808}
91809
91810
91811/*
91812** Record in the column cache that a particular column from a
91813** particular table is stored in a particular register.
91814*/
91815SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
91816  int i;
91817  int minLru;
91818  int idxLru;
91819  struct yColCache *p;
91820
91821  /* Unless an error has occurred, register numbers are always positive. */
91822  assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
91823  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
91824
91825  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
91826  ** for testing only - to verify that SQLite always gets the same answer
91827  ** with and without the column cache.
91828  */
91829  if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
91830
91831  /* First replace any existing entry.
91832  **
91833  ** Actually, the way the column cache is currently used, we are guaranteed
91834  ** that the object will never already be in cache.  Verify this guarantee.
91835  */
91836#ifndef NDEBUG
91837  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91838    assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
91839  }
91840#endif
91841
91842  /* Find an empty slot and replace it */
91843  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91844    if( p->iReg==0 ){
91845      p->iLevel = pParse->iCacheLevel;
91846      p->iTable = iTab;
91847      p->iColumn = iCol;
91848      p->iReg = iReg;
91849      p->tempReg = 0;
91850      p->lru = pParse->iCacheCnt++;
91851      pParse->nColCache++;
91852      assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
91853      return;
91854    }
91855  }
91856
91857  /* Replace the last recently used */
91858  minLru = 0x7fffffff;
91859  idxLru = -1;
91860  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91861    if( p->lru<minLru ){
91862      idxLru = i;
91863      minLru = p->lru;
91864    }
91865  }
91866  if( ALWAYS(idxLru>=0) ){
91867    p = &pParse->aColCache[idxLru];
91868    p->iLevel = pParse->iCacheLevel;
91869    p->iTable = iTab;
91870    p->iColumn = iCol;
91871    p->iReg = iReg;
91872    p->tempReg = 0;
91873    p->lru = pParse->iCacheCnt++;
91874    assert( cacheIsValid(pParse) );
91875    return;
91876  }
91877}
91878
91879/*
91880** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
91881** Purge the range of registers from the column cache.
91882*/
91883SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
91884  struct yColCache *p;
91885  if( iReg<=0 || pParse->nColCache==0 ) return;
91886  p = &pParse->aColCache[SQLITE_N_COLCACHE-1];
91887  while(1){
91888    if( p->iReg >= iReg && p->iReg < iReg+nReg ) cacheEntryClear(pParse, p);
91889    if( p==pParse->aColCache ) break;
91890    p--;
91891  }
91892}
91893
91894/*
91895** Remember the current column cache context.  Any new entries added
91896** added to the column cache after this call are removed when the
91897** corresponding pop occurs.
91898*/
91899SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
91900  pParse->iCacheLevel++;
91901#ifdef SQLITE_DEBUG
91902  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
91903    printf("PUSH to %d\n", pParse->iCacheLevel);
91904  }
91905#endif
91906}
91907
91908/*
91909** Remove from the column cache any entries that were added since the
91910** the previous sqlite3ExprCachePush operation.  In other words, restore
91911** the cache to the state it was in prior the most recent Push.
91912*/
91913SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
91914  int i;
91915  struct yColCache *p;
91916  assert( pParse->iCacheLevel>=1 );
91917  pParse->iCacheLevel--;
91918#ifdef SQLITE_DEBUG
91919  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
91920    printf("POP  to %d\n", pParse->iCacheLevel);
91921  }
91922#endif
91923  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91924    if( p->iReg && p->iLevel>pParse->iCacheLevel ){
91925      cacheEntryClear(pParse, p);
91926    }
91927  }
91928}
91929
91930/*
91931** When a cached column is reused, make sure that its register is
91932** no longer available as a temp register.  ticket #3879:  that same
91933** register might be in the cache in multiple places, so be sure to
91934** get them all.
91935*/
91936static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
91937  int i;
91938  struct yColCache *p;
91939  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91940    if( p->iReg==iReg ){
91941      p->tempReg = 0;
91942    }
91943  }
91944}
91945
91946/* Generate code that will load into register regOut a value that is
91947** appropriate for the iIdxCol-th column of index pIdx.
91948*/
91949SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
91950  Parse *pParse,  /* The parsing context */
91951  Index *pIdx,    /* The index whose column is to be loaded */
91952  int iTabCur,    /* Cursor pointing to a table row */
91953  int iIdxCol,    /* The column of the index to be loaded */
91954  int regOut      /* Store the index column value in this register */
91955){
91956  i16 iTabCol = pIdx->aiColumn[iIdxCol];
91957  if( iTabCol==XN_EXPR ){
91958    assert( pIdx->aColExpr );
91959    assert( pIdx->aColExpr->nExpr>iIdxCol );
91960    pParse->iSelfTab = iTabCur;
91961    sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
91962  }else{
91963    sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
91964                                    iTabCol, regOut);
91965  }
91966}
91967
91968/*
91969** Generate code to extract the value of the iCol-th column of a table.
91970*/
91971SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
91972  Vdbe *v,        /* The VDBE under construction */
91973  Table *pTab,    /* The table containing the value */
91974  int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
91975  int iCol,       /* Index of the column to extract */
91976  int regOut      /* Extract the value into this register */
91977){
91978  if( iCol<0 || iCol==pTab->iPKey ){
91979    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
91980  }else{
91981    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
91982    int x = iCol;
91983    if( !HasRowid(pTab) && !IsVirtual(pTab) ){
91984      x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
91985    }
91986    sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
91987  }
91988  if( iCol>=0 ){
91989    sqlite3ColumnDefault(v, pTab, iCol, regOut);
91990  }
91991}
91992
91993/*
91994** Generate code that will extract the iColumn-th column from
91995** table pTab and store the column value in a register.
91996**
91997** An effort is made to store the column value in register iReg.  This
91998** is not garanteeed for GetColumn() - the result can be stored in
91999** any register.  But the result is guaranteed to land in register iReg
92000** for GetColumnToReg().
92001**
92002** There must be an open cursor to pTab in iTable when this routine
92003** is called.  If iColumn<0 then code is generated that extracts the rowid.
92004*/
92005SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
92006  Parse *pParse,   /* Parsing and code generating context */
92007  Table *pTab,     /* Description of the table we are reading from */
92008  int iColumn,     /* Index of the table column */
92009  int iTable,      /* The cursor pointing to the table */
92010  int iReg,        /* Store results here */
92011  u8 p5            /* P5 value for OP_Column + FLAGS */
92012){
92013  Vdbe *v = pParse->pVdbe;
92014  int i;
92015  struct yColCache *p;
92016
92017  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
92018    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
92019      p->lru = pParse->iCacheCnt++;
92020      sqlite3ExprCachePinRegister(pParse, p->iReg);
92021      return p->iReg;
92022    }
92023  }
92024  assert( v!=0 );
92025  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
92026  if( p5 ){
92027    sqlite3VdbeChangeP5(v, p5);
92028  }else{
92029    sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
92030  }
92031  return iReg;
92032}
92033SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(
92034  Parse *pParse,   /* Parsing and code generating context */
92035  Table *pTab,     /* Description of the table we are reading from */
92036  int iColumn,     /* Index of the table column */
92037  int iTable,      /* The cursor pointing to the table */
92038  int iReg         /* Store results here */
92039){
92040  int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
92041  if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
92042}
92043
92044
92045/*
92046** Clear all column cache entries.
92047*/
92048SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
92049  int i;
92050  struct yColCache *p;
92051
92052#if SQLITE_DEBUG
92053  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
92054    printf("CLEAR\n");
92055  }
92056#endif
92057  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
92058    if( p->iReg ){
92059      cacheEntryClear(pParse, p);
92060    }
92061  }
92062}
92063
92064/*
92065** Record the fact that an affinity change has occurred on iCount
92066** registers starting with iStart.
92067*/
92068SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
92069  sqlite3ExprCacheRemove(pParse, iStart, iCount);
92070}
92071
92072/*
92073** Generate code to move content from registers iFrom...iFrom+nReg-1
92074** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
92075*/
92076SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
92077  assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
92078  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
92079  sqlite3ExprCacheRemove(pParse, iFrom, nReg);
92080}
92081
92082#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
92083/*
92084** Return true if any register in the range iFrom..iTo (inclusive)
92085** is used as part of the column cache.
92086**
92087** This routine is used within assert() and testcase() macros only
92088** and does not appear in a normal build.
92089*/
92090static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
92091  int i;
92092  struct yColCache *p;
92093  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
92094    int r = p->iReg;
92095    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
92096  }
92097  return 0;
92098}
92099#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
92100
92101
92102/*
92103** Convert an expression node to a TK_REGISTER
92104*/
92105static void exprToRegister(Expr *p, int iReg){
92106  p->op2 = p->op;
92107  p->op = TK_REGISTER;
92108  p->iTable = iReg;
92109  ExprClearProperty(p, EP_Skip);
92110}
92111
92112/*
92113** Generate code into the current Vdbe to evaluate the given
92114** expression.  Attempt to store the results in register "target".
92115** Return the register where results are stored.
92116**
92117** With this routine, there is no guarantee that results will
92118** be stored in target.  The result might be stored in some other
92119** register if it is convenient to do so.  The calling function
92120** must check the return code and move the results to the desired
92121** register.
92122*/
92123SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
92124  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
92125  int op;                   /* The opcode being coded */
92126  int inReg = target;       /* Results stored in register inReg */
92127  int regFree1 = 0;         /* If non-zero free this temporary register */
92128  int regFree2 = 0;         /* If non-zero free this temporary register */
92129  int r1, r2, r3, r4;       /* Various register numbers */
92130  sqlite3 *db = pParse->db; /* The database connection */
92131  Expr tempX;               /* Temporary expression node */
92132
92133  assert( target>0 && target<=pParse->nMem );
92134  if( v==0 ){
92135    assert( pParse->db->mallocFailed );
92136    return 0;
92137  }
92138
92139  if( pExpr==0 ){
92140    op = TK_NULL;
92141  }else{
92142    op = pExpr->op;
92143  }
92144  switch( op ){
92145    case TK_AGG_COLUMN: {
92146      AggInfo *pAggInfo = pExpr->pAggInfo;
92147      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
92148      if( !pAggInfo->directMode ){
92149        assert( pCol->iMem>0 );
92150        inReg = pCol->iMem;
92151        break;
92152      }else if( pAggInfo->useSortingIdx ){
92153        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
92154                              pCol->iSorterColumn, target);
92155        break;
92156      }
92157      /* Otherwise, fall thru into the TK_COLUMN case */
92158    }
92159    case TK_COLUMN: {
92160      int iTab = pExpr->iTable;
92161      if( iTab<0 ){
92162        if( pParse->ckBase>0 ){
92163          /* Generating CHECK constraints or inserting into partial index */
92164          inReg = pExpr->iColumn + pParse->ckBase;
92165          break;
92166        }else{
92167          /* Coding an expression that is part of an index where column names
92168          ** in the index refer to the table to which the index belongs */
92169          iTab = pParse->iSelfTab;
92170        }
92171      }
92172      inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
92173                               pExpr->iColumn, iTab, target,
92174                               pExpr->op2);
92175      break;
92176    }
92177    case TK_INTEGER: {
92178      codeInteger(pParse, pExpr, 0, target);
92179      break;
92180    }
92181#ifndef SQLITE_OMIT_FLOATING_POINT
92182    case TK_FLOAT: {
92183      assert( !ExprHasProperty(pExpr, EP_IntValue) );
92184      codeReal(v, pExpr->u.zToken, 0, target);
92185      break;
92186    }
92187#endif
92188    case TK_STRING: {
92189      assert( !ExprHasProperty(pExpr, EP_IntValue) );
92190      sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
92191      break;
92192    }
92193    case TK_NULL: {
92194      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
92195      break;
92196    }
92197#ifndef SQLITE_OMIT_BLOB_LITERAL
92198    case TK_BLOB: {
92199      int n;
92200      const char *z;
92201      char *zBlob;
92202      assert( !ExprHasProperty(pExpr, EP_IntValue) );
92203      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
92204      assert( pExpr->u.zToken[1]=='\'' );
92205      z = &pExpr->u.zToken[2];
92206      n = sqlite3Strlen30(z) - 1;
92207      assert( z[n]=='\'' );
92208      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
92209      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
92210      break;
92211    }
92212#endif
92213    case TK_VARIABLE: {
92214      assert( !ExprHasProperty(pExpr, EP_IntValue) );
92215      assert( pExpr->u.zToken!=0 );
92216      assert( pExpr->u.zToken[0]!=0 );
92217      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
92218      if( pExpr->u.zToken[1]!=0 ){
92219        assert( pExpr->u.zToken[0]=='?'
92220             || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
92221        sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
92222      }
92223      break;
92224    }
92225    case TK_REGISTER: {
92226      inReg = pExpr->iTable;
92227      break;
92228    }
92229#ifndef SQLITE_OMIT_CAST
92230    case TK_CAST: {
92231      /* Expressions of the form:   CAST(pLeft AS token) */
92232      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
92233      if( inReg!=target ){
92234        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
92235        inReg = target;
92236      }
92237      sqlite3VdbeAddOp2(v, OP_Cast, target,
92238                        sqlite3AffinityType(pExpr->u.zToken, 0));
92239      testcase( usedAsColumnCache(pParse, inReg, inReg) );
92240      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
92241      break;
92242    }
92243#endif /* SQLITE_OMIT_CAST */
92244    case TK_LT:
92245    case TK_LE:
92246    case TK_GT:
92247    case TK_GE:
92248    case TK_NE:
92249    case TK_EQ: {
92250      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92251      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
92252      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
92253                  r1, r2, inReg, SQLITE_STOREP2);
92254      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
92255      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
92256      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
92257      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
92258      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
92259      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
92260      testcase( regFree1==0 );
92261      testcase( regFree2==0 );
92262      break;
92263    }
92264    case TK_IS:
92265    case TK_ISNOT: {
92266      testcase( op==TK_IS );
92267      testcase( op==TK_ISNOT );
92268      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92269      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
92270      op = (op==TK_IS) ? TK_EQ : TK_NE;
92271      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
92272                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
92273      VdbeCoverageIf(v, op==TK_EQ);
92274      VdbeCoverageIf(v, op==TK_NE);
92275      testcase( regFree1==0 );
92276      testcase( regFree2==0 );
92277      break;
92278    }
92279    case TK_AND:
92280    case TK_OR:
92281    case TK_PLUS:
92282    case TK_STAR:
92283    case TK_MINUS:
92284    case TK_REM:
92285    case TK_BITAND:
92286    case TK_BITOR:
92287    case TK_SLASH:
92288    case TK_LSHIFT:
92289    case TK_RSHIFT:
92290    case TK_CONCAT: {
92291      assert( TK_AND==OP_And );            testcase( op==TK_AND );
92292      assert( TK_OR==OP_Or );              testcase( op==TK_OR );
92293      assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
92294      assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
92295      assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
92296      assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
92297      assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
92298      assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
92299      assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
92300      assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
92301      assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
92302      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92303      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
92304      sqlite3VdbeAddOp3(v, op, r2, r1, target);
92305      testcase( regFree1==0 );
92306      testcase( regFree2==0 );
92307      break;
92308    }
92309    case TK_UMINUS: {
92310      Expr *pLeft = pExpr->pLeft;
92311      assert( pLeft );
92312      if( pLeft->op==TK_INTEGER ){
92313        codeInteger(pParse, pLeft, 1, target);
92314#ifndef SQLITE_OMIT_FLOATING_POINT
92315      }else if( pLeft->op==TK_FLOAT ){
92316        assert( !ExprHasProperty(pExpr, EP_IntValue) );
92317        codeReal(v, pLeft->u.zToken, 1, target);
92318#endif
92319      }else{
92320        tempX.op = TK_INTEGER;
92321        tempX.flags = EP_IntValue|EP_TokenOnly;
92322        tempX.u.iValue = 0;
92323        r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
92324        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
92325        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
92326        testcase( regFree2==0 );
92327      }
92328      inReg = target;
92329      break;
92330    }
92331    case TK_BITNOT:
92332    case TK_NOT: {
92333      assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
92334      assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
92335      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92336      testcase( regFree1==0 );
92337      inReg = target;
92338      sqlite3VdbeAddOp2(v, op, r1, inReg);
92339      break;
92340    }
92341    case TK_ISNULL:
92342    case TK_NOTNULL: {
92343      int addr;
92344      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
92345      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
92346      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
92347      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92348      testcase( regFree1==0 );
92349      addr = sqlite3VdbeAddOp1(v, op, r1);
92350      VdbeCoverageIf(v, op==TK_ISNULL);
92351      VdbeCoverageIf(v, op==TK_NOTNULL);
92352      sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
92353      sqlite3VdbeJumpHere(v, addr);
92354      break;
92355    }
92356    case TK_AGG_FUNCTION: {
92357      AggInfo *pInfo = pExpr->pAggInfo;
92358      if( pInfo==0 ){
92359        assert( !ExprHasProperty(pExpr, EP_IntValue) );
92360        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
92361      }else{
92362        inReg = pInfo->aFunc[pExpr->iAgg].iMem;
92363      }
92364      break;
92365    }
92366    case TK_FUNCTION: {
92367      ExprList *pFarg;       /* List of function arguments */
92368      int nFarg;             /* Number of function arguments */
92369      FuncDef *pDef;         /* The function definition object */
92370      const char *zId;       /* The function name */
92371      u32 constMask = 0;     /* Mask of function arguments that are constant */
92372      int i;                 /* Loop counter */
92373      u8 enc = ENC(db);      /* The text encoding used by this database */
92374      CollSeq *pColl = 0;    /* A collating sequence */
92375
92376      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
92377      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
92378        pFarg = 0;
92379      }else{
92380        pFarg = pExpr->x.pList;
92381      }
92382      nFarg = pFarg ? pFarg->nExpr : 0;
92383      assert( !ExprHasProperty(pExpr, EP_IntValue) );
92384      zId = pExpr->u.zToken;
92385      pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
92386#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
92387      if( pDef==0 && pParse->explain ){
92388        pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
92389      }
92390#endif
92391      if( pDef==0 || pDef->xFinalize!=0 ){
92392        sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
92393        break;
92394      }
92395
92396      /* Attempt a direct implementation of the built-in COALESCE() and
92397      ** IFNULL() functions.  This avoids unnecessary evaluation of
92398      ** arguments past the first non-NULL argument.
92399      */
92400      if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
92401        int endCoalesce = sqlite3VdbeMakeLabel(v);
92402        assert( nFarg>=2 );
92403        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
92404        for(i=1; i<nFarg; i++){
92405          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
92406          VdbeCoverage(v);
92407          sqlite3ExprCacheRemove(pParse, target, 1);
92408          sqlite3ExprCachePush(pParse);
92409          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
92410          sqlite3ExprCachePop(pParse);
92411        }
92412        sqlite3VdbeResolveLabel(v, endCoalesce);
92413        break;
92414      }
92415
92416      /* The UNLIKELY() function is a no-op.  The result is the value
92417      ** of the first argument.
92418      */
92419      if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
92420        assert( nFarg>=1 );
92421        inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
92422        break;
92423      }
92424
92425      for(i=0; i<nFarg; i++){
92426        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
92427          testcase( i==31 );
92428          constMask |= MASKBIT32(i);
92429        }
92430        if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
92431          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
92432        }
92433      }
92434      if( pFarg ){
92435        if( constMask ){
92436          r1 = pParse->nMem+1;
92437          pParse->nMem += nFarg;
92438        }else{
92439          r1 = sqlite3GetTempRange(pParse, nFarg);
92440        }
92441
92442        /* For length() and typeof() functions with a column argument,
92443        ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
92444        ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
92445        ** loading.
92446        */
92447        if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
92448          u8 exprOp;
92449          assert( nFarg==1 );
92450          assert( pFarg->a[0].pExpr!=0 );
92451          exprOp = pFarg->a[0].pExpr->op;
92452          if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
92453            assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
92454            assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
92455            testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
92456            pFarg->a[0].pExpr->op2 =
92457                  pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
92458          }
92459        }
92460
92461        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
92462        sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
92463                                SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
92464        sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
92465      }else{
92466        r1 = 0;
92467      }
92468#ifndef SQLITE_OMIT_VIRTUALTABLE
92469      /* Possibly overload the function if the first argument is
92470      ** a virtual table column.
92471      **
92472      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
92473      ** second argument, not the first, as the argument to test to
92474      ** see if it is a column in a virtual table.  This is done because
92475      ** the left operand of infix functions (the operand we want to
92476      ** control overloading) ends up as the second argument to the
92477      ** function.  The expression "A glob B" is equivalent to
92478      ** "glob(B,A).  We want to use the A in "A glob B" to test
92479      ** for function overloading.  But we use the B term in "glob(B,A)".
92480      */
92481      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
92482        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
92483      }else if( nFarg>0 ){
92484        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
92485      }
92486#endif
92487      if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
92488        if( !pColl ) pColl = db->pDfltColl;
92489        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
92490      }
92491      sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
92492                        (char*)pDef, P4_FUNCDEF);
92493      sqlite3VdbeChangeP5(v, (u8)nFarg);
92494      if( nFarg && constMask==0 ){
92495        sqlite3ReleaseTempRange(pParse, r1, nFarg);
92496      }
92497      break;
92498    }
92499#ifndef SQLITE_OMIT_SUBQUERY
92500    case TK_EXISTS:
92501    case TK_SELECT: {
92502      testcase( op==TK_EXISTS );
92503      testcase( op==TK_SELECT );
92504      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
92505      break;
92506    }
92507    case TK_IN: {
92508      int destIfFalse = sqlite3VdbeMakeLabel(v);
92509      int destIfNull = sqlite3VdbeMakeLabel(v);
92510      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
92511      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
92512      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
92513      sqlite3VdbeResolveLabel(v, destIfFalse);
92514      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
92515      sqlite3VdbeResolveLabel(v, destIfNull);
92516      break;
92517    }
92518#endif /* SQLITE_OMIT_SUBQUERY */
92519
92520
92521    /*
92522    **    x BETWEEN y AND z
92523    **
92524    ** This is equivalent to
92525    **
92526    **    x>=y AND x<=z
92527    **
92528    ** X is stored in pExpr->pLeft.
92529    ** Y is stored in pExpr->pList->a[0].pExpr.
92530    ** Z is stored in pExpr->pList->a[1].pExpr.
92531    */
92532    case TK_BETWEEN: {
92533      Expr *pLeft = pExpr->pLeft;
92534      struct ExprList_item *pLItem = pExpr->x.pList->a;
92535      Expr *pRight = pLItem->pExpr;
92536
92537      r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
92538      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
92539      testcase( regFree1==0 );
92540      testcase( regFree2==0 );
92541      r3 = sqlite3GetTempReg(pParse);
92542      r4 = sqlite3GetTempReg(pParse);
92543      codeCompare(pParse, pLeft, pRight, OP_Ge,
92544                  r1, r2, r3, SQLITE_STOREP2);  VdbeCoverage(v);
92545      pLItem++;
92546      pRight = pLItem->pExpr;
92547      sqlite3ReleaseTempReg(pParse, regFree2);
92548      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
92549      testcase( regFree2==0 );
92550      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
92551      VdbeCoverage(v);
92552      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
92553      sqlite3ReleaseTempReg(pParse, r3);
92554      sqlite3ReleaseTempReg(pParse, r4);
92555      break;
92556    }
92557    case TK_SPAN:
92558    case TK_COLLATE:
92559    case TK_UPLUS: {
92560      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
92561      break;
92562    }
92563
92564    case TK_TRIGGER: {
92565      /* If the opcode is TK_TRIGGER, then the expression is a reference
92566      ** to a column in the new.* or old.* pseudo-tables available to
92567      ** trigger programs. In this case Expr.iTable is set to 1 for the
92568      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
92569      ** is set to the column of the pseudo-table to read, or to -1 to
92570      ** read the rowid field.
92571      **
92572      ** The expression is implemented using an OP_Param opcode. The p1
92573      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
92574      ** to reference another column of the old.* pseudo-table, where
92575      ** i is the index of the column. For a new.rowid reference, p1 is
92576      ** set to (n+1), where n is the number of columns in each pseudo-table.
92577      ** For a reference to any other column in the new.* pseudo-table, p1
92578      ** is set to (n+2+i), where n and i are as defined previously. For
92579      ** example, if the table on which triggers are being fired is
92580      ** declared as:
92581      **
92582      **   CREATE TABLE t1(a, b);
92583      **
92584      ** Then p1 is interpreted as follows:
92585      **
92586      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
92587      **   p1==1   ->    old.a         p1==4   ->    new.a
92588      **   p1==2   ->    old.b         p1==5   ->    new.b
92589      */
92590      Table *pTab = pExpr->pTab;
92591      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
92592
92593      assert( pExpr->iTable==0 || pExpr->iTable==1 );
92594      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
92595      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
92596      assert( p1>=0 && p1<(pTab->nCol*2+2) );
92597
92598      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
92599      VdbeComment((v, "%s.%s -> $%d",
92600        (pExpr->iTable ? "new" : "old"),
92601        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
92602        target
92603      ));
92604
92605#ifndef SQLITE_OMIT_FLOATING_POINT
92606      /* If the column has REAL affinity, it may currently be stored as an
92607      ** integer. Use OP_RealAffinity to make sure it is really real.
92608      **
92609      ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
92610      ** floating point when extracting it from the record.  */
92611      if( pExpr->iColumn>=0
92612       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
92613      ){
92614        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
92615      }
92616#endif
92617      break;
92618    }
92619
92620
92621    /*
92622    ** Form A:
92623    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
92624    **
92625    ** Form B:
92626    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
92627    **
92628    ** Form A is can be transformed into the equivalent form B as follows:
92629    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
92630    **        WHEN x=eN THEN rN ELSE y END
92631    **
92632    ** X (if it exists) is in pExpr->pLeft.
92633    ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
92634    ** odd.  The Y is also optional.  If the number of elements in x.pList
92635    ** is even, then Y is omitted and the "otherwise" result is NULL.
92636    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
92637    **
92638    ** The result of the expression is the Ri for the first matching Ei,
92639    ** or if there is no matching Ei, the ELSE term Y, or if there is
92640    ** no ELSE term, NULL.
92641    */
92642    default: assert( op==TK_CASE ); {
92643      int endLabel;                     /* GOTO label for end of CASE stmt */
92644      int nextCase;                     /* GOTO label for next WHEN clause */
92645      int nExpr;                        /* 2x number of WHEN terms */
92646      int i;                            /* Loop counter */
92647      ExprList *pEList;                 /* List of WHEN terms */
92648      struct ExprList_item *aListelem;  /* Array of WHEN terms */
92649      Expr opCompare;                   /* The X==Ei expression */
92650      Expr *pX;                         /* The X expression */
92651      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
92652      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
92653
92654      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
92655      assert(pExpr->x.pList->nExpr > 0);
92656      pEList = pExpr->x.pList;
92657      aListelem = pEList->a;
92658      nExpr = pEList->nExpr;
92659      endLabel = sqlite3VdbeMakeLabel(v);
92660      if( (pX = pExpr->pLeft)!=0 ){
92661        tempX = *pX;
92662        testcase( pX->op==TK_COLUMN );
92663        exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
92664        testcase( regFree1==0 );
92665        opCompare.op = TK_EQ;
92666        opCompare.pLeft = &tempX;
92667        pTest = &opCompare;
92668        /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
92669        ** The value in regFree1 might get SCopy-ed into the file result.
92670        ** So make sure that the regFree1 register is not reused for other
92671        ** purposes and possibly overwritten.  */
92672        regFree1 = 0;
92673      }
92674      for(i=0; i<nExpr-1; i=i+2){
92675        sqlite3ExprCachePush(pParse);
92676        if( pX ){
92677          assert( pTest!=0 );
92678          opCompare.pRight = aListelem[i].pExpr;
92679        }else{
92680          pTest = aListelem[i].pExpr;
92681        }
92682        nextCase = sqlite3VdbeMakeLabel(v);
92683        testcase( pTest->op==TK_COLUMN );
92684        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
92685        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
92686        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
92687        sqlite3VdbeGoto(v, endLabel);
92688        sqlite3ExprCachePop(pParse);
92689        sqlite3VdbeResolveLabel(v, nextCase);
92690      }
92691      if( (nExpr&1)!=0 ){
92692        sqlite3ExprCachePush(pParse);
92693        sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
92694        sqlite3ExprCachePop(pParse);
92695      }else{
92696        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
92697      }
92698      assert( db->mallocFailed || pParse->nErr>0
92699           || pParse->iCacheLevel==iCacheLevel );
92700      sqlite3VdbeResolveLabel(v, endLabel);
92701      break;
92702    }
92703#ifndef SQLITE_OMIT_TRIGGER
92704    case TK_RAISE: {
92705      assert( pExpr->affinity==OE_Rollback
92706           || pExpr->affinity==OE_Abort
92707           || pExpr->affinity==OE_Fail
92708           || pExpr->affinity==OE_Ignore
92709      );
92710      if( !pParse->pTriggerTab ){
92711        sqlite3ErrorMsg(pParse,
92712                       "RAISE() may only be used within a trigger-program");
92713        return 0;
92714      }
92715      if( pExpr->affinity==OE_Abort ){
92716        sqlite3MayAbort(pParse);
92717      }
92718      assert( !ExprHasProperty(pExpr, EP_IntValue) );
92719      if( pExpr->affinity==OE_Ignore ){
92720        sqlite3VdbeAddOp4(
92721            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
92722        VdbeCoverage(v);
92723      }else{
92724        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
92725                              pExpr->affinity, pExpr->u.zToken, 0, 0);
92726      }
92727
92728      break;
92729    }
92730#endif
92731  }
92732  sqlite3ReleaseTempReg(pParse, regFree1);
92733  sqlite3ReleaseTempReg(pParse, regFree2);
92734  return inReg;
92735}
92736
92737/*
92738** Factor out the code of the given expression to initialization time.
92739*/
92740SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
92741  Parse *pParse,    /* Parsing context */
92742  Expr *pExpr,      /* The expression to code when the VDBE initializes */
92743  int regDest,      /* Store the value in this register */
92744  u8 reusable       /* True if this expression is reusable */
92745){
92746  ExprList *p;
92747  assert( ConstFactorOk(pParse) );
92748  p = pParse->pConstExpr;
92749  pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
92750  p = sqlite3ExprListAppend(pParse, p, pExpr);
92751  if( p ){
92752     struct ExprList_item *pItem = &p->a[p->nExpr-1];
92753     pItem->u.iConstExprReg = regDest;
92754     pItem->reusable = reusable;
92755  }
92756  pParse->pConstExpr = p;
92757}
92758
92759/*
92760** Generate code to evaluate an expression and store the results
92761** into a register.  Return the register number where the results
92762** are stored.
92763**
92764** If the register is a temporary register that can be deallocated,
92765** then write its number into *pReg.  If the result register is not
92766** a temporary, then set *pReg to zero.
92767**
92768** If pExpr is a constant, then this routine might generate this
92769** code to fill the register in the initialization section of the
92770** VDBE program, in order to factor it out of the evaluation loop.
92771*/
92772SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
92773  int r2;
92774  pExpr = sqlite3ExprSkipCollate(pExpr);
92775  if( ConstFactorOk(pParse)
92776   && pExpr->op!=TK_REGISTER
92777   && sqlite3ExprIsConstantNotJoin(pExpr)
92778  ){
92779    ExprList *p = pParse->pConstExpr;
92780    int i;
92781    *pReg  = 0;
92782    if( p ){
92783      struct ExprList_item *pItem;
92784      for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
92785        if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
92786          return pItem->u.iConstExprReg;
92787        }
92788      }
92789    }
92790    r2 = ++pParse->nMem;
92791    sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
92792  }else{
92793    int r1 = sqlite3GetTempReg(pParse);
92794    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
92795    if( r2==r1 ){
92796      *pReg = r1;
92797    }else{
92798      sqlite3ReleaseTempReg(pParse, r1);
92799      *pReg = 0;
92800    }
92801  }
92802  return r2;
92803}
92804
92805/*
92806** Generate code that will evaluate expression pExpr and store the
92807** results in register target.  The results are guaranteed to appear
92808** in register target.
92809*/
92810SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
92811  int inReg;
92812
92813  assert( target>0 && target<=pParse->nMem );
92814  if( pExpr && pExpr->op==TK_REGISTER ){
92815    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
92816  }else{
92817    inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
92818    assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
92819    if( inReg!=target && pParse->pVdbe ){
92820      sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
92821    }
92822  }
92823}
92824
92825/*
92826** Make a transient copy of expression pExpr and then code it using
92827** sqlite3ExprCode().  This routine works just like sqlite3ExprCode()
92828** except that the input expression is guaranteed to be unchanged.
92829*/
92830SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
92831  sqlite3 *db = pParse->db;
92832  pExpr = sqlite3ExprDup(db, pExpr, 0);
92833  if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
92834  sqlite3ExprDelete(db, pExpr);
92835}
92836
92837/*
92838** Generate code that will evaluate expression pExpr and store the
92839** results in register target.  The results are guaranteed to appear
92840** in register target.  If the expression is constant, then this routine
92841** might choose to code the expression at initialization time.
92842*/
92843SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
92844  if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
92845    sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
92846  }else{
92847    sqlite3ExprCode(pParse, pExpr, target);
92848  }
92849}
92850
92851/*
92852** Generate code that evaluates the given expression and puts the result
92853** in register target.
92854**
92855** Also make a copy of the expression results into another "cache" register
92856** and modify the expression so that the next time it is evaluated,
92857** the result is a copy of the cache register.
92858**
92859** This routine is used for expressions that are used multiple
92860** times.  They are evaluated once and the results of the expression
92861** are reused.
92862*/
92863SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
92864  Vdbe *v = pParse->pVdbe;
92865  int iMem;
92866
92867  assert( target>0 );
92868  assert( pExpr->op!=TK_REGISTER );
92869  sqlite3ExprCode(pParse, pExpr, target);
92870  iMem = ++pParse->nMem;
92871  sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
92872  exprToRegister(pExpr, iMem);
92873}
92874
92875/*
92876** Generate code that pushes the value of every element of the given
92877** expression list into a sequence of registers beginning at target.
92878**
92879** Return the number of elements evaluated.
92880**
92881** The SQLITE_ECEL_DUP flag prevents the arguments from being
92882** filled using OP_SCopy.  OP_Copy must be used instead.
92883**
92884** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
92885** factored out into initialization code.
92886**
92887** The SQLITE_ECEL_REF flag means that expressions in the list with
92888** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
92889** in registers at srcReg, and so the value can be copied from there.
92890*/
92891SQLITE_PRIVATE int sqlite3ExprCodeExprList(
92892  Parse *pParse,     /* Parsing context */
92893  ExprList *pList,   /* The expression list to be coded */
92894  int target,        /* Where to write results */
92895  int srcReg,        /* Source registers if SQLITE_ECEL_REF */
92896  u8 flags           /* SQLITE_ECEL_* flags */
92897){
92898  struct ExprList_item *pItem;
92899  int i, j, n;
92900  u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
92901  Vdbe *v = pParse->pVdbe;
92902  assert( pList!=0 );
92903  assert( target>0 );
92904  assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
92905  n = pList->nExpr;
92906  if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
92907  for(pItem=pList->a, i=0; i<n; i++, pItem++){
92908    Expr *pExpr = pItem->pExpr;
92909    if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
92910      sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
92911    }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
92912      sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
92913    }else{
92914      int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
92915      if( inReg!=target+i ){
92916        VdbeOp *pOp;
92917        if( copyOp==OP_Copy
92918         && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
92919         && pOp->p1+pOp->p3+1==inReg
92920         && pOp->p2+pOp->p3+1==target+i
92921        ){
92922          pOp->p3++;
92923        }else{
92924          sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
92925        }
92926      }
92927    }
92928  }
92929  return n;
92930}
92931
92932/*
92933** Generate code for a BETWEEN operator.
92934**
92935**    x BETWEEN y AND z
92936**
92937** The above is equivalent to
92938**
92939**    x>=y AND x<=z
92940**
92941** Code it as such, taking care to do the common subexpression
92942** elimination of x.
92943*/
92944static void exprCodeBetween(
92945  Parse *pParse,    /* Parsing and code generating context */
92946  Expr *pExpr,      /* The BETWEEN expression */
92947  int dest,         /* Jump here if the jump is taken */
92948  int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
92949  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
92950){
92951  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
92952  Expr compLeft;    /* The  x>=y  term */
92953  Expr compRight;   /* The  x<=z  term */
92954  Expr exprX;       /* The  x  subexpression */
92955  int regFree1 = 0; /* Temporary use register */
92956
92957  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
92958  exprX = *pExpr->pLeft;
92959  exprAnd.op = TK_AND;
92960  exprAnd.pLeft = &compLeft;
92961  exprAnd.pRight = &compRight;
92962  compLeft.op = TK_GE;
92963  compLeft.pLeft = &exprX;
92964  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
92965  compRight.op = TK_LE;
92966  compRight.pLeft = &exprX;
92967  compRight.pRight = pExpr->x.pList->a[1].pExpr;
92968  exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
92969  if( jumpIfTrue ){
92970    sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
92971  }else{
92972    sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
92973  }
92974  sqlite3ReleaseTempReg(pParse, regFree1);
92975
92976  /* Ensure adequate test coverage */
92977  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
92978  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
92979  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
92980  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
92981  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
92982  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
92983  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
92984  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
92985}
92986
92987/*
92988** Generate code for a boolean expression such that a jump is made
92989** to the label "dest" if the expression is true but execution
92990** continues straight thru if the expression is false.
92991**
92992** If the expression evaluates to NULL (neither true nor false), then
92993** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
92994**
92995** This code depends on the fact that certain token values (ex: TK_EQ)
92996** are the same as opcode values (ex: OP_Eq) that implement the corresponding
92997** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
92998** the make process cause these values to align.  Assert()s in the code
92999** below verify that the numbers are aligned correctly.
93000*/
93001SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
93002  Vdbe *v = pParse->pVdbe;
93003  int op = 0;
93004  int regFree1 = 0;
93005  int regFree2 = 0;
93006  int r1, r2;
93007
93008  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
93009  if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
93010  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
93011  op = pExpr->op;
93012  switch( op ){
93013    case TK_AND: {
93014      int d2 = sqlite3VdbeMakeLabel(v);
93015      testcase( jumpIfNull==0 );
93016      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
93017      sqlite3ExprCachePush(pParse);
93018      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
93019      sqlite3VdbeResolveLabel(v, d2);
93020      sqlite3ExprCachePop(pParse);
93021      break;
93022    }
93023    case TK_OR: {
93024      testcase( jumpIfNull==0 );
93025      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
93026      sqlite3ExprCachePush(pParse);
93027      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
93028      sqlite3ExprCachePop(pParse);
93029      break;
93030    }
93031    case TK_NOT: {
93032      testcase( jumpIfNull==0 );
93033      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
93034      break;
93035    }
93036    case TK_IS:
93037    case TK_ISNOT:
93038      testcase( op==TK_IS );
93039      testcase( op==TK_ISNOT );
93040      op = (op==TK_IS) ? TK_EQ : TK_NE;
93041      jumpIfNull = SQLITE_NULLEQ;
93042      /* Fall thru */
93043    case TK_LT:
93044    case TK_LE:
93045    case TK_GT:
93046    case TK_GE:
93047    case TK_NE:
93048    case TK_EQ: {
93049      testcase( jumpIfNull==0 );
93050      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93051      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
93052      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
93053                  r1, r2, dest, jumpIfNull);
93054      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
93055      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
93056      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
93057      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
93058      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
93059      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
93060      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
93061      assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
93062      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
93063      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
93064      testcase( regFree1==0 );
93065      testcase( regFree2==0 );
93066      break;
93067    }
93068    case TK_ISNULL:
93069    case TK_NOTNULL: {
93070      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
93071      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
93072      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93073      sqlite3VdbeAddOp2(v, op, r1, dest);
93074      VdbeCoverageIf(v, op==TK_ISNULL);
93075      VdbeCoverageIf(v, op==TK_NOTNULL);
93076      testcase( regFree1==0 );
93077      break;
93078    }
93079    case TK_BETWEEN: {
93080      testcase( jumpIfNull==0 );
93081      exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
93082      break;
93083    }
93084#ifndef SQLITE_OMIT_SUBQUERY
93085    case TK_IN: {
93086      int destIfFalse = sqlite3VdbeMakeLabel(v);
93087      int destIfNull = jumpIfNull ? dest : destIfFalse;
93088      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
93089      sqlite3VdbeGoto(v, dest);
93090      sqlite3VdbeResolveLabel(v, destIfFalse);
93091      break;
93092    }
93093#endif
93094    default: {
93095      if( exprAlwaysTrue(pExpr) ){
93096        sqlite3VdbeGoto(v, dest);
93097      }else if( exprAlwaysFalse(pExpr) ){
93098        /* No-op */
93099      }else{
93100        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
93101        sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
93102        VdbeCoverage(v);
93103        testcase( regFree1==0 );
93104        testcase( jumpIfNull==0 );
93105      }
93106      break;
93107    }
93108  }
93109  sqlite3ReleaseTempReg(pParse, regFree1);
93110  sqlite3ReleaseTempReg(pParse, regFree2);
93111}
93112
93113/*
93114** Generate code for a boolean expression such that a jump is made
93115** to the label "dest" if the expression is false but execution
93116** continues straight thru if the expression is true.
93117**
93118** If the expression evaluates to NULL (neither true nor false) then
93119** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
93120** is 0.
93121*/
93122SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
93123  Vdbe *v = pParse->pVdbe;
93124  int op = 0;
93125  int regFree1 = 0;
93126  int regFree2 = 0;
93127  int r1, r2;
93128
93129  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
93130  if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
93131  if( pExpr==0 )    return;
93132
93133  /* The value of pExpr->op and op are related as follows:
93134  **
93135  **       pExpr->op            op
93136  **       ---------          ----------
93137  **       TK_ISNULL          OP_NotNull
93138  **       TK_NOTNULL         OP_IsNull
93139  **       TK_NE              OP_Eq
93140  **       TK_EQ              OP_Ne
93141  **       TK_GT              OP_Le
93142  **       TK_LE              OP_Gt
93143  **       TK_GE              OP_Lt
93144  **       TK_LT              OP_Ge
93145  **
93146  ** For other values of pExpr->op, op is undefined and unused.
93147  ** The value of TK_ and OP_ constants are arranged such that we
93148  ** can compute the mapping above using the following expression.
93149  ** Assert()s verify that the computation is correct.
93150  */
93151  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
93152
93153  /* Verify correct alignment of TK_ and OP_ constants
93154  */
93155  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
93156  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
93157  assert( pExpr->op!=TK_NE || op==OP_Eq );
93158  assert( pExpr->op!=TK_EQ || op==OP_Ne );
93159  assert( pExpr->op!=TK_LT || op==OP_Ge );
93160  assert( pExpr->op!=TK_LE || op==OP_Gt );
93161  assert( pExpr->op!=TK_GT || op==OP_Le );
93162  assert( pExpr->op!=TK_GE || op==OP_Lt );
93163
93164  switch( pExpr->op ){
93165    case TK_AND: {
93166      testcase( jumpIfNull==0 );
93167      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
93168      sqlite3ExprCachePush(pParse);
93169      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
93170      sqlite3ExprCachePop(pParse);
93171      break;
93172    }
93173    case TK_OR: {
93174      int d2 = sqlite3VdbeMakeLabel(v);
93175      testcase( jumpIfNull==0 );
93176      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
93177      sqlite3ExprCachePush(pParse);
93178      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
93179      sqlite3VdbeResolveLabel(v, d2);
93180      sqlite3ExprCachePop(pParse);
93181      break;
93182    }
93183    case TK_NOT: {
93184      testcase( jumpIfNull==0 );
93185      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
93186      break;
93187    }
93188    case TK_IS:
93189    case TK_ISNOT:
93190      testcase( pExpr->op==TK_IS );
93191      testcase( pExpr->op==TK_ISNOT );
93192      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
93193      jumpIfNull = SQLITE_NULLEQ;
93194      /* Fall thru */
93195    case TK_LT:
93196    case TK_LE:
93197    case TK_GT:
93198    case TK_GE:
93199    case TK_NE:
93200    case TK_EQ: {
93201      testcase( jumpIfNull==0 );
93202      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93203      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
93204      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
93205                  r1, r2, dest, jumpIfNull);
93206      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
93207      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
93208      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
93209      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
93210      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
93211      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
93212      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
93213      assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
93214      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
93215      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
93216      testcase( regFree1==0 );
93217      testcase( regFree2==0 );
93218      break;
93219    }
93220    case TK_ISNULL:
93221    case TK_NOTNULL: {
93222      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93223      sqlite3VdbeAddOp2(v, op, r1, dest);
93224      testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
93225      testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
93226      testcase( regFree1==0 );
93227      break;
93228    }
93229    case TK_BETWEEN: {
93230      testcase( jumpIfNull==0 );
93231      exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
93232      break;
93233    }
93234#ifndef SQLITE_OMIT_SUBQUERY
93235    case TK_IN: {
93236      if( jumpIfNull ){
93237        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
93238      }else{
93239        int destIfNull = sqlite3VdbeMakeLabel(v);
93240        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
93241        sqlite3VdbeResolveLabel(v, destIfNull);
93242      }
93243      break;
93244    }
93245#endif
93246    default: {
93247      if( exprAlwaysFalse(pExpr) ){
93248        sqlite3VdbeGoto(v, dest);
93249      }else if( exprAlwaysTrue(pExpr) ){
93250        /* no-op */
93251      }else{
93252        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
93253        sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
93254        VdbeCoverage(v);
93255        testcase( regFree1==0 );
93256        testcase( jumpIfNull==0 );
93257      }
93258      break;
93259    }
93260  }
93261  sqlite3ReleaseTempReg(pParse, regFree1);
93262  sqlite3ReleaseTempReg(pParse, regFree2);
93263}
93264
93265/*
93266** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
93267** code generation, and that copy is deleted after code generation. This
93268** ensures that the original pExpr is unchanged.
93269*/
93270SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
93271  sqlite3 *db = pParse->db;
93272  Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
93273  if( db->mallocFailed==0 ){
93274    sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
93275  }
93276  sqlite3ExprDelete(db, pCopy);
93277}
93278
93279
93280/*
93281** Do a deep comparison of two expression trees.  Return 0 if the two
93282** expressions are completely identical.  Return 1 if they differ only
93283** by a COLLATE operator at the top level.  Return 2 if there are differences
93284** other than the top-level COLLATE operator.
93285**
93286** If any subelement of pB has Expr.iTable==(-1) then it is allowed
93287** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
93288**
93289** The pA side might be using TK_REGISTER.  If that is the case and pB is
93290** not using TK_REGISTER but is otherwise equivalent, then still return 0.
93291**
93292** Sometimes this routine will return 2 even if the two expressions
93293** really are equivalent.  If we cannot prove that the expressions are
93294** identical, we return 2 just to be safe.  So if this routine
93295** returns 2, then you do not really know for certain if the two
93296** expressions are the same.  But if you get a 0 or 1 return, then you
93297** can be sure the expressions are the same.  In the places where
93298** this routine is used, it does not hurt to get an extra 2 - that
93299** just might result in some slightly slower code.  But returning
93300** an incorrect 0 or 1 could lead to a malfunction.
93301*/
93302SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
93303  u32 combinedFlags;
93304  if( pA==0 || pB==0 ){
93305    return pB==pA ? 0 : 2;
93306  }
93307  combinedFlags = pA->flags | pB->flags;
93308  if( combinedFlags & EP_IntValue ){
93309    if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
93310      return 0;
93311    }
93312    return 2;
93313  }
93314  if( pA->op!=pB->op ){
93315    if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
93316      return 1;
93317    }
93318    if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
93319      return 1;
93320    }
93321    return 2;
93322  }
93323  if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
93324    if( pA->op==TK_FUNCTION ){
93325      if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
93326    }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
93327      return pA->op==TK_COLLATE ? 1 : 2;
93328    }
93329  }
93330  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
93331  if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
93332    if( combinedFlags & EP_xIsSelect ) return 2;
93333    if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
93334    if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
93335    if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
93336    if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
93337      if( pA->iColumn!=pB->iColumn ) return 2;
93338      if( pA->iTable!=pB->iTable
93339       && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
93340    }
93341  }
93342  return 0;
93343}
93344
93345/*
93346** Compare two ExprList objects.  Return 0 if they are identical and
93347** non-zero if they differ in any way.
93348**
93349** If any subelement of pB has Expr.iTable==(-1) then it is allowed
93350** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
93351**
93352** This routine might return non-zero for equivalent ExprLists.  The
93353** only consequence will be disabled optimizations.  But this routine
93354** must never return 0 if the two ExprList objects are different, or
93355** a malfunction will result.
93356**
93357** Two NULL pointers are considered to be the same.  But a NULL pointer
93358** always differs from a non-NULL pointer.
93359*/
93360SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
93361  int i;
93362  if( pA==0 && pB==0 ) return 0;
93363  if( pA==0 || pB==0 ) return 1;
93364  if( pA->nExpr!=pB->nExpr ) return 1;
93365  for(i=0; i<pA->nExpr; i++){
93366    Expr *pExprA = pA->a[i].pExpr;
93367    Expr *pExprB = pB->a[i].pExpr;
93368    if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
93369    if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
93370  }
93371  return 0;
93372}
93373
93374/*
93375** Return true if we can prove the pE2 will always be true if pE1 is
93376** true.  Return false if we cannot complete the proof or if pE2 might
93377** be false.  Examples:
93378**
93379**     pE1: x==5       pE2: x==5             Result: true
93380**     pE1: x>0        pE2: x==5             Result: false
93381**     pE1: x=21       pE2: x=21 OR y=43     Result: true
93382**     pE1: x!=123     pE2: x IS NOT NULL    Result: true
93383**     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
93384**     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
93385**     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
93386**
93387** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
93388** Expr.iTable<0 then assume a table number given by iTab.
93389**
93390** When in doubt, return false.  Returning true might give a performance
93391** improvement.  Returning false might cause a performance reduction, but
93392** it will always give the correct answer and is hence always safe.
93393*/
93394SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
93395  if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
93396    return 1;
93397  }
93398  if( pE2->op==TK_OR
93399   && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
93400             || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
93401  ){
93402    return 1;
93403  }
93404  if( pE2->op==TK_NOTNULL
93405   && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
93406   && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
93407  ){
93408    return 1;
93409  }
93410  return 0;
93411}
93412
93413/*
93414** An instance of the following structure is used by the tree walker
93415** to determine if an expression can be evaluated by reference to the
93416** index only, without having to do a search for the corresponding
93417** table entry.  The IdxCover.pIdx field is the index.  IdxCover.iCur
93418** is the cursor for the table.
93419*/
93420struct IdxCover {
93421  Index *pIdx;     /* The index to be tested for coverage */
93422  int iCur;        /* Cursor number for the table corresponding to the index */
93423};
93424
93425/*
93426** Check to see if there are references to columns in table
93427** pWalker->u.pIdxCover->iCur can be satisfied using the index
93428** pWalker->u.pIdxCover->pIdx.
93429*/
93430static int exprIdxCover(Walker *pWalker, Expr *pExpr){
93431  if( pExpr->op==TK_COLUMN
93432   && pExpr->iTable==pWalker->u.pIdxCover->iCur
93433   && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
93434  ){
93435    pWalker->eCode = 1;
93436    return WRC_Abort;
93437  }
93438  return WRC_Continue;
93439}
93440
93441/*
93442** Determine if an index pIdx on table with cursor iCur contains will
93443** the expression pExpr.  Return true if the index does cover the
93444** expression and false if the pExpr expression references table columns
93445** that are not found in the index pIdx.
93446**
93447** An index covering an expression means that the expression can be
93448** evaluated using only the index and without having to lookup the
93449** corresponding table entry.
93450*/
93451SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
93452  Expr *pExpr,        /* The index to be tested */
93453  int iCur,           /* The cursor number for the corresponding table */
93454  Index *pIdx         /* The index that might be used for coverage */
93455){
93456  Walker w;
93457  struct IdxCover xcov;
93458  memset(&w, 0, sizeof(w));
93459  xcov.iCur = iCur;
93460  xcov.pIdx = pIdx;
93461  w.xExprCallback = exprIdxCover;
93462  w.u.pIdxCover = &xcov;
93463  sqlite3WalkExpr(&w, pExpr);
93464  return !w.eCode;
93465}
93466
93467
93468/*
93469** An instance of the following structure is used by the tree walker
93470** to count references to table columns in the arguments of an
93471** aggregate function, in order to implement the
93472** sqlite3FunctionThisSrc() routine.
93473*/
93474struct SrcCount {
93475  SrcList *pSrc;   /* One particular FROM clause in a nested query */
93476  int nThis;       /* Number of references to columns in pSrcList */
93477  int nOther;      /* Number of references to columns in other FROM clauses */
93478};
93479
93480/*
93481** Count the number of references to columns.
93482*/
93483static int exprSrcCount(Walker *pWalker, Expr *pExpr){
93484  /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
93485  ** is always called before sqlite3ExprAnalyzeAggregates() and so the
93486  ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
93487  ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
93488  ** NEVER() will need to be removed. */
93489  if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
93490    int i;
93491    struct SrcCount *p = pWalker->u.pSrcCount;
93492    SrcList *pSrc = p->pSrc;
93493    int nSrc = pSrc ? pSrc->nSrc : 0;
93494    for(i=0; i<nSrc; i++){
93495      if( pExpr->iTable==pSrc->a[i].iCursor ) break;
93496    }
93497    if( i<nSrc ){
93498      p->nThis++;
93499    }else{
93500      p->nOther++;
93501    }
93502  }
93503  return WRC_Continue;
93504}
93505
93506/*
93507** Determine if any of the arguments to the pExpr Function reference
93508** pSrcList.  Return true if they do.  Also return true if the function
93509** has no arguments or has only constant arguments.  Return false if pExpr
93510** references columns but not columns of tables found in pSrcList.
93511*/
93512SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
93513  Walker w;
93514  struct SrcCount cnt;
93515  assert( pExpr->op==TK_AGG_FUNCTION );
93516  memset(&w, 0, sizeof(w));
93517  w.xExprCallback = exprSrcCount;
93518  w.u.pSrcCount = &cnt;
93519  cnt.pSrc = pSrcList;
93520  cnt.nThis = 0;
93521  cnt.nOther = 0;
93522  sqlite3WalkExprList(&w, pExpr->x.pList);
93523  return cnt.nThis>0 || cnt.nOther==0;
93524}
93525
93526/*
93527** Add a new element to the pAggInfo->aCol[] array.  Return the index of
93528** the new element.  Return a negative number if malloc fails.
93529*/
93530static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
93531  int i;
93532  pInfo->aCol = sqlite3ArrayAllocate(
93533       db,
93534       pInfo->aCol,
93535       sizeof(pInfo->aCol[0]),
93536       &pInfo->nColumn,
93537       &i
93538  );
93539  return i;
93540}
93541
93542/*
93543** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
93544** the new element.  Return a negative number if malloc fails.
93545*/
93546static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
93547  int i;
93548  pInfo->aFunc = sqlite3ArrayAllocate(
93549       db,
93550       pInfo->aFunc,
93551       sizeof(pInfo->aFunc[0]),
93552       &pInfo->nFunc,
93553       &i
93554  );
93555  return i;
93556}
93557
93558/*
93559** This is the xExprCallback for a tree walker.  It is used to
93560** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
93561** for additional information.
93562*/
93563static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
93564  int i;
93565  NameContext *pNC = pWalker->u.pNC;
93566  Parse *pParse = pNC->pParse;
93567  SrcList *pSrcList = pNC->pSrcList;
93568  AggInfo *pAggInfo = pNC->pAggInfo;
93569
93570  switch( pExpr->op ){
93571    case TK_AGG_COLUMN:
93572    case TK_COLUMN: {
93573      testcase( pExpr->op==TK_AGG_COLUMN );
93574      testcase( pExpr->op==TK_COLUMN );
93575      /* Check to see if the column is in one of the tables in the FROM
93576      ** clause of the aggregate query */
93577      if( ALWAYS(pSrcList!=0) ){
93578        struct SrcList_item *pItem = pSrcList->a;
93579        for(i=0; i<pSrcList->nSrc; i++, pItem++){
93580          struct AggInfo_col *pCol;
93581          assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
93582          if( pExpr->iTable==pItem->iCursor ){
93583            /* If we reach this point, it means that pExpr refers to a table
93584            ** that is in the FROM clause of the aggregate query.
93585            **
93586            ** Make an entry for the column in pAggInfo->aCol[] if there
93587            ** is not an entry there already.
93588            */
93589            int k;
93590            pCol = pAggInfo->aCol;
93591            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
93592              if( pCol->iTable==pExpr->iTable &&
93593                  pCol->iColumn==pExpr->iColumn ){
93594                break;
93595              }
93596            }
93597            if( (k>=pAggInfo->nColumn)
93598             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
93599            ){
93600              pCol = &pAggInfo->aCol[k];
93601              pCol->pTab = pExpr->pTab;
93602              pCol->iTable = pExpr->iTable;
93603              pCol->iColumn = pExpr->iColumn;
93604              pCol->iMem = ++pParse->nMem;
93605              pCol->iSorterColumn = -1;
93606              pCol->pExpr = pExpr;
93607              if( pAggInfo->pGroupBy ){
93608                int j, n;
93609                ExprList *pGB = pAggInfo->pGroupBy;
93610                struct ExprList_item *pTerm = pGB->a;
93611                n = pGB->nExpr;
93612                for(j=0; j<n; j++, pTerm++){
93613                  Expr *pE = pTerm->pExpr;
93614                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
93615                      pE->iColumn==pExpr->iColumn ){
93616                    pCol->iSorterColumn = j;
93617                    break;
93618                  }
93619                }
93620              }
93621              if( pCol->iSorterColumn<0 ){
93622                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
93623              }
93624            }
93625            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
93626            ** because it was there before or because we just created it).
93627            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
93628            ** pAggInfo->aCol[] entry.
93629            */
93630            ExprSetVVAProperty(pExpr, EP_NoReduce);
93631            pExpr->pAggInfo = pAggInfo;
93632            pExpr->op = TK_AGG_COLUMN;
93633            pExpr->iAgg = (i16)k;
93634            break;
93635          } /* endif pExpr->iTable==pItem->iCursor */
93636        } /* end loop over pSrcList */
93637      }
93638      return WRC_Prune;
93639    }
93640    case TK_AGG_FUNCTION: {
93641      if( (pNC->ncFlags & NC_InAggFunc)==0
93642       && pWalker->walkerDepth==pExpr->op2
93643      ){
93644        /* Check to see if pExpr is a duplicate of another aggregate
93645        ** function that is already in the pAggInfo structure
93646        */
93647        struct AggInfo_func *pItem = pAggInfo->aFunc;
93648        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
93649          if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
93650            break;
93651          }
93652        }
93653        if( i>=pAggInfo->nFunc ){
93654          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
93655          */
93656          u8 enc = ENC(pParse->db);
93657          i = addAggInfoFunc(pParse->db, pAggInfo);
93658          if( i>=0 ){
93659            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
93660            pItem = &pAggInfo->aFunc[i];
93661            pItem->pExpr = pExpr;
93662            pItem->iMem = ++pParse->nMem;
93663            assert( !ExprHasProperty(pExpr, EP_IntValue) );
93664            pItem->pFunc = sqlite3FindFunction(pParse->db,
93665                   pExpr->u.zToken,
93666                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
93667            if( pExpr->flags & EP_Distinct ){
93668              pItem->iDistinct = pParse->nTab++;
93669            }else{
93670              pItem->iDistinct = -1;
93671            }
93672          }
93673        }
93674        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
93675        */
93676        assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
93677        ExprSetVVAProperty(pExpr, EP_NoReduce);
93678        pExpr->iAgg = (i16)i;
93679        pExpr->pAggInfo = pAggInfo;
93680        return WRC_Prune;
93681      }else{
93682        return WRC_Continue;
93683      }
93684    }
93685  }
93686  return WRC_Continue;
93687}
93688static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
93689  UNUSED_PARAMETER(pWalker);
93690  UNUSED_PARAMETER(pSelect);
93691  return WRC_Continue;
93692}
93693
93694/*
93695** Analyze the pExpr expression looking for aggregate functions and
93696** for variables that need to be added to AggInfo object that pNC->pAggInfo
93697** points to.  Additional entries are made on the AggInfo object as
93698** necessary.
93699**
93700** This routine should only be called after the expression has been
93701** analyzed by sqlite3ResolveExprNames().
93702*/
93703SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
93704  Walker w;
93705  memset(&w, 0, sizeof(w));
93706  w.xExprCallback = analyzeAggregate;
93707  w.xSelectCallback = analyzeAggregatesInSelect;
93708  w.u.pNC = pNC;
93709  assert( pNC->pSrcList!=0 );
93710  sqlite3WalkExpr(&w, pExpr);
93711}
93712
93713/*
93714** Call sqlite3ExprAnalyzeAggregates() for every expression in an
93715** expression list.  Return the number of errors.
93716**
93717** If an error is found, the analysis is cut short.
93718*/
93719SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
93720  struct ExprList_item *pItem;
93721  int i;
93722  if( pList ){
93723    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
93724      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
93725    }
93726  }
93727}
93728
93729/*
93730** Allocate a single new register for use to hold some intermediate result.
93731*/
93732SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
93733  if( pParse->nTempReg==0 ){
93734    return ++pParse->nMem;
93735  }
93736  return pParse->aTempReg[--pParse->nTempReg];
93737}
93738
93739/*
93740** Deallocate a register, making available for reuse for some other
93741** purpose.
93742**
93743** If a register is currently being used by the column cache, then
93744** the deallocation is deferred until the column cache line that uses
93745** the register becomes stale.
93746*/
93747SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
93748  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
93749    int i;
93750    struct yColCache *p;
93751    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
93752      if( p->iReg==iReg ){
93753        p->tempReg = 1;
93754        return;
93755      }
93756    }
93757    pParse->aTempReg[pParse->nTempReg++] = iReg;
93758  }
93759}
93760
93761/*
93762** Allocate or deallocate a block of nReg consecutive registers
93763*/
93764SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
93765  int i, n;
93766  i = pParse->iRangeReg;
93767  n = pParse->nRangeReg;
93768  if( nReg<=n ){
93769    assert( !usedAsColumnCache(pParse, i, i+n-1) );
93770    pParse->iRangeReg += nReg;
93771    pParse->nRangeReg -= nReg;
93772  }else{
93773    i = pParse->nMem+1;
93774    pParse->nMem += nReg;
93775  }
93776  return i;
93777}
93778SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
93779  sqlite3ExprCacheRemove(pParse, iReg, nReg);
93780  if( nReg>pParse->nRangeReg ){
93781    pParse->nRangeReg = nReg;
93782    pParse->iRangeReg = iReg;
93783  }
93784}
93785
93786/*
93787** Mark all temporary registers as being unavailable for reuse.
93788*/
93789SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
93790  pParse->nTempReg = 0;
93791  pParse->nRangeReg = 0;
93792}
93793
93794/*
93795** Validate that no temporary register falls within the range of
93796** iFirst..iLast, inclusive.  This routine is only call from within assert()
93797** statements.
93798*/
93799#ifdef SQLITE_DEBUG
93800SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
93801  int i;
93802  if( pParse->nRangeReg>0
93803   && pParse->iRangeReg+pParse->nRangeReg<iLast
93804   && pParse->iRangeReg>=iFirst
93805  ){
93806     return 0;
93807  }
93808  for(i=0; i<pParse->nTempReg; i++){
93809    if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
93810      return 0;
93811    }
93812  }
93813  return 1;
93814}
93815#endif /* SQLITE_DEBUG */
93816
93817/************** End of expr.c ************************************************/
93818/************** Begin file alter.c *******************************************/
93819/*
93820** 2005 February 15
93821**
93822** The author disclaims copyright to this source code.  In place of
93823** a legal notice, here is a blessing:
93824**
93825**    May you do good and not evil.
93826**    May you find forgiveness for yourself and forgive others.
93827**    May you share freely, never taking more than you give.
93828**
93829*************************************************************************
93830** This file contains C code routines that used to generate VDBE code
93831** that implements the ALTER TABLE command.
93832*/
93833/* #include "sqliteInt.h" */
93834
93835/*
93836** The code in this file only exists if we are not omitting the
93837** ALTER TABLE logic from the build.
93838*/
93839#ifndef SQLITE_OMIT_ALTERTABLE
93840
93841
93842/*
93843** This function is used by SQL generated to implement the
93844** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
93845** CREATE INDEX command. The second is a table name. The table name in
93846** the CREATE TABLE or CREATE INDEX statement is replaced with the third
93847** argument and the result returned. Examples:
93848**
93849** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
93850**     -> 'CREATE TABLE def(a, b, c)'
93851**
93852** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
93853**     -> 'CREATE INDEX i ON def(a, b, c)'
93854*/
93855static void renameTableFunc(
93856  sqlite3_context *context,
93857  int NotUsed,
93858  sqlite3_value **argv
93859){
93860  unsigned char const *zSql = sqlite3_value_text(argv[0]);
93861  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
93862
93863  int token;
93864  Token tname;
93865  unsigned char const *zCsr = zSql;
93866  int len = 0;
93867  char *zRet;
93868
93869  sqlite3 *db = sqlite3_context_db_handle(context);
93870
93871  UNUSED_PARAMETER(NotUsed);
93872
93873  /* The principle used to locate the table name in the CREATE TABLE
93874  ** statement is that the table name is the first non-space token that
93875  ** is immediately followed by a TK_LP or TK_USING token.
93876  */
93877  if( zSql ){
93878    do {
93879      if( !*zCsr ){
93880        /* Ran out of input before finding an opening bracket. Return NULL. */
93881        return;
93882      }
93883
93884      /* Store the token that zCsr points to in tname. */
93885      tname.z = (char*)zCsr;
93886      tname.n = len;
93887
93888      /* Advance zCsr to the next token. Store that token type in 'token',
93889      ** and its length in 'len' (to be used next iteration of this loop).
93890      */
93891      do {
93892        zCsr += len;
93893        len = sqlite3GetToken(zCsr, &token);
93894      } while( token==TK_SPACE );
93895      assert( len>0 );
93896    } while( token!=TK_LP && token!=TK_USING );
93897
93898    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
93899       zSql, zTableName, tname.z+tname.n);
93900    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
93901  }
93902}
93903
93904/*
93905** This C function implements an SQL user function that is used by SQL code
93906** generated by the ALTER TABLE ... RENAME command to modify the definition
93907** of any foreign key constraints that use the table being renamed as the
93908** parent table. It is passed three arguments:
93909**
93910**   1) The complete text of the CREATE TABLE statement being modified,
93911**   2) The old name of the table being renamed, and
93912**   3) The new name of the table being renamed.
93913**
93914** It returns the new CREATE TABLE statement. For example:
93915**
93916**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
93917**       -> 'CREATE TABLE t1(a REFERENCES t3)'
93918*/
93919#ifndef SQLITE_OMIT_FOREIGN_KEY
93920static void renameParentFunc(
93921  sqlite3_context *context,
93922  int NotUsed,
93923  sqlite3_value **argv
93924){
93925  sqlite3 *db = sqlite3_context_db_handle(context);
93926  char *zOutput = 0;
93927  char *zResult;
93928  unsigned char const *zInput = sqlite3_value_text(argv[0]);
93929  unsigned char const *zOld = sqlite3_value_text(argv[1]);
93930  unsigned char const *zNew = sqlite3_value_text(argv[2]);
93931
93932  unsigned const char *z;         /* Pointer to token */
93933  int n;                          /* Length of token z */
93934  int token;                      /* Type of token */
93935
93936  UNUSED_PARAMETER(NotUsed);
93937  if( zInput==0 || zOld==0 ) return;
93938  for(z=zInput; *z; z=z+n){
93939    n = sqlite3GetToken(z, &token);
93940    if( token==TK_REFERENCES ){
93941      char *zParent;
93942      do {
93943        z += n;
93944        n = sqlite3GetToken(z, &token);
93945      }while( token==TK_SPACE );
93946
93947      if( token==TK_ILLEGAL ) break;
93948      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
93949      if( zParent==0 ) break;
93950      sqlite3Dequote(zParent);
93951      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
93952        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
93953            (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
93954        );
93955        sqlite3DbFree(db, zOutput);
93956        zOutput = zOut;
93957        zInput = &z[n];
93958      }
93959      sqlite3DbFree(db, zParent);
93960    }
93961  }
93962
93963  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
93964  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
93965  sqlite3DbFree(db, zOutput);
93966}
93967#endif
93968
93969#ifndef SQLITE_OMIT_TRIGGER
93970/* This function is used by SQL generated to implement the
93971** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
93972** statement. The second is a table name. The table name in the CREATE
93973** TRIGGER statement is replaced with the third argument and the result
93974** returned. This is analagous to renameTableFunc() above, except for CREATE
93975** TRIGGER, not CREATE INDEX and CREATE TABLE.
93976*/
93977static void renameTriggerFunc(
93978  sqlite3_context *context,
93979  int NotUsed,
93980  sqlite3_value **argv
93981){
93982  unsigned char const *zSql = sqlite3_value_text(argv[0]);
93983  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
93984
93985  int token;
93986  Token tname;
93987  int dist = 3;
93988  unsigned char const *zCsr = zSql;
93989  int len = 0;
93990  char *zRet;
93991  sqlite3 *db = sqlite3_context_db_handle(context);
93992
93993  UNUSED_PARAMETER(NotUsed);
93994
93995  /* The principle used to locate the table name in the CREATE TRIGGER
93996  ** statement is that the table name is the first token that is immediately
93997  ** preceded by either TK_ON or TK_DOT and immediately followed by one
93998  ** of TK_WHEN, TK_BEGIN or TK_FOR.
93999  */
94000  if( zSql ){
94001    do {
94002
94003      if( !*zCsr ){
94004        /* Ran out of input before finding the table name. Return NULL. */
94005        return;
94006      }
94007
94008      /* Store the token that zCsr points to in tname. */
94009      tname.z = (char*)zCsr;
94010      tname.n = len;
94011
94012      /* Advance zCsr to the next token. Store that token type in 'token',
94013      ** and its length in 'len' (to be used next iteration of this loop).
94014      */
94015      do {
94016        zCsr += len;
94017        len = sqlite3GetToken(zCsr, &token);
94018      }while( token==TK_SPACE );
94019      assert( len>0 );
94020
94021      /* Variable 'dist' stores the number of tokens read since the most
94022      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
94023      ** token is read and 'dist' equals 2, the condition stated above
94024      ** to be met.
94025      **
94026      ** Note that ON cannot be a database, table or column name, so
94027      ** there is no need to worry about syntax like
94028      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
94029      */
94030      dist++;
94031      if( token==TK_DOT || token==TK_ON ){
94032        dist = 0;
94033      }
94034    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
94035
94036    /* Variable tname now contains the token that is the old table-name
94037    ** in the CREATE TRIGGER statement.
94038    */
94039    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
94040       zSql, zTableName, tname.z+tname.n);
94041    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
94042  }
94043}
94044#endif   /* !SQLITE_OMIT_TRIGGER */
94045
94046/*
94047** Register built-in functions used to help implement ALTER TABLE
94048*/
94049SQLITE_PRIVATE void sqlite3AlterFunctions(void){
94050  static FuncDef aAlterTableFuncs[] = {
94051    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
94052#ifndef SQLITE_OMIT_TRIGGER
94053    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
94054#endif
94055#ifndef SQLITE_OMIT_FOREIGN_KEY
94056    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
94057#endif
94058  };
94059  sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
94060}
94061
94062/*
94063** This function is used to create the text of expressions of the form:
94064**
94065**   name=<constant1> OR name=<constant2> OR ...
94066**
94067** If argument zWhere is NULL, then a pointer string containing the text
94068** "name=<constant>" is returned, where <constant> is the quoted version
94069** of the string passed as argument zConstant. The returned buffer is
94070** allocated using sqlite3DbMalloc(). It is the responsibility of the
94071** caller to ensure that it is eventually freed.
94072**
94073** If argument zWhere is not NULL, then the string returned is
94074** "<where> OR name=<constant>", where <where> is the contents of zWhere.
94075** In this case zWhere is passed to sqlite3DbFree() before returning.
94076**
94077*/
94078static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
94079  char *zNew;
94080  if( !zWhere ){
94081    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
94082  }else{
94083    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
94084    sqlite3DbFree(db, zWhere);
94085  }
94086  return zNew;
94087}
94088
94089#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
94090/*
94091** Generate the text of a WHERE expression which can be used to select all
94092** tables that have foreign key constraints that refer to table pTab (i.e.
94093** constraints for which pTab is the parent table) from the sqlite_master
94094** table.
94095*/
94096static char *whereForeignKeys(Parse *pParse, Table *pTab){
94097  FKey *p;
94098  char *zWhere = 0;
94099  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
94100    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
94101  }
94102  return zWhere;
94103}
94104#endif
94105
94106/*
94107** Generate the text of a WHERE expression which can be used to select all
94108** temporary triggers on table pTab from the sqlite_temp_master table. If
94109** table pTab has no temporary triggers, or is itself stored in the
94110** temporary database, NULL is returned.
94111*/
94112static char *whereTempTriggers(Parse *pParse, Table *pTab){
94113  Trigger *pTrig;
94114  char *zWhere = 0;
94115  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
94116
94117  /* If the table is not located in the temp-db (in which case NULL is
94118  ** returned, loop through the tables list of triggers. For each trigger
94119  ** that is not part of the temp-db schema, add a clause to the WHERE
94120  ** expression being built up in zWhere.
94121  */
94122  if( pTab->pSchema!=pTempSchema ){
94123    sqlite3 *db = pParse->db;
94124    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
94125      if( pTrig->pSchema==pTempSchema ){
94126        zWhere = whereOrName(db, zWhere, pTrig->zName);
94127      }
94128    }
94129  }
94130  if( zWhere ){
94131    char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
94132    sqlite3DbFree(pParse->db, zWhere);
94133    zWhere = zNew;
94134  }
94135  return zWhere;
94136}
94137
94138/*
94139** Generate code to drop and reload the internal representation of table
94140** pTab from the database, including triggers and temporary triggers.
94141** Argument zName is the name of the table in the database schema at
94142** the time the generated code is executed. This can be different from
94143** pTab->zName if this function is being called to code part of an
94144** "ALTER TABLE RENAME TO" statement.
94145*/
94146static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
94147  Vdbe *v;
94148  char *zWhere;
94149  int iDb;                   /* Index of database containing pTab */
94150#ifndef SQLITE_OMIT_TRIGGER
94151  Trigger *pTrig;
94152#endif
94153
94154  v = sqlite3GetVdbe(pParse);
94155  if( NEVER(v==0) ) return;
94156  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
94157  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
94158  assert( iDb>=0 );
94159
94160#ifndef SQLITE_OMIT_TRIGGER
94161  /* Drop any table triggers from the internal schema. */
94162  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
94163    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
94164    assert( iTrigDb==iDb || iTrigDb==1 );
94165    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
94166  }
94167#endif
94168
94169  /* Drop the table and index from the internal schema.  */
94170  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
94171
94172  /* Reload the table, index and permanent trigger schemas. */
94173  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
94174  if( !zWhere ) return;
94175  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
94176
94177#ifndef SQLITE_OMIT_TRIGGER
94178  /* Now, if the table is not stored in the temp database, reload any temp
94179  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
94180  */
94181  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
94182    sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
94183  }
94184#endif
94185}
94186
94187/*
94188** Parameter zName is the name of a table that is about to be altered
94189** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
94190** If the table is a system table, this function leaves an error message
94191** in pParse->zErr (system tables may not be altered) and returns non-zero.
94192**
94193** Or, if zName is not a system table, zero is returned.
94194*/
94195static int isSystemTable(Parse *pParse, const char *zName){
94196  if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
94197    sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
94198    return 1;
94199  }
94200  return 0;
94201}
94202
94203/*
94204** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
94205** command.
94206*/
94207SQLITE_PRIVATE void sqlite3AlterRenameTable(
94208  Parse *pParse,            /* Parser context. */
94209  SrcList *pSrc,            /* The table to rename. */
94210  Token *pName              /* The new table name. */
94211){
94212  int iDb;                  /* Database that contains the table */
94213  char *zDb;                /* Name of database iDb */
94214  Table *pTab;              /* Table being renamed */
94215  char *zName = 0;          /* NULL-terminated version of pName */
94216  sqlite3 *db = pParse->db; /* Database connection */
94217  int nTabName;             /* Number of UTF-8 characters in zTabName */
94218  const char *zTabName;     /* Original name of the table */
94219  Vdbe *v;
94220#ifndef SQLITE_OMIT_TRIGGER
94221  char *zWhere = 0;         /* Where clause to locate temp triggers */
94222#endif
94223  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
94224  int savedDbFlags;         /* Saved value of db->flags */
94225
94226  savedDbFlags = db->flags;
94227  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
94228  assert( pSrc->nSrc==1 );
94229  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
94230
94231  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
94232  if( !pTab ) goto exit_rename_table;
94233  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
94234  zDb = db->aDb[iDb].zName;
94235  db->flags |= SQLITE_PreferBuiltin;
94236
94237  /* Get a NULL terminated version of the new table name. */
94238  zName = sqlite3NameFromToken(db, pName);
94239  if( !zName ) goto exit_rename_table;
94240
94241  /* Check that a table or index named 'zName' does not already exist
94242  ** in database iDb. If so, this is an error.
94243  */
94244  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
94245    sqlite3ErrorMsg(pParse,
94246        "there is already another table or index with this name: %s", zName);
94247    goto exit_rename_table;
94248  }
94249
94250  /* Make sure it is not a system table being altered, or a reserved name
94251  ** that the table is being renamed to.
94252  */
94253  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
94254    goto exit_rename_table;
94255  }
94256  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
94257    exit_rename_table;
94258  }
94259
94260#ifndef SQLITE_OMIT_VIEW
94261  if( pTab->pSelect ){
94262    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
94263    goto exit_rename_table;
94264  }
94265#endif
94266
94267#ifndef SQLITE_OMIT_AUTHORIZATION
94268  /* Invoke the authorization callback. */
94269  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
94270    goto exit_rename_table;
94271  }
94272#endif
94273
94274#ifndef SQLITE_OMIT_VIRTUALTABLE
94275  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
94276    goto exit_rename_table;
94277  }
94278  if( IsVirtual(pTab) ){
94279    pVTab = sqlite3GetVTable(db, pTab);
94280    if( pVTab->pVtab->pModule->xRename==0 ){
94281      pVTab = 0;
94282    }
94283  }
94284#endif
94285
94286  /* Begin a transaction for database iDb.
94287  ** Then modify the schema cookie (since the ALTER TABLE modifies the
94288  ** schema). Open a statement transaction if the table is a virtual
94289  ** table.
94290  */
94291  v = sqlite3GetVdbe(pParse);
94292  if( v==0 ){
94293    goto exit_rename_table;
94294  }
94295  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
94296  sqlite3ChangeCookie(pParse, iDb);
94297
94298  /* If this is a virtual table, invoke the xRename() function if
94299  ** one is defined. The xRename() callback will modify the names
94300  ** of any resources used by the v-table implementation (including other
94301  ** SQLite tables) that are identified by the name of the virtual table.
94302  */
94303#ifndef SQLITE_OMIT_VIRTUALTABLE
94304  if( pVTab ){
94305    int i = ++pParse->nMem;
94306    sqlite3VdbeLoadString(v, i, zName);
94307    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
94308    sqlite3MayAbort(pParse);
94309  }
94310#endif
94311
94312  /* figure out how many UTF-8 characters are in zName */
94313  zTabName = pTab->zName;
94314  nTabName = sqlite3Utf8CharLen(zTabName, -1);
94315
94316#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
94317  if( db->flags&SQLITE_ForeignKeys ){
94318    /* If foreign-key support is enabled, rewrite the CREATE TABLE
94319    ** statements corresponding to all child tables of foreign key constraints
94320    ** for which the renamed table is the parent table.  */
94321    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
94322      sqlite3NestedParse(pParse,
94323          "UPDATE \"%w\".%s SET "
94324              "sql = sqlite_rename_parent(sql, %Q, %Q) "
94325              "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
94326      sqlite3DbFree(db, zWhere);
94327    }
94328  }
94329#endif
94330
94331  /* Modify the sqlite_master table to use the new table name. */
94332  sqlite3NestedParse(pParse,
94333      "UPDATE %Q.%s SET "
94334#ifdef SQLITE_OMIT_TRIGGER
94335          "sql = sqlite_rename_table(sql, %Q), "
94336#else
94337          "sql = CASE "
94338            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
94339            "ELSE sqlite_rename_table(sql, %Q) END, "
94340#endif
94341          "tbl_name = %Q, "
94342          "name = CASE "
94343            "WHEN type='table' THEN %Q "
94344            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
94345             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
94346            "ELSE name END "
94347      "WHERE tbl_name=%Q COLLATE nocase AND "
94348          "(type='table' OR type='index' OR type='trigger');",
94349      zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
94350#ifndef SQLITE_OMIT_TRIGGER
94351      zName,
94352#endif
94353      zName, nTabName, zTabName
94354  );
94355
94356#ifndef SQLITE_OMIT_AUTOINCREMENT
94357  /* If the sqlite_sequence table exists in this database, then update
94358  ** it with the new table name.
94359  */
94360  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
94361    sqlite3NestedParse(pParse,
94362        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
94363        zDb, zName, pTab->zName);
94364  }
94365#endif
94366
94367#ifndef SQLITE_OMIT_TRIGGER
94368  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
94369  ** table. Don't do this if the table being ALTERed is itself located in
94370  ** the temp database.
94371  */
94372  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
94373    sqlite3NestedParse(pParse,
94374        "UPDATE sqlite_temp_master SET "
94375            "sql = sqlite_rename_trigger(sql, %Q), "
94376            "tbl_name = %Q "
94377            "WHERE %s;", zName, zName, zWhere);
94378    sqlite3DbFree(db, zWhere);
94379  }
94380#endif
94381
94382#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
94383  if( db->flags&SQLITE_ForeignKeys ){
94384    FKey *p;
94385    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
94386      Table *pFrom = p->pFrom;
94387      if( pFrom!=pTab ){
94388        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
94389      }
94390    }
94391  }
94392#endif
94393
94394  /* Drop and reload the internal table schema. */
94395  reloadTableSchema(pParse, pTab, zName);
94396
94397exit_rename_table:
94398  sqlite3SrcListDelete(db, pSrc);
94399  sqlite3DbFree(db, zName);
94400  db->flags = savedDbFlags;
94401}
94402
94403/*
94404** This function is called after an "ALTER TABLE ... ADD" statement
94405** has been parsed. Argument pColDef contains the text of the new
94406** column definition.
94407**
94408** The Table structure pParse->pNewTable was extended to include
94409** the new column during parsing.
94410*/
94411SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
94412  Table *pNew;              /* Copy of pParse->pNewTable */
94413  Table *pTab;              /* Table being altered */
94414  int iDb;                  /* Database number */
94415  const char *zDb;          /* Database name */
94416  const char *zTab;         /* Table name */
94417  char *zCol;               /* Null-terminated column definition */
94418  Column *pCol;             /* The new column */
94419  Expr *pDflt;              /* Default value for the new column */
94420  sqlite3 *db;              /* The database connection; */
94421  Vdbe *v = pParse->pVdbe;  /* The prepared statement under construction */
94422  int r1;                   /* Temporary registers */
94423
94424  db = pParse->db;
94425  if( pParse->nErr || db->mallocFailed ) return;
94426  assert( v!=0 );
94427  pNew = pParse->pNewTable;
94428  assert( pNew );
94429
94430  assert( sqlite3BtreeHoldsAllMutexes(db) );
94431  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
94432  zDb = db->aDb[iDb].zName;
94433  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
94434  pCol = &pNew->aCol[pNew->nCol-1];
94435  pDflt = pCol->pDflt;
94436  pTab = sqlite3FindTable(db, zTab, zDb);
94437  assert( pTab );
94438
94439#ifndef SQLITE_OMIT_AUTHORIZATION
94440  /* Invoke the authorization callback. */
94441  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
94442    return;
94443  }
94444#endif
94445
94446  /* If the default value for the new column was specified with a
94447  ** literal NULL, then set pDflt to 0. This simplifies checking
94448  ** for an SQL NULL default below.
94449  */
94450  assert( pDflt==0 || pDflt->op==TK_SPAN );
94451  if( pDflt && pDflt->pLeft->op==TK_NULL ){
94452    pDflt = 0;
94453  }
94454
94455  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
94456  ** If there is a NOT NULL constraint, then the default value for the
94457  ** column must not be NULL.
94458  */
94459  if( pCol->colFlags & COLFLAG_PRIMKEY ){
94460    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
94461    return;
94462  }
94463  if( pNew->pIndex ){
94464    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
94465    return;
94466  }
94467  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
94468    sqlite3ErrorMsg(pParse,
94469        "Cannot add a REFERENCES column with non-NULL default value");
94470    return;
94471  }
94472  if( pCol->notNull && !pDflt ){
94473    sqlite3ErrorMsg(pParse,
94474        "Cannot add a NOT NULL column with default value NULL");
94475    return;
94476  }
94477
94478  /* Ensure the default expression is something that sqlite3ValueFromExpr()
94479  ** can handle (i.e. not CURRENT_TIME etc.)
94480  */
94481  if( pDflt ){
94482    sqlite3_value *pVal = 0;
94483    int rc;
94484    rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
94485    assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
94486    if( rc!=SQLITE_OK ){
94487      assert( db->mallocFailed == 1 );
94488      return;
94489    }
94490    if( !pVal ){
94491      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
94492      return;
94493    }
94494    sqlite3ValueFree(pVal);
94495  }
94496
94497  /* Modify the CREATE TABLE statement. */
94498  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
94499  if( zCol ){
94500    char *zEnd = &zCol[pColDef->n-1];
94501    int savedDbFlags = db->flags;
94502    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
94503      *zEnd-- = '\0';
94504    }
94505    db->flags |= SQLITE_PreferBuiltin;
94506    sqlite3NestedParse(pParse,
94507        "UPDATE \"%w\".%s SET "
94508          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
94509        "WHERE type = 'table' AND name = %Q",
94510      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
94511      zTab
94512    );
94513    sqlite3DbFree(db, zCol);
94514    db->flags = savedDbFlags;
94515  }
94516
94517  /* Make sure the schema version is at least 3.  But do not upgrade
94518  ** from less than 3 to 4, as that will corrupt any preexisting DESC
94519  ** index.
94520  */
94521  r1 = sqlite3GetTempReg(pParse);
94522  sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
94523  sqlite3VdbeUsesBtree(v, iDb);
94524  sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
94525  sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
94526  VdbeCoverage(v);
94527  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
94528  sqlite3ReleaseTempReg(pParse, r1);
94529
94530  /* Reload the schema of the modified table. */
94531  reloadTableSchema(pParse, pTab, pTab->zName);
94532}
94533
94534/*
94535** This function is called by the parser after the table-name in
94536** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
94537** pSrc is the full-name of the table being altered.
94538**
94539** This routine makes a (partial) copy of the Table structure
94540** for the table being altered and sets Parse.pNewTable to point
94541** to it. Routines called by the parser as the column definition
94542** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
94543** the copy. The copy of the Table structure is deleted by tokenize.c
94544** after parsing is finished.
94545**
94546** Routine sqlite3AlterFinishAddColumn() will be called to complete
94547** coding the "ALTER TABLE ... ADD" statement.
94548*/
94549SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
94550  Table *pNew;
94551  Table *pTab;
94552  Vdbe *v;
94553  int iDb;
94554  int i;
94555  int nAlloc;
94556  sqlite3 *db = pParse->db;
94557
94558  /* Look up the table being altered. */
94559  assert( pParse->pNewTable==0 );
94560  assert( sqlite3BtreeHoldsAllMutexes(db) );
94561  if( db->mallocFailed ) goto exit_begin_add_column;
94562  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
94563  if( !pTab ) goto exit_begin_add_column;
94564
94565#ifndef SQLITE_OMIT_VIRTUALTABLE
94566  if( IsVirtual(pTab) ){
94567    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
94568    goto exit_begin_add_column;
94569  }
94570#endif
94571
94572  /* Make sure this is not an attempt to ALTER a view. */
94573  if( pTab->pSelect ){
94574    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
94575    goto exit_begin_add_column;
94576  }
94577  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
94578    goto exit_begin_add_column;
94579  }
94580
94581  assert( pTab->addColOffset>0 );
94582  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
94583
94584  /* Put a copy of the Table struct in Parse.pNewTable for the
94585  ** sqlite3AddColumn() function and friends to modify.  But modify
94586  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
94587  ** prefix, we insure that the name will not collide with an existing
94588  ** table because user table are not allowed to have the "sqlite_"
94589  ** prefix on their name.
94590  */
94591  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
94592  if( !pNew ) goto exit_begin_add_column;
94593  pParse->pNewTable = pNew;
94594  pNew->nRef = 1;
94595  pNew->nCol = pTab->nCol;
94596  assert( pNew->nCol>0 );
94597  nAlloc = (((pNew->nCol-1)/8)*8)+8;
94598  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
94599  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
94600  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
94601  if( !pNew->aCol || !pNew->zName ){
94602    assert( db->mallocFailed );
94603    goto exit_begin_add_column;
94604  }
94605  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
94606  for(i=0; i<pNew->nCol; i++){
94607    Column *pCol = &pNew->aCol[i];
94608    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
94609    pCol->zColl = 0;
94610    pCol->pDflt = 0;
94611  }
94612  pNew->pSchema = db->aDb[iDb].pSchema;
94613  pNew->addColOffset = pTab->addColOffset;
94614  pNew->nRef = 1;
94615
94616  /* Begin a transaction and increment the schema cookie.  */
94617  sqlite3BeginWriteOperation(pParse, 0, iDb);
94618  v = sqlite3GetVdbe(pParse);
94619  if( !v ) goto exit_begin_add_column;
94620  sqlite3ChangeCookie(pParse, iDb);
94621
94622exit_begin_add_column:
94623  sqlite3SrcListDelete(db, pSrc);
94624  return;
94625}
94626#endif  /* SQLITE_ALTER_TABLE */
94627
94628/************** End of alter.c ***********************************************/
94629/************** Begin file analyze.c *****************************************/
94630/*
94631** 2005-07-08
94632**
94633** The author disclaims copyright to this source code.  In place of
94634** a legal notice, here is a blessing:
94635**
94636**    May you do good and not evil.
94637**    May you find forgiveness for yourself and forgive others.
94638**    May you share freely, never taking more than you give.
94639**
94640*************************************************************************
94641** This file contains code associated with the ANALYZE command.
94642**
94643** The ANALYZE command gather statistics about the content of tables
94644** and indices.  These statistics are made available to the query planner
94645** to help it make better decisions about how to perform queries.
94646**
94647** The following system tables are or have been supported:
94648**
94649**    CREATE TABLE sqlite_stat1(tbl, idx, stat);
94650**    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
94651**    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
94652**    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
94653**
94654** Additional tables might be added in future releases of SQLite.
94655** The sqlite_stat2 table is not created or used unless the SQLite version
94656** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
94657** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
94658** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
94659** created and used by SQLite versions 3.7.9 and later and with
94660** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
94661** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
94662** version of sqlite_stat3 and is only available when compiled with
94663** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
94664** not possible to enable both STAT3 and STAT4 at the same time.  If they
94665** are both enabled, then STAT4 takes precedence.
94666**
94667** For most applications, sqlite_stat1 provides all the statistics required
94668** for the query planner to make good choices.
94669**
94670** Format of sqlite_stat1:
94671**
94672** There is normally one row per index, with the index identified by the
94673** name in the idx column.  The tbl column is the name of the table to
94674** which the index belongs.  In each such row, the stat column will be
94675** a string consisting of a list of integers.  The first integer in this
94676** list is the number of rows in the index.  (This is the same as the
94677** number of rows in the table, except for partial indices.)  The second
94678** integer is the average number of rows in the index that have the same
94679** value in the first column of the index.  The third integer is the average
94680** number of rows in the index that have the same value for the first two
94681** columns.  The N-th integer (for N>1) is the average number of rows in
94682** the index which have the same value for the first N-1 columns.  For
94683** a K-column index, there will be K+1 integers in the stat column.  If
94684** the index is unique, then the last integer will be 1.
94685**
94686** The list of integers in the stat column can optionally be followed
94687** by the keyword "unordered".  The "unordered" keyword, if it is present,
94688** must be separated from the last integer by a single space.  If the
94689** "unordered" keyword is present, then the query planner assumes that
94690** the index is unordered and will not use the index for a range query.
94691**
94692** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
94693** column contains a single integer which is the (estimated) number of
94694** rows in the table identified by sqlite_stat1.tbl.
94695**
94696** Format of sqlite_stat2:
94697**
94698** The sqlite_stat2 is only created and is only used if SQLite is compiled
94699** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
94700** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
94701** about the distribution of keys within an index.  The index is identified by
94702** the "idx" column and the "tbl" column is the name of the table to which
94703** the index belongs.  There are usually 10 rows in the sqlite_stat2
94704** table for each index.
94705**
94706** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
94707** inclusive are samples of the left-most key value in the index taken at
94708** evenly spaced points along the index.  Let the number of samples be S
94709** (10 in the standard build) and let C be the number of rows in the index.
94710** Then the sampled rows are given by:
94711**
94712**     rownumber = (i*C*2 + C)/(S*2)
94713**
94714** For i between 0 and S-1.  Conceptually, the index space is divided into
94715** S uniform buckets and the samples are the middle row from each bucket.
94716**
94717** The format for sqlite_stat2 is recorded here for legacy reference.  This
94718** version of SQLite does not support sqlite_stat2.  It neither reads nor
94719** writes the sqlite_stat2 table.  This version of SQLite only supports
94720** sqlite_stat3.
94721**
94722** Format for sqlite_stat3:
94723**
94724** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
94725** sqlite_stat4 format will be described first.  Further information
94726** about sqlite_stat3 follows the sqlite_stat4 description.
94727**
94728** Format for sqlite_stat4:
94729**
94730** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
94731** to aid the query planner in choosing good indices based on the values
94732** that indexed columns are compared against in the WHERE clauses of
94733** queries.
94734**
94735** The sqlite_stat4 table contains multiple entries for each index.
94736** The idx column names the index and the tbl column is the table of the
94737** index.  If the idx and tbl columns are the same, then the sample is
94738** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
94739** binary encoding of a key from the index.  The nEq column is a
94740** list of integers.  The first integer is the approximate number
94741** of entries in the index whose left-most column exactly matches
94742** the left-most column of the sample.  The second integer in nEq
94743** is the approximate number of entries in the index where the
94744** first two columns match the first two columns of the sample.
94745** And so forth.  nLt is another list of integers that show the approximate
94746** number of entries that are strictly less than the sample.  The first
94747** integer in nLt contains the number of entries in the index where the
94748** left-most column is less than the left-most column of the sample.
94749** The K-th integer in the nLt entry is the number of index entries
94750** where the first K columns are less than the first K columns of the
94751** sample.  The nDLt column is like nLt except that it contains the
94752** number of distinct entries in the index that are less than the
94753** sample.
94754**
94755** There can be an arbitrary number of sqlite_stat4 entries per index.
94756** The ANALYZE command will typically generate sqlite_stat4 tables
94757** that contain between 10 and 40 samples which are distributed across
94758** the key space, though not uniformly, and which include samples with
94759** large nEq values.
94760**
94761** Format for sqlite_stat3 redux:
94762**
94763** The sqlite_stat3 table is like sqlite_stat4 except that it only
94764** looks at the left-most column of the index.  The sqlite_stat3.sample
94765** column contains the actual value of the left-most column instead
94766** of a blob encoding of the complete index key as is found in
94767** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
94768** all contain just a single integer which is the same as the first
94769** integer in the equivalent columns in sqlite_stat4.
94770*/
94771#ifndef SQLITE_OMIT_ANALYZE
94772/* #include "sqliteInt.h" */
94773
94774#if defined(SQLITE_ENABLE_STAT4)
94775# define IsStat4     1
94776# define IsStat3     0
94777#elif defined(SQLITE_ENABLE_STAT3)
94778# define IsStat4     0
94779# define IsStat3     1
94780#else
94781# define IsStat4     0
94782# define IsStat3     0
94783# undef SQLITE_STAT4_SAMPLES
94784# define SQLITE_STAT4_SAMPLES 1
94785#endif
94786#define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
94787
94788/*
94789** This routine generates code that opens the sqlite_statN tables.
94790** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
94791** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
94792** appropriate compile-time options are provided.
94793**
94794** If the sqlite_statN tables do not previously exist, it is created.
94795**
94796** Argument zWhere may be a pointer to a buffer containing a table name,
94797** or it may be a NULL pointer. If it is not NULL, then all entries in
94798** the sqlite_statN tables associated with the named table are deleted.
94799** If zWhere==0, then code is generated to delete all stat table entries.
94800*/
94801static void openStatTable(
94802  Parse *pParse,          /* Parsing context */
94803  int iDb,                /* The database we are looking in */
94804  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
94805  const char *zWhere,     /* Delete entries for this table or index */
94806  const char *zWhereType  /* Either "tbl" or "idx" */
94807){
94808  static const struct {
94809    const char *zName;
94810    const char *zCols;
94811  } aTable[] = {
94812    { "sqlite_stat1", "tbl,idx,stat" },
94813#if defined(SQLITE_ENABLE_STAT4)
94814    { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
94815    { "sqlite_stat3", 0 },
94816#elif defined(SQLITE_ENABLE_STAT3)
94817    { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
94818    { "sqlite_stat4", 0 },
94819#else
94820    { "sqlite_stat3", 0 },
94821    { "sqlite_stat4", 0 },
94822#endif
94823  };
94824  int i;
94825  sqlite3 *db = pParse->db;
94826  Db *pDb;
94827  Vdbe *v = sqlite3GetVdbe(pParse);
94828  int aRoot[ArraySize(aTable)];
94829  u8 aCreateTbl[ArraySize(aTable)];
94830
94831  if( v==0 ) return;
94832  assert( sqlite3BtreeHoldsAllMutexes(db) );
94833  assert( sqlite3VdbeDb(v)==db );
94834  pDb = &db->aDb[iDb];
94835
94836  /* Create new statistic tables if they do not exist, or clear them
94837  ** if they do already exist.
94838  */
94839  for(i=0; i<ArraySize(aTable); i++){
94840    const char *zTab = aTable[i].zName;
94841    Table *pStat;
94842    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
94843      if( aTable[i].zCols ){
94844        /* The sqlite_statN table does not exist. Create it. Note that a
94845        ** side-effect of the CREATE TABLE statement is to leave the rootpage
94846        ** of the new table in register pParse->regRoot. This is important
94847        ** because the OpenWrite opcode below will be needing it. */
94848        sqlite3NestedParse(pParse,
94849            "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
94850        );
94851        aRoot[i] = pParse->regRoot;
94852        aCreateTbl[i] = OPFLAG_P2ISREG;
94853      }
94854    }else{
94855      /* The table already exists. If zWhere is not NULL, delete all entries
94856      ** associated with the table zWhere. If zWhere is NULL, delete the
94857      ** entire contents of the table. */
94858      aRoot[i] = pStat->tnum;
94859      aCreateTbl[i] = 0;
94860      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
94861      if( zWhere ){
94862        sqlite3NestedParse(pParse,
94863           "DELETE FROM %Q.%s WHERE %s=%Q",
94864           pDb->zName, zTab, zWhereType, zWhere
94865        );
94866      }else{
94867        /* The sqlite_stat[134] table already exists.  Delete all rows. */
94868        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
94869      }
94870    }
94871  }
94872
94873  /* Open the sqlite_stat[134] tables for writing. */
94874  for(i=0; aTable[i].zCols; i++){
94875    assert( i<ArraySize(aTable) );
94876    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
94877    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
94878    VdbeComment((v, aTable[i].zName));
94879  }
94880}
94881
94882/*
94883** Recommended number of samples for sqlite_stat4
94884*/
94885#ifndef SQLITE_STAT4_SAMPLES
94886# define SQLITE_STAT4_SAMPLES 24
94887#endif
94888
94889/*
94890** Three SQL functions - stat_init(), stat_push(), and stat_get() -
94891** share an instance of the following structure to hold their state
94892** information.
94893*/
94894typedef struct Stat4Accum Stat4Accum;
94895typedef struct Stat4Sample Stat4Sample;
94896struct Stat4Sample {
94897  tRowcnt *anEq;                  /* sqlite_stat4.nEq */
94898  tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
94899#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94900  tRowcnt *anLt;                  /* sqlite_stat4.nLt */
94901  union {
94902    i64 iRowid;                     /* Rowid in main table of the key */
94903    u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
94904  } u;
94905  u32 nRowid;                     /* Sizeof aRowid[] */
94906  u8 isPSample;                   /* True if a periodic sample */
94907  int iCol;                       /* If !isPSample, the reason for inclusion */
94908  u32 iHash;                      /* Tiebreaker hash */
94909#endif
94910};
94911struct Stat4Accum {
94912  tRowcnt nRow;             /* Number of rows in the entire table */
94913  tRowcnt nPSample;         /* How often to do a periodic sample */
94914  int nCol;                 /* Number of columns in index + pk/rowid */
94915  int nKeyCol;              /* Number of index columns w/o the pk/rowid */
94916  int mxSample;             /* Maximum number of samples to accumulate */
94917  Stat4Sample current;      /* Current row as a Stat4Sample */
94918  u32 iPrn;                 /* Pseudo-random number used for sampling */
94919  Stat4Sample *aBest;       /* Array of nCol best samples */
94920  int iMin;                 /* Index in a[] of entry with minimum score */
94921  int nSample;              /* Current number of samples */
94922  int iGet;                 /* Index of current sample accessed by stat_get() */
94923  Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
94924  sqlite3 *db;              /* Database connection, for malloc() */
94925};
94926
94927/* Reclaim memory used by a Stat4Sample
94928*/
94929#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94930static void sampleClear(sqlite3 *db, Stat4Sample *p){
94931  assert( db!=0 );
94932  if( p->nRowid ){
94933    sqlite3DbFree(db, p->u.aRowid);
94934    p->nRowid = 0;
94935  }
94936}
94937#endif
94938
94939/* Initialize the BLOB value of a ROWID
94940*/
94941#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94942static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
94943  assert( db!=0 );
94944  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
94945  p->u.aRowid = sqlite3DbMallocRawNN(db, n);
94946  if( p->u.aRowid ){
94947    p->nRowid = n;
94948    memcpy(p->u.aRowid, pData, n);
94949  }else{
94950    p->nRowid = 0;
94951  }
94952}
94953#endif
94954
94955/* Initialize the INTEGER value of a ROWID.
94956*/
94957#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94958static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
94959  assert( db!=0 );
94960  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
94961  p->nRowid = 0;
94962  p->u.iRowid = iRowid;
94963}
94964#endif
94965
94966
94967/*
94968** Copy the contents of object (*pFrom) into (*pTo).
94969*/
94970#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94971static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
94972  pTo->isPSample = pFrom->isPSample;
94973  pTo->iCol = pFrom->iCol;
94974  pTo->iHash = pFrom->iHash;
94975  memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
94976  memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
94977  memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
94978  if( pFrom->nRowid ){
94979    sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
94980  }else{
94981    sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
94982  }
94983}
94984#endif
94985
94986/*
94987** Reclaim all memory of a Stat4Accum structure.
94988*/
94989static void stat4Destructor(void *pOld){
94990  Stat4Accum *p = (Stat4Accum*)pOld;
94991#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94992  int i;
94993  for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
94994  for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
94995  sampleClear(p->db, &p->current);
94996#endif
94997  sqlite3DbFree(p->db, p);
94998}
94999
95000/*
95001** Implementation of the stat_init(N,K,C) SQL function. The three parameters
95002** are:
95003**     N:    The number of columns in the index including the rowid/pk (note 1)
95004**     K:    The number of columns in the index excluding the rowid/pk.
95005**     C:    The number of rows in the index (note 2)
95006**
95007** Note 1:  In the special case of the covering index that implements a
95008** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
95009** total number of columns in the table.
95010**
95011** Note 2:  C is only used for STAT3 and STAT4.
95012**
95013** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
95014** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
95015** PRIMARY KEY of the table.  The covering index that implements the
95016** original WITHOUT ROWID table as N==K as a special case.
95017**
95018** This routine allocates the Stat4Accum object in heap memory. The return
95019** value is a pointer to the Stat4Accum object.  The datatype of the
95020** return value is BLOB, but it is really just a pointer to the Stat4Accum
95021** object.
95022*/
95023static void statInit(
95024  sqlite3_context *context,
95025  int argc,
95026  sqlite3_value **argv
95027){
95028  Stat4Accum *p;
95029  int nCol;                       /* Number of columns in index being sampled */
95030  int nKeyCol;                    /* Number of key columns */
95031  int nColUp;                     /* nCol rounded up for alignment */
95032  int n;                          /* Bytes of space to allocate */
95033  sqlite3 *db;                    /* Database connection */
95034#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95035  int mxSample = SQLITE_STAT4_SAMPLES;
95036#endif
95037
95038  /* Decode the three function arguments */
95039  UNUSED_PARAMETER(argc);
95040  nCol = sqlite3_value_int(argv[0]);
95041  assert( nCol>0 );
95042  nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
95043  nKeyCol = sqlite3_value_int(argv[1]);
95044  assert( nKeyCol<=nCol );
95045  assert( nKeyCol>0 );
95046
95047  /* Allocate the space required for the Stat4Accum object */
95048  n = sizeof(*p)
95049    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
95050    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
95051#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95052    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
95053    + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
95054    + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
95055#endif
95056  ;
95057  db = sqlite3_context_db_handle(context);
95058  p = sqlite3DbMallocZero(db, n);
95059  if( p==0 ){
95060    sqlite3_result_error_nomem(context);
95061    return;
95062  }
95063
95064  p->db = db;
95065  p->nRow = 0;
95066  p->nCol = nCol;
95067  p->nKeyCol = nKeyCol;
95068  p->current.anDLt = (tRowcnt*)&p[1];
95069  p->current.anEq = &p->current.anDLt[nColUp];
95070
95071#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95072  {
95073    u8 *pSpace;                     /* Allocated space not yet assigned */
95074    int i;                          /* Used to iterate through p->aSample[] */
95075
95076    p->iGet = -1;
95077    p->mxSample = mxSample;
95078    p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
95079    p->current.anLt = &p->current.anEq[nColUp];
95080    p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
95081
95082    /* Set up the Stat4Accum.a[] and aBest[] arrays */
95083    p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
95084    p->aBest = &p->a[mxSample];
95085    pSpace = (u8*)(&p->a[mxSample+nCol]);
95086    for(i=0; i<(mxSample+nCol); i++){
95087      p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
95088      p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
95089      p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
95090    }
95091    assert( (pSpace - (u8*)p)==n );
95092
95093    for(i=0; i<nCol; i++){
95094      p->aBest[i].iCol = i;
95095    }
95096  }
95097#endif
95098
95099  /* Return a pointer to the allocated object to the caller.  Note that
95100  ** only the pointer (the 2nd parameter) matters.  The size of the object
95101  ** (given by the 3rd parameter) is never used and can be any positive
95102  ** value. */
95103  sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
95104}
95105static const FuncDef statInitFuncdef = {
95106  2+IsStat34,      /* nArg */
95107  SQLITE_UTF8,     /* funcFlags */
95108  0,               /* pUserData */
95109  0,               /* pNext */
95110  statInit,        /* xSFunc */
95111  0,               /* xFinalize */
95112  "stat_init",     /* zName */
95113  {0}
95114};
95115
95116#ifdef SQLITE_ENABLE_STAT4
95117/*
95118** pNew and pOld are both candidate non-periodic samples selected for
95119** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
95120** considering only any trailing columns and the sample hash value, this
95121** function returns true if sample pNew is to be preferred over pOld.
95122** In other words, if we assume that the cardinalities of the selected
95123** column for pNew and pOld are equal, is pNew to be preferred over pOld.
95124**
95125** This function assumes that for each argument sample, the contents of
95126** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
95127*/
95128static int sampleIsBetterPost(
95129  Stat4Accum *pAccum,
95130  Stat4Sample *pNew,
95131  Stat4Sample *pOld
95132){
95133  int nCol = pAccum->nCol;
95134  int i;
95135  assert( pNew->iCol==pOld->iCol );
95136  for(i=pNew->iCol+1; i<nCol; i++){
95137    if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
95138    if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
95139  }
95140  if( pNew->iHash>pOld->iHash ) return 1;
95141  return 0;
95142}
95143#endif
95144
95145#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95146/*
95147** Return true if pNew is to be preferred over pOld.
95148**
95149** This function assumes that for each argument sample, the contents of
95150** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
95151*/
95152static int sampleIsBetter(
95153  Stat4Accum *pAccum,
95154  Stat4Sample *pNew,
95155  Stat4Sample *pOld
95156){
95157  tRowcnt nEqNew = pNew->anEq[pNew->iCol];
95158  tRowcnt nEqOld = pOld->anEq[pOld->iCol];
95159
95160  assert( pOld->isPSample==0 && pNew->isPSample==0 );
95161  assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
95162
95163  if( (nEqNew>nEqOld) ) return 1;
95164#ifdef SQLITE_ENABLE_STAT4
95165  if( nEqNew==nEqOld ){
95166    if( pNew->iCol<pOld->iCol ) return 1;
95167    return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
95168  }
95169  return 0;
95170#else
95171  return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
95172#endif
95173}
95174
95175/*
95176** Copy the contents of sample *pNew into the p->a[] array. If necessary,
95177** remove the least desirable sample from p->a[] to make room.
95178*/
95179static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
95180  Stat4Sample *pSample = 0;
95181  int i;
95182
95183  assert( IsStat4 || nEqZero==0 );
95184
95185#ifdef SQLITE_ENABLE_STAT4
95186  if( pNew->isPSample==0 ){
95187    Stat4Sample *pUpgrade = 0;
95188    assert( pNew->anEq[pNew->iCol]>0 );
95189
95190    /* This sample is being added because the prefix that ends in column
95191    ** iCol occurs many times in the table. However, if we have already
95192    ** added a sample that shares this prefix, there is no need to add
95193    ** this one. Instead, upgrade the priority of the highest priority
95194    ** existing sample that shares this prefix.  */
95195    for(i=p->nSample-1; i>=0; i--){
95196      Stat4Sample *pOld = &p->a[i];
95197      if( pOld->anEq[pNew->iCol]==0 ){
95198        if( pOld->isPSample ) return;
95199        assert( pOld->iCol>pNew->iCol );
95200        assert( sampleIsBetter(p, pNew, pOld) );
95201        if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
95202          pUpgrade = pOld;
95203        }
95204      }
95205    }
95206    if( pUpgrade ){
95207      pUpgrade->iCol = pNew->iCol;
95208      pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
95209      goto find_new_min;
95210    }
95211  }
95212#endif
95213
95214  /* If necessary, remove sample iMin to make room for the new sample. */
95215  if( p->nSample>=p->mxSample ){
95216    Stat4Sample *pMin = &p->a[p->iMin];
95217    tRowcnt *anEq = pMin->anEq;
95218    tRowcnt *anLt = pMin->anLt;
95219    tRowcnt *anDLt = pMin->anDLt;
95220    sampleClear(p->db, pMin);
95221    memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
95222    pSample = &p->a[p->nSample-1];
95223    pSample->nRowid = 0;
95224    pSample->anEq = anEq;
95225    pSample->anDLt = anDLt;
95226    pSample->anLt = anLt;
95227    p->nSample = p->mxSample-1;
95228  }
95229
95230  /* The "rows less-than" for the rowid column must be greater than that
95231  ** for the last sample in the p->a[] array. Otherwise, the samples would
95232  ** be out of order. */
95233#ifdef SQLITE_ENABLE_STAT4
95234  assert( p->nSample==0
95235       || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
95236#endif
95237
95238  /* Insert the new sample */
95239  pSample = &p->a[p->nSample];
95240  sampleCopy(p, pSample, pNew);
95241  p->nSample++;
95242
95243  /* Zero the first nEqZero entries in the anEq[] array. */
95244  memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
95245
95246#ifdef SQLITE_ENABLE_STAT4
95247 find_new_min:
95248#endif
95249  if( p->nSample>=p->mxSample ){
95250    int iMin = -1;
95251    for(i=0; i<p->mxSample; i++){
95252      if( p->a[i].isPSample ) continue;
95253      if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
95254        iMin = i;
95255      }
95256    }
95257    assert( iMin>=0 );
95258    p->iMin = iMin;
95259  }
95260}
95261#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
95262
95263/*
95264** Field iChng of the index being scanned has changed. So at this point
95265** p->current contains a sample that reflects the previous row of the
95266** index. The value of anEq[iChng] and subsequent anEq[] elements are
95267** correct at this point.
95268*/
95269static void samplePushPrevious(Stat4Accum *p, int iChng){
95270#ifdef SQLITE_ENABLE_STAT4
95271  int i;
95272
95273  /* Check if any samples from the aBest[] array should be pushed
95274  ** into IndexSample.a[] at this point.  */
95275  for(i=(p->nCol-2); i>=iChng; i--){
95276    Stat4Sample *pBest = &p->aBest[i];
95277    pBest->anEq[i] = p->current.anEq[i];
95278    if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
95279      sampleInsert(p, pBest, i);
95280    }
95281  }
95282
95283  /* Update the anEq[] fields of any samples already collected. */
95284  for(i=p->nSample-1; i>=0; i--){
95285    int j;
95286    for(j=iChng; j<p->nCol; j++){
95287      if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
95288    }
95289  }
95290#endif
95291
95292#if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
95293  if( iChng==0 ){
95294    tRowcnt nLt = p->current.anLt[0];
95295    tRowcnt nEq = p->current.anEq[0];
95296
95297    /* Check if this is to be a periodic sample. If so, add it. */
95298    if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
95299      p->current.isPSample = 1;
95300      sampleInsert(p, &p->current, 0);
95301      p->current.isPSample = 0;
95302    }else
95303
95304    /* Or if it is a non-periodic sample. Add it in this case too. */
95305    if( p->nSample<p->mxSample
95306     || sampleIsBetter(p, &p->current, &p->a[p->iMin])
95307    ){
95308      sampleInsert(p, &p->current, 0);
95309    }
95310  }
95311#endif
95312
95313#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
95314  UNUSED_PARAMETER( p );
95315  UNUSED_PARAMETER( iChng );
95316#endif
95317}
95318
95319/*
95320** Implementation of the stat_push SQL function:  stat_push(P,C,R)
95321** Arguments:
95322**
95323**    P     Pointer to the Stat4Accum object created by stat_init()
95324**    C     Index of left-most column to differ from previous row
95325**    R     Rowid for the current row.  Might be a key record for
95326**          WITHOUT ROWID tables.
95327**
95328** This SQL function always returns NULL.  It's purpose it to accumulate
95329** statistical data and/or samples in the Stat4Accum object about the
95330** index being analyzed.  The stat_get() SQL function will later be used to
95331** extract relevant information for constructing the sqlite_statN tables.
95332**
95333** The R parameter is only used for STAT3 and STAT4
95334*/
95335static void statPush(
95336  sqlite3_context *context,
95337  int argc,
95338  sqlite3_value **argv
95339){
95340  int i;
95341
95342  /* The three function arguments */
95343  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
95344  int iChng = sqlite3_value_int(argv[1]);
95345
95346  UNUSED_PARAMETER( argc );
95347  UNUSED_PARAMETER( context );
95348  assert( p->nCol>0 );
95349  assert( iChng<p->nCol );
95350
95351  if( p->nRow==0 ){
95352    /* This is the first call to this function. Do initialization. */
95353    for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
95354  }else{
95355    /* Second and subsequent calls get processed here */
95356    samplePushPrevious(p, iChng);
95357
95358    /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
95359    ** to the current row of the index. */
95360    for(i=0; i<iChng; i++){
95361      p->current.anEq[i]++;
95362    }
95363    for(i=iChng; i<p->nCol; i++){
95364      p->current.anDLt[i]++;
95365#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95366      p->current.anLt[i] += p->current.anEq[i];
95367#endif
95368      p->current.anEq[i] = 1;
95369    }
95370  }
95371  p->nRow++;
95372#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95373  if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
95374    sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
95375  }else{
95376    sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
95377                                       sqlite3_value_blob(argv[2]));
95378  }
95379  p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
95380#endif
95381
95382#ifdef SQLITE_ENABLE_STAT4
95383  {
95384    tRowcnt nLt = p->current.anLt[p->nCol-1];
95385
95386    /* Check if this is to be a periodic sample. If so, add it. */
95387    if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
95388      p->current.isPSample = 1;
95389      p->current.iCol = 0;
95390      sampleInsert(p, &p->current, p->nCol-1);
95391      p->current.isPSample = 0;
95392    }
95393
95394    /* Update the aBest[] array. */
95395    for(i=0; i<(p->nCol-1); i++){
95396      p->current.iCol = i;
95397      if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
95398        sampleCopy(p, &p->aBest[i], &p->current);
95399      }
95400    }
95401  }
95402#endif
95403}
95404static const FuncDef statPushFuncdef = {
95405  2+IsStat34,      /* nArg */
95406  SQLITE_UTF8,     /* funcFlags */
95407  0,               /* pUserData */
95408  0,               /* pNext */
95409  statPush,        /* xSFunc */
95410  0,               /* xFinalize */
95411  "stat_push",     /* zName */
95412  {0}
95413};
95414
95415#define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
95416#define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
95417#define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
95418#define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
95419#define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
95420
95421/*
95422** Implementation of the stat_get(P,J) SQL function.  This routine is
95423** used to query statistical information that has been gathered into
95424** the Stat4Accum object by prior calls to stat_push().  The P parameter
95425** has type BLOB but it is really just a pointer to the Stat4Accum object.
95426** The content to returned is determined by the parameter J
95427** which is one of the STAT_GET_xxxx values defined above.
95428**
95429** If neither STAT3 nor STAT4 are enabled, then J is always
95430** STAT_GET_STAT1 and is hence omitted and this routine becomes
95431** a one-parameter function, stat_get(P), that always returns the
95432** stat1 table entry information.
95433*/
95434static void statGet(
95435  sqlite3_context *context,
95436  int argc,
95437  sqlite3_value **argv
95438){
95439  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
95440#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95441  /* STAT3 and STAT4 have a parameter on this routine. */
95442  int eCall = sqlite3_value_int(argv[1]);
95443  assert( argc==2 );
95444  assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
95445       || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
95446       || eCall==STAT_GET_NDLT
95447  );
95448  if( eCall==STAT_GET_STAT1 )
95449#else
95450  assert( argc==1 );
95451#endif
95452  {
95453    /* Return the value to store in the "stat" column of the sqlite_stat1
95454    ** table for this index.
95455    **
95456    ** The value is a string composed of a list of integers describing
95457    ** the index. The first integer in the list is the total number of
95458    ** entries in the index. There is one additional integer in the list
95459    ** for each indexed column. This additional integer is an estimate of
95460    ** the number of rows matched by a stabbing query on the index using
95461    ** a key with the corresponding number of fields. In other words,
95462    ** if the index is on columns (a,b) and the sqlite_stat1 value is
95463    ** "100 10 2", then SQLite estimates that:
95464    **
95465    **   * the index contains 100 rows,
95466    **   * "WHERE a=?" matches 10 rows, and
95467    **   * "WHERE a=? AND b=?" matches 2 rows.
95468    **
95469    ** If D is the count of distinct values and K is the total number of
95470    ** rows, then each estimate is computed as:
95471    **
95472    **        I = (K+D-1)/D
95473    */
95474    char *z;
95475    int i;
95476
95477    char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
95478    if( zRet==0 ){
95479      sqlite3_result_error_nomem(context);
95480      return;
95481    }
95482
95483    sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
95484    z = zRet + sqlite3Strlen30(zRet);
95485    for(i=0; i<p->nKeyCol; i++){
95486      u64 nDistinct = p->current.anDLt[i] + 1;
95487      u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
95488      sqlite3_snprintf(24, z, " %llu", iVal);
95489      z += sqlite3Strlen30(z);
95490      assert( p->current.anEq[i] );
95491    }
95492    assert( z[0]=='\0' && z>zRet );
95493
95494    sqlite3_result_text(context, zRet, -1, sqlite3_free);
95495  }
95496#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95497  else if( eCall==STAT_GET_ROWID ){
95498    if( p->iGet<0 ){
95499      samplePushPrevious(p, 0);
95500      p->iGet = 0;
95501    }
95502    if( p->iGet<p->nSample ){
95503      Stat4Sample *pS = p->a + p->iGet;
95504      if( pS->nRowid==0 ){
95505        sqlite3_result_int64(context, pS->u.iRowid);
95506      }else{
95507        sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
95508                            SQLITE_TRANSIENT);
95509      }
95510    }
95511  }else{
95512    tRowcnt *aCnt = 0;
95513
95514    assert( p->iGet<p->nSample );
95515    switch( eCall ){
95516      case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
95517      case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
95518      default: {
95519        aCnt = p->a[p->iGet].anDLt;
95520        p->iGet++;
95521        break;
95522      }
95523    }
95524
95525    if( IsStat3 ){
95526      sqlite3_result_int64(context, (i64)aCnt[0]);
95527    }else{
95528      char *zRet = sqlite3MallocZero(p->nCol * 25);
95529      if( zRet==0 ){
95530        sqlite3_result_error_nomem(context);
95531      }else{
95532        int i;
95533        char *z = zRet;
95534        for(i=0; i<p->nCol; i++){
95535          sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
95536          z += sqlite3Strlen30(z);
95537        }
95538        assert( z[0]=='\0' && z>zRet );
95539        z[-1] = '\0';
95540        sqlite3_result_text(context, zRet, -1, sqlite3_free);
95541      }
95542    }
95543  }
95544#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
95545#ifndef SQLITE_DEBUG
95546  UNUSED_PARAMETER( argc );
95547#endif
95548}
95549static const FuncDef statGetFuncdef = {
95550  1+IsStat34,      /* nArg */
95551  SQLITE_UTF8,     /* funcFlags */
95552  0,               /* pUserData */
95553  0,               /* pNext */
95554  statGet,         /* xSFunc */
95555  0,               /* xFinalize */
95556  "stat_get",      /* zName */
95557  {0}
95558};
95559
95560static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
95561  assert( regOut!=regStat4 && regOut!=regStat4+1 );
95562#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95563  sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
95564#elif SQLITE_DEBUG
95565  assert( iParam==STAT_GET_STAT1 );
95566#else
95567  UNUSED_PARAMETER( iParam );
95568#endif
95569  sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
95570                    (char*)&statGetFuncdef, P4_FUNCDEF);
95571  sqlite3VdbeChangeP5(v, 1 + IsStat34);
95572}
95573
95574/*
95575** Generate code to do an analysis of all indices associated with
95576** a single table.
95577*/
95578static void analyzeOneTable(
95579  Parse *pParse,   /* Parser context */
95580  Table *pTab,     /* Table whose indices are to be analyzed */
95581  Index *pOnlyIdx, /* If not NULL, only analyze this one index */
95582  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
95583  int iMem,        /* Available memory locations begin here */
95584  int iTab         /* Next available cursor */
95585){
95586  sqlite3 *db = pParse->db;    /* Database handle */
95587  Index *pIdx;                 /* An index to being analyzed */
95588  int iIdxCur;                 /* Cursor open on index being analyzed */
95589  int iTabCur;                 /* Table cursor */
95590  Vdbe *v;                     /* The virtual machine being built up */
95591  int i;                       /* Loop counter */
95592  int jZeroRows = -1;          /* Jump from here if number of rows is zero */
95593  int iDb;                     /* Index of database containing pTab */
95594  u8 needTableCnt = 1;         /* True to count the table */
95595  int regNewRowid = iMem++;    /* Rowid for the inserted record */
95596  int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
95597  int regChng = iMem++;        /* Index of changed index field */
95598#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95599  int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
95600#endif
95601  int regTemp = iMem++;        /* Temporary use register */
95602  int regTabname = iMem++;     /* Register containing table name */
95603  int regIdxname = iMem++;     /* Register containing index name */
95604  int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
95605  int regPrev = iMem;          /* MUST BE LAST (see below) */
95606
95607  pParse->nMem = MAX(pParse->nMem, iMem);
95608  v = sqlite3GetVdbe(pParse);
95609  if( v==0 || NEVER(pTab==0) ){
95610    return;
95611  }
95612  if( pTab->tnum==0 ){
95613    /* Do not gather statistics on views or virtual tables */
95614    return;
95615  }
95616  if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){
95617    /* Do not gather statistics on system tables */
95618    return;
95619  }
95620  assert( sqlite3BtreeHoldsAllMutexes(db) );
95621  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
95622  assert( iDb>=0 );
95623  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95624#ifndef SQLITE_OMIT_AUTHORIZATION
95625  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
95626      db->aDb[iDb].zName ) ){
95627    return;
95628  }
95629#endif
95630
95631  /* Establish a read-lock on the table at the shared-cache level.
95632  ** Open a read-only cursor on the table. Also allocate a cursor number
95633  ** to use for scanning indexes (iIdxCur). No index cursor is opened at
95634  ** this time though.  */
95635  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
95636  iTabCur = iTab++;
95637  iIdxCur = iTab++;
95638  pParse->nTab = MAX(pParse->nTab, iTab);
95639  sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
95640  sqlite3VdbeLoadString(v, regTabname, pTab->zName);
95641
95642  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
95643    int nCol;                     /* Number of columns in pIdx. "N" */
95644    int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
95645    int addrNextRow;              /* Address of "next_row:" */
95646    const char *zIdxName;         /* Name of the index */
95647    int nColTest;                 /* Number of columns to test for changes */
95648
95649    if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
95650    if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
95651    if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
95652      nCol = pIdx->nKeyCol;
95653      zIdxName = pTab->zName;
95654      nColTest = nCol - 1;
95655    }else{
95656      nCol = pIdx->nColumn;
95657      zIdxName = pIdx->zName;
95658      nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
95659    }
95660
95661    /* Populate the register containing the index name. */
95662    sqlite3VdbeLoadString(v, regIdxname, zIdxName);
95663    VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
95664
95665    /*
95666    ** Pseudo-code for loop that calls stat_push():
95667    **
95668    **   Rewind csr
95669    **   if eof(csr) goto end_of_scan;
95670    **   regChng = 0
95671    **   goto chng_addr_0;
95672    **
95673    **  next_row:
95674    **   regChng = 0
95675    **   if( idx(0) != regPrev(0) ) goto chng_addr_0
95676    **   regChng = 1
95677    **   if( idx(1) != regPrev(1) ) goto chng_addr_1
95678    **   ...
95679    **   regChng = N
95680    **   goto chng_addr_N
95681    **
95682    **  chng_addr_0:
95683    **   regPrev(0) = idx(0)
95684    **  chng_addr_1:
95685    **   regPrev(1) = idx(1)
95686    **  ...
95687    **
95688    **  endDistinctTest:
95689    **   regRowid = idx(rowid)
95690    **   stat_push(P, regChng, regRowid)
95691    **   Next csr
95692    **   if !eof(csr) goto next_row;
95693    **
95694    **  end_of_scan:
95695    */
95696
95697    /* Make sure there are enough memory cells allocated to accommodate
95698    ** the regPrev array and a trailing rowid (the rowid slot is required
95699    ** when building a record to insert into the sample column of
95700    ** the sqlite_stat4 table.  */
95701    pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
95702
95703    /* Open a read-only cursor on the index being analyzed. */
95704    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
95705    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
95706    sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
95707    VdbeComment((v, "%s", pIdx->zName));
95708
95709    /* Invoke the stat_init() function. The arguments are:
95710    **
95711    **    (1) the number of columns in the index including the rowid
95712    **        (or for a WITHOUT ROWID table, the number of PK columns),
95713    **    (2) the number of columns in the key without the rowid/pk
95714    **    (3) the number of rows in the index,
95715    **
95716    **
95717    ** The third argument is only used for STAT3 and STAT4
95718    */
95719#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95720    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
95721#endif
95722    sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
95723    sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
95724    sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
95725                     (char*)&statInitFuncdef, P4_FUNCDEF);
95726    sqlite3VdbeChangeP5(v, 2+IsStat34);
95727
95728    /* Implementation of the following:
95729    **
95730    **   Rewind csr
95731    **   if eof(csr) goto end_of_scan;
95732    **   regChng = 0
95733    **   goto next_push_0;
95734    **
95735    */
95736    addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
95737    VdbeCoverage(v);
95738    sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
95739    addrNextRow = sqlite3VdbeCurrentAddr(v);
95740
95741    if( nColTest>0 ){
95742      int endDistinctTest = sqlite3VdbeMakeLabel(v);
95743      int *aGotoChng;               /* Array of jump instruction addresses */
95744      aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
95745      if( aGotoChng==0 ) continue;
95746
95747      /*
95748      **  next_row:
95749      **   regChng = 0
95750      **   if( idx(0) != regPrev(0) ) goto chng_addr_0
95751      **   regChng = 1
95752      **   if( idx(1) != regPrev(1) ) goto chng_addr_1
95753      **   ...
95754      **   regChng = N
95755      **   goto endDistinctTest
95756      */
95757      sqlite3VdbeAddOp0(v, OP_Goto);
95758      addrNextRow = sqlite3VdbeCurrentAddr(v);
95759      if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
95760        /* For a single-column UNIQUE index, once we have found a non-NULL
95761        ** row, we know that all the rest will be distinct, so skip
95762        ** subsequent distinctness tests. */
95763        sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
95764        VdbeCoverage(v);
95765      }
95766      for(i=0; i<nColTest; i++){
95767        char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
95768        sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
95769        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
95770        aGotoChng[i] =
95771        sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
95772        sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
95773        VdbeCoverage(v);
95774      }
95775      sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
95776      sqlite3VdbeGoto(v, endDistinctTest);
95777
95778
95779      /*
95780      **  chng_addr_0:
95781      **   regPrev(0) = idx(0)
95782      **  chng_addr_1:
95783      **   regPrev(1) = idx(1)
95784      **  ...
95785      */
95786      sqlite3VdbeJumpHere(v, addrNextRow-1);
95787      for(i=0; i<nColTest; i++){
95788        sqlite3VdbeJumpHere(v, aGotoChng[i]);
95789        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
95790      }
95791      sqlite3VdbeResolveLabel(v, endDistinctTest);
95792      sqlite3DbFree(db, aGotoChng);
95793    }
95794
95795    /*
95796    **  chng_addr_N:
95797    **   regRowid = idx(rowid)            // STAT34 only
95798    **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
95799    **   Next csr
95800    **   if !eof(csr) goto next_row;
95801    */
95802#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95803    assert( regRowid==(regStat4+2) );
95804    if( HasRowid(pTab) ){
95805      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
95806    }else{
95807      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
95808      int j, k, regKey;
95809      regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
95810      for(j=0; j<pPk->nKeyCol; j++){
95811        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
95812        assert( k>=0 && k<pTab->nCol );
95813        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
95814        VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
95815      }
95816      sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
95817      sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
95818    }
95819#endif
95820    assert( regChng==(regStat4+1) );
95821    sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
95822                     (char*)&statPushFuncdef, P4_FUNCDEF);
95823    sqlite3VdbeChangeP5(v, 2+IsStat34);
95824    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
95825
95826    /* Add the entry to the stat1 table. */
95827    callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
95828    assert( "BBB"[0]==SQLITE_AFF_TEXT );
95829    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
95830    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
95831    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
95832    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
95833
95834    /* Add the entries to the stat3 or stat4 table. */
95835#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95836    {
95837      int regEq = regStat1;
95838      int regLt = regStat1+1;
95839      int regDLt = regStat1+2;
95840      int regSample = regStat1+3;
95841      int regCol = regStat1+4;
95842      int regSampleRowid = regCol + nCol;
95843      int addrNext;
95844      int addrIsNull;
95845      u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
95846
95847      pParse->nMem = MAX(pParse->nMem, regCol+nCol);
95848
95849      addrNext = sqlite3VdbeCurrentAddr(v);
95850      callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
95851      addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
95852      VdbeCoverage(v);
95853      callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
95854      callStatGet(v, regStat4, STAT_GET_NLT, regLt);
95855      callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
95856      sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
95857      /* We know that the regSampleRowid row exists because it was read by
95858      ** the previous loop.  Thus the not-found jump of seekOp will never
95859      ** be taken */
95860      VdbeCoverageNeverTaken(v);
95861#ifdef SQLITE_ENABLE_STAT3
95862      sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
95863#else
95864      for(i=0; i<nCol; i++){
95865        sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
95866      }
95867      sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
95868#endif
95869      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
95870      sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
95871      sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
95872      sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
95873      sqlite3VdbeJumpHere(v, addrIsNull);
95874    }
95875#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
95876
95877    /* End of analysis */
95878    sqlite3VdbeJumpHere(v, addrRewind);
95879  }
95880
95881
95882  /* Create a single sqlite_stat1 entry containing NULL as the index
95883  ** name and the row count as the content.
95884  */
95885  if( pOnlyIdx==0 && needTableCnt ){
95886    VdbeComment((v, "%s", pTab->zName));
95887    sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
95888    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
95889    sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
95890    assert( "BBB"[0]==SQLITE_AFF_TEXT );
95891    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
95892    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
95893    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
95894    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
95895    sqlite3VdbeJumpHere(v, jZeroRows);
95896  }
95897}
95898
95899
95900/*
95901** Generate code that will cause the most recent index analysis to
95902** be loaded into internal hash tables where is can be used.
95903*/
95904static void loadAnalysis(Parse *pParse, int iDb){
95905  Vdbe *v = sqlite3GetVdbe(pParse);
95906  if( v ){
95907    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
95908  }
95909}
95910
95911/*
95912** Generate code that will do an analysis of an entire database
95913*/
95914static void analyzeDatabase(Parse *pParse, int iDb){
95915  sqlite3 *db = pParse->db;
95916  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
95917  HashElem *k;
95918  int iStatCur;
95919  int iMem;
95920  int iTab;
95921
95922  sqlite3BeginWriteOperation(pParse, 0, iDb);
95923  iStatCur = pParse->nTab;
95924  pParse->nTab += 3;
95925  openStatTable(pParse, iDb, iStatCur, 0, 0);
95926  iMem = pParse->nMem+1;
95927  iTab = pParse->nTab;
95928  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95929  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
95930    Table *pTab = (Table*)sqliteHashData(k);
95931    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
95932  }
95933  loadAnalysis(pParse, iDb);
95934}
95935
95936/*
95937** Generate code that will do an analysis of a single table in
95938** a database.  If pOnlyIdx is not NULL then it is a single index
95939** in pTab that should be analyzed.
95940*/
95941static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
95942  int iDb;
95943  int iStatCur;
95944
95945  assert( pTab!=0 );
95946  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
95947  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
95948  sqlite3BeginWriteOperation(pParse, 0, iDb);
95949  iStatCur = pParse->nTab;
95950  pParse->nTab += 3;
95951  if( pOnlyIdx ){
95952    openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
95953  }else{
95954    openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
95955  }
95956  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
95957  loadAnalysis(pParse, iDb);
95958}
95959
95960/*
95961** Generate code for the ANALYZE command.  The parser calls this routine
95962** when it recognizes an ANALYZE command.
95963**
95964**        ANALYZE                            -- 1
95965**        ANALYZE  <database>                -- 2
95966**        ANALYZE  ?<database>.?<tablename>  -- 3
95967**
95968** Form 1 causes all indices in all attached databases to be analyzed.
95969** Form 2 analyzes all indices the single database named.
95970** Form 3 analyzes all indices associated with the named table.
95971*/
95972SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
95973  sqlite3 *db = pParse->db;
95974  int iDb;
95975  int i;
95976  char *z, *zDb;
95977  Table *pTab;
95978  Index *pIdx;
95979  Token *pTableName;
95980  Vdbe *v;
95981
95982  /* Read the database schema. If an error occurs, leave an error message
95983  ** and code in pParse and return NULL. */
95984  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
95985  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
95986    return;
95987  }
95988
95989  assert( pName2!=0 || pName1==0 );
95990  if( pName1==0 ){
95991    /* Form 1:  Analyze everything */
95992    for(i=0; i<db->nDb; i++){
95993      if( i==1 ) continue;  /* Do not analyze the TEMP database */
95994      analyzeDatabase(pParse, i);
95995    }
95996  }else if( pName2->n==0 ){
95997    /* Form 2:  Analyze the database or table named */
95998    iDb = sqlite3FindDb(db, pName1);
95999    if( iDb>=0 ){
96000      analyzeDatabase(pParse, iDb);
96001    }else{
96002      z = sqlite3NameFromToken(db, pName1);
96003      if( z ){
96004        if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
96005          analyzeTable(pParse, pIdx->pTable, pIdx);
96006        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
96007          analyzeTable(pParse, pTab, 0);
96008        }
96009        sqlite3DbFree(db, z);
96010      }
96011    }
96012  }else{
96013    /* Form 3: Analyze the fully qualified table name */
96014    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
96015    if( iDb>=0 ){
96016      zDb = db->aDb[iDb].zName;
96017      z = sqlite3NameFromToken(db, pTableName);
96018      if( z ){
96019        if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
96020          analyzeTable(pParse, pIdx->pTable, pIdx);
96021        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
96022          analyzeTable(pParse, pTab, 0);
96023        }
96024        sqlite3DbFree(db, z);
96025      }
96026    }
96027  }
96028  v = sqlite3GetVdbe(pParse);
96029  if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
96030}
96031
96032/*
96033** Used to pass information from the analyzer reader through to the
96034** callback routine.
96035*/
96036typedef struct analysisInfo analysisInfo;
96037struct analysisInfo {
96038  sqlite3 *db;
96039  const char *zDatabase;
96040};
96041
96042/*
96043** The first argument points to a nul-terminated string containing a
96044** list of space separated integers. Read the first nOut of these into
96045** the array aOut[].
96046*/
96047static void decodeIntArray(
96048  char *zIntArray,       /* String containing int array to decode */
96049  int nOut,              /* Number of slots in aOut[] */
96050  tRowcnt *aOut,         /* Store integers here */
96051  LogEst *aLog,          /* Or, if aOut==0, here */
96052  Index *pIndex          /* Handle extra flags for this index, if not NULL */
96053){
96054  char *z = zIntArray;
96055  int c;
96056  int i;
96057  tRowcnt v;
96058
96059#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96060  if( z==0 ) z = "";
96061#else
96062  assert( z!=0 );
96063#endif
96064  for(i=0; *z && i<nOut; i++){
96065    v = 0;
96066    while( (c=z[0])>='0' && c<='9' ){
96067      v = v*10 + c - '0';
96068      z++;
96069    }
96070#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96071    if( aOut ) aOut[i] = v;
96072    if( aLog ) aLog[i] = sqlite3LogEst(v);
96073#else
96074    assert( aOut==0 );
96075    UNUSED_PARAMETER(aOut);
96076    assert( aLog!=0 );
96077    aLog[i] = sqlite3LogEst(v);
96078#endif
96079    if( *z==' ' ) z++;
96080  }
96081#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
96082  assert( pIndex!=0 ); {
96083#else
96084  if( pIndex ){
96085#endif
96086    pIndex->bUnordered = 0;
96087    pIndex->noSkipScan = 0;
96088    while( z[0] ){
96089      if( sqlite3_strglob("unordered*", z)==0 ){
96090        pIndex->bUnordered = 1;
96091      }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
96092        pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
96093      }else if( sqlite3_strglob("noskipscan*", z)==0 ){
96094        pIndex->noSkipScan = 1;
96095      }
96096#ifdef SQLITE_ENABLE_COSTMULT
96097      else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
96098        pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
96099      }
96100#endif
96101      while( z[0]!=0 && z[0]!=' ' ) z++;
96102      while( z[0]==' ' ) z++;
96103    }
96104  }
96105}
96106
96107/*
96108** This callback is invoked once for each index when reading the
96109** sqlite_stat1 table.
96110**
96111**     argv[0] = name of the table
96112**     argv[1] = name of the index (might be NULL)
96113**     argv[2] = results of analysis - on integer for each column
96114**
96115** Entries for which argv[1]==NULL simply record the number of rows in
96116** the table.
96117*/
96118static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
96119  analysisInfo *pInfo = (analysisInfo*)pData;
96120  Index *pIndex;
96121  Table *pTable;
96122  const char *z;
96123
96124  assert( argc==3 );
96125  UNUSED_PARAMETER2(NotUsed, argc);
96126
96127  if( argv==0 || argv[0]==0 || argv[2]==0 ){
96128    return 0;
96129  }
96130  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
96131  if( pTable==0 ){
96132    return 0;
96133  }
96134  if( argv[1]==0 ){
96135    pIndex = 0;
96136  }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
96137    pIndex = sqlite3PrimaryKeyIndex(pTable);
96138  }else{
96139    pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
96140  }
96141  z = argv[2];
96142
96143  if( pIndex ){
96144    tRowcnt *aiRowEst = 0;
96145    int nCol = pIndex->nKeyCol+1;
96146#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96147    /* Index.aiRowEst may already be set here if there are duplicate
96148    ** sqlite_stat1 entries for this index. In that case just clobber
96149    ** the old data with the new instead of allocating a new array.  */
96150    if( pIndex->aiRowEst==0 ){
96151      pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
96152      if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
96153    }
96154    aiRowEst = pIndex->aiRowEst;
96155#endif
96156    pIndex->bUnordered = 0;
96157    decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
96158    if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
96159  }else{
96160    Index fakeIdx;
96161    fakeIdx.szIdxRow = pTable->szTabRow;
96162#ifdef SQLITE_ENABLE_COSTMULT
96163    fakeIdx.pTable = pTable;
96164#endif
96165    decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
96166    pTable->szTabRow = fakeIdx.szIdxRow;
96167  }
96168
96169  return 0;
96170}
96171
96172/*
96173** If the Index.aSample variable is not NULL, delete the aSample[] array
96174** and its contents.
96175*/
96176SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
96177#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96178  if( pIdx->aSample ){
96179    int j;
96180    for(j=0; j<pIdx->nSample; j++){
96181      IndexSample *p = &pIdx->aSample[j];
96182      sqlite3DbFree(db, p->p);
96183    }
96184    sqlite3DbFree(db, pIdx->aSample);
96185  }
96186  if( db && db->pnBytesFreed==0 ){
96187    pIdx->nSample = 0;
96188    pIdx->aSample = 0;
96189  }
96190#else
96191  UNUSED_PARAMETER(db);
96192  UNUSED_PARAMETER(pIdx);
96193#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
96194}
96195
96196#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96197/*
96198** Populate the pIdx->aAvgEq[] array based on the samples currently
96199** stored in pIdx->aSample[].
96200*/
96201static void initAvgEq(Index *pIdx){
96202  if( pIdx ){
96203    IndexSample *aSample = pIdx->aSample;
96204    IndexSample *pFinal = &aSample[pIdx->nSample-1];
96205    int iCol;
96206    int nCol = 1;
96207    if( pIdx->nSampleCol>1 ){
96208      /* If this is stat4 data, then calculate aAvgEq[] values for all
96209      ** sample columns except the last. The last is always set to 1, as
96210      ** once the trailing PK fields are considered all index keys are
96211      ** unique.  */
96212      nCol = pIdx->nSampleCol-1;
96213      pIdx->aAvgEq[nCol] = 1;
96214    }
96215    for(iCol=0; iCol<nCol; iCol++){
96216      int nSample = pIdx->nSample;
96217      int i;                    /* Used to iterate through samples */
96218      tRowcnt sumEq = 0;        /* Sum of the nEq values */
96219      tRowcnt avgEq = 0;
96220      tRowcnt nRow;             /* Number of rows in index */
96221      i64 nSum100 = 0;          /* Number of terms contributing to sumEq */
96222      i64 nDist100;             /* Number of distinct values in index */
96223
96224      if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
96225        nRow = pFinal->anLt[iCol];
96226        nDist100 = (i64)100 * pFinal->anDLt[iCol];
96227        nSample--;
96228      }else{
96229        nRow = pIdx->aiRowEst[0];
96230        nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
96231      }
96232      pIdx->nRowEst0 = nRow;
96233
96234      /* Set nSum to the number of distinct (iCol+1) field prefixes that
96235      ** occur in the stat4 table for this index. Set sumEq to the sum of
96236      ** the nEq values for column iCol for the same set (adding the value
96237      ** only once where there exist duplicate prefixes).  */
96238      for(i=0; i<nSample; i++){
96239        if( i==(pIdx->nSample-1)
96240         || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
96241        ){
96242          sumEq += aSample[i].anEq[iCol];
96243          nSum100 += 100;
96244        }
96245      }
96246
96247      if( nDist100>nSum100 ){
96248        avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
96249      }
96250      if( avgEq==0 ) avgEq = 1;
96251      pIdx->aAvgEq[iCol] = avgEq;
96252    }
96253  }
96254}
96255
96256/*
96257** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
96258** is supplied instead, find the PRIMARY KEY index for that table.
96259*/
96260static Index *findIndexOrPrimaryKey(
96261  sqlite3 *db,
96262  const char *zName,
96263  const char *zDb
96264){
96265  Index *pIdx = sqlite3FindIndex(db, zName, zDb);
96266  if( pIdx==0 ){
96267    Table *pTab = sqlite3FindTable(db, zName, zDb);
96268    if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
96269  }
96270  return pIdx;
96271}
96272
96273/*
96274** Load the content from either the sqlite_stat4 or sqlite_stat3 table
96275** into the relevant Index.aSample[] arrays.
96276**
96277** Arguments zSql1 and zSql2 must point to SQL statements that return
96278** data equivalent to the following (statements are different for stat3,
96279** see the caller of this function for details):
96280**
96281**    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
96282**    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
96283**
96284** where %Q is replaced with the database name before the SQL is executed.
96285*/
96286static int loadStatTbl(
96287  sqlite3 *db,                  /* Database handle */
96288  int bStat3,                   /* Assume single column records only */
96289  const char *zSql1,            /* SQL statement 1 (see above) */
96290  const char *zSql2,            /* SQL statement 2 (see above) */
96291  const char *zDb               /* Database name (e.g. "main") */
96292){
96293  int rc;                       /* Result codes from subroutines */
96294  sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
96295  char *zSql;                   /* Text of the SQL statement */
96296  Index *pPrevIdx = 0;          /* Previous index in the loop */
96297  IndexSample *pSample;         /* A slot in pIdx->aSample[] */
96298
96299  assert( db->lookaside.bDisable );
96300  zSql = sqlite3MPrintf(db, zSql1, zDb);
96301  if( !zSql ){
96302    return SQLITE_NOMEM_BKPT;
96303  }
96304  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
96305  sqlite3DbFree(db, zSql);
96306  if( rc ) return rc;
96307
96308  while( sqlite3_step(pStmt)==SQLITE_ROW ){
96309    int nIdxCol = 1;              /* Number of columns in stat4 records */
96310
96311    char *zIndex;   /* Index name */
96312    Index *pIdx;    /* Pointer to the index object */
96313    int nSample;    /* Number of samples */
96314    int nByte;      /* Bytes of space required */
96315    int i;          /* Bytes of space required */
96316    tRowcnt *pSpace;
96317
96318    zIndex = (char *)sqlite3_column_text(pStmt, 0);
96319    if( zIndex==0 ) continue;
96320    nSample = sqlite3_column_int(pStmt, 1);
96321    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
96322    assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
96323    /* Index.nSample is non-zero at this point if data has already been
96324    ** loaded from the stat4 table. In this case ignore stat3 data.  */
96325    if( pIdx==0 || pIdx->nSample ) continue;
96326    if( bStat3==0 ){
96327      assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
96328      if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
96329        nIdxCol = pIdx->nKeyCol;
96330      }else{
96331        nIdxCol = pIdx->nColumn;
96332      }
96333    }
96334    pIdx->nSampleCol = nIdxCol;
96335    nByte = sizeof(IndexSample) * nSample;
96336    nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
96337    nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
96338
96339    pIdx->aSample = sqlite3DbMallocZero(db, nByte);
96340    if( pIdx->aSample==0 ){
96341      sqlite3_finalize(pStmt);
96342      return SQLITE_NOMEM_BKPT;
96343    }
96344    pSpace = (tRowcnt*)&pIdx->aSample[nSample];
96345    pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
96346    for(i=0; i<nSample; i++){
96347      pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
96348      pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
96349      pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
96350    }
96351    assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
96352  }
96353  rc = sqlite3_finalize(pStmt);
96354  if( rc ) return rc;
96355
96356  zSql = sqlite3MPrintf(db, zSql2, zDb);
96357  if( !zSql ){
96358    return SQLITE_NOMEM_BKPT;
96359  }
96360  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
96361  sqlite3DbFree(db, zSql);
96362  if( rc ) return rc;
96363
96364  while( sqlite3_step(pStmt)==SQLITE_ROW ){
96365    char *zIndex;                 /* Index name */
96366    Index *pIdx;                  /* Pointer to the index object */
96367    int nCol = 1;                 /* Number of columns in index */
96368
96369    zIndex = (char *)sqlite3_column_text(pStmt, 0);
96370    if( zIndex==0 ) continue;
96371    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
96372    if( pIdx==0 ) continue;
96373    /* This next condition is true if data has already been loaded from
96374    ** the sqlite_stat4 table. In this case ignore stat3 data.  */
96375    nCol = pIdx->nSampleCol;
96376    if( bStat3 && nCol>1 ) continue;
96377    if( pIdx!=pPrevIdx ){
96378      initAvgEq(pPrevIdx);
96379      pPrevIdx = pIdx;
96380    }
96381    pSample = &pIdx->aSample[pIdx->nSample];
96382    decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
96383    decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
96384    decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
96385
96386    /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
96387    ** This is in case the sample record is corrupted. In that case, the
96388    ** sqlite3VdbeRecordCompare() may read up to two varints past the
96389    ** end of the allocated buffer before it realizes it is dealing with
96390    ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
96391    ** a buffer overread.  */
96392    pSample->n = sqlite3_column_bytes(pStmt, 4);
96393    pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
96394    if( pSample->p==0 ){
96395      sqlite3_finalize(pStmt);
96396      return SQLITE_NOMEM_BKPT;
96397    }
96398    memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
96399    pIdx->nSample++;
96400  }
96401  rc = sqlite3_finalize(pStmt);
96402  if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
96403  return rc;
96404}
96405
96406/*
96407** Load content from the sqlite_stat4 and sqlite_stat3 tables into
96408** the Index.aSample[] arrays of all indices.
96409*/
96410static int loadStat4(sqlite3 *db, const char *zDb){
96411  int rc = SQLITE_OK;             /* Result codes from subroutines */
96412
96413  assert( db->lookaside.bDisable );
96414  if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
96415    rc = loadStatTbl(db, 0,
96416      "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
96417      "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
96418      zDb
96419    );
96420  }
96421
96422  if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
96423    rc = loadStatTbl(db, 1,
96424      "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
96425      "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
96426      zDb
96427    );
96428  }
96429
96430  return rc;
96431}
96432#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
96433
96434/*
96435** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
96436** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
96437** arrays. The contents of sqlite_stat3/4 are used to populate the
96438** Index.aSample[] arrays.
96439**
96440** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
96441** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
96442** during compilation and the sqlite_stat3/4 table is present, no data is
96443** read from it.
96444**
96445** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
96446** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
96447** returned. However, in this case, data is read from the sqlite_stat1
96448** table (if it is present) before returning.
96449**
96450** If an OOM error occurs, this function always sets db->mallocFailed.
96451** This means if the caller does not care about other errors, the return
96452** code may be ignored.
96453*/
96454SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
96455  analysisInfo sInfo;
96456  HashElem *i;
96457  char *zSql;
96458  int rc = SQLITE_OK;
96459
96460  assert( iDb>=0 && iDb<db->nDb );
96461  assert( db->aDb[iDb].pBt!=0 );
96462
96463  /* Clear any prior statistics */
96464  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
96465  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
96466    Index *pIdx = sqliteHashData(i);
96467    pIdx->aiRowLogEst[0] = 0;
96468#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96469    sqlite3DeleteIndexSamples(db, pIdx);
96470    pIdx->aSample = 0;
96471#endif
96472  }
96473
96474  /* Load new statistics out of the sqlite_stat1 table */
96475  sInfo.db = db;
96476  sInfo.zDatabase = db->aDb[iDb].zName;
96477  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
96478    zSql = sqlite3MPrintf(db,
96479        "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
96480    if( zSql==0 ){
96481      rc = SQLITE_NOMEM_BKPT;
96482    }else{
96483      rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
96484      sqlite3DbFree(db, zSql);
96485    }
96486  }
96487
96488  /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
96489  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
96490  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
96491    Index *pIdx = sqliteHashData(i);
96492    if( pIdx->aiRowLogEst[0]==0 ) sqlite3DefaultRowEst(pIdx);
96493  }
96494
96495  /* Load the statistics from the sqlite_stat4 table. */
96496#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96497  if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
96498    db->lookaside.bDisable++;
96499    rc = loadStat4(db, sInfo.zDatabase);
96500    db->lookaside.bDisable--;
96501  }
96502  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
96503    Index *pIdx = sqliteHashData(i);
96504    sqlite3_free(pIdx->aiRowEst);
96505    pIdx->aiRowEst = 0;
96506  }
96507#endif
96508
96509  if( rc==SQLITE_NOMEM ){
96510    sqlite3OomFault(db);
96511  }
96512  return rc;
96513}
96514
96515
96516#endif /* SQLITE_OMIT_ANALYZE */
96517
96518/************** End of analyze.c *********************************************/
96519/************** Begin file attach.c ******************************************/
96520/*
96521** 2003 April 6
96522**
96523** The author disclaims copyright to this source code.  In place of
96524** a legal notice, here is a blessing:
96525**
96526**    May you do good and not evil.
96527**    May you find forgiveness for yourself and forgive others.
96528**    May you share freely, never taking more than you give.
96529**
96530*************************************************************************
96531** This file contains code used to implement the ATTACH and DETACH commands.
96532*/
96533/* #include "sqliteInt.h" */
96534
96535#ifndef SQLITE_OMIT_ATTACH
96536/*
96537** Resolve an expression that was part of an ATTACH or DETACH statement. This
96538** is slightly different from resolving a normal SQL expression, because simple
96539** identifiers are treated as strings, not possible column names or aliases.
96540**
96541** i.e. if the parser sees:
96542**
96543**     ATTACH DATABASE abc AS def
96544**
96545** it treats the two expressions as literal strings 'abc' and 'def' instead of
96546** looking for columns of the same name.
96547**
96548** This only applies to the root node of pExpr, so the statement:
96549**
96550**     ATTACH DATABASE abc||def AS 'db2'
96551**
96552** will fail because neither abc or def can be resolved.
96553*/
96554static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
96555{
96556  int rc = SQLITE_OK;
96557  if( pExpr ){
96558    if( pExpr->op!=TK_ID ){
96559      rc = sqlite3ResolveExprNames(pName, pExpr);
96560    }else{
96561      pExpr->op = TK_STRING;
96562    }
96563  }
96564  return rc;
96565}
96566
96567/*
96568** An SQL user-function registered to do the work of an ATTACH statement. The
96569** three arguments to the function come directly from an attach statement:
96570**
96571**     ATTACH DATABASE x AS y KEY z
96572**
96573**     SELECT sqlite_attach(x, y, z)
96574**
96575** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
96576** third argument.
96577*/
96578static void attachFunc(
96579  sqlite3_context *context,
96580  int NotUsed,
96581  sqlite3_value **argv
96582){
96583  int i;
96584  int rc = 0;
96585  sqlite3 *db = sqlite3_context_db_handle(context);
96586  const char *zName;
96587  const char *zFile;
96588  char *zPath = 0;
96589  char *zErr = 0;
96590  unsigned int flags;
96591  Db *aNew;
96592  char *zErrDyn = 0;
96593  sqlite3_vfs *pVfs;
96594
96595  UNUSED_PARAMETER(NotUsed);
96596
96597  zFile = (const char *)sqlite3_value_text(argv[0]);
96598  zName = (const char *)sqlite3_value_text(argv[1]);
96599  if( zFile==0 ) zFile = "";
96600  if( zName==0 ) zName = "";
96601
96602  /* Check for the following errors:
96603  **
96604  **     * Too many attached databases,
96605  **     * Transaction currently open
96606  **     * Specified database name already being used.
96607  */
96608  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
96609    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
96610      db->aLimit[SQLITE_LIMIT_ATTACHED]
96611    );
96612    goto attach_error;
96613  }
96614  if( !db->autoCommit ){
96615    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
96616    goto attach_error;
96617  }
96618  for(i=0; i<db->nDb; i++){
96619    char *z = db->aDb[i].zName;
96620    assert( z && zName );
96621    if( sqlite3StrICmp(z, zName)==0 ){
96622      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
96623      goto attach_error;
96624    }
96625  }
96626
96627  /* Allocate the new entry in the db->aDb[] array and initialize the schema
96628  ** hash tables.
96629  */
96630  if( db->aDb==db->aDbStatic ){
96631    aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
96632    if( aNew==0 ) return;
96633    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
96634  }else{
96635    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
96636    if( aNew==0 ) return;
96637  }
96638  db->aDb = aNew;
96639  aNew = &db->aDb[db->nDb];
96640  memset(aNew, 0, sizeof(*aNew));
96641
96642  /* Open the database file. If the btree is successfully opened, use
96643  ** it to obtain the database schema. At this point the schema may
96644  ** or may not be initialized.
96645  */
96646  flags = db->openFlags;
96647  rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
96648  if( rc!=SQLITE_OK ){
96649    if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
96650    sqlite3_result_error(context, zErr, -1);
96651    sqlite3_free(zErr);
96652    return;
96653  }
96654  assert( pVfs );
96655  flags |= SQLITE_OPEN_MAIN_DB;
96656  rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
96657  sqlite3_free( zPath );
96658  db->nDb++;
96659  if( rc==SQLITE_CONSTRAINT ){
96660    rc = SQLITE_ERROR;
96661    zErrDyn = sqlite3MPrintf(db, "database is already attached");
96662  }else if( rc==SQLITE_OK ){
96663    Pager *pPager;
96664    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
96665    if( !aNew->pSchema ){
96666      rc = SQLITE_NOMEM_BKPT;
96667    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
96668      zErrDyn = sqlite3MPrintf(db,
96669        "attached databases must use the same text encoding as main database");
96670      rc = SQLITE_ERROR;
96671    }
96672    sqlite3BtreeEnter(aNew->pBt);
96673    pPager = sqlite3BtreePager(aNew->pBt);
96674    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
96675    sqlite3BtreeSecureDelete(aNew->pBt,
96676                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
96677#ifndef SQLITE_OMIT_PAGER_PRAGMAS
96678    sqlite3BtreeSetPagerFlags(aNew->pBt,
96679                      PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
96680#endif
96681    sqlite3BtreeLeave(aNew->pBt);
96682  }
96683  aNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
96684  aNew->zName = sqlite3DbStrDup(db, zName);
96685  if( rc==SQLITE_OK && aNew->zName==0 ){
96686    rc = SQLITE_NOMEM_BKPT;
96687  }
96688
96689
96690#ifdef SQLITE_HAS_CODEC
96691  if( rc==SQLITE_OK ){
96692    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
96693    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
96694    int nKey;
96695    char *zKey;
96696    int t = sqlite3_value_type(argv[2]);
96697    switch( t ){
96698      case SQLITE_INTEGER:
96699      case SQLITE_FLOAT:
96700        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
96701        rc = SQLITE_ERROR;
96702        break;
96703
96704      case SQLITE_TEXT:
96705      case SQLITE_BLOB:
96706        nKey = sqlite3_value_bytes(argv[2]);
96707        zKey = (char *)sqlite3_value_blob(argv[2]);
96708        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
96709        break;
96710
96711      case SQLITE_NULL:
96712        /* No key specified.  Use the key from the main database */
96713        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
96714        if( nKey>0 || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
96715          rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
96716        }
96717        break;
96718    }
96719  }
96720#endif
96721
96722  /* If the file was opened successfully, read the schema for the new database.
96723  ** If this fails, or if opening the file failed, then close the file and
96724  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
96725  ** we found it.
96726  */
96727  if( rc==SQLITE_OK ){
96728    sqlite3BtreeEnterAll(db);
96729    rc = sqlite3Init(db, &zErrDyn);
96730    sqlite3BtreeLeaveAll(db);
96731  }
96732#ifdef SQLITE_USER_AUTHENTICATION
96733  if( rc==SQLITE_OK ){
96734    u8 newAuth = 0;
96735    rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
96736    if( newAuth<db->auth.authLevel ){
96737      rc = SQLITE_AUTH_USER;
96738    }
96739  }
96740#endif
96741  if( rc ){
96742    int iDb = db->nDb - 1;
96743    assert( iDb>=2 );
96744    if( db->aDb[iDb].pBt ){
96745      sqlite3BtreeClose(db->aDb[iDb].pBt);
96746      db->aDb[iDb].pBt = 0;
96747      db->aDb[iDb].pSchema = 0;
96748    }
96749    sqlite3ResetAllSchemasOfConnection(db);
96750    db->nDb = iDb;
96751    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
96752      sqlite3OomFault(db);
96753      sqlite3DbFree(db, zErrDyn);
96754      zErrDyn = sqlite3MPrintf(db, "out of memory");
96755    }else if( zErrDyn==0 ){
96756      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
96757    }
96758    goto attach_error;
96759  }
96760
96761  return;
96762
96763attach_error:
96764  /* Return an error if we get here */
96765  if( zErrDyn ){
96766    sqlite3_result_error(context, zErrDyn, -1);
96767    sqlite3DbFree(db, zErrDyn);
96768  }
96769  if( rc ) sqlite3_result_error_code(context, rc);
96770}
96771
96772/*
96773** An SQL user-function registered to do the work of an DETACH statement. The
96774** three arguments to the function come directly from a detach statement:
96775**
96776**     DETACH DATABASE x
96777**
96778**     SELECT sqlite_detach(x)
96779*/
96780static void detachFunc(
96781  sqlite3_context *context,
96782  int NotUsed,
96783  sqlite3_value **argv
96784){
96785  const char *zName = (const char *)sqlite3_value_text(argv[0]);
96786  sqlite3 *db = sqlite3_context_db_handle(context);
96787  int i;
96788  Db *pDb = 0;
96789  char zErr[128];
96790
96791  UNUSED_PARAMETER(NotUsed);
96792
96793  if( zName==0 ) zName = "";
96794  for(i=0; i<db->nDb; i++){
96795    pDb = &db->aDb[i];
96796    if( pDb->pBt==0 ) continue;
96797    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
96798  }
96799
96800  if( i>=db->nDb ){
96801    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
96802    goto detach_error;
96803  }
96804  if( i<2 ){
96805    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
96806    goto detach_error;
96807  }
96808  if( !db->autoCommit ){
96809    sqlite3_snprintf(sizeof(zErr), zErr,
96810                     "cannot DETACH database within transaction");
96811    goto detach_error;
96812  }
96813  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
96814    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
96815    goto detach_error;
96816  }
96817
96818  sqlite3BtreeClose(pDb->pBt);
96819  pDb->pBt = 0;
96820  pDb->pSchema = 0;
96821  sqlite3CollapseDatabaseArray(db);
96822  return;
96823
96824detach_error:
96825  sqlite3_result_error(context, zErr, -1);
96826}
96827
96828/*
96829** This procedure generates VDBE code for a single invocation of either the
96830** sqlite_detach() or sqlite_attach() SQL user functions.
96831*/
96832static void codeAttach(
96833  Parse *pParse,       /* The parser context */
96834  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
96835  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
96836  Expr *pAuthArg,      /* Expression to pass to authorization callback */
96837  Expr *pFilename,     /* Name of database file */
96838  Expr *pDbname,       /* Name of the database to use internally */
96839  Expr *pKey           /* Database key for encryption extension */
96840){
96841  int rc;
96842  NameContext sName;
96843  Vdbe *v;
96844  sqlite3* db = pParse->db;
96845  int regArgs;
96846
96847  memset(&sName, 0, sizeof(NameContext));
96848  sName.pParse = pParse;
96849
96850  if(
96851      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
96852      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
96853      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
96854  ){
96855    goto attach_end;
96856  }
96857
96858#ifndef SQLITE_OMIT_AUTHORIZATION
96859  if( pAuthArg ){
96860    char *zAuthArg;
96861    if( pAuthArg->op==TK_STRING ){
96862      zAuthArg = pAuthArg->u.zToken;
96863    }else{
96864      zAuthArg = 0;
96865    }
96866    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
96867    if(rc!=SQLITE_OK ){
96868      goto attach_end;
96869    }
96870  }
96871#endif /* SQLITE_OMIT_AUTHORIZATION */
96872
96873
96874  v = sqlite3GetVdbe(pParse);
96875  regArgs = sqlite3GetTempRange(pParse, 4);
96876  sqlite3ExprCode(pParse, pFilename, regArgs);
96877  sqlite3ExprCode(pParse, pDbname, regArgs+1);
96878  sqlite3ExprCode(pParse, pKey, regArgs+2);
96879
96880  assert( v || db->mallocFailed );
96881  if( v ){
96882    sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
96883                      (char *)pFunc, P4_FUNCDEF);
96884    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
96885    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
96886
96887    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
96888    ** statement only). For DETACH, set it to false (expire all existing
96889    ** statements).
96890    */
96891    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
96892  }
96893
96894attach_end:
96895  sqlite3ExprDelete(db, pFilename);
96896  sqlite3ExprDelete(db, pDbname);
96897  sqlite3ExprDelete(db, pKey);
96898}
96899
96900/*
96901** Called by the parser to compile a DETACH statement.
96902**
96903**     DETACH pDbname
96904*/
96905SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
96906  static const FuncDef detach_func = {
96907    1,                /* nArg */
96908    SQLITE_UTF8,      /* funcFlags */
96909    0,                /* pUserData */
96910    0,                /* pNext */
96911    detachFunc,       /* xSFunc */
96912    0,                /* xFinalize */
96913    "sqlite_detach",  /* zName */
96914    {0}
96915  };
96916  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
96917}
96918
96919/*
96920** Called by the parser to compile an ATTACH statement.
96921**
96922**     ATTACH p AS pDbname KEY pKey
96923*/
96924SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
96925  static const FuncDef attach_func = {
96926    3,                /* nArg */
96927    SQLITE_UTF8,      /* funcFlags */
96928    0,                /* pUserData */
96929    0,                /* pNext */
96930    attachFunc,       /* xSFunc */
96931    0,                /* xFinalize */
96932    "sqlite_attach",  /* zName */
96933    {0}
96934  };
96935  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
96936}
96937#endif /* SQLITE_OMIT_ATTACH */
96938
96939/*
96940** Initialize a DbFixer structure.  This routine must be called prior
96941** to passing the structure to one of the sqliteFixAAAA() routines below.
96942*/
96943SQLITE_PRIVATE void sqlite3FixInit(
96944  DbFixer *pFix,      /* The fixer to be initialized */
96945  Parse *pParse,      /* Error messages will be written here */
96946  int iDb,            /* This is the database that must be used */
96947  const char *zType,  /* "view", "trigger", or "index" */
96948  const Token *pName  /* Name of the view, trigger, or index */
96949){
96950  sqlite3 *db;
96951
96952  db = pParse->db;
96953  assert( db->nDb>iDb );
96954  pFix->pParse = pParse;
96955  pFix->zDb = db->aDb[iDb].zName;
96956  pFix->pSchema = db->aDb[iDb].pSchema;
96957  pFix->zType = zType;
96958  pFix->pName = pName;
96959  pFix->bVarOnly = (iDb==1);
96960}
96961
96962/*
96963** The following set of routines walk through the parse tree and assign
96964** a specific database to all table references where the database name
96965** was left unspecified in the original SQL statement.  The pFix structure
96966** must have been initialized by a prior call to sqlite3FixInit().
96967**
96968** These routines are used to make sure that an index, trigger, or
96969** view in one database does not refer to objects in a different database.
96970** (Exception: indices, triggers, and views in the TEMP database are
96971** allowed to refer to anything.)  If a reference is explicitly made
96972** to an object in a different database, an error message is added to
96973** pParse->zErrMsg and these routines return non-zero.  If everything
96974** checks out, these routines return 0.
96975*/
96976SQLITE_PRIVATE int sqlite3FixSrcList(
96977  DbFixer *pFix,       /* Context of the fixation */
96978  SrcList *pList       /* The Source list to check and modify */
96979){
96980  int i;
96981  const char *zDb;
96982  struct SrcList_item *pItem;
96983
96984  if( NEVER(pList==0) ) return 0;
96985  zDb = pFix->zDb;
96986  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
96987    if( pFix->bVarOnly==0 ){
96988      if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
96989        sqlite3ErrorMsg(pFix->pParse,
96990            "%s %T cannot reference objects in database %s",
96991            pFix->zType, pFix->pName, pItem->zDatabase);
96992        return 1;
96993      }
96994      sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
96995      pItem->zDatabase = 0;
96996      pItem->pSchema = pFix->pSchema;
96997    }
96998#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
96999    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
97000    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
97001#endif
97002  }
97003  return 0;
97004}
97005#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
97006SQLITE_PRIVATE int sqlite3FixSelect(
97007  DbFixer *pFix,       /* Context of the fixation */
97008  Select *pSelect      /* The SELECT statement to be fixed to one database */
97009){
97010  while( pSelect ){
97011    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
97012      return 1;
97013    }
97014    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
97015      return 1;
97016    }
97017    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
97018      return 1;
97019    }
97020    if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
97021      return 1;
97022    }
97023    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
97024      return 1;
97025    }
97026    if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
97027      return 1;
97028    }
97029    if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
97030      return 1;
97031    }
97032    if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
97033      return 1;
97034    }
97035    pSelect = pSelect->pPrior;
97036  }
97037  return 0;
97038}
97039SQLITE_PRIVATE int sqlite3FixExpr(
97040  DbFixer *pFix,     /* Context of the fixation */
97041  Expr *pExpr        /* The expression to be fixed to one database */
97042){
97043  while( pExpr ){
97044    if( pExpr->op==TK_VARIABLE ){
97045      if( pFix->pParse->db->init.busy ){
97046        pExpr->op = TK_NULL;
97047      }else{
97048        sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
97049        return 1;
97050      }
97051    }
97052    if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
97053    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
97054      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
97055    }else{
97056      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
97057    }
97058    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
97059      return 1;
97060    }
97061    pExpr = pExpr->pLeft;
97062  }
97063  return 0;
97064}
97065SQLITE_PRIVATE int sqlite3FixExprList(
97066  DbFixer *pFix,     /* Context of the fixation */
97067  ExprList *pList    /* The expression to be fixed to one database */
97068){
97069  int i;
97070  struct ExprList_item *pItem;
97071  if( pList==0 ) return 0;
97072  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
97073    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
97074      return 1;
97075    }
97076  }
97077  return 0;
97078}
97079#endif
97080
97081#ifndef SQLITE_OMIT_TRIGGER
97082SQLITE_PRIVATE int sqlite3FixTriggerStep(
97083  DbFixer *pFix,     /* Context of the fixation */
97084  TriggerStep *pStep /* The trigger step be fixed to one database */
97085){
97086  while( pStep ){
97087    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
97088      return 1;
97089    }
97090    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
97091      return 1;
97092    }
97093    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
97094      return 1;
97095    }
97096    pStep = pStep->pNext;
97097  }
97098  return 0;
97099}
97100#endif
97101
97102/************** End of attach.c **********************************************/
97103/************** Begin file auth.c ********************************************/
97104/*
97105** 2003 January 11
97106**
97107** The author disclaims copyright to this source code.  In place of
97108** a legal notice, here is a blessing:
97109**
97110**    May you do good and not evil.
97111**    May you find forgiveness for yourself and forgive others.
97112**    May you share freely, never taking more than you give.
97113**
97114*************************************************************************
97115** This file contains code used to implement the sqlite3_set_authorizer()
97116** API.  This facility is an optional feature of the library.  Embedded
97117** systems that do not need this facility may omit it by recompiling
97118** the library with -DSQLITE_OMIT_AUTHORIZATION=1
97119*/
97120/* #include "sqliteInt.h" */
97121
97122/*
97123** All of the code in this file may be omitted by defining a single
97124** macro.
97125*/
97126#ifndef SQLITE_OMIT_AUTHORIZATION
97127
97128/*
97129** Set or clear the access authorization function.
97130**
97131** The access authorization function is be called during the compilation
97132** phase to verify that the user has read and/or write access permission on
97133** various fields of the database.  The first argument to the auth function
97134** is a copy of the 3rd argument to this routine.  The second argument
97135** to the auth function is one of these constants:
97136**
97137**       SQLITE_CREATE_INDEX
97138**       SQLITE_CREATE_TABLE
97139**       SQLITE_CREATE_TEMP_INDEX
97140**       SQLITE_CREATE_TEMP_TABLE
97141**       SQLITE_CREATE_TEMP_TRIGGER
97142**       SQLITE_CREATE_TEMP_VIEW
97143**       SQLITE_CREATE_TRIGGER
97144**       SQLITE_CREATE_VIEW
97145**       SQLITE_DELETE
97146**       SQLITE_DROP_INDEX
97147**       SQLITE_DROP_TABLE
97148**       SQLITE_DROP_TEMP_INDEX
97149**       SQLITE_DROP_TEMP_TABLE
97150**       SQLITE_DROP_TEMP_TRIGGER
97151**       SQLITE_DROP_TEMP_VIEW
97152**       SQLITE_DROP_TRIGGER
97153**       SQLITE_DROP_VIEW
97154**       SQLITE_INSERT
97155**       SQLITE_PRAGMA
97156**       SQLITE_READ
97157**       SQLITE_SELECT
97158**       SQLITE_TRANSACTION
97159**       SQLITE_UPDATE
97160**
97161** The third and fourth arguments to the auth function are the name of
97162** the table and the column that are being accessed.  The auth function
97163** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
97164** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
97165** means that the SQL statement will never-run - the sqlite3_exec() call
97166** will return with an error.  SQLITE_IGNORE means that the SQL statement
97167** should run but attempts to read the specified column will return NULL
97168** and attempts to write the column will be ignored.
97169**
97170** Setting the auth function to NULL disables this hook.  The default
97171** setting of the auth function is NULL.
97172*/
97173SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
97174  sqlite3 *db,
97175  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
97176  void *pArg
97177){
97178#ifdef SQLITE_ENABLE_API_ARMOR
97179  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
97180#endif
97181  sqlite3_mutex_enter(db->mutex);
97182  db->xAuth = (sqlite3_xauth)xAuth;
97183  db->pAuthArg = pArg;
97184  sqlite3ExpirePreparedStatements(db);
97185  sqlite3_mutex_leave(db->mutex);
97186  return SQLITE_OK;
97187}
97188
97189/*
97190** Write an error message into pParse->zErrMsg that explains that the
97191** user-supplied authorization function returned an illegal value.
97192*/
97193static void sqliteAuthBadReturnCode(Parse *pParse){
97194  sqlite3ErrorMsg(pParse, "authorizer malfunction");
97195  pParse->rc = SQLITE_ERROR;
97196}
97197
97198/*
97199** Invoke the authorization callback for permission to read column zCol from
97200** table zTab in database zDb. This function assumes that an authorization
97201** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
97202**
97203** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
97204** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
97205** is treated as SQLITE_DENY. In this case an error is left in pParse.
97206*/
97207SQLITE_PRIVATE int sqlite3AuthReadCol(
97208  Parse *pParse,                  /* The parser context */
97209  const char *zTab,               /* Table name */
97210  const char *zCol,               /* Column name */
97211  int iDb                         /* Index of containing database. */
97212){
97213  sqlite3 *db = pParse->db;       /* Database handle */
97214  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
97215  int rc;                         /* Auth callback return code */
97216
97217  if( db->init.busy ) return SQLITE_OK;
97218  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
97219#ifdef SQLITE_USER_AUTHENTICATION
97220                 ,db->auth.zAuthUser
97221#endif
97222                );
97223  if( rc==SQLITE_DENY ){
97224    if( db->nDb>2 || iDb!=0 ){
97225      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
97226    }else{
97227      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
97228    }
97229    pParse->rc = SQLITE_AUTH;
97230  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
97231    sqliteAuthBadReturnCode(pParse);
97232  }
97233  return rc;
97234}
97235
97236/*
97237** The pExpr should be a TK_COLUMN expression.  The table referred to
97238** is in pTabList or else it is the NEW or OLD table of a trigger.
97239** Check to see if it is OK to read this particular column.
97240**
97241** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
97242** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
97243** then generate an error.
97244*/
97245SQLITE_PRIVATE void sqlite3AuthRead(
97246  Parse *pParse,        /* The parser context */
97247  Expr *pExpr,          /* The expression to check authorization on */
97248  Schema *pSchema,      /* The schema of the expression */
97249  SrcList *pTabList     /* All table that pExpr might refer to */
97250){
97251  sqlite3 *db = pParse->db;
97252  Table *pTab = 0;      /* The table being read */
97253  const char *zCol;     /* Name of the column of the table */
97254  int iSrc;             /* Index in pTabList->a[] of table being read */
97255  int iDb;              /* The index of the database the expression refers to */
97256  int iCol;             /* Index of column in table */
97257
97258  if( db->xAuth==0 ) return;
97259  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
97260  if( iDb<0 ){
97261    /* An attempt to read a column out of a subquery or other
97262    ** temporary table. */
97263    return;
97264  }
97265
97266  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
97267  if( pExpr->op==TK_TRIGGER ){
97268    pTab = pParse->pTriggerTab;
97269  }else{
97270    assert( pTabList );
97271    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
97272      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
97273        pTab = pTabList->a[iSrc].pTab;
97274        break;
97275      }
97276    }
97277  }
97278  iCol = pExpr->iColumn;
97279  if( NEVER(pTab==0) ) return;
97280
97281  if( iCol>=0 ){
97282    assert( iCol<pTab->nCol );
97283    zCol = pTab->aCol[iCol].zName;
97284  }else if( pTab->iPKey>=0 ){
97285    assert( pTab->iPKey<pTab->nCol );
97286    zCol = pTab->aCol[pTab->iPKey].zName;
97287  }else{
97288    zCol = "ROWID";
97289  }
97290  assert( iDb>=0 && iDb<db->nDb );
97291  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
97292    pExpr->op = TK_NULL;
97293  }
97294}
97295
97296/*
97297** Do an authorization check using the code and arguments given.  Return
97298** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
97299** is returned, then the error count and error message in pParse are
97300** modified appropriately.
97301*/
97302SQLITE_PRIVATE int sqlite3AuthCheck(
97303  Parse *pParse,
97304  int code,
97305  const char *zArg1,
97306  const char *zArg2,
97307  const char *zArg3
97308){
97309  sqlite3 *db = pParse->db;
97310  int rc;
97311
97312  /* Don't do any authorization checks if the database is initialising
97313  ** or if the parser is being invoked from within sqlite3_declare_vtab.
97314  */
97315  if( db->init.busy || IN_DECLARE_VTAB ){
97316    return SQLITE_OK;
97317  }
97318
97319  if( db->xAuth==0 ){
97320    return SQLITE_OK;
97321  }
97322  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
97323#ifdef SQLITE_USER_AUTHENTICATION
97324                 ,db->auth.zAuthUser
97325#endif
97326                );
97327  if( rc==SQLITE_DENY ){
97328    sqlite3ErrorMsg(pParse, "not authorized");
97329    pParse->rc = SQLITE_AUTH;
97330  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
97331    rc = SQLITE_DENY;
97332    sqliteAuthBadReturnCode(pParse);
97333  }
97334  return rc;
97335}
97336
97337/*
97338** Push an authorization context.  After this routine is called, the
97339** zArg3 argument to authorization callbacks will be zContext until
97340** popped.  Or if pParse==0, this routine is a no-op.
97341*/
97342SQLITE_PRIVATE void sqlite3AuthContextPush(
97343  Parse *pParse,
97344  AuthContext *pContext,
97345  const char *zContext
97346){
97347  assert( pParse );
97348  pContext->pParse = pParse;
97349  pContext->zAuthContext = pParse->zAuthContext;
97350  pParse->zAuthContext = zContext;
97351}
97352
97353/*
97354** Pop an authorization context that was previously pushed
97355** by sqlite3AuthContextPush
97356*/
97357SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
97358  if( pContext->pParse ){
97359    pContext->pParse->zAuthContext = pContext->zAuthContext;
97360    pContext->pParse = 0;
97361  }
97362}
97363
97364#endif /* SQLITE_OMIT_AUTHORIZATION */
97365
97366/************** End of auth.c ************************************************/
97367/************** Begin file build.c *******************************************/
97368/*
97369** 2001 September 15
97370**
97371** The author disclaims copyright to this source code.  In place of
97372** a legal notice, here is a blessing:
97373**
97374**    May you do good and not evil.
97375**    May you find forgiveness for yourself and forgive others.
97376**    May you share freely, never taking more than you give.
97377**
97378*************************************************************************
97379** This file contains C code routines that are called by the SQLite parser
97380** when syntax rules are reduced.  The routines in this file handle the
97381** following kinds of SQL syntax:
97382**
97383**     CREATE TABLE
97384**     DROP TABLE
97385**     CREATE INDEX
97386**     DROP INDEX
97387**     creating ID lists
97388**     BEGIN TRANSACTION
97389**     COMMIT
97390**     ROLLBACK
97391*/
97392/* #include "sqliteInt.h" */
97393
97394#ifndef SQLITE_OMIT_SHARED_CACHE
97395/*
97396** The TableLock structure is only used by the sqlite3TableLock() and
97397** codeTableLocks() functions.
97398*/
97399struct TableLock {
97400  int iDb;             /* The database containing the table to be locked */
97401  int iTab;            /* The root page of the table to be locked */
97402  u8 isWriteLock;      /* True for write lock.  False for a read lock */
97403  const char *zName;   /* Name of the table */
97404};
97405
97406/*
97407** Record the fact that we want to lock a table at run-time.
97408**
97409** The table to be locked has root page iTab and is found in database iDb.
97410** A read or a write lock can be taken depending on isWritelock.
97411**
97412** This routine just records the fact that the lock is desired.  The
97413** code to make the lock occur is generated by a later call to
97414** codeTableLocks() which occurs during sqlite3FinishCoding().
97415*/
97416SQLITE_PRIVATE void sqlite3TableLock(
97417  Parse *pParse,     /* Parsing context */
97418  int iDb,           /* Index of the database containing the table to lock */
97419  int iTab,          /* Root page number of the table to be locked */
97420  u8 isWriteLock,    /* True for a write lock */
97421  const char *zName  /* Name of the table to be locked */
97422){
97423  Parse *pToplevel = sqlite3ParseToplevel(pParse);
97424  int i;
97425  int nBytes;
97426  TableLock *p;
97427  assert( iDb>=0 );
97428
97429  for(i=0; i<pToplevel->nTableLock; i++){
97430    p = &pToplevel->aTableLock[i];
97431    if( p->iDb==iDb && p->iTab==iTab ){
97432      p->isWriteLock = (p->isWriteLock || isWriteLock);
97433      return;
97434    }
97435  }
97436
97437  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
97438  pToplevel->aTableLock =
97439      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
97440  if( pToplevel->aTableLock ){
97441    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
97442    p->iDb = iDb;
97443    p->iTab = iTab;
97444    p->isWriteLock = isWriteLock;
97445    p->zName = zName;
97446  }else{
97447    pToplevel->nTableLock = 0;
97448    sqlite3OomFault(pToplevel->db);
97449  }
97450}
97451
97452/*
97453** Code an OP_TableLock instruction for each table locked by the
97454** statement (configured by calls to sqlite3TableLock()).
97455*/
97456static void codeTableLocks(Parse *pParse){
97457  int i;
97458  Vdbe *pVdbe;
97459
97460  pVdbe = sqlite3GetVdbe(pParse);
97461  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
97462
97463  for(i=0; i<pParse->nTableLock; i++){
97464    TableLock *p = &pParse->aTableLock[i];
97465    int p1 = p->iDb;
97466    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
97467                      p->zName, P4_STATIC);
97468  }
97469}
97470#else
97471  #define codeTableLocks(x)
97472#endif
97473
97474/*
97475** Return TRUE if the given yDbMask object is empty - if it contains no
97476** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
97477** macros when SQLITE_MAX_ATTACHED is greater than 30.
97478*/
97479#if SQLITE_MAX_ATTACHED>30
97480SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
97481  int i;
97482  for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
97483  return 1;
97484}
97485#endif
97486
97487/*
97488** This routine is called after a single SQL statement has been
97489** parsed and a VDBE program to execute that statement has been
97490** prepared.  This routine puts the finishing touches on the
97491** VDBE program and resets the pParse structure for the next
97492** parse.
97493**
97494** Note that if an error occurred, it might be the case that
97495** no VDBE code was generated.
97496*/
97497SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
97498  sqlite3 *db;
97499  Vdbe *v;
97500
97501  assert( pParse->pToplevel==0 );
97502  db = pParse->db;
97503  if( pParse->nested ) return;
97504  if( db->mallocFailed || pParse->nErr ){
97505    if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
97506    return;
97507  }
97508
97509  /* Begin by generating some termination code at the end of the
97510  ** vdbe program
97511  */
97512  v = sqlite3GetVdbe(pParse);
97513  assert( !pParse->isMultiWrite
97514       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
97515  if( v ){
97516    while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
97517    sqlite3VdbeAddOp0(v, OP_Halt);
97518
97519#if SQLITE_USER_AUTHENTICATION
97520    if( pParse->nTableLock>0 && db->init.busy==0 ){
97521      sqlite3UserAuthInit(db);
97522      if( db->auth.authLevel<UAUTH_User ){
97523        pParse->rc = SQLITE_AUTH_USER;
97524        sqlite3ErrorMsg(pParse, "user not authenticated");
97525        return;
97526      }
97527    }
97528#endif
97529
97530    /* The cookie mask contains one bit for each database file open.
97531    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
97532    ** set for each database that is used.  Generate code to start a
97533    ** transaction on each used database and to verify the schema cookie
97534    ** on each used database.
97535    */
97536    if( db->mallocFailed==0
97537     && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
97538    ){
97539      int iDb, i;
97540      assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
97541      sqlite3VdbeJumpHere(v, 0);
97542      for(iDb=0; iDb<db->nDb; iDb++){
97543        if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
97544        sqlite3VdbeUsesBtree(v, iDb);
97545        sqlite3VdbeAddOp4Int(v,
97546          OP_Transaction,                    /* Opcode */
97547          iDb,                               /* P1 */
97548          DbMaskTest(pParse->writeMask,iDb), /* P2 */
97549          pParse->cookieValue[iDb],          /* P3 */
97550          db->aDb[iDb].pSchema->iGeneration  /* P4 */
97551        );
97552        if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
97553        VdbeComment((v,
97554              "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
97555      }
97556#ifndef SQLITE_OMIT_VIRTUALTABLE
97557      for(i=0; i<pParse->nVtabLock; i++){
97558        char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
97559        sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
97560      }
97561      pParse->nVtabLock = 0;
97562#endif
97563
97564      /* Once all the cookies have been verified and transactions opened,
97565      ** obtain the required table-locks. This is a no-op unless the
97566      ** shared-cache feature is enabled.
97567      */
97568      codeTableLocks(pParse);
97569
97570      /* Initialize any AUTOINCREMENT data structures required.
97571      */
97572      sqlite3AutoincrementBegin(pParse);
97573
97574      /* Code constant expressions that where factored out of inner loops */
97575      if( pParse->pConstExpr ){
97576        ExprList *pEL = pParse->pConstExpr;
97577        pParse->okConstFactor = 0;
97578        for(i=0; i<pEL->nExpr; i++){
97579          sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
97580        }
97581      }
97582
97583      /* Finally, jump back to the beginning of the executable code. */
97584      sqlite3VdbeGoto(v, 1);
97585    }
97586  }
97587
97588
97589  /* Get the VDBE program ready for execution
97590  */
97591  if( v && pParse->nErr==0 && !db->mallocFailed ){
97592    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
97593    /* A minimum of one cursor is required if autoincrement is used
97594    *  See ticket [a696379c1f08866] */
97595    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
97596    sqlite3VdbeMakeReady(v, pParse);
97597    pParse->rc = SQLITE_DONE;
97598  }else{
97599    pParse->rc = SQLITE_ERROR;
97600  }
97601
97602  /* We are done with this Parse object. There is no need to de-initialize it */
97603#if 0
97604  pParse->colNamesSet = 0;
97605  pParse->nTab = 0;
97606  pParse->nMem = 0;
97607  pParse->nSet = 0;
97608  pParse->nVar = 0;
97609  DbMaskZero(pParse->cookieMask);
97610#endif
97611}
97612
97613/*
97614** Run the parser and code generator recursively in order to generate
97615** code for the SQL statement given onto the end of the pParse context
97616** currently under construction.  When the parser is run recursively
97617** this way, the final OP_Halt is not appended and other initialization
97618** and finalization steps are omitted because those are handling by the
97619** outermost parser.
97620**
97621** Not everything is nestable.  This facility is designed to permit
97622** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
97623** care if you decide to try to use this routine for some other purposes.
97624*/
97625SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
97626  va_list ap;
97627  char *zSql;
97628  char *zErrMsg = 0;
97629  sqlite3 *db = pParse->db;
97630# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
97631  char saveBuf[SAVE_SZ];
97632
97633  if( pParse->nErr ) return;
97634  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
97635  va_start(ap, zFormat);
97636  zSql = sqlite3VMPrintf(db, zFormat, ap);
97637  va_end(ap);
97638  if( zSql==0 ){
97639    return;   /* A malloc must have failed */
97640  }
97641  pParse->nested++;
97642  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
97643  memset(&pParse->nVar, 0, SAVE_SZ);
97644  sqlite3RunParser(pParse, zSql, &zErrMsg);
97645  sqlite3DbFree(db, zErrMsg);
97646  sqlite3DbFree(db, zSql);
97647  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
97648  pParse->nested--;
97649}
97650
97651#if SQLITE_USER_AUTHENTICATION
97652/*
97653** Return TRUE if zTable is the name of the system table that stores the
97654** list of users and their access credentials.
97655*/
97656SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
97657  return sqlite3_stricmp(zTable, "sqlite_user")==0;
97658}
97659#endif
97660
97661/*
97662** Locate the in-memory structure that describes a particular database
97663** table given the name of that table and (optionally) the name of the
97664** database containing the table.  Return NULL if not found.
97665**
97666** If zDatabase is 0, all databases are searched for the table and the
97667** first matching table is returned.  (No checking for duplicate table
97668** names is done.)  The search order is TEMP first, then MAIN, then any
97669** auxiliary databases added using the ATTACH command.
97670**
97671** See also sqlite3LocateTable().
97672*/
97673SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
97674  Table *p = 0;
97675  int i;
97676
97677  /* All mutexes are required for schema access.  Make sure we hold them. */
97678  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
97679#if SQLITE_USER_AUTHENTICATION
97680  /* Only the admin user is allowed to know that the sqlite_user table
97681  ** exists */
97682  if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
97683    return 0;
97684  }
97685#endif
97686  for(i=OMIT_TEMPDB; i<db->nDb; i++){
97687    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
97688    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
97689    assert( sqlite3SchemaMutexHeld(db, j, 0) );
97690    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
97691    if( p ) break;
97692  }
97693  return p;
97694}
97695
97696/*
97697** Locate the in-memory structure that describes a particular database
97698** table given the name of that table and (optionally) the name of the
97699** database containing the table.  Return NULL if not found.  Also leave an
97700** error message in pParse->zErrMsg.
97701**
97702** The difference between this routine and sqlite3FindTable() is that this
97703** routine leaves an error message in pParse->zErrMsg where
97704** sqlite3FindTable() does not.
97705*/
97706SQLITE_PRIVATE Table *sqlite3LocateTable(
97707  Parse *pParse,         /* context in which to report errors */
97708  u32 flags,             /* LOCATE_VIEW or LOCATE_NOERR */
97709  const char *zName,     /* Name of the table we are looking for */
97710  const char *zDbase     /* Name of the database.  Might be NULL */
97711){
97712  Table *p;
97713
97714  /* Read the database schema. If an error occurs, leave an error message
97715  ** and code in pParse and return NULL. */
97716  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
97717    return 0;
97718  }
97719
97720  p = sqlite3FindTable(pParse->db, zName, zDbase);
97721  if( p==0 ){
97722    const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
97723#ifndef SQLITE_OMIT_VIRTUALTABLE
97724    if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
97725      /* If zName is the not the name of a table in the schema created using
97726      ** CREATE, then check to see if it is the name of an virtual table that
97727      ** can be an eponymous virtual table. */
97728      Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
97729      if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
97730        return pMod->pEpoTab;
97731      }
97732    }
97733#endif
97734    if( (flags & LOCATE_NOERR)==0 ){
97735      if( zDbase ){
97736        sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
97737      }else{
97738        sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
97739      }
97740      pParse->checkSchema = 1;
97741    }
97742  }
97743
97744  return p;
97745}
97746
97747/*
97748** Locate the table identified by *p.
97749**
97750** This is a wrapper around sqlite3LocateTable(). The difference between
97751** sqlite3LocateTable() and this function is that this function restricts
97752** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
97753** non-NULL if it is part of a view or trigger program definition. See
97754** sqlite3FixSrcList() for details.
97755*/
97756SQLITE_PRIVATE Table *sqlite3LocateTableItem(
97757  Parse *pParse,
97758  u32 flags,
97759  struct SrcList_item *p
97760){
97761  const char *zDb;
97762  assert( p->pSchema==0 || p->zDatabase==0 );
97763  if( p->pSchema ){
97764    int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
97765    zDb = pParse->db->aDb[iDb].zName;
97766  }else{
97767    zDb = p->zDatabase;
97768  }
97769  return sqlite3LocateTable(pParse, flags, p->zName, zDb);
97770}
97771
97772/*
97773** Locate the in-memory structure that describes
97774** a particular index given the name of that index
97775** and the name of the database that contains the index.
97776** Return NULL if not found.
97777**
97778** If zDatabase is 0, all databases are searched for the
97779** table and the first matching index is returned.  (No checking
97780** for duplicate index names is done.)  The search order is
97781** TEMP first, then MAIN, then any auxiliary databases added
97782** using the ATTACH command.
97783*/
97784SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
97785  Index *p = 0;
97786  int i;
97787  /* All mutexes are required for schema access.  Make sure we hold them. */
97788  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
97789  for(i=OMIT_TEMPDB; i<db->nDb; i++){
97790    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
97791    Schema *pSchema = db->aDb[j].pSchema;
97792    assert( pSchema );
97793    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
97794    assert( sqlite3SchemaMutexHeld(db, j, 0) );
97795    p = sqlite3HashFind(&pSchema->idxHash, zName);
97796    if( p ) break;
97797  }
97798  return p;
97799}
97800
97801/*
97802** Reclaim the memory used by an index
97803*/
97804static void freeIndex(sqlite3 *db, Index *p){
97805#ifndef SQLITE_OMIT_ANALYZE
97806  sqlite3DeleteIndexSamples(db, p);
97807#endif
97808  sqlite3ExprDelete(db, p->pPartIdxWhere);
97809  sqlite3ExprListDelete(db, p->aColExpr);
97810  sqlite3DbFree(db, p->zColAff);
97811  if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
97812#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97813  sqlite3_free(p->aiRowEst);
97814#endif
97815  sqlite3DbFree(db, p);
97816}
97817
97818/*
97819** For the index called zIdxName which is found in the database iDb,
97820** unlike that index from its Table then remove the index from
97821** the index hash table and free all memory structures associated
97822** with the index.
97823*/
97824SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
97825  Index *pIndex;
97826  Hash *pHash;
97827
97828  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97829  pHash = &db->aDb[iDb].pSchema->idxHash;
97830  pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
97831  if( ALWAYS(pIndex) ){
97832    if( pIndex->pTable->pIndex==pIndex ){
97833      pIndex->pTable->pIndex = pIndex->pNext;
97834    }else{
97835      Index *p;
97836      /* Justification of ALWAYS();  The index must be on the list of
97837      ** indices. */
97838      p = pIndex->pTable->pIndex;
97839      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
97840      if( ALWAYS(p && p->pNext==pIndex) ){
97841        p->pNext = pIndex->pNext;
97842      }
97843    }
97844    freeIndex(db, pIndex);
97845  }
97846  db->flags |= SQLITE_InternChanges;
97847}
97848
97849/*
97850** Look through the list of open database files in db->aDb[] and if
97851** any have been closed, remove them from the list.  Reallocate the
97852** db->aDb[] structure to a smaller size, if possible.
97853**
97854** Entry 0 (the "main" database) and entry 1 (the "temp" database)
97855** are never candidates for being collapsed.
97856*/
97857SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
97858  int i, j;
97859  for(i=j=2; i<db->nDb; i++){
97860    struct Db *pDb = &db->aDb[i];
97861    if( pDb->pBt==0 ){
97862      sqlite3DbFree(db, pDb->zName);
97863      pDb->zName = 0;
97864      continue;
97865    }
97866    if( j<i ){
97867      db->aDb[j] = db->aDb[i];
97868    }
97869    j++;
97870  }
97871  db->nDb = j;
97872  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
97873    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
97874    sqlite3DbFree(db, db->aDb);
97875    db->aDb = db->aDbStatic;
97876  }
97877}
97878
97879/*
97880** Reset the schema for the database at index iDb.  Also reset the
97881** TEMP schema.
97882*/
97883SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
97884  Db *pDb;
97885  assert( iDb<db->nDb );
97886
97887  /* Case 1:  Reset the single schema identified by iDb */
97888  pDb = &db->aDb[iDb];
97889  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97890  assert( pDb->pSchema!=0 );
97891  sqlite3SchemaClear(pDb->pSchema);
97892
97893  /* If any database other than TEMP is reset, then also reset TEMP
97894  ** since TEMP might be holding triggers that reference tables in the
97895  ** other database.
97896  */
97897  if( iDb!=1 ){
97898    pDb = &db->aDb[1];
97899    assert( pDb->pSchema!=0 );
97900    sqlite3SchemaClear(pDb->pSchema);
97901  }
97902  return;
97903}
97904
97905/*
97906** Erase all schema information from all attached databases (including
97907** "main" and "temp") for a single database connection.
97908*/
97909SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
97910  int i;
97911  sqlite3BtreeEnterAll(db);
97912  for(i=0; i<db->nDb; i++){
97913    Db *pDb = &db->aDb[i];
97914    if( pDb->pSchema ){
97915      sqlite3SchemaClear(pDb->pSchema);
97916    }
97917  }
97918  db->flags &= ~SQLITE_InternChanges;
97919  sqlite3VtabUnlockList(db);
97920  sqlite3BtreeLeaveAll(db);
97921  sqlite3CollapseDatabaseArray(db);
97922}
97923
97924/*
97925** This routine is called when a commit occurs.
97926*/
97927SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
97928  db->flags &= ~SQLITE_InternChanges;
97929}
97930
97931/*
97932** Delete memory allocated for the column names of a table or view (the
97933** Table.aCol[] array).
97934*/
97935SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
97936  int i;
97937  Column *pCol;
97938  assert( pTable!=0 );
97939  if( (pCol = pTable->aCol)!=0 ){
97940    for(i=0; i<pTable->nCol; i++, pCol++){
97941      sqlite3DbFree(db, pCol->zName);
97942      sqlite3ExprDelete(db, pCol->pDflt);
97943      sqlite3DbFree(db, pCol->zColl);
97944    }
97945    sqlite3DbFree(db, pTable->aCol);
97946  }
97947}
97948
97949/*
97950** Remove the memory data structures associated with the given
97951** Table.  No changes are made to disk by this routine.
97952**
97953** This routine just deletes the data structure.  It does not unlink
97954** the table data structure from the hash table.  But it does destroy
97955** memory structures of the indices and foreign keys associated with
97956** the table.
97957**
97958** The db parameter is optional.  It is needed if the Table object
97959** contains lookaside memory.  (Table objects in the schema do not use
97960** lookaside memory, but some ephemeral Table objects do.)  Or the
97961** db parameter can be used with db->pnBytesFreed to measure the memory
97962** used by the Table object.
97963*/
97964static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
97965  Index *pIndex, *pNext;
97966  TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
97967
97968  /* Record the number of outstanding lookaside allocations in schema Tables
97969  ** prior to doing any free() operations.  Since schema Tables do not use
97970  ** lookaside, this number should not change. */
97971  TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
97972                         db->lookaside.nOut : 0 );
97973
97974  /* Delete all indices associated with this table. */
97975  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
97976    pNext = pIndex->pNext;
97977    assert( pIndex->pSchema==pTable->pSchema
97978         || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
97979    if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
97980      char *zName = pIndex->zName;
97981      TESTONLY ( Index *pOld = ) sqlite3HashInsert(
97982         &pIndex->pSchema->idxHash, zName, 0
97983      );
97984      assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
97985      assert( pOld==pIndex || pOld==0 );
97986    }
97987    freeIndex(db, pIndex);
97988  }
97989
97990  /* Delete any foreign keys attached to this table. */
97991  sqlite3FkDelete(db, pTable);
97992
97993  /* Delete the Table structure itself.
97994  */
97995  sqlite3DeleteColumnNames(db, pTable);
97996  sqlite3DbFree(db, pTable->zName);
97997  sqlite3DbFree(db, pTable->zColAff);
97998  sqlite3SelectDelete(db, pTable->pSelect);
97999  sqlite3ExprListDelete(db, pTable->pCheck);
98000#ifndef SQLITE_OMIT_VIRTUALTABLE
98001  sqlite3VtabClear(db, pTable);
98002#endif
98003  sqlite3DbFree(db, pTable);
98004
98005  /* Verify that no lookaside memory was used by schema tables */
98006  assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
98007}
98008SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
98009  /* Do not delete the table until the reference count reaches zero. */
98010  if( !pTable ) return;
98011  if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
98012  deleteTable(db, pTable);
98013}
98014
98015
98016/*
98017** Unlink the given table from the hash tables and the delete the
98018** table structure with all its indices and foreign keys.
98019*/
98020SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
98021  Table *p;
98022  Db *pDb;
98023
98024  assert( db!=0 );
98025  assert( iDb>=0 && iDb<db->nDb );
98026  assert( zTabName );
98027  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98028  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
98029  pDb = &db->aDb[iDb];
98030  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
98031  sqlite3DeleteTable(db, p);
98032  db->flags |= SQLITE_InternChanges;
98033}
98034
98035/*
98036** Given a token, return a string that consists of the text of that
98037** token.  Space to hold the returned string
98038** is obtained from sqliteMalloc() and must be freed by the calling
98039** function.
98040**
98041** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
98042** surround the body of the token are removed.
98043**
98044** Tokens are often just pointers into the original SQL text and so
98045** are not \000 terminated and are not persistent.  The returned string
98046** is \000 terminated and is persistent.
98047*/
98048SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
98049  char *zName;
98050  if( pName ){
98051    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
98052    sqlite3Dequote(zName);
98053  }else{
98054    zName = 0;
98055  }
98056  return zName;
98057}
98058
98059/*
98060** Open the sqlite_master table stored in database number iDb for
98061** writing. The table is opened using cursor 0.
98062*/
98063SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
98064  Vdbe *v = sqlite3GetVdbe(p);
98065  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
98066  sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
98067  if( p->nTab==0 ){
98068    p->nTab = 1;
98069  }
98070}
98071
98072/*
98073** Parameter zName points to a nul-terminated buffer containing the name
98074** of a database ("main", "temp" or the name of an attached db). This
98075** function returns the index of the named database in db->aDb[], or
98076** -1 if the named db cannot be found.
98077*/
98078SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
98079  int i = -1;         /* Database number */
98080  if( zName ){
98081    Db *pDb;
98082    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
98083      if( 0==sqlite3StrICmp(pDb->zName, zName) ) break;
98084    }
98085  }
98086  return i;
98087}
98088
98089/*
98090** The token *pName contains the name of a database (either "main" or
98091** "temp" or the name of an attached db). This routine returns the
98092** index of the named database in db->aDb[], or -1 if the named db
98093** does not exist.
98094*/
98095SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
98096  int i;                               /* Database number */
98097  char *zName;                         /* Name we are searching for */
98098  zName = sqlite3NameFromToken(db, pName);
98099  i = sqlite3FindDbName(db, zName);
98100  sqlite3DbFree(db, zName);
98101  return i;
98102}
98103
98104/* The table or view or trigger name is passed to this routine via tokens
98105** pName1 and pName2. If the table name was fully qualified, for example:
98106**
98107** CREATE TABLE xxx.yyy (...);
98108**
98109** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
98110** the table name is not fully qualified, i.e.:
98111**
98112** CREATE TABLE yyy(...);
98113**
98114** Then pName1 is set to "yyy" and pName2 is "".
98115**
98116** This routine sets the *ppUnqual pointer to point at the token (pName1 or
98117** pName2) that stores the unqualified table name.  The index of the
98118** database "xxx" is returned.
98119*/
98120SQLITE_PRIVATE int sqlite3TwoPartName(
98121  Parse *pParse,      /* Parsing and code generating context */
98122  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
98123  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
98124  Token **pUnqual     /* Write the unqualified object name here */
98125){
98126  int iDb;                    /* Database holding the object */
98127  sqlite3 *db = pParse->db;
98128
98129  assert( pName2!=0 );
98130  if( pName2->n>0 ){
98131    if( db->init.busy ) {
98132      sqlite3ErrorMsg(pParse, "corrupt database");
98133      return -1;
98134    }
98135    *pUnqual = pName2;
98136    iDb = sqlite3FindDb(db, pName1);
98137    if( iDb<0 ){
98138      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
98139      return -1;
98140    }
98141  }else{
98142    assert( db->init.iDb==0 || db->init.busy );
98143    iDb = db->init.iDb;
98144    *pUnqual = pName1;
98145  }
98146  return iDb;
98147}
98148
98149/*
98150** This routine is used to check if the UTF-8 string zName is a legal
98151** unqualified name for a new schema object (table, index, view or
98152** trigger). All names are legal except those that begin with the string
98153** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
98154** is reserved for internal use.
98155*/
98156SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
98157  if( !pParse->db->init.busy && pParse->nested==0
98158          && (pParse->db->flags & SQLITE_WriteSchema)==0
98159          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
98160    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
98161    return SQLITE_ERROR;
98162  }
98163  return SQLITE_OK;
98164}
98165
98166/*
98167** Return the PRIMARY KEY index of a table
98168*/
98169SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
98170  Index *p;
98171  for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
98172  return p;
98173}
98174
98175/*
98176** Return the column of index pIdx that corresponds to table
98177** column iCol.  Return -1 if not found.
98178*/
98179SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
98180  int i;
98181  for(i=0; i<pIdx->nColumn; i++){
98182    if( iCol==pIdx->aiColumn[i] ) return i;
98183  }
98184  return -1;
98185}
98186
98187/*
98188** Begin constructing a new table representation in memory.  This is
98189** the first of several action routines that get called in response
98190** to a CREATE TABLE statement.  In particular, this routine is called
98191** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
98192** flag is true if the table should be stored in the auxiliary database
98193** file instead of in the main database file.  This is normally the case
98194** when the "TEMP" or "TEMPORARY" keyword occurs in between
98195** CREATE and TABLE.
98196**
98197** The new table record is initialized and put in pParse->pNewTable.
98198** As more of the CREATE TABLE statement is parsed, additional action
98199** routines will be called to add more information to this record.
98200** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
98201** is called to complete the construction of the new table record.
98202*/
98203SQLITE_PRIVATE void sqlite3StartTable(
98204  Parse *pParse,   /* Parser context */
98205  Token *pName1,   /* First part of the name of the table or view */
98206  Token *pName2,   /* Second part of the name of the table or view */
98207  int isTemp,      /* True if this is a TEMP table */
98208  int isView,      /* True if this is a VIEW */
98209  int isVirtual,   /* True if this is a VIRTUAL table */
98210  int noErr        /* Do nothing if table already exists */
98211){
98212  Table *pTable;
98213  char *zName = 0; /* The name of the new table */
98214  sqlite3 *db = pParse->db;
98215  Vdbe *v;
98216  int iDb;         /* Database number to create the table in */
98217  Token *pName;    /* Unqualified name of the table to create */
98218
98219  if( db->init.busy && db->init.newTnum==1 ){
98220    /* Special case:  Parsing the sqlite_master or sqlite_temp_master schema */
98221    iDb = db->init.iDb;
98222    zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
98223    pName = pName1;
98224  }else{
98225    /* The common case */
98226    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
98227    if( iDb<0 ) return;
98228    if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
98229      /* If creating a temp table, the name may not be qualified. Unless
98230      ** the database name is "temp" anyway.  */
98231      sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
98232      return;
98233    }
98234    if( !OMIT_TEMPDB && isTemp ) iDb = 1;
98235    zName = sqlite3NameFromToken(db, pName);
98236  }
98237  pParse->sNameToken = *pName;
98238  if( zName==0 ) return;
98239  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
98240    goto begin_table_error;
98241  }
98242  if( db->init.iDb==1 ) isTemp = 1;
98243#ifndef SQLITE_OMIT_AUTHORIZATION
98244  assert( isTemp==0 || isTemp==1 );
98245  assert( isView==0 || isView==1 );
98246  {
98247    static const u8 aCode[] = {
98248       SQLITE_CREATE_TABLE,
98249       SQLITE_CREATE_TEMP_TABLE,
98250       SQLITE_CREATE_VIEW,
98251       SQLITE_CREATE_TEMP_VIEW
98252    };
98253    char *zDb = db->aDb[iDb].zName;
98254    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
98255      goto begin_table_error;
98256    }
98257    if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
98258                                       zName, 0, zDb) ){
98259      goto begin_table_error;
98260    }
98261  }
98262#endif
98263
98264  /* Make sure the new table name does not collide with an existing
98265  ** index or table name in the same database.  Issue an error message if
98266  ** it does. The exception is if the statement being parsed was passed
98267  ** to an sqlite3_declare_vtab() call. In that case only the column names
98268  ** and types will be used, so there is no need to test for namespace
98269  ** collisions.
98270  */
98271  if( !IN_DECLARE_VTAB ){
98272    char *zDb = db->aDb[iDb].zName;
98273    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
98274      goto begin_table_error;
98275    }
98276    pTable = sqlite3FindTable(db, zName, zDb);
98277    if( pTable ){
98278      if( !noErr ){
98279        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
98280      }else{
98281        assert( !db->init.busy || CORRUPT_DB );
98282        sqlite3CodeVerifySchema(pParse, iDb);
98283      }
98284      goto begin_table_error;
98285    }
98286    if( sqlite3FindIndex(db, zName, zDb)!=0 ){
98287      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
98288      goto begin_table_error;
98289    }
98290  }
98291
98292  pTable = sqlite3DbMallocZero(db, sizeof(Table));
98293  if( pTable==0 ){
98294    assert( db->mallocFailed );
98295    pParse->rc = SQLITE_NOMEM_BKPT;
98296    pParse->nErr++;
98297    goto begin_table_error;
98298  }
98299  pTable->zName = zName;
98300  pTable->iPKey = -1;
98301  pTable->pSchema = db->aDb[iDb].pSchema;
98302  pTable->nRef = 1;
98303  pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
98304  assert( pParse->pNewTable==0 );
98305  pParse->pNewTable = pTable;
98306
98307  /* If this is the magic sqlite_sequence table used by autoincrement,
98308  ** then record a pointer to this table in the main database structure
98309  ** so that INSERT can find the table easily.
98310  */
98311#ifndef SQLITE_OMIT_AUTOINCREMENT
98312  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
98313    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98314    pTable->pSchema->pSeqTab = pTable;
98315  }
98316#endif
98317
98318  /* Begin generating the code that will insert the table record into
98319  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
98320  ** and allocate the record number for the table entry now.  Before any
98321  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
98322  ** indices to be created and the table record must come before the
98323  ** indices.  Hence, the record number for the table must be allocated
98324  ** now.
98325  */
98326  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
98327    int addr1;
98328    int fileFormat;
98329    int reg1, reg2, reg3;
98330    /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
98331    static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
98332    sqlite3BeginWriteOperation(pParse, 1, iDb);
98333
98334#ifndef SQLITE_OMIT_VIRTUALTABLE
98335    if( isVirtual ){
98336      sqlite3VdbeAddOp0(v, OP_VBegin);
98337    }
98338#endif
98339
98340    /* If the file format and encoding in the database have not been set,
98341    ** set them now.
98342    */
98343    reg1 = pParse->regRowid = ++pParse->nMem;
98344    reg2 = pParse->regRoot = ++pParse->nMem;
98345    reg3 = ++pParse->nMem;
98346    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
98347    sqlite3VdbeUsesBtree(v, iDb);
98348    addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
98349    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
98350                  1 : SQLITE_MAX_FILE_FORMAT;
98351    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
98352    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
98353    sqlite3VdbeJumpHere(v, addr1);
98354
98355    /* This just creates a place-holder record in the sqlite_master table.
98356    ** The record created does not contain anything yet.  It will be replaced
98357    ** by the real entry in code generated at sqlite3EndTable().
98358    **
98359    ** The rowid for the new entry is left in register pParse->regRowid.
98360    ** The root page number of the new table is left in reg pParse->regRoot.
98361    ** The rowid and root page number values are needed by the code that
98362    ** sqlite3EndTable will generate.
98363    */
98364#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
98365    if( isView || isVirtual ){
98366      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
98367    }else
98368#endif
98369    {
98370      pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
98371    }
98372    sqlite3OpenMasterTable(pParse, iDb);
98373    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
98374    sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
98375    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
98376    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
98377    sqlite3VdbeAddOp0(v, OP_Close);
98378  }
98379
98380  /* Normal (non-error) return. */
98381  return;
98382
98383  /* If an error occurs, we jump here */
98384begin_table_error:
98385  sqlite3DbFree(db, zName);
98386  return;
98387}
98388
98389/* Set properties of a table column based on the (magical)
98390** name of the column.
98391*/
98392#if SQLITE_ENABLE_HIDDEN_COLUMNS
98393SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
98394  if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
98395    pCol->colFlags |= COLFLAG_HIDDEN;
98396  }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
98397    pTab->tabFlags |= TF_OOOHidden;
98398  }
98399}
98400#endif
98401
98402
98403/*
98404** Add a new column to the table currently being constructed.
98405**
98406** The parser calls this routine once for each column declaration
98407** in a CREATE TABLE statement.  sqlite3StartTable() gets called
98408** first to get things going.  Then this routine is called for each
98409** column.
98410*/
98411SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
98412  Table *p;
98413  int i;
98414  char *z;
98415  char *zType;
98416  Column *pCol;
98417  sqlite3 *db = pParse->db;
98418  if( (p = pParse->pNewTable)==0 ) return;
98419#if SQLITE_MAX_COLUMN
98420  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
98421    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
98422    return;
98423  }
98424#endif
98425  z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
98426  if( z==0 ) return;
98427  memcpy(z, pName->z, pName->n);
98428  z[pName->n] = 0;
98429  sqlite3Dequote(z);
98430  for(i=0; i<p->nCol; i++){
98431    if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
98432      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
98433      sqlite3DbFree(db, z);
98434      return;
98435    }
98436  }
98437  if( (p->nCol & 0x7)==0 ){
98438    Column *aNew;
98439    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
98440    if( aNew==0 ){
98441      sqlite3DbFree(db, z);
98442      return;
98443    }
98444    p->aCol = aNew;
98445  }
98446  pCol = &p->aCol[p->nCol];
98447  memset(pCol, 0, sizeof(p->aCol[0]));
98448  pCol->zName = z;
98449  sqlite3ColumnPropertiesFromName(p, pCol);
98450
98451  if( pType->n==0 ){
98452    /* If there is no type specified, columns have the default affinity
98453    ** 'BLOB'. */
98454    pCol->affinity = SQLITE_AFF_BLOB;
98455    pCol->szEst = 1;
98456  }else{
98457    zType = z + sqlite3Strlen30(z) + 1;
98458    memcpy(zType, pType->z, pType->n);
98459    zType[pType->n] = 0;
98460    sqlite3Dequote(zType);
98461    pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
98462    pCol->colFlags |= COLFLAG_HASTYPE;
98463  }
98464  p->nCol++;
98465  pParse->constraintName.n = 0;
98466}
98467
98468/*
98469** This routine is called by the parser while in the middle of
98470** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
98471** been seen on a column.  This routine sets the notNull flag on
98472** the column currently under construction.
98473*/
98474SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
98475  Table *p;
98476  p = pParse->pNewTable;
98477  if( p==0 || NEVER(p->nCol<1) ) return;
98478  p->aCol[p->nCol-1].notNull = (u8)onError;
98479}
98480
98481/*
98482** Scan the column type name zType (length nType) and return the
98483** associated affinity type.
98484**
98485** This routine does a case-independent search of zType for the
98486** substrings in the following table. If one of the substrings is
98487** found, the corresponding affinity is returned. If zType contains
98488** more than one of the substrings, entries toward the top of
98489** the table take priority. For example, if zType is 'BLOBINT',
98490** SQLITE_AFF_INTEGER is returned.
98491**
98492** Substring     | Affinity
98493** --------------------------------
98494** 'INT'         | SQLITE_AFF_INTEGER
98495** 'CHAR'        | SQLITE_AFF_TEXT
98496** 'CLOB'        | SQLITE_AFF_TEXT
98497** 'TEXT'        | SQLITE_AFF_TEXT
98498** 'BLOB'        | SQLITE_AFF_BLOB
98499** 'REAL'        | SQLITE_AFF_REAL
98500** 'FLOA'        | SQLITE_AFF_REAL
98501** 'DOUB'        | SQLITE_AFF_REAL
98502**
98503** If none of the substrings in the above table are found,
98504** SQLITE_AFF_NUMERIC is returned.
98505*/
98506SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
98507  u32 h = 0;
98508  char aff = SQLITE_AFF_NUMERIC;
98509  const char *zChar = 0;
98510
98511  assert( zIn!=0 );
98512  while( zIn[0] ){
98513    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
98514    zIn++;
98515    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
98516      aff = SQLITE_AFF_TEXT;
98517      zChar = zIn;
98518    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
98519      aff = SQLITE_AFF_TEXT;
98520    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
98521      aff = SQLITE_AFF_TEXT;
98522    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
98523        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
98524      aff = SQLITE_AFF_BLOB;
98525      if( zIn[0]=='(' ) zChar = zIn;
98526#ifndef SQLITE_OMIT_FLOATING_POINT
98527    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
98528        && aff==SQLITE_AFF_NUMERIC ){
98529      aff = SQLITE_AFF_REAL;
98530    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
98531        && aff==SQLITE_AFF_NUMERIC ){
98532      aff = SQLITE_AFF_REAL;
98533    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
98534        && aff==SQLITE_AFF_NUMERIC ){
98535      aff = SQLITE_AFF_REAL;
98536#endif
98537    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
98538      aff = SQLITE_AFF_INTEGER;
98539      break;
98540    }
98541  }
98542
98543  /* If pszEst is not NULL, store an estimate of the field size.  The
98544  ** estimate is scaled so that the size of an integer is 1.  */
98545  if( pszEst ){
98546    *pszEst = 1;   /* default size is approx 4 bytes */
98547    if( aff<SQLITE_AFF_NUMERIC ){
98548      if( zChar ){
98549        while( zChar[0] ){
98550          if( sqlite3Isdigit(zChar[0]) ){
98551            int v = 0;
98552            sqlite3GetInt32(zChar, &v);
98553            v = v/4 + 1;
98554            if( v>255 ) v = 255;
98555            *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
98556            break;
98557          }
98558          zChar++;
98559        }
98560      }else{
98561        *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
98562      }
98563    }
98564  }
98565  return aff;
98566}
98567
98568/*
98569** The expression is the default value for the most recently added column
98570** of the table currently under construction.
98571**
98572** Default value expressions must be constant.  Raise an exception if this
98573** is not the case.
98574**
98575** This routine is called by the parser while in the middle of
98576** parsing a CREATE TABLE statement.
98577*/
98578SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
98579  Table *p;
98580  Column *pCol;
98581  sqlite3 *db = pParse->db;
98582  p = pParse->pNewTable;
98583  if( p!=0 ){
98584    pCol = &(p->aCol[p->nCol-1]);
98585    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
98586      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
98587          pCol->zName);
98588    }else{
98589      /* A copy of pExpr is used instead of the original, as pExpr contains
98590      ** tokens that point to volatile memory. The 'span' of the expression
98591      ** is required by pragma table_info.
98592      */
98593      Expr x;
98594      sqlite3ExprDelete(db, pCol->pDflt);
98595      memset(&x, 0, sizeof(x));
98596      x.op = TK_SPAN;
98597      x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
98598                                    (int)(pSpan->zEnd - pSpan->zStart));
98599      x.pLeft = pSpan->pExpr;
98600      x.flags = EP_Skip;
98601      pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
98602      sqlite3DbFree(db, x.u.zToken);
98603    }
98604  }
98605  sqlite3ExprDelete(db, pSpan->pExpr);
98606}
98607
98608/*
98609** Backwards Compatibility Hack:
98610**
98611** Historical versions of SQLite accepted strings as column names in
98612** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:
98613**
98614**     CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
98615**     CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
98616**
98617** This is goofy.  But to preserve backwards compatibility we continue to
98618** accept it.  This routine does the necessary conversion.  It converts
98619** the expression given in its argument from a TK_STRING into a TK_ID
98620** if the expression is just a TK_STRING with an optional COLLATE clause.
98621** If the epxression is anything other than TK_STRING, the expression is
98622** unchanged.
98623*/
98624static void sqlite3StringToId(Expr *p){
98625  if( p->op==TK_STRING ){
98626    p->op = TK_ID;
98627  }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
98628    p->pLeft->op = TK_ID;
98629  }
98630}
98631
98632/*
98633** Designate the PRIMARY KEY for the table.  pList is a list of names
98634** of columns that form the primary key.  If pList is NULL, then the
98635** most recently added column of the table is the primary key.
98636**
98637** A table can have at most one primary key.  If the table already has
98638** a primary key (and this is the second primary key) then create an
98639** error.
98640**
98641** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
98642** then we will try to use that column as the rowid.  Set the Table.iPKey
98643** field of the table under construction to be the index of the
98644** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
98645** no INTEGER PRIMARY KEY.
98646**
98647** If the key is not an INTEGER PRIMARY KEY, then create a unique
98648** index for the key.  No index is created for INTEGER PRIMARY KEYs.
98649*/
98650SQLITE_PRIVATE void sqlite3AddPrimaryKey(
98651  Parse *pParse,    /* Parsing context */
98652  ExprList *pList,  /* List of field names to be indexed */
98653  int onError,      /* What to do with a uniqueness conflict */
98654  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
98655  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
98656){
98657  Table *pTab = pParse->pNewTable;
98658  Column *pCol = 0;
98659  int iCol = -1, i;
98660  int nTerm;
98661  if( pTab==0 ) goto primary_key_exit;
98662  if( pTab->tabFlags & TF_HasPrimaryKey ){
98663    sqlite3ErrorMsg(pParse,
98664      "table \"%s\" has more than one primary key", pTab->zName);
98665    goto primary_key_exit;
98666  }
98667  pTab->tabFlags |= TF_HasPrimaryKey;
98668  if( pList==0 ){
98669    iCol = pTab->nCol - 1;
98670    pCol = &pTab->aCol[iCol];
98671    pCol->colFlags |= COLFLAG_PRIMKEY;
98672    nTerm = 1;
98673  }else{
98674    nTerm = pList->nExpr;
98675    for(i=0; i<nTerm; i++){
98676      Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
98677      assert( pCExpr!=0 );
98678      sqlite3StringToId(pCExpr);
98679      if( pCExpr->op==TK_ID ){
98680        const char *zCName = pCExpr->u.zToken;
98681        for(iCol=0; iCol<pTab->nCol; iCol++){
98682          if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
98683            pCol = &pTab->aCol[iCol];
98684            pCol->colFlags |= COLFLAG_PRIMKEY;
98685            break;
98686          }
98687        }
98688      }
98689    }
98690  }
98691  if( nTerm==1
98692   && pCol
98693   && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
98694   && sortOrder!=SQLITE_SO_DESC
98695  ){
98696    pTab->iPKey = iCol;
98697    pTab->keyConf = (u8)onError;
98698    assert( autoInc==0 || autoInc==1 );
98699    pTab->tabFlags |= autoInc*TF_Autoincrement;
98700    if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
98701  }else if( autoInc ){
98702#ifndef SQLITE_OMIT_AUTOINCREMENT
98703    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
98704       "INTEGER PRIMARY KEY");
98705#endif
98706  }else{
98707    sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
98708                           0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
98709    pList = 0;
98710  }
98711
98712primary_key_exit:
98713  sqlite3ExprListDelete(pParse->db, pList);
98714  return;
98715}
98716
98717/*
98718** Add a new CHECK constraint to the table currently under construction.
98719*/
98720SQLITE_PRIVATE void sqlite3AddCheckConstraint(
98721  Parse *pParse,    /* Parsing context */
98722  Expr *pCheckExpr  /* The check expression */
98723){
98724#ifndef SQLITE_OMIT_CHECK
98725  Table *pTab = pParse->pNewTable;
98726  sqlite3 *db = pParse->db;
98727  if( pTab && !IN_DECLARE_VTAB
98728   && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
98729  ){
98730    pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
98731    if( pParse->constraintName.n ){
98732      sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
98733    }
98734  }else
98735#endif
98736  {
98737    sqlite3ExprDelete(pParse->db, pCheckExpr);
98738  }
98739}
98740
98741/*
98742** Set the collation function of the most recently parsed table column
98743** to the CollSeq given.
98744*/
98745SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
98746  Table *p;
98747  int i;
98748  char *zColl;              /* Dequoted name of collation sequence */
98749  sqlite3 *db;
98750
98751  if( (p = pParse->pNewTable)==0 ) return;
98752  i = p->nCol-1;
98753  db = pParse->db;
98754  zColl = sqlite3NameFromToken(db, pToken);
98755  if( !zColl ) return;
98756
98757  if( sqlite3LocateCollSeq(pParse, zColl) ){
98758    Index *pIdx;
98759    sqlite3DbFree(db, p->aCol[i].zColl);
98760    p->aCol[i].zColl = zColl;
98761
98762    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
98763    ** then an index may have been created on this column before the
98764    ** collation type was added. Correct this if it is the case.
98765    */
98766    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
98767      assert( pIdx->nKeyCol==1 );
98768      if( pIdx->aiColumn[0]==i ){
98769        pIdx->azColl[0] = p->aCol[i].zColl;
98770      }
98771    }
98772  }else{
98773    sqlite3DbFree(db, zColl);
98774  }
98775}
98776
98777/*
98778** This function returns the collation sequence for database native text
98779** encoding identified by the string zName, length nName.
98780**
98781** If the requested collation sequence is not available, or not available
98782** in the database native encoding, the collation factory is invoked to
98783** request it. If the collation factory does not supply such a sequence,
98784** and the sequence is available in another text encoding, then that is
98785** returned instead.
98786**
98787** If no versions of the requested collations sequence are available, or
98788** another error occurs, NULL is returned and an error message written into
98789** pParse.
98790**
98791** This routine is a wrapper around sqlite3FindCollSeq().  This routine
98792** invokes the collation factory if the named collation cannot be found
98793** and generates an error message.
98794**
98795** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
98796*/
98797SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
98798  sqlite3 *db = pParse->db;
98799  u8 enc = ENC(db);
98800  u8 initbusy = db->init.busy;
98801  CollSeq *pColl;
98802
98803  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
98804  if( !initbusy && (!pColl || !pColl->xCmp) ){
98805    pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
98806  }
98807
98808  return pColl;
98809}
98810
98811
98812/*
98813** Generate code that will increment the schema cookie.
98814**
98815** The schema cookie is used to determine when the schema for the
98816** database changes.  After each schema change, the cookie value
98817** changes.  When a process first reads the schema it records the
98818** cookie.  Thereafter, whenever it goes to access the database,
98819** it checks the cookie to make sure the schema has not changed
98820** since it was last read.
98821**
98822** This plan is not completely bullet-proof.  It is possible for
98823** the schema to change multiple times and for the cookie to be
98824** set back to prior value.  But schema changes are infrequent
98825** and the probability of hitting the same cookie value is only
98826** 1 chance in 2^32.  So we're safe enough.
98827*/
98828SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
98829  sqlite3 *db = pParse->db;
98830  Vdbe *v = pParse->pVdbe;
98831  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98832  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
98833                    db->aDb[iDb].pSchema->schema_cookie+1);
98834}
98835
98836/*
98837** Measure the number of characters needed to output the given
98838** identifier.  The number returned includes any quotes used
98839** but does not include the null terminator.
98840**
98841** The estimate is conservative.  It might be larger that what is
98842** really needed.
98843*/
98844static int identLength(const char *z){
98845  int n;
98846  for(n=0; *z; n++, z++){
98847    if( *z=='"' ){ n++; }
98848  }
98849  return n + 2;
98850}
98851
98852/*
98853** The first parameter is a pointer to an output buffer. The second
98854** parameter is a pointer to an integer that contains the offset at
98855** which to write into the output buffer. This function copies the
98856** nul-terminated string pointed to by the third parameter, zSignedIdent,
98857** to the specified offset in the buffer and updates *pIdx to refer
98858** to the first byte after the last byte written before returning.
98859**
98860** If the string zSignedIdent consists entirely of alpha-numeric
98861** characters, does not begin with a digit and is not an SQL keyword,
98862** then it is copied to the output buffer exactly as it is. Otherwise,
98863** it is quoted using double-quotes.
98864*/
98865static void identPut(char *z, int *pIdx, char *zSignedIdent){
98866  unsigned char *zIdent = (unsigned char*)zSignedIdent;
98867  int i, j, needQuote;
98868  i = *pIdx;
98869
98870  for(j=0; zIdent[j]; j++){
98871    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
98872  }
98873  needQuote = sqlite3Isdigit(zIdent[0])
98874            || sqlite3KeywordCode(zIdent, j)!=TK_ID
98875            || zIdent[j]!=0
98876            || j==0;
98877
98878  if( needQuote ) z[i++] = '"';
98879  for(j=0; zIdent[j]; j++){
98880    z[i++] = zIdent[j];
98881    if( zIdent[j]=='"' ) z[i++] = '"';
98882  }
98883  if( needQuote ) z[i++] = '"';
98884  z[i] = 0;
98885  *pIdx = i;
98886}
98887
98888/*
98889** Generate a CREATE TABLE statement appropriate for the given
98890** table.  Memory to hold the text of the statement is obtained
98891** from sqliteMalloc() and must be freed by the calling function.
98892*/
98893static char *createTableStmt(sqlite3 *db, Table *p){
98894  int i, k, n;
98895  char *zStmt;
98896  char *zSep, *zSep2, *zEnd;
98897  Column *pCol;
98898  n = 0;
98899  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
98900    n += identLength(pCol->zName) + 5;
98901  }
98902  n += identLength(p->zName);
98903  if( n<50 ){
98904    zSep = "";
98905    zSep2 = ",";
98906    zEnd = ")";
98907  }else{
98908    zSep = "\n  ";
98909    zSep2 = ",\n  ";
98910    zEnd = "\n)";
98911  }
98912  n += 35 + 6*p->nCol;
98913  zStmt = sqlite3DbMallocRaw(0, n);
98914  if( zStmt==0 ){
98915    sqlite3OomFault(db);
98916    return 0;
98917  }
98918  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
98919  k = sqlite3Strlen30(zStmt);
98920  identPut(zStmt, &k, p->zName);
98921  zStmt[k++] = '(';
98922  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
98923    static const char * const azType[] = {
98924        /* SQLITE_AFF_BLOB    */ "",
98925        /* SQLITE_AFF_TEXT    */ " TEXT",
98926        /* SQLITE_AFF_NUMERIC */ " NUM",
98927        /* SQLITE_AFF_INTEGER */ " INT",
98928        /* SQLITE_AFF_REAL    */ " REAL"
98929    };
98930    int len;
98931    const char *zType;
98932
98933    sqlite3_snprintf(n-k, &zStmt[k], zSep);
98934    k += sqlite3Strlen30(&zStmt[k]);
98935    zSep = zSep2;
98936    identPut(zStmt, &k, pCol->zName);
98937    assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
98938    assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
98939    testcase( pCol->affinity==SQLITE_AFF_BLOB );
98940    testcase( pCol->affinity==SQLITE_AFF_TEXT );
98941    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
98942    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
98943    testcase( pCol->affinity==SQLITE_AFF_REAL );
98944
98945    zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
98946    len = sqlite3Strlen30(zType);
98947    assert( pCol->affinity==SQLITE_AFF_BLOB
98948            || pCol->affinity==sqlite3AffinityType(zType, 0) );
98949    memcpy(&zStmt[k], zType, len);
98950    k += len;
98951    assert( k<=n );
98952  }
98953  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
98954  return zStmt;
98955}
98956
98957/*
98958** Resize an Index object to hold N columns total.  Return SQLITE_OK
98959** on success and SQLITE_NOMEM on an OOM error.
98960*/
98961static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
98962  char *zExtra;
98963  int nByte;
98964  if( pIdx->nColumn>=N ) return SQLITE_OK;
98965  assert( pIdx->isResized==0 );
98966  nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
98967  zExtra = sqlite3DbMallocZero(db, nByte);
98968  if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
98969  memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
98970  pIdx->azColl = (const char**)zExtra;
98971  zExtra += sizeof(char*)*N;
98972  memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
98973  pIdx->aiColumn = (i16*)zExtra;
98974  zExtra += sizeof(i16)*N;
98975  memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
98976  pIdx->aSortOrder = (u8*)zExtra;
98977  pIdx->nColumn = N;
98978  pIdx->isResized = 1;
98979  return SQLITE_OK;
98980}
98981
98982/*
98983** Estimate the total row width for a table.
98984*/
98985static void estimateTableWidth(Table *pTab){
98986  unsigned wTable = 0;
98987  const Column *pTabCol;
98988  int i;
98989  for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
98990    wTable += pTabCol->szEst;
98991  }
98992  if( pTab->iPKey<0 ) wTable++;
98993  pTab->szTabRow = sqlite3LogEst(wTable*4);
98994}
98995
98996/*
98997** Estimate the average size of a row for an index.
98998*/
98999static void estimateIndexWidth(Index *pIdx){
99000  unsigned wIndex = 0;
99001  int i;
99002  const Column *aCol = pIdx->pTable->aCol;
99003  for(i=0; i<pIdx->nColumn; i++){
99004    i16 x = pIdx->aiColumn[i];
99005    assert( x<pIdx->pTable->nCol );
99006    wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
99007  }
99008  pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
99009}
99010
99011/* Return true if value x is found any of the first nCol entries of aiCol[]
99012*/
99013static int hasColumn(const i16 *aiCol, int nCol, int x){
99014  while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
99015  return 0;
99016}
99017
99018/*
99019** This routine runs at the end of parsing a CREATE TABLE statement that
99020** has a WITHOUT ROWID clause.  The job of this routine is to convert both
99021** internal schema data structures and the generated VDBE code so that they
99022** are appropriate for a WITHOUT ROWID table instead of a rowid table.
99023** Changes include:
99024**
99025**     (1)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
99026**     (2)  Convert the OP_CreateTable into an OP_CreateIndex.  There is
99027**          no rowid btree for a WITHOUT ROWID.  Instead, the canonical
99028**          data storage is a covering index btree.
99029**     (3)  Bypass the creation of the sqlite_master table entry
99030**          for the PRIMARY KEY as the primary key index is now
99031**          identified by the sqlite_master table entry of the table itself.
99032**     (4)  Set the Index.tnum of the PRIMARY KEY Index object in the
99033**          schema to the rootpage from the main table.
99034**     (5)  Add all table columns to the PRIMARY KEY Index object
99035**          so that the PRIMARY KEY is a covering index.  The surplus
99036**          columns are part of KeyInfo.nXField and are not used for
99037**          sorting or lookup or uniqueness checks.
99038**     (6)  Replace the rowid tail on all automatically generated UNIQUE
99039**          indices with the PRIMARY KEY columns.
99040**
99041** For virtual tables, only (1) is performed.
99042*/
99043static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
99044  Index *pIdx;
99045  Index *pPk;
99046  int nPk;
99047  int i, j;
99048  sqlite3 *db = pParse->db;
99049  Vdbe *v = pParse->pVdbe;
99050
99051  /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
99052  */
99053  if( !db->init.imposterTable ){
99054    for(i=0; i<pTab->nCol; i++){
99055      if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
99056        pTab->aCol[i].notNull = OE_Abort;
99057      }
99058    }
99059  }
99060
99061  /* The remaining transformations only apply to b-tree tables, not to
99062  ** virtual tables */
99063  if( IN_DECLARE_VTAB ) return;
99064
99065  /* Convert the OP_CreateTable opcode that would normally create the
99066  ** root-page for the table into an OP_CreateIndex opcode.  The index
99067  ** created will become the PRIMARY KEY index.
99068  */
99069  if( pParse->addrCrTab ){
99070    assert( v );
99071    sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex);
99072  }
99073
99074  /* Locate the PRIMARY KEY index.  Or, if this table was originally
99075  ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
99076  */
99077  if( pTab->iPKey>=0 ){
99078    ExprList *pList;
99079    Token ipkToken;
99080    sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
99081    pList = sqlite3ExprListAppend(pParse, 0,
99082                  sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
99083    if( pList==0 ) return;
99084    pList->a[0].sortOrder = pParse->iPkSortOrder;
99085    assert( pParse->pNewTable==pTab );
99086    sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
99087                       SQLITE_IDXTYPE_PRIMARYKEY);
99088    if( db->mallocFailed ) return;
99089    pPk = sqlite3PrimaryKeyIndex(pTab);
99090    pTab->iPKey = -1;
99091  }else{
99092    pPk = sqlite3PrimaryKeyIndex(pTab);
99093
99094    /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
99095    ** table entry. This is only required if currently generating VDBE
99096    ** code for a CREATE TABLE (not when parsing one as part of reading
99097    ** a database schema).  */
99098    if( v ){
99099      assert( db->init.busy==0 );
99100      sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
99101    }
99102
99103    /*
99104    ** Remove all redundant columns from the PRIMARY KEY.  For example, change
99105    ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
99106    ** code assumes the PRIMARY KEY contains no repeated columns.
99107    */
99108    for(i=j=1; i<pPk->nKeyCol; i++){
99109      if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
99110        pPk->nColumn--;
99111      }else{
99112        pPk->aiColumn[j++] = pPk->aiColumn[i];
99113      }
99114    }
99115    pPk->nKeyCol = j;
99116  }
99117  assert( pPk!=0 );
99118  pPk->isCovering = 1;
99119  if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
99120  nPk = pPk->nKeyCol;
99121
99122  /* The root page of the PRIMARY KEY is the table root page */
99123  pPk->tnum = pTab->tnum;
99124
99125  /* Update the in-memory representation of all UNIQUE indices by converting
99126  ** the final rowid column into one or more columns of the PRIMARY KEY.
99127  */
99128  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99129    int n;
99130    if( IsPrimaryKeyIndex(pIdx) ) continue;
99131    for(i=n=0; i<nPk; i++){
99132      if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
99133    }
99134    if( n==0 ){
99135      /* This index is a superset of the primary key */
99136      pIdx->nColumn = pIdx->nKeyCol;
99137      continue;
99138    }
99139    if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
99140    for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
99141      if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
99142        pIdx->aiColumn[j] = pPk->aiColumn[i];
99143        pIdx->azColl[j] = pPk->azColl[i];
99144        j++;
99145      }
99146    }
99147    assert( pIdx->nColumn>=pIdx->nKeyCol+n );
99148    assert( pIdx->nColumn>=j );
99149  }
99150
99151  /* Add all table columns to the PRIMARY KEY index
99152  */
99153  if( nPk<pTab->nCol ){
99154    if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
99155    for(i=0, j=nPk; i<pTab->nCol; i++){
99156      if( !hasColumn(pPk->aiColumn, j, i) ){
99157        assert( j<pPk->nColumn );
99158        pPk->aiColumn[j] = i;
99159        pPk->azColl[j] = sqlite3StrBINARY;
99160        j++;
99161      }
99162    }
99163    assert( pPk->nColumn==j );
99164    assert( pTab->nCol==j );
99165  }else{
99166    pPk->nColumn = pTab->nCol;
99167  }
99168}
99169
99170/*
99171** This routine is called to report the final ")" that terminates
99172** a CREATE TABLE statement.
99173**
99174** The table structure that other action routines have been building
99175** is added to the internal hash tables, assuming no errors have
99176** occurred.
99177**
99178** An entry for the table is made in the master table on disk, unless
99179** this is a temporary table or db->init.busy==1.  When db->init.busy==1
99180** it means we are reading the sqlite_master table because we just
99181** connected to the database or because the sqlite_master table has
99182** recently changed, so the entry for this table already exists in
99183** the sqlite_master table.  We do not want to create it again.
99184**
99185** If the pSelect argument is not NULL, it means that this routine
99186** was called to create a table generated from a
99187** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
99188** the new table will match the result set of the SELECT.
99189*/
99190SQLITE_PRIVATE void sqlite3EndTable(
99191  Parse *pParse,          /* Parse context */
99192  Token *pCons,           /* The ',' token after the last column defn. */
99193  Token *pEnd,            /* The ')' before options in the CREATE TABLE */
99194  u8 tabOpts,             /* Extra table options. Usually 0. */
99195  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
99196){
99197  Table *p;                 /* The new table */
99198  sqlite3 *db = pParse->db; /* The database connection */
99199  int iDb;                  /* Database in which the table lives */
99200  Index *pIdx;              /* An implied index of the table */
99201
99202  if( pEnd==0 && pSelect==0 ){
99203    return;
99204  }
99205  assert( !db->mallocFailed );
99206  p = pParse->pNewTable;
99207  if( p==0 ) return;
99208
99209  assert( !db->init.busy || !pSelect );
99210
99211  /* If the db->init.busy is 1 it means we are reading the SQL off the
99212  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
99213  ** So do not write to the disk again.  Extract the root page number
99214  ** for the table from the db->init.newTnum field.  (The page number
99215  ** should have been put there by the sqliteOpenCb routine.)
99216  **
99217  ** If the root page number is 1, that means this is the sqlite_master
99218  ** table itself.  So mark it read-only.
99219  */
99220  if( db->init.busy ){
99221    p->tnum = db->init.newTnum;
99222    if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
99223  }
99224
99225  /* Special processing for WITHOUT ROWID Tables */
99226  if( tabOpts & TF_WithoutRowid ){
99227    if( (p->tabFlags & TF_Autoincrement) ){
99228      sqlite3ErrorMsg(pParse,
99229          "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
99230      return;
99231    }
99232    if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
99233      sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
99234    }else{
99235      p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
99236      convertToWithoutRowidTable(pParse, p);
99237    }
99238  }
99239
99240  iDb = sqlite3SchemaToIndex(db, p->pSchema);
99241
99242#ifndef SQLITE_OMIT_CHECK
99243  /* Resolve names in all CHECK constraint expressions.
99244  */
99245  if( p->pCheck ){
99246    sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
99247  }
99248#endif /* !defined(SQLITE_OMIT_CHECK) */
99249
99250  /* Estimate the average row size for the table and for all implied indices */
99251  estimateTableWidth(p);
99252  for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
99253    estimateIndexWidth(pIdx);
99254  }
99255
99256  /* If not initializing, then create a record for the new table
99257  ** in the SQLITE_MASTER table of the database.
99258  **
99259  ** If this is a TEMPORARY table, write the entry into the auxiliary
99260  ** file instead of into the main database file.
99261  */
99262  if( !db->init.busy ){
99263    int n;
99264    Vdbe *v;
99265    char *zType;    /* "view" or "table" */
99266    char *zType2;   /* "VIEW" or "TABLE" */
99267    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
99268
99269    v = sqlite3GetVdbe(pParse);
99270    if( NEVER(v==0) ) return;
99271
99272    sqlite3VdbeAddOp1(v, OP_Close, 0);
99273
99274    /*
99275    ** Initialize zType for the new view or table.
99276    */
99277    if( p->pSelect==0 ){
99278      /* A regular table */
99279      zType = "table";
99280      zType2 = "TABLE";
99281#ifndef SQLITE_OMIT_VIEW
99282    }else{
99283      /* A view */
99284      zType = "view";
99285      zType2 = "VIEW";
99286#endif
99287    }
99288
99289    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
99290    ** statement to populate the new table. The root-page number for the
99291    ** new table is in register pParse->regRoot.
99292    **
99293    ** Once the SELECT has been coded by sqlite3Select(), it is in a
99294    ** suitable state to query for the column names and types to be used
99295    ** by the new table.
99296    **
99297    ** A shared-cache write-lock is not required to write to the new table,
99298    ** as a schema-lock must have already been obtained to create it. Since
99299    ** a schema-lock excludes all other database users, the write-lock would
99300    ** be redundant.
99301    */
99302    if( pSelect ){
99303      SelectDest dest;    /* Where the SELECT should store results */
99304      int regYield;       /* Register holding co-routine entry-point */
99305      int addrTop;        /* Top of the co-routine */
99306      int regRec;         /* A record to be insert into the new table */
99307      int regRowid;       /* Rowid of the next row to insert */
99308      int addrInsLoop;    /* Top of the loop for inserting rows */
99309      Table *pSelTab;     /* A table that describes the SELECT results */
99310
99311      regYield = ++pParse->nMem;
99312      regRec = ++pParse->nMem;
99313      regRowid = ++pParse->nMem;
99314      assert(pParse->nTab==1);
99315      sqlite3MayAbort(pParse);
99316      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
99317      sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
99318      pParse->nTab = 2;
99319      addrTop = sqlite3VdbeCurrentAddr(v) + 1;
99320      sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
99321      sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
99322      sqlite3Select(pParse, pSelect, &dest);
99323      sqlite3VdbeEndCoroutine(v, regYield);
99324      sqlite3VdbeJumpHere(v, addrTop - 1);
99325      if( pParse->nErr ) return;
99326      pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
99327      if( pSelTab==0 ) return;
99328      assert( p->aCol==0 );
99329      p->nCol = pSelTab->nCol;
99330      p->aCol = pSelTab->aCol;
99331      pSelTab->nCol = 0;
99332      pSelTab->aCol = 0;
99333      sqlite3DeleteTable(db, pSelTab);
99334      addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
99335      VdbeCoverage(v);
99336      sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
99337      sqlite3TableAffinity(v, p, 0);
99338      sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
99339      sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
99340      sqlite3VdbeGoto(v, addrInsLoop);
99341      sqlite3VdbeJumpHere(v, addrInsLoop);
99342      sqlite3VdbeAddOp1(v, OP_Close, 1);
99343    }
99344
99345    /* Compute the complete text of the CREATE statement */
99346    if( pSelect ){
99347      zStmt = createTableStmt(db, p);
99348    }else{
99349      Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
99350      n = (int)(pEnd2->z - pParse->sNameToken.z);
99351      if( pEnd2->z[0]!=';' ) n += pEnd2->n;
99352      zStmt = sqlite3MPrintf(db,
99353          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
99354      );
99355    }
99356
99357    /* A slot for the record has already been allocated in the
99358    ** SQLITE_MASTER table.  We just need to update that slot with all
99359    ** the information we've collected.
99360    */
99361    sqlite3NestedParse(pParse,
99362      "UPDATE %Q.%s "
99363         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
99364       "WHERE rowid=#%d",
99365      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
99366      zType,
99367      p->zName,
99368      p->zName,
99369      pParse->regRoot,
99370      zStmt,
99371      pParse->regRowid
99372    );
99373    sqlite3DbFree(db, zStmt);
99374    sqlite3ChangeCookie(pParse, iDb);
99375
99376#ifndef SQLITE_OMIT_AUTOINCREMENT
99377    /* Check to see if we need to create an sqlite_sequence table for
99378    ** keeping track of autoincrement keys.
99379    */
99380    if( p->tabFlags & TF_Autoincrement ){
99381      Db *pDb = &db->aDb[iDb];
99382      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99383      if( pDb->pSchema->pSeqTab==0 ){
99384        sqlite3NestedParse(pParse,
99385          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
99386          pDb->zName
99387        );
99388      }
99389    }
99390#endif
99391
99392    /* Reparse everything to update our internal data structures */
99393    sqlite3VdbeAddParseSchemaOp(v, iDb,
99394           sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
99395  }
99396
99397
99398  /* Add the table to the in-memory representation of the database.
99399  */
99400  if( db->init.busy ){
99401    Table *pOld;
99402    Schema *pSchema = p->pSchema;
99403    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99404    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
99405    if( pOld ){
99406      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
99407      sqlite3OomFault(db);
99408      return;
99409    }
99410    pParse->pNewTable = 0;
99411    db->flags |= SQLITE_InternChanges;
99412
99413#ifndef SQLITE_OMIT_ALTERTABLE
99414    if( !p->pSelect ){
99415      const char *zName = (const char *)pParse->sNameToken.z;
99416      int nName;
99417      assert( !pSelect && pCons && pEnd );
99418      if( pCons->z==0 ){
99419        pCons = pEnd;
99420      }
99421      nName = (int)((const char *)pCons->z - zName);
99422      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
99423    }
99424#endif
99425  }
99426}
99427
99428#ifndef SQLITE_OMIT_VIEW
99429/*
99430** The parser calls this routine in order to create a new VIEW
99431*/
99432SQLITE_PRIVATE void sqlite3CreateView(
99433  Parse *pParse,     /* The parsing context */
99434  Token *pBegin,     /* The CREATE token that begins the statement */
99435  Token *pName1,     /* The token that holds the name of the view */
99436  Token *pName2,     /* The token that holds the name of the view */
99437  ExprList *pCNames, /* Optional list of view column names */
99438  Select *pSelect,   /* A SELECT statement that will become the new view */
99439  int isTemp,        /* TRUE for a TEMPORARY view */
99440  int noErr          /* Suppress error messages if VIEW already exists */
99441){
99442  Table *p;
99443  int n;
99444  const char *z;
99445  Token sEnd;
99446  DbFixer sFix;
99447  Token *pName = 0;
99448  int iDb;
99449  sqlite3 *db = pParse->db;
99450
99451  if( pParse->nVar>0 ){
99452    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
99453    goto create_view_fail;
99454  }
99455  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
99456  p = pParse->pNewTable;
99457  if( p==0 || pParse->nErr ) goto create_view_fail;
99458  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
99459  iDb = sqlite3SchemaToIndex(db, p->pSchema);
99460  sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
99461  if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
99462
99463  /* Make a copy of the entire SELECT statement that defines the view.
99464  ** This will force all the Expr.token.z values to be dynamically
99465  ** allocated rather than point to the input string - which means that
99466  ** they will persist after the current sqlite3_exec() call returns.
99467  */
99468  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
99469  p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
99470  if( db->mallocFailed ) goto create_view_fail;
99471
99472  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
99473  ** the end.
99474  */
99475  sEnd = pParse->sLastToken;
99476  assert( sEnd.z[0]!=0 );
99477  if( sEnd.z[0]!=';' ){
99478    sEnd.z += sEnd.n;
99479  }
99480  sEnd.n = 0;
99481  n = (int)(sEnd.z - pBegin->z);
99482  assert( n>0 );
99483  z = pBegin->z;
99484  while( sqlite3Isspace(z[n-1]) ){ n--; }
99485  sEnd.z = &z[n-1];
99486  sEnd.n = 1;
99487
99488  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
99489  sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
99490
99491create_view_fail:
99492  sqlite3SelectDelete(db, pSelect);
99493  sqlite3ExprListDelete(db, pCNames);
99494  return;
99495}
99496#endif /* SQLITE_OMIT_VIEW */
99497
99498#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
99499/*
99500** The Table structure pTable is really a VIEW.  Fill in the names of
99501** the columns of the view in the pTable structure.  Return the number
99502** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
99503*/
99504SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
99505  Table *pSelTab;   /* A fake table from which we get the result set */
99506  Select *pSel;     /* Copy of the SELECT that implements the view */
99507  int nErr = 0;     /* Number of errors encountered */
99508  int n;            /* Temporarily holds the number of cursors assigned */
99509  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
99510  sqlite3_xauth xAuth;       /* Saved xAuth pointer */
99511
99512  assert( pTable );
99513
99514#ifndef SQLITE_OMIT_VIRTUALTABLE
99515  if( sqlite3VtabCallConnect(pParse, pTable) ){
99516    return SQLITE_ERROR;
99517  }
99518  if( IsVirtual(pTable) ) return 0;
99519#endif
99520
99521#ifndef SQLITE_OMIT_VIEW
99522  /* A positive nCol means the columns names for this view are
99523  ** already known.
99524  */
99525  if( pTable->nCol>0 ) return 0;
99526
99527  /* A negative nCol is a special marker meaning that we are currently
99528  ** trying to compute the column names.  If we enter this routine with
99529  ** a negative nCol, it means two or more views form a loop, like this:
99530  **
99531  **     CREATE VIEW one AS SELECT * FROM two;
99532  **     CREATE VIEW two AS SELECT * FROM one;
99533  **
99534  ** Actually, the error above is now caught prior to reaching this point.
99535  ** But the following test is still important as it does come up
99536  ** in the following:
99537  **
99538  **     CREATE TABLE main.ex1(a);
99539  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
99540  **     SELECT * FROM temp.ex1;
99541  */
99542  if( pTable->nCol<0 ){
99543    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
99544    return 1;
99545  }
99546  assert( pTable->nCol>=0 );
99547
99548  /* If we get this far, it means we need to compute the table names.
99549  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
99550  ** "*" elements in the results set of the view and will assign cursors
99551  ** to the elements of the FROM clause.  But we do not want these changes
99552  ** to be permanent.  So the computation is done on a copy of the SELECT
99553  ** statement that defines the view.
99554  */
99555  assert( pTable->pSelect );
99556  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
99557  if( pSel ){
99558    n = pParse->nTab;
99559    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
99560    pTable->nCol = -1;
99561    db->lookaside.bDisable++;
99562#ifndef SQLITE_OMIT_AUTHORIZATION
99563    xAuth = db->xAuth;
99564    db->xAuth = 0;
99565    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
99566    db->xAuth = xAuth;
99567#else
99568    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
99569#endif
99570    pParse->nTab = n;
99571    if( pTable->pCheck ){
99572      /* CREATE VIEW name(arglist) AS ...
99573      ** The names of the columns in the table are taken from
99574      ** arglist which is stored in pTable->pCheck.  The pCheck field
99575      ** normally holds CHECK constraints on an ordinary table, but for
99576      ** a VIEW it holds the list of column names.
99577      */
99578      sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
99579                                 &pTable->nCol, &pTable->aCol);
99580      if( db->mallocFailed==0
99581       && pParse->nErr==0
99582       && pTable->nCol==pSel->pEList->nExpr
99583      ){
99584        sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
99585      }
99586    }else if( pSelTab ){
99587      /* CREATE VIEW name AS...  without an argument list.  Construct
99588      ** the column names from the SELECT statement that defines the view.
99589      */
99590      assert( pTable->aCol==0 );
99591      pTable->nCol = pSelTab->nCol;
99592      pTable->aCol = pSelTab->aCol;
99593      pSelTab->nCol = 0;
99594      pSelTab->aCol = 0;
99595      assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
99596    }else{
99597      pTable->nCol = 0;
99598      nErr++;
99599    }
99600    sqlite3DeleteTable(db, pSelTab);
99601    sqlite3SelectDelete(db, pSel);
99602    db->lookaside.bDisable--;
99603  } else {
99604    nErr++;
99605  }
99606  pTable->pSchema->schemaFlags |= DB_UnresetViews;
99607#endif /* SQLITE_OMIT_VIEW */
99608  return nErr;
99609}
99610#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
99611
99612#ifndef SQLITE_OMIT_VIEW
99613/*
99614** Clear the column names from every VIEW in database idx.
99615*/
99616static void sqliteViewResetAll(sqlite3 *db, int idx){
99617  HashElem *i;
99618  assert( sqlite3SchemaMutexHeld(db, idx, 0) );
99619  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
99620  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
99621    Table *pTab = sqliteHashData(i);
99622    if( pTab->pSelect ){
99623      sqlite3DeleteColumnNames(db, pTab);
99624      pTab->aCol = 0;
99625      pTab->nCol = 0;
99626    }
99627  }
99628  DbClearProperty(db, idx, DB_UnresetViews);
99629}
99630#else
99631# define sqliteViewResetAll(A,B)
99632#endif /* SQLITE_OMIT_VIEW */
99633
99634/*
99635** This function is called by the VDBE to adjust the internal schema
99636** used by SQLite when the btree layer moves a table root page. The
99637** root-page of a table or index in database iDb has changed from iFrom
99638** to iTo.
99639**
99640** Ticket #1728:  The symbol table might still contain information
99641** on tables and/or indices that are the process of being deleted.
99642** If you are unlucky, one of those deleted indices or tables might
99643** have the same rootpage number as the real table or index that is
99644** being moved.  So we cannot stop searching after the first match
99645** because the first match might be for one of the deleted indices
99646** or tables and not the table/index that is actually being moved.
99647** We must continue looping until all tables and indices with
99648** rootpage==iFrom have been converted to have a rootpage of iTo
99649** in order to be certain that we got the right one.
99650*/
99651#ifndef SQLITE_OMIT_AUTOVACUUM
99652SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
99653  HashElem *pElem;
99654  Hash *pHash;
99655  Db *pDb;
99656
99657  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99658  pDb = &db->aDb[iDb];
99659  pHash = &pDb->pSchema->tblHash;
99660  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
99661    Table *pTab = sqliteHashData(pElem);
99662    if( pTab->tnum==iFrom ){
99663      pTab->tnum = iTo;
99664    }
99665  }
99666  pHash = &pDb->pSchema->idxHash;
99667  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
99668    Index *pIdx = sqliteHashData(pElem);
99669    if( pIdx->tnum==iFrom ){
99670      pIdx->tnum = iTo;
99671    }
99672  }
99673}
99674#endif
99675
99676/*
99677** Write code to erase the table with root-page iTable from database iDb.
99678** Also write code to modify the sqlite_master table and internal schema
99679** if a root-page of another table is moved by the btree-layer whilst
99680** erasing iTable (this can happen with an auto-vacuum database).
99681*/
99682static void destroyRootPage(Parse *pParse, int iTable, int iDb){
99683  Vdbe *v = sqlite3GetVdbe(pParse);
99684  int r1 = sqlite3GetTempReg(pParse);
99685  assert( iTable>1 );
99686  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
99687  sqlite3MayAbort(pParse);
99688#ifndef SQLITE_OMIT_AUTOVACUUM
99689  /* OP_Destroy stores an in integer r1. If this integer
99690  ** is non-zero, then it is the root page number of a table moved to
99691  ** location iTable. The following code modifies the sqlite_master table to
99692  ** reflect this.
99693  **
99694  ** The "#NNN" in the SQL is a special constant that means whatever value
99695  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
99696  ** token for additional information.
99697  */
99698  sqlite3NestedParse(pParse,
99699     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
99700     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
99701#endif
99702  sqlite3ReleaseTempReg(pParse, r1);
99703}
99704
99705/*
99706** Write VDBE code to erase table pTab and all associated indices on disk.
99707** Code to update the sqlite_master tables and internal schema definitions
99708** in case a root-page belonging to another table is moved by the btree layer
99709** is also added (this can happen with an auto-vacuum database).
99710*/
99711static void destroyTable(Parse *pParse, Table *pTab){
99712#ifdef SQLITE_OMIT_AUTOVACUUM
99713  Index *pIdx;
99714  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
99715  destroyRootPage(pParse, pTab->tnum, iDb);
99716  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99717    destroyRootPage(pParse, pIdx->tnum, iDb);
99718  }
99719#else
99720  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
99721  ** is not defined), then it is important to call OP_Destroy on the
99722  ** table and index root-pages in order, starting with the numerically
99723  ** largest root-page number. This guarantees that none of the root-pages
99724  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
99725  ** following were coded:
99726  **
99727  ** OP_Destroy 4 0
99728  ** ...
99729  ** OP_Destroy 5 0
99730  **
99731  ** and root page 5 happened to be the largest root-page number in the
99732  ** database, then root page 5 would be moved to page 4 by the
99733  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
99734  ** a free-list page.
99735  */
99736  int iTab = pTab->tnum;
99737  int iDestroyed = 0;
99738
99739  while( 1 ){
99740    Index *pIdx;
99741    int iLargest = 0;
99742
99743    if( iDestroyed==0 || iTab<iDestroyed ){
99744      iLargest = iTab;
99745    }
99746    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99747      int iIdx = pIdx->tnum;
99748      assert( pIdx->pSchema==pTab->pSchema );
99749      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
99750        iLargest = iIdx;
99751      }
99752    }
99753    if( iLargest==0 ){
99754      return;
99755    }else{
99756      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
99757      assert( iDb>=0 && iDb<pParse->db->nDb );
99758      destroyRootPage(pParse, iLargest, iDb);
99759      iDestroyed = iLargest;
99760    }
99761  }
99762#endif
99763}
99764
99765/*
99766** Remove entries from the sqlite_statN tables (for N in (1,2,3))
99767** after a DROP INDEX or DROP TABLE command.
99768*/
99769static void sqlite3ClearStatTables(
99770  Parse *pParse,         /* The parsing context */
99771  int iDb,               /* The database number */
99772  const char *zType,     /* "idx" or "tbl" */
99773  const char *zName      /* Name of index or table */
99774){
99775  int i;
99776  const char *zDbName = pParse->db->aDb[iDb].zName;
99777  for(i=1; i<=4; i++){
99778    char zTab[24];
99779    sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
99780    if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
99781      sqlite3NestedParse(pParse,
99782        "DELETE FROM %Q.%s WHERE %s=%Q",
99783        zDbName, zTab, zType, zName
99784      );
99785    }
99786  }
99787}
99788
99789/*
99790** Generate code to drop a table.
99791*/
99792SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
99793  Vdbe *v;
99794  sqlite3 *db = pParse->db;
99795  Trigger *pTrigger;
99796  Db *pDb = &db->aDb[iDb];
99797
99798  v = sqlite3GetVdbe(pParse);
99799  assert( v!=0 );
99800  sqlite3BeginWriteOperation(pParse, 1, iDb);
99801
99802#ifndef SQLITE_OMIT_VIRTUALTABLE
99803  if( IsVirtual(pTab) ){
99804    sqlite3VdbeAddOp0(v, OP_VBegin);
99805  }
99806#endif
99807
99808  /* Drop all triggers associated with the table being dropped. Code
99809  ** is generated to remove entries from sqlite_master and/or
99810  ** sqlite_temp_master if required.
99811  */
99812  pTrigger = sqlite3TriggerList(pParse, pTab);
99813  while( pTrigger ){
99814    assert( pTrigger->pSchema==pTab->pSchema ||
99815        pTrigger->pSchema==db->aDb[1].pSchema );
99816    sqlite3DropTriggerPtr(pParse, pTrigger);
99817    pTrigger = pTrigger->pNext;
99818  }
99819
99820#ifndef SQLITE_OMIT_AUTOINCREMENT
99821  /* Remove any entries of the sqlite_sequence table associated with
99822  ** the table being dropped. This is done before the table is dropped
99823  ** at the btree level, in case the sqlite_sequence table needs to
99824  ** move as a result of the drop (can happen in auto-vacuum mode).
99825  */
99826  if( pTab->tabFlags & TF_Autoincrement ){
99827    sqlite3NestedParse(pParse,
99828      "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
99829      pDb->zName, pTab->zName
99830    );
99831  }
99832#endif
99833
99834  /* Drop all SQLITE_MASTER table and index entries that refer to the
99835  ** table. The program name loops through the master table and deletes
99836  ** every row that refers to a table of the same name as the one being
99837  ** dropped. Triggers are handled separately because a trigger can be
99838  ** created in the temp database that refers to a table in another
99839  ** database.
99840  */
99841  sqlite3NestedParse(pParse,
99842      "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
99843      pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
99844  if( !isView && !IsVirtual(pTab) ){
99845    destroyTable(pParse, pTab);
99846  }
99847
99848  /* Remove the table entry from SQLite's internal schema and modify
99849  ** the schema cookie.
99850  */
99851  if( IsVirtual(pTab) ){
99852    sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
99853  }
99854  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
99855  sqlite3ChangeCookie(pParse, iDb);
99856  sqliteViewResetAll(db, iDb);
99857}
99858
99859/*
99860** This routine is called to do the work of a DROP TABLE statement.
99861** pName is the name of the table to be dropped.
99862*/
99863SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
99864  Table *pTab;
99865  Vdbe *v;
99866  sqlite3 *db = pParse->db;
99867  int iDb;
99868
99869  if( db->mallocFailed ){
99870    goto exit_drop_table;
99871  }
99872  assert( pParse->nErr==0 );
99873  assert( pName->nSrc==1 );
99874  if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
99875  if( noErr ) db->suppressErr++;
99876  assert( isView==0 || isView==LOCATE_VIEW );
99877  pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
99878  if( noErr ) db->suppressErr--;
99879
99880  if( pTab==0 ){
99881    if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
99882    goto exit_drop_table;
99883  }
99884  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99885  assert( iDb>=0 && iDb<db->nDb );
99886
99887  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
99888  ** it is initialized.
99889  */
99890  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
99891    goto exit_drop_table;
99892  }
99893#ifndef SQLITE_OMIT_AUTHORIZATION
99894  {
99895    int code;
99896    const char *zTab = SCHEMA_TABLE(iDb);
99897    const char *zDb = db->aDb[iDb].zName;
99898    const char *zArg2 = 0;
99899    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
99900      goto exit_drop_table;
99901    }
99902    if( isView ){
99903      if( !OMIT_TEMPDB && iDb==1 ){
99904        code = SQLITE_DROP_TEMP_VIEW;
99905      }else{
99906        code = SQLITE_DROP_VIEW;
99907      }
99908#ifndef SQLITE_OMIT_VIRTUALTABLE
99909    }else if( IsVirtual(pTab) ){
99910      code = SQLITE_DROP_VTABLE;
99911      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
99912#endif
99913    }else{
99914      if( !OMIT_TEMPDB && iDb==1 ){
99915        code = SQLITE_DROP_TEMP_TABLE;
99916      }else{
99917        code = SQLITE_DROP_TABLE;
99918      }
99919    }
99920    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
99921      goto exit_drop_table;
99922    }
99923    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
99924      goto exit_drop_table;
99925    }
99926  }
99927#endif
99928  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
99929    && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
99930    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
99931    goto exit_drop_table;
99932  }
99933
99934#ifndef SQLITE_OMIT_VIEW
99935  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
99936  ** on a table.
99937  */
99938  if( isView && pTab->pSelect==0 ){
99939    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
99940    goto exit_drop_table;
99941  }
99942  if( !isView && pTab->pSelect ){
99943    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
99944    goto exit_drop_table;
99945  }
99946#endif
99947
99948  /* Generate code to remove the table from the master table
99949  ** on disk.
99950  */
99951  v = sqlite3GetVdbe(pParse);
99952  if( v ){
99953    sqlite3BeginWriteOperation(pParse, 1, iDb);
99954    sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
99955    sqlite3FkDropTable(pParse, pName, pTab);
99956    sqlite3CodeDropTable(pParse, pTab, iDb, isView);
99957  }
99958
99959exit_drop_table:
99960  sqlite3SrcListDelete(db, pName);
99961}
99962
99963/*
99964** This routine is called to create a new foreign key on the table
99965** currently under construction.  pFromCol determines which columns
99966** in the current table point to the foreign key.  If pFromCol==0 then
99967** connect the key to the last column inserted.  pTo is the name of
99968** the table referred to (a.k.a the "parent" table).  pToCol is a list
99969** of tables in the parent pTo table.  flags contains all
99970** information about the conflict resolution algorithms specified
99971** in the ON DELETE, ON UPDATE and ON INSERT clauses.
99972**
99973** An FKey structure is created and added to the table currently
99974** under construction in the pParse->pNewTable field.
99975**
99976** The foreign key is set for IMMEDIATE processing.  A subsequent call
99977** to sqlite3DeferForeignKey() might change this to DEFERRED.
99978*/
99979SQLITE_PRIVATE void sqlite3CreateForeignKey(
99980  Parse *pParse,       /* Parsing context */
99981  ExprList *pFromCol,  /* Columns in this table that point to other table */
99982  Token *pTo,          /* Name of the other table */
99983  ExprList *pToCol,    /* Columns in the other table */
99984  int flags            /* Conflict resolution algorithms. */
99985){
99986  sqlite3 *db = pParse->db;
99987#ifndef SQLITE_OMIT_FOREIGN_KEY
99988  FKey *pFKey = 0;
99989  FKey *pNextTo;
99990  Table *p = pParse->pNewTable;
99991  int nByte;
99992  int i;
99993  int nCol;
99994  char *z;
99995
99996  assert( pTo!=0 );
99997  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
99998  if( pFromCol==0 ){
99999    int iCol = p->nCol-1;
100000    if( NEVER(iCol<0) ) goto fk_end;
100001    if( pToCol && pToCol->nExpr!=1 ){
100002      sqlite3ErrorMsg(pParse, "foreign key on %s"
100003         " should reference only one column of table %T",
100004         p->aCol[iCol].zName, pTo);
100005      goto fk_end;
100006    }
100007    nCol = 1;
100008  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
100009    sqlite3ErrorMsg(pParse,
100010        "number of columns in foreign key does not match the number of "
100011        "columns in the referenced table");
100012    goto fk_end;
100013  }else{
100014    nCol = pFromCol->nExpr;
100015  }
100016  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
100017  if( pToCol ){
100018    for(i=0; i<pToCol->nExpr; i++){
100019      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
100020    }
100021  }
100022  pFKey = sqlite3DbMallocZero(db, nByte );
100023  if( pFKey==0 ){
100024    goto fk_end;
100025  }
100026  pFKey->pFrom = p;
100027  pFKey->pNextFrom = p->pFKey;
100028  z = (char*)&pFKey->aCol[nCol];
100029  pFKey->zTo = z;
100030  memcpy(z, pTo->z, pTo->n);
100031  z[pTo->n] = 0;
100032  sqlite3Dequote(z);
100033  z += pTo->n+1;
100034  pFKey->nCol = nCol;
100035  if( pFromCol==0 ){
100036    pFKey->aCol[0].iFrom = p->nCol-1;
100037  }else{
100038    for(i=0; i<nCol; i++){
100039      int j;
100040      for(j=0; j<p->nCol; j++){
100041        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
100042          pFKey->aCol[i].iFrom = j;
100043          break;
100044        }
100045      }
100046      if( j>=p->nCol ){
100047        sqlite3ErrorMsg(pParse,
100048          "unknown column \"%s\" in foreign key definition",
100049          pFromCol->a[i].zName);
100050        goto fk_end;
100051      }
100052    }
100053  }
100054  if( pToCol ){
100055    for(i=0; i<nCol; i++){
100056      int n = sqlite3Strlen30(pToCol->a[i].zName);
100057      pFKey->aCol[i].zCol = z;
100058      memcpy(z, pToCol->a[i].zName, n);
100059      z[n] = 0;
100060      z += n+1;
100061    }
100062  }
100063  pFKey->isDeferred = 0;
100064  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
100065  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
100066
100067  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
100068  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
100069      pFKey->zTo, (void *)pFKey
100070  );
100071  if( pNextTo==pFKey ){
100072    sqlite3OomFault(db);
100073    goto fk_end;
100074  }
100075  if( pNextTo ){
100076    assert( pNextTo->pPrevTo==0 );
100077    pFKey->pNextTo = pNextTo;
100078    pNextTo->pPrevTo = pFKey;
100079  }
100080
100081  /* Link the foreign key to the table as the last step.
100082  */
100083  p->pFKey = pFKey;
100084  pFKey = 0;
100085
100086fk_end:
100087  sqlite3DbFree(db, pFKey);
100088#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
100089  sqlite3ExprListDelete(db, pFromCol);
100090  sqlite3ExprListDelete(db, pToCol);
100091}
100092
100093/*
100094** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
100095** clause is seen as part of a foreign key definition.  The isDeferred
100096** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
100097** The behavior of the most recently created foreign key is adjusted
100098** accordingly.
100099*/
100100SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
100101#ifndef SQLITE_OMIT_FOREIGN_KEY
100102  Table *pTab;
100103  FKey *pFKey;
100104  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
100105  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
100106  pFKey->isDeferred = (u8)isDeferred;
100107#endif
100108}
100109
100110/*
100111** Generate code that will erase and refill index *pIdx.  This is
100112** used to initialize a newly created index or to recompute the
100113** content of an index in response to a REINDEX command.
100114**
100115** if memRootPage is not negative, it means that the index is newly
100116** created.  The register specified by memRootPage contains the
100117** root page number of the index.  If memRootPage is negative, then
100118** the index already exists and must be cleared before being refilled and
100119** the root page number of the index is taken from pIndex->tnum.
100120*/
100121static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
100122  Table *pTab = pIndex->pTable;  /* The table that is indexed */
100123  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
100124  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
100125  int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
100126  int addr1;                     /* Address of top of loop */
100127  int addr2;                     /* Address to jump to for next iteration */
100128  int tnum;                      /* Root page of index */
100129  int iPartIdxLabel;             /* Jump to this label to skip a row */
100130  Vdbe *v;                       /* Generate code into this virtual machine */
100131  KeyInfo *pKey;                 /* KeyInfo for index */
100132  int regRecord;                 /* Register holding assembled index record */
100133  sqlite3 *db = pParse->db;      /* The database connection */
100134  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
100135
100136#ifndef SQLITE_OMIT_AUTHORIZATION
100137  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
100138      db->aDb[iDb].zName ) ){
100139    return;
100140  }
100141#endif
100142
100143  /* Require a write-lock on the table to perform this operation */
100144  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
100145
100146  v = sqlite3GetVdbe(pParse);
100147  if( v==0 ) return;
100148  if( memRootPage>=0 ){
100149    tnum = memRootPage;
100150  }else{
100151    tnum = pIndex->tnum;
100152  }
100153  pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
100154  assert( pKey!=0 || db->mallocFailed || pParse->nErr );
100155
100156  /* Open the sorter cursor if we are to use one. */
100157  iSorter = pParse->nTab++;
100158  sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
100159                    sqlite3KeyInfoRef(pKey), P4_KEYINFO);
100160
100161  /* Open the table. Loop through all rows of the table, inserting index
100162  ** records into the sorter. */
100163  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
100164  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
100165  regRecord = sqlite3GetTempReg(pParse);
100166
100167  sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
100168  sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
100169  sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
100170  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
100171  sqlite3VdbeJumpHere(v, addr1);
100172  if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
100173  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
100174                    (char *)pKey, P4_KEYINFO);
100175  sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
100176
100177  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
100178  if( IsUniqueIndex(pIndex) ){
100179    int j2 = sqlite3VdbeCurrentAddr(v) + 3;
100180    sqlite3VdbeGoto(v, j2);
100181    addr2 = sqlite3VdbeCurrentAddr(v);
100182    sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
100183                         pIndex->nKeyCol); VdbeCoverage(v);
100184    sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
100185  }else{
100186    addr2 = sqlite3VdbeCurrentAddr(v);
100187  }
100188  sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
100189  sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
100190  sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
100191  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
100192  sqlite3ReleaseTempReg(pParse, regRecord);
100193  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
100194  sqlite3VdbeJumpHere(v, addr1);
100195
100196  sqlite3VdbeAddOp1(v, OP_Close, iTab);
100197  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
100198  sqlite3VdbeAddOp1(v, OP_Close, iSorter);
100199}
100200
100201/*
100202** Allocate heap space to hold an Index object with nCol columns.
100203**
100204** Increase the allocation size to provide an extra nExtra bytes
100205** of 8-byte aligned space after the Index object and return a
100206** pointer to this extra space in *ppExtra.
100207*/
100208SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
100209  sqlite3 *db,         /* Database connection */
100210  i16 nCol,            /* Total number of columns in the index */
100211  int nExtra,          /* Number of bytes of extra space to alloc */
100212  char **ppExtra       /* Pointer to the "extra" space */
100213){
100214  Index *p;            /* Allocated index object */
100215  int nByte;           /* Bytes of space for Index object + arrays */
100216
100217  nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
100218          ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
100219          ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
100220                 sizeof(i16)*nCol +            /* Index.aiColumn   */
100221                 sizeof(u8)*nCol);             /* Index.aSortOrder */
100222  p = sqlite3DbMallocZero(db, nByte + nExtra);
100223  if( p ){
100224    char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
100225    p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
100226    p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
100227    p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
100228    p->aSortOrder = (u8*)pExtra;
100229    p->nColumn = nCol;
100230    p->nKeyCol = nCol - 1;
100231    *ppExtra = ((char*)p) + nByte;
100232  }
100233  return p;
100234}
100235
100236/*
100237** Create a new index for an SQL table.  pName1.pName2 is the name of the index
100238** and pTblList is the name of the table that is to be indexed.  Both will
100239** be NULL for a primary key or an index that is created to satisfy a
100240** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
100241** as the table to be indexed.  pParse->pNewTable is a table that is
100242** currently being constructed by a CREATE TABLE statement.
100243**
100244** pList is a list of columns to be indexed.  pList will be NULL if this
100245** is a primary key or unique-constraint on the most recent column added
100246** to the table currently under construction.
100247*/
100248SQLITE_PRIVATE void sqlite3CreateIndex(
100249  Parse *pParse,     /* All information about this parse */
100250  Token *pName1,     /* First part of index name. May be NULL */
100251  Token *pName2,     /* Second part of index name. May be NULL */
100252  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
100253  ExprList *pList,   /* A list of columns to be indexed */
100254  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
100255  Token *pStart,     /* The CREATE token that begins this statement */
100256  Expr *pPIWhere,    /* WHERE clause for partial indices */
100257  int sortOrder,     /* Sort order of primary key when pList==NULL */
100258  int ifNotExist,    /* Omit error if index already exists */
100259  u8 idxType         /* The index type */
100260){
100261  Table *pTab = 0;     /* Table to be indexed */
100262  Index *pIndex = 0;   /* The index to be created */
100263  char *zName = 0;     /* Name of the index */
100264  int nName;           /* Number of characters in zName */
100265  int i, j;
100266  DbFixer sFix;        /* For assigning database names to pTable */
100267  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
100268  sqlite3 *db = pParse->db;
100269  Db *pDb;             /* The specific table containing the indexed database */
100270  int iDb;             /* Index of the database that is being written */
100271  Token *pName = 0;    /* Unqualified name of the index to create */
100272  struct ExprList_item *pListItem; /* For looping over pList */
100273  int nExtra = 0;                  /* Space allocated for zExtra[] */
100274  int nExtraCol;                   /* Number of extra columns needed */
100275  char *zExtra = 0;                /* Extra space after the Index object */
100276  Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
100277
100278  if( db->mallocFailed || pParse->nErr>0 ){
100279    goto exit_create_index;
100280  }
100281  if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
100282    goto exit_create_index;
100283  }
100284  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
100285    goto exit_create_index;
100286  }
100287
100288  /*
100289  ** Find the table that is to be indexed.  Return early if not found.
100290  */
100291  if( pTblName!=0 ){
100292
100293    /* Use the two-part index name to determine the database
100294    ** to search for the table. 'Fix' the table name to this db
100295    ** before looking up the table.
100296    */
100297    assert( pName1 && pName2 );
100298    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
100299    if( iDb<0 ) goto exit_create_index;
100300    assert( pName && pName->z );
100301
100302#ifndef SQLITE_OMIT_TEMPDB
100303    /* If the index name was unqualified, check if the table
100304    ** is a temp table. If so, set the database to 1. Do not do this
100305    ** if initialising a database schema.
100306    */
100307    if( !db->init.busy ){
100308      pTab = sqlite3SrcListLookup(pParse, pTblName);
100309      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
100310        iDb = 1;
100311      }
100312    }
100313#endif
100314
100315    sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
100316    if( sqlite3FixSrcList(&sFix, pTblName) ){
100317      /* Because the parser constructs pTblName from a single identifier,
100318      ** sqlite3FixSrcList can never fail. */
100319      assert(0);
100320    }
100321    pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
100322    assert( db->mallocFailed==0 || pTab==0 );
100323    if( pTab==0 ) goto exit_create_index;
100324    if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
100325      sqlite3ErrorMsg(pParse,
100326           "cannot create a TEMP index on non-TEMP table \"%s\"",
100327           pTab->zName);
100328      goto exit_create_index;
100329    }
100330    if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
100331  }else{
100332    assert( pName==0 );
100333    assert( pStart==0 );
100334    pTab = pParse->pNewTable;
100335    if( !pTab ) goto exit_create_index;
100336    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
100337  }
100338  pDb = &db->aDb[iDb];
100339
100340  assert( pTab!=0 );
100341  assert( pParse->nErr==0 );
100342  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
100343       && db->init.busy==0
100344#if SQLITE_USER_AUTHENTICATION
100345       && sqlite3UserAuthTable(pTab->zName)==0
100346#endif
100347       && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
100348    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
100349    goto exit_create_index;
100350  }
100351#ifndef SQLITE_OMIT_VIEW
100352  if( pTab->pSelect ){
100353    sqlite3ErrorMsg(pParse, "views may not be indexed");
100354    goto exit_create_index;
100355  }
100356#endif
100357#ifndef SQLITE_OMIT_VIRTUALTABLE
100358  if( IsVirtual(pTab) ){
100359    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
100360    goto exit_create_index;
100361  }
100362#endif
100363
100364  /*
100365  ** Find the name of the index.  Make sure there is not already another
100366  ** index or table with the same name.
100367  **
100368  ** Exception:  If we are reading the names of permanent indices from the
100369  ** sqlite_master table (because some other process changed the schema) and
100370  ** one of the index names collides with the name of a temporary table or
100371  ** index, then we will continue to process this index.
100372  **
100373  ** If pName==0 it means that we are
100374  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
100375  ** own name.
100376  */
100377  if( pName ){
100378    zName = sqlite3NameFromToken(db, pName);
100379    if( zName==0 ) goto exit_create_index;
100380    assert( pName->z!=0 );
100381    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
100382      goto exit_create_index;
100383    }
100384    if( !db->init.busy ){
100385      if( sqlite3FindTable(db, zName, 0)!=0 ){
100386        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
100387        goto exit_create_index;
100388      }
100389    }
100390    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
100391      if( !ifNotExist ){
100392        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
100393      }else{
100394        assert( !db->init.busy );
100395        sqlite3CodeVerifySchema(pParse, iDb);
100396      }
100397      goto exit_create_index;
100398    }
100399  }else{
100400    int n;
100401    Index *pLoop;
100402    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
100403    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
100404    if( zName==0 ){
100405      goto exit_create_index;
100406    }
100407
100408    /* Automatic index names generated from within sqlite3_declare_vtab()
100409    ** must have names that are distinct from normal automatic index names.
100410    ** The following statement converts "sqlite3_autoindex..." into
100411    ** "sqlite3_butoindex..." in order to make the names distinct.
100412    ** The "vtab_err.test" test demonstrates the need of this statement. */
100413    if( IN_DECLARE_VTAB ) zName[7]++;
100414  }
100415
100416  /* Check for authorization to create an index.
100417  */
100418#ifndef SQLITE_OMIT_AUTHORIZATION
100419  {
100420    const char *zDb = pDb->zName;
100421    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
100422      goto exit_create_index;
100423    }
100424    i = SQLITE_CREATE_INDEX;
100425    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
100426    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
100427      goto exit_create_index;
100428    }
100429  }
100430#endif
100431
100432  /* If pList==0, it means this routine was called to make a primary
100433  ** key out of the last column added to the table under construction.
100434  ** So create a fake list to simulate this.
100435  */
100436  if( pList==0 ){
100437    Token prevCol;
100438    sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName);
100439    pList = sqlite3ExprListAppend(pParse, 0,
100440              sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
100441    if( pList==0 ) goto exit_create_index;
100442    assert( pList->nExpr==1 );
100443    sqlite3ExprListSetSortOrder(pList, sortOrder);
100444  }else{
100445    sqlite3ExprListCheckLength(pParse, pList, "index");
100446  }
100447
100448  /* Figure out how many bytes of space are required to store explicitly
100449  ** specified collation sequence names.
100450  */
100451  for(i=0; i<pList->nExpr; i++){
100452    Expr *pExpr = pList->a[i].pExpr;
100453    assert( pExpr!=0 );
100454    if( pExpr->op==TK_COLLATE ){
100455      nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
100456    }
100457  }
100458
100459  /*
100460  ** Allocate the index structure.
100461  */
100462  nName = sqlite3Strlen30(zName);
100463  nExtraCol = pPk ? pPk->nKeyCol : 1;
100464  pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
100465                                      nName + nExtra + 1, &zExtra);
100466  if( db->mallocFailed ){
100467    goto exit_create_index;
100468  }
100469  assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
100470  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
100471  pIndex->zName = zExtra;
100472  zExtra += nName + 1;
100473  memcpy(pIndex->zName, zName, nName+1);
100474  pIndex->pTable = pTab;
100475  pIndex->onError = (u8)onError;
100476  pIndex->uniqNotNull = onError!=OE_None;
100477  pIndex->idxType = idxType;
100478  pIndex->pSchema = db->aDb[iDb].pSchema;
100479  pIndex->nKeyCol = pList->nExpr;
100480  if( pPIWhere ){
100481    sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
100482    pIndex->pPartIdxWhere = pPIWhere;
100483    pPIWhere = 0;
100484  }
100485  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100486
100487  /* Check to see if we should honor DESC requests on index columns
100488  */
100489  if( pDb->pSchema->file_format>=4 ){
100490    sortOrderMask = -1;   /* Honor DESC */
100491  }else{
100492    sortOrderMask = 0;    /* Ignore DESC */
100493  }
100494
100495  /* Analyze the list of expressions that form the terms of the index and
100496  ** report any errors.  In the common case where the expression is exactly
100497  ** a table column, store that column in aiColumn[].  For general expressions,
100498  ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
100499  **
100500  ** TODO: Issue a warning if two or more columns of the index are identical.
100501  ** TODO: Issue a warning if the table primary key is used as part of the
100502  ** index key.
100503  */
100504  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
100505    Expr *pCExpr;                  /* The i-th index expression */
100506    int requestedSortOrder;        /* ASC or DESC on the i-th expression */
100507    const char *zColl;             /* Collation sequence name */
100508
100509    sqlite3StringToId(pListItem->pExpr);
100510    sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
100511    if( pParse->nErr ) goto exit_create_index;
100512    pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
100513    if( pCExpr->op!=TK_COLUMN ){
100514      if( pTab==pParse->pNewTable ){
100515        sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
100516                                "UNIQUE constraints");
100517        goto exit_create_index;
100518      }
100519      if( pIndex->aColExpr==0 ){
100520        ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
100521        pIndex->aColExpr = pCopy;
100522        if( !db->mallocFailed ){
100523          assert( pCopy!=0 );
100524          pListItem = &pCopy->a[i];
100525        }
100526      }
100527      j = XN_EXPR;
100528      pIndex->aiColumn[i] = XN_EXPR;
100529      pIndex->uniqNotNull = 0;
100530    }else{
100531      j = pCExpr->iColumn;
100532      assert( j<=0x7fff );
100533      if( j<0 ){
100534        j = pTab->iPKey;
100535      }else if( pTab->aCol[j].notNull==0 ){
100536        pIndex->uniqNotNull = 0;
100537      }
100538      pIndex->aiColumn[i] = (i16)j;
100539    }
100540    zColl = 0;
100541    if( pListItem->pExpr->op==TK_COLLATE ){
100542      int nColl;
100543      zColl = pListItem->pExpr->u.zToken;
100544      nColl = sqlite3Strlen30(zColl) + 1;
100545      assert( nExtra>=nColl );
100546      memcpy(zExtra, zColl, nColl);
100547      zColl = zExtra;
100548      zExtra += nColl;
100549      nExtra -= nColl;
100550    }else if( j>=0 ){
100551      zColl = pTab->aCol[j].zColl;
100552    }
100553    if( !zColl ) zColl = sqlite3StrBINARY;
100554    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
100555      goto exit_create_index;
100556    }
100557    pIndex->azColl[i] = zColl;
100558    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
100559    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
100560  }
100561
100562  /* Append the table key to the end of the index.  For WITHOUT ROWID
100563  ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For
100564  ** normal tables (when pPk==0) this will be the rowid.
100565  */
100566  if( pPk ){
100567    for(j=0; j<pPk->nKeyCol; j++){
100568      int x = pPk->aiColumn[j];
100569      assert( x>=0 );
100570      if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
100571        pIndex->nColumn--;
100572      }else{
100573        pIndex->aiColumn[i] = x;
100574        pIndex->azColl[i] = pPk->azColl[j];
100575        pIndex->aSortOrder[i] = pPk->aSortOrder[j];
100576        i++;
100577      }
100578    }
100579    assert( i==pIndex->nColumn );
100580  }else{
100581    pIndex->aiColumn[i] = XN_ROWID;
100582    pIndex->azColl[i] = sqlite3StrBINARY;
100583  }
100584  sqlite3DefaultRowEst(pIndex);
100585  if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
100586
100587  /* If this index contains every column of its table, then mark
100588  ** it as a covering index */
100589  assert( HasRowid(pTab)
100590      || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
100591  if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
100592    pIndex->isCovering = 1;
100593    for(j=0; j<pTab->nCol; j++){
100594      if( j==pTab->iPKey ) continue;
100595      if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
100596      pIndex->isCovering = 0;
100597      break;
100598    }
100599  }
100600
100601  if( pTab==pParse->pNewTable ){
100602    /* This routine has been called to create an automatic index as a
100603    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
100604    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
100605    ** i.e. one of:
100606    **
100607    ** CREATE TABLE t(x PRIMARY KEY, y);
100608    ** CREATE TABLE t(x, y, UNIQUE(x, y));
100609    **
100610    ** Either way, check to see if the table already has such an index. If
100611    ** so, don't bother creating this one. This only applies to
100612    ** automatically created indices. Users can do as they wish with
100613    ** explicit indices.
100614    **
100615    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
100616    ** (and thus suppressing the second one) even if they have different
100617    ** sort orders.
100618    **
100619    ** If there are different collating sequences or if the columns of
100620    ** the constraint occur in different orders, then the constraints are
100621    ** considered distinct and both result in separate indices.
100622    */
100623    Index *pIdx;
100624    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100625      int k;
100626      assert( IsUniqueIndex(pIdx) );
100627      assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
100628      assert( IsUniqueIndex(pIndex) );
100629
100630      if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
100631      for(k=0; k<pIdx->nKeyCol; k++){
100632        const char *z1;
100633        const char *z2;
100634        assert( pIdx->aiColumn[k]>=0 );
100635        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
100636        z1 = pIdx->azColl[k];
100637        z2 = pIndex->azColl[k];
100638        if( sqlite3StrICmp(z1, z2) ) break;
100639      }
100640      if( k==pIdx->nKeyCol ){
100641        if( pIdx->onError!=pIndex->onError ){
100642          /* This constraint creates the same index as a previous
100643          ** constraint specified somewhere in the CREATE TABLE statement.
100644          ** However the ON CONFLICT clauses are different. If both this
100645          ** constraint and the previous equivalent constraint have explicit
100646          ** ON CONFLICT clauses this is an error. Otherwise, use the
100647          ** explicitly specified behavior for the index.
100648          */
100649          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
100650            sqlite3ErrorMsg(pParse,
100651                "conflicting ON CONFLICT clauses specified", 0);
100652          }
100653          if( pIdx->onError==OE_Default ){
100654            pIdx->onError = pIndex->onError;
100655          }
100656        }
100657        if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
100658        goto exit_create_index;
100659      }
100660    }
100661  }
100662
100663  /* Link the new Index structure to its table and to the other
100664  ** in-memory database structures.
100665  */
100666  assert( pParse->nErr==0 );
100667  if( db->init.busy ){
100668    Index *p;
100669    assert( !IN_DECLARE_VTAB );
100670    assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
100671    p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
100672                          pIndex->zName, pIndex);
100673    if( p ){
100674      assert( p==pIndex );  /* Malloc must have failed */
100675      sqlite3OomFault(db);
100676      goto exit_create_index;
100677    }
100678    db->flags |= SQLITE_InternChanges;
100679    if( pTblName!=0 ){
100680      pIndex->tnum = db->init.newTnum;
100681    }
100682  }
100683
100684  /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
100685  ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
100686  ** emit code to allocate the index rootpage on disk and make an entry for
100687  ** the index in the sqlite_master table and populate the index with
100688  ** content.  But, do not do this if we are simply reading the sqlite_master
100689  ** table to parse the schema, or if this index is the PRIMARY KEY index
100690  ** of a WITHOUT ROWID table.
100691  **
100692  ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
100693  ** or UNIQUE index in a CREATE TABLE statement.  Since the table
100694  ** has just been created, it contains no data and the index initialization
100695  ** step can be skipped.
100696  */
100697  else if( HasRowid(pTab) || pTblName!=0 ){
100698    Vdbe *v;
100699    char *zStmt;
100700    int iMem = ++pParse->nMem;
100701
100702    v = sqlite3GetVdbe(pParse);
100703    if( v==0 ) goto exit_create_index;
100704
100705    sqlite3BeginWriteOperation(pParse, 1, iDb);
100706
100707    /* Create the rootpage for the index using CreateIndex. But before
100708    ** doing so, code a Noop instruction and store its address in
100709    ** Index.tnum. This is required in case this index is actually a
100710    ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
100711    ** that case the convertToWithoutRowidTable() routine will replace
100712    ** the Noop with a Goto to jump over the VDBE code generated below. */
100713    pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
100714    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
100715
100716    /* Gather the complete text of the CREATE INDEX statement into
100717    ** the zStmt variable
100718    */
100719    if( pStart ){
100720      int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
100721      if( pName->z[n-1]==';' ) n--;
100722      /* A named index with an explicit CREATE INDEX statement */
100723      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
100724        onError==OE_None ? "" : " UNIQUE", n, pName->z);
100725    }else{
100726      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
100727      /* zStmt = sqlite3MPrintf(""); */
100728      zStmt = 0;
100729    }
100730
100731    /* Add an entry in sqlite_master for this index
100732    */
100733    sqlite3NestedParse(pParse,
100734        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
100735        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
100736        pIndex->zName,
100737        pTab->zName,
100738        iMem,
100739        zStmt
100740    );
100741    sqlite3DbFree(db, zStmt);
100742
100743    /* Fill the index with data and reparse the schema. Code an OP_Expire
100744    ** to invalidate all pre-compiled statements.
100745    */
100746    if( pTblName ){
100747      sqlite3RefillIndex(pParse, pIndex, iMem);
100748      sqlite3ChangeCookie(pParse, iDb);
100749      sqlite3VdbeAddParseSchemaOp(v, iDb,
100750         sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
100751      sqlite3VdbeAddOp0(v, OP_Expire);
100752    }
100753
100754    sqlite3VdbeJumpHere(v, pIndex->tnum);
100755  }
100756
100757  /* When adding an index to the list of indices for a table, make
100758  ** sure all indices labeled OE_Replace come after all those labeled
100759  ** OE_Ignore.  This is necessary for the correct constraint check
100760  ** processing (in sqlite3GenerateConstraintChecks()) as part of
100761  ** UPDATE and INSERT statements.
100762  */
100763  if( db->init.busy || pTblName==0 ){
100764    if( onError!=OE_Replace || pTab->pIndex==0
100765         || pTab->pIndex->onError==OE_Replace){
100766      pIndex->pNext = pTab->pIndex;
100767      pTab->pIndex = pIndex;
100768    }else{
100769      Index *pOther = pTab->pIndex;
100770      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
100771        pOther = pOther->pNext;
100772      }
100773      pIndex->pNext = pOther->pNext;
100774      pOther->pNext = pIndex;
100775    }
100776    pIndex = 0;
100777  }
100778
100779  /* Clean up before exiting */
100780exit_create_index:
100781  if( pIndex ) freeIndex(db, pIndex);
100782  sqlite3ExprDelete(db, pPIWhere);
100783  sqlite3ExprListDelete(db, pList);
100784  sqlite3SrcListDelete(db, pTblName);
100785  sqlite3DbFree(db, zName);
100786}
100787
100788/*
100789** Fill the Index.aiRowEst[] array with default information - information
100790** to be used when we have not run the ANALYZE command.
100791**
100792** aiRowEst[0] is supposed to contain the number of elements in the index.
100793** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
100794** number of rows in the table that match any particular value of the
100795** first column of the index.  aiRowEst[2] is an estimate of the number
100796** of rows that match any particular combination of the first 2 columns
100797** of the index.  And so forth.  It must always be the case that
100798*
100799**           aiRowEst[N]<=aiRowEst[N-1]
100800**           aiRowEst[N]>=1
100801**
100802** Apart from that, we have little to go on besides intuition as to
100803** how aiRowEst[] should be initialized.  The numbers generated here
100804** are based on typical values found in actual indices.
100805*/
100806SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
100807  /*                10,  9,  8,  7,  6 */
100808  LogEst aVal[] = { 33, 32, 30, 28, 26 };
100809  LogEst *a = pIdx->aiRowLogEst;
100810  int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
100811  int i;
100812
100813  /* Set the first entry (number of rows in the index) to the estimated
100814  ** number of rows in the table, or half the number of rows in the table
100815  ** for a partial index.   But do not let the estimate drop below 10. */
100816  a[0] = pIdx->pTable->nRowLogEst;
100817  if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10;  assert( 10==sqlite3LogEst(2) );
100818  if( a[0]<33 ) a[0] = 33;                  assert( 33==sqlite3LogEst(10) );
100819
100820  /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
100821  ** 6 and each subsequent value (if any) is 5.  */
100822  memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
100823  for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
100824    a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
100825  }
100826
100827  assert( 0==sqlite3LogEst(1) );
100828  if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
100829}
100830
100831/*
100832** This routine will drop an existing named index.  This routine
100833** implements the DROP INDEX statement.
100834*/
100835SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
100836  Index *pIndex;
100837  Vdbe *v;
100838  sqlite3 *db = pParse->db;
100839  int iDb;
100840
100841  assert( pParse->nErr==0 );   /* Never called with prior errors */
100842  if( db->mallocFailed ){
100843    goto exit_drop_index;
100844  }
100845  assert( pName->nSrc==1 );
100846  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
100847    goto exit_drop_index;
100848  }
100849  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
100850  if( pIndex==0 ){
100851    if( !ifExists ){
100852      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
100853    }else{
100854      sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
100855    }
100856    pParse->checkSchema = 1;
100857    goto exit_drop_index;
100858  }
100859  if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
100860    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
100861      "or PRIMARY KEY constraint cannot be dropped", 0);
100862    goto exit_drop_index;
100863  }
100864  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
100865#ifndef SQLITE_OMIT_AUTHORIZATION
100866  {
100867    int code = SQLITE_DROP_INDEX;
100868    Table *pTab = pIndex->pTable;
100869    const char *zDb = db->aDb[iDb].zName;
100870    const char *zTab = SCHEMA_TABLE(iDb);
100871    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
100872      goto exit_drop_index;
100873    }
100874    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
100875    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
100876      goto exit_drop_index;
100877    }
100878  }
100879#endif
100880
100881  /* Generate code to remove the index and from the master table */
100882  v = sqlite3GetVdbe(pParse);
100883  if( v ){
100884    sqlite3BeginWriteOperation(pParse, 1, iDb);
100885    sqlite3NestedParse(pParse,
100886       "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
100887       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
100888    );
100889    sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
100890    sqlite3ChangeCookie(pParse, iDb);
100891    destroyRootPage(pParse, pIndex->tnum, iDb);
100892    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
100893  }
100894
100895exit_drop_index:
100896  sqlite3SrcListDelete(db, pName);
100897}
100898
100899/*
100900** pArray is a pointer to an array of objects. Each object in the
100901** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
100902** to extend the array so that there is space for a new object at the end.
100903**
100904** When this function is called, *pnEntry contains the current size of
100905** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
100906** in total).
100907**
100908** If the realloc() is successful (i.e. if no OOM condition occurs), the
100909** space allocated for the new object is zeroed, *pnEntry updated to
100910** reflect the new size of the array and a pointer to the new allocation
100911** returned. *pIdx is set to the index of the new array entry in this case.
100912**
100913** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
100914** unchanged and a copy of pArray returned.
100915*/
100916SQLITE_PRIVATE void *sqlite3ArrayAllocate(
100917  sqlite3 *db,      /* Connection to notify of malloc failures */
100918  void *pArray,     /* Array of objects.  Might be reallocated */
100919  int szEntry,      /* Size of each object in the array */
100920  int *pnEntry,     /* Number of objects currently in use */
100921  int *pIdx         /* Write the index of a new slot here */
100922){
100923  char *z;
100924  int n = *pnEntry;
100925  if( (n & (n-1))==0 ){
100926    int sz = (n==0) ? 1 : 2*n;
100927    void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
100928    if( pNew==0 ){
100929      *pIdx = -1;
100930      return pArray;
100931    }
100932    pArray = pNew;
100933  }
100934  z = (char*)pArray;
100935  memset(&z[n * szEntry], 0, szEntry);
100936  *pIdx = n;
100937  ++*pnEntry;
100938  return pArray;
100939}
100940
100941/*
100942** Append a new element to the given IdList.  Create a new IdList if
100943** need be.
100944**
100945** A new IdList is returned, or NULL if malloc() fails.
100946*/
100947SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
100948  int i;
100949  if( pList==0 ){
100950    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
100951    if( pList==0 ) return 0;
100952  }
100953  pList->a = sqlite3ArrayAllocate(
100954      db,
100955      pList->a,
100956      sizeof(pList->a[0]),
100957      &pList->nId,
100958      &i
100959  );
100960  if( i<0 ){
100961    sqlite3IdListDelete(db, pList);
100962    return 0;
100963  }
100964  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
100965  return pList;
100966}
100967
100968/*
100969** Delete an IdList.
100970*/
100971SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
100972  int i;
100973  if( pList==0 ) return;
100974  for(i=0; i<pList->nId; i++){
100975    sqlite3DbFree(db, pList->a[i].zName);
100976  }
100977  sqlite3DbFree(db, pList->a);
100978  sqlite3DbFree(db, pList);
100979}
100980
100981/*
100982** Return the index in pList of the identifier named zId.  Return -1
100983** if not found.
100984*/
100985SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
100986  int i;
100987  if( pList==0 ) return -1;
100988  for(i=0; i<pList->nId; i++){
100989    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
100990  }
100991  return -1;
100992}
100993
100994/*
100995** Expand the space allocated for the given SrcList object by
100996** creating nExtra new slots beginning at iStart.  iStart is zero based.
100997** New slots are zeroed.
100998**
100999** For example, suppose a SrcList initially contains two entries: A,B.
101000** To append 3 new entries onto the end, do this:
101001**
101002**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
101003**
101004** After the call above it would contain:  A, B, nil, nil, nil.
101005** If the iStart argument had been 1 instead of 2, then the result
101006** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
101007** the iStart value would be 0.  The result then would
101008** be: nil, nil, nil, A, B.
101009**
101010** If a memory allocation fails the SrcList is unchanged.  The
101011** db->mallocFailed flag will be set to true.
101012*/
101013SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
101014  sqlite3 *db,       /* Database connection to notify of OOM errors */
101015  SrcList *pSrc,     /* The SrcList to be enlarged */
101016  int nExtra,        /* Number of new slots to add to pSrc->a[] */
101017  int iStart         /* Index in pSrc->a[] of first new slot */
101018){
101019  int i;
101020
101021  /* Sanity checking on calling parameters */
101022  assert( iStart>=0 );
101023  assert( nExtra>=1 );
101024  assert( pSrc!=0 );
101025  assert( iStart<=pSrc->nSrc );
101026
101027  /* Allocate additional space if needed */
101028  if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
101029    SrcList *pNew;
101030    int nAlloc = pSrc->nSrc+nExtra;
101031    int nGot;
101032    pNew = sqlite3DbRealloc(db, pSrc,
101033               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
101034    if( pNew==0 ){
101035      assert( db->mallocFailed );
101036      return pSrc;
101037    }
101038    pSrc = pNew;
101039    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
101040    pSrc->nAlloc = nGot;
101041  }
101042
101043  /* Move existing slots that come after the newly inserted slots
101044  ** out of the way */
101045  for(i=pSrc->nSrc-1; i>=iStart; i--){
101046    pSrc->a[i+nExtra] = pSrc->a[i];
101047  }
101048  pSrc->nSrc += nExtra;
101049
101050  /* Zero the newly allocated slots */
101051  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
101052  for(i=iStart; i<iStart+nExtra; i++){
101053    pSrc->a[i].iCursor = -1;
101054  }
101055
101056  /* Return a pointer to the enlarged SrcList */
101057  return pSrc;
101058}
101059
101060
101061/*
101062** Append a new table name to the given SrcList.  Create a new SrcList if
101063** need be.  A new entry is created in the SrcList even if pTable is NULL.
101064**
101065** A SrcList is returned, or NULL if there is an OOM error.  The returned
101066** SrcList might be the same as the SrcList that was input or it might be
101067** a new one.  If an OOM error does occurs, then the prior value of pList
101068** that is input to this routine is automatically freed.
101069**
101070** If pDatabase is not null, it means that the table has an optional
101071** database name prefix.  Like this:  "database.table".  The pDatabase
101072** points to the table name and the pTable points to the database name.
101073** The SrcList.a[].zName field is filled with the table name which might
101074** come from pTable (if pDatabase is NULL) or from pDatabase.
101075** SrcList.a[].zDatabase is filled with the database name from pTable,
101076** or with NULL if no database is specified.
101077**
101078** In other words, if call like this:
101079**
101080**         sqlite3SrcListAppend(D,A,B,0);
101081**
101082** Then B is a table name and the database name is unspecified.  If called
101083** like this:
101084**
101085**         sqlite3SrcListAppend(D,A,B,C);
101086**
101087** Then C is the table name and B is the database name.  If C is defined
101088** then so is B.  In other words, we never have a case where:
101089**
101090**         sqlite3SrcListAppend(D,A,0,C);
101091**
101092** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
101093** before being added to the SrcList.
101094*/
101095SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
101096  sqlite3 *db,        /* Connection to notify of malloc failures */
101097  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
101098  Token *pTable,      /* Table to append */
101099  Token *pDatabase    /* Database of the table */
101100){
101101  struct SrcList_item *pItem;
101102  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
101103  assert( db!=0 );
101104  if( pList==0 ){
101105    pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
101106    if( pList==0 ) return 0;
101107    pList->nAlloc = 1;
101108    pList->nSrc = 0;
101109  }
101110  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
101111  if( db->mallocFailed ){
101112    sqlite3SrcListDelete(db, pList);
101113    return 0;
101114  }
101115  pItem = &pList->a[pList->nSrc-1];
101116  if( pDatabase && pDatabase->z==0 ){
101117    pDatabase = 0;
101118  }
101119  if( pDatabase ){
101120    Token *pTemp = pDatabase;
101121    pDatabase = pTable;
101122    pTable = pTemp;
101123  }
101124  pItem->zName = sqlite3NameFromToken(db, pTable);
101125  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
101126  return pList;
101127}
101128
101129/*
101130** Assign VdbeCursor index numbers to all tables in a SrcList
101131*/
101132SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
101133  int i;
101134  struct SrcList_item *pItem;
101135  assert(pList || pParse->db->mallocFailed );
101136  if( pList ){
101137    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
101138      if( pItem->iCursor>=0 ) break;
101139      pItem->iCursor = pParse->nTab++;
101140      if( pItem->pSelect ){
101141        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
101142      }
101143    }
101144  }
101145}
101146
101147/*
101148** Delete an entire SrcList including all its substructure.
101149*/
101150SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
101151  int i;
101152  struct SrcList_item *pItem;
101153  if( pList==0 ) return;
101154  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
101155    sqlite3DbFree(db, pItem->zDatabase);
101156    sqlite3DbFree(db, pItem->zName);
101157    sqlite3DbFree(db, pItem->zAlias);
101158    if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
101159    if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
101160    sqlite3DeleteTable(db, pItem->pTab);
101161    sqlite3SelectDelete(db, pItem->pSelect);
101162    sqlite3ExprDelete(db, pItem->pOn);
101163    sqlite3IdListDelete(db, pItem->pUsing);
101164  }
101165  sqlite3DbFree(db, pList);
101166}
101167
101168/*
101169** This routine is called by the parser to add a new term to the
101170** end of a growing FROM clause.  The "p" parameter is the part of
101171** the FROM clause that has already been constructed.  "p" is NULL
101172** if this is the first term of the FROM clause.  pTable and pDatabase
101173** are the name of the table and database named in the FROM clause term.
101174** pDatabase is NULL if the database name qualifier is missing - the
101175** usual case.  If the term has an alias, then pAlias points to the
101176** alias token.  If the term is a subquery, then pSubquery is the
101177** SELECT statement that the subquery encodes.  The pTable and
101178** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
101179** parameters are the content of the ON and USING clauses.
101180**
101181** Return a new SrcList which encodes is the FROM with the new
101182** term added.
101183*/
101184SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
101185  Parse *pParse,          /* Parsing context */
101186  SrcList *p,             /* The left part of the FROM clause already seen */
101187  Token *pTable,          /* Name of the table to add to the FROM clause */
101188  Token *pDatabase,       /* Name of the database containing pTable */
101189  Token *pAlias,          /* The right-hand side of the AS subexpression */
101190  Select *pSubquery,      /* A subquery used in place of a table name */
101191  Expr *pOn,              /* The ON clause of a join */
101192  IdList *pUsing          /* The USING clause of a join */
101193){
101194  struct SrcList_item *pItem;
101195  sqlite3 *db = pParse->db;
101196  if( !p && (pOn || pUsing) ){
101197    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
101198      (pOn ? "ON" : "USING")
101199    );
101200    goto append_from_error;
101201  }
101202  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
101203  if( p==0 || NEVER(p->nSrc==0) ){
101204    goto append_from_error;
101205  }
101206  pItem = &p->a[p->nSrc-1];
101207  assert( pAlias!=0 );
101208  if( pAlias->n ){
101209    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
101210  }
101211  pItem->pSelect = pSubquery;
101212  pItem->pOn = pOn;
101213  pItem->pUsing = pUsing;
101214  return p;
101215
101216 append_from_error:
101217  assert( p==0 );
101218  sqlite3ExprDelete(db, pOn);
101219  sqlite3IdListDelete(db, pUsing);
101220  sqlite3SelectDelete(db, pSubquery);
101221  return 0;
101222}
101223
101224/*
101225** Add an INDEXED BY or NOT INDEXED clause to the most recently added
101226** element of the source-list passed as the second argument.
101227*/
101228SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
101229  assert( pIndexedBy!=0 );
101230  if( p && ALWAYS(p->nSrc>0) ){
101231    struct SrcList_item *pItem = &p->a[p->nSrc-1];
101232    assert( pItem->fg.notIndexed==0 );
101233    assert( pItem->fg.isIndexedBy==0 );
101234    assert( pItem->fg.isTabFunc==0 );
101235    if( pIndexedBy->n==1 && !pIndexedBy->z ){
101236      /* A "NOT INDEXED" clause was supplied. See parse.y
101237      ** construct "indexed_opt" for details. */
101238      pItem->fg.notIndexed = 1;
101239    }else{
101240      pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
101241      pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
101242    }
101243  }
101244}
101245
101246/*
101247** Add the list of function arguments to the SrcList entry for a
101248** table-valued-function.
101249*/
101250SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
101251  if( p ){
101252    struct SrcList_item *pItem = &p->a[p->nSrc-1];
101253    assert( pItem->fg.notIndexed==0 );
101254    assert( pItem->fg.isIndexedBy==0 );
101255    assert( pItem->fg.isTabFunc==0 );
101256    pItem->u1.pFuncArg = pList;
101257    pItem->fg.isTabFunc = 1;
101258  }else{
101259    sqlite3ExprListDelete(pParse->db, pList);
101260  }
101261}
101262
101263/*
101264** When building up a FROM clause in the parser, the join operator
101265** is initially attached to the left operand.  But the code generator
101266** expects the join operator to be on the right operand.  This routine
101267** Shifts all join operators from left to right for an entire FROM
101268** clause.
101269**
101270** Example: Suppose the join is like this:
101271**
101272**           A natural cross join B
101273**
101274** The operator is "natural cross join".  The A and B operands are stored
101275** in p->a[0] and p->a[1], respectively.  The parser initially stores the
101276** operator with A.  This routine shifts that operator over to B.
101277*/
101278SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
101279  if( p ){
101280    int i;
101281    for(i=p->nSrc-1; i>0; i--){
101282      p->a[i].fg.jointype = p->a[i-1].fg.jointype;
101283    }
101284    p->a[0].fg.jointype = 0;
101285  }
101286}
101287
101288/*
101289** Generate VDBE code for a BEGIN statement.
101290*/
101291SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
101292  sqlite3 *db;
101293  Vdbe *v;
101294  int i;
101295
101296  assert( pParse!=0 );
101297  db = pParse->db;
101298  assert( db!=0 );
101299  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
101300    return;
101301  }
101302  v = sqlite3GetVdbe(pParse);
101303  if( !v ) return;
101304  if( type!=TK_DEFERRED ){
101305    for(i=0; i<db->nDb; i++){
101306      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
101307      sqlite3VdbeUsesBtree(v, i);
101308    }
101309  }
101310  sqlite3VdbeAddOp0(v, OP_AutoCommit);
101311}
101312
101313/*
101314** Generate VDBE code for a COMMIT statement.
101315*/
101316SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
101317  Vdbe *v;
101318
101319  assert( pParse!=0 );
101320  assert( pParse->db!=0 );
101321  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
101322    return;
101323  }
101324  v = sqlite3GetVdbe(pParse);
101325  if( v ){
101326    sqlite3VdbeAddOp1(v, OP_AutoCommit, 1);
101327  }
101328}
101329
101330/*
101331** Generate VDBE code for a ROLLBACK statement.
101332*/
101333SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
101334  Vdbe *v;
101335
101336  assert( pParse!=0 );
101337  assert( pParse->db!=0 );
101338  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
101339    return;
101340  }
101341  v = sqlite3GetVdbe(pParse);
101342  if( v ){
101343    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
101344  }
101345}
101346
101347/*
101348** This function is called by the parser when it parses a command to create,
101349** release or rollback an SQL savepoint.
101350*/
101351SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
101352  char *zName = sqlite3NameFromToken(pParse->db, pName);
101353  if( zName ){
101354    Vdbe *v = sqlite3GetVdbe(pParse);
101355#ifndef SQLITE_OMIT_AUTHORIZATION
101356    static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
101357    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
101358#endif
101359    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
101360      sqlite3DbFree(pParse->db, zName);
101361      return;
101362    }
101363    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
101364  }
101365}
101366
101367/*
101368** Make sure the TEMP database is open and available for use.  Return
101369** the number of errors.  Leave any error messages in the pParse structure.
101370*/
101371SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
101372  sqlite3 *db = pParse->db;
101373  if( db->aDb[1].pBt==0 && !pParse->explain ){
101374    int rc;
101375    Btree *pBt;
101376    static const int flags =
101377          SQLITE_OPEN_READWRITE |
101378          SQLITE_OPEN_CREATE |
101379          SQLITE_OPEN_EXCLUSIVE |
101380          SQLITE_OPEN_DELETEONCLOSE |
101381          SQLITE_OPEN_TEMP_DB;
101382
101383    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
101384    if( rc!=SQLITE_OK ){
101385      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
101386        "file for storing temporary tables");
101387      pParse->rc = rc;
101388      return 1;
101389    }
101390    db->aDb[1].pBt = pBt;
101391    assert( db->aDb[1].pSchema );
101392    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
101393      sqlite3OomFault(db);
101394      return 1;
101395    }
101396  }
101397  return 0;
101398}
101399
101400/*
101401** Record the fact that the schema cookie will need to be verified
101402** for database iDb.  The code to actually verify the schema cookie
101403** will occur at the end of the top-level VDBE and will be generated
101404** later, by sqlite3FinishCoding().
101405*/
101406SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
101407  Parse *pToplevel = sqlite3ParseToplevel(pParse);
101408  sqlite3 *db = pToplevel->db;
101409
101410  assert( iDb>=0 && iDb<db->nDb );
101411  assert( db->aDb[iDb].pBt!=0 || iDb==1 );
101412  assert( iDb<SQLITE_MAX_ATTACHED+2 );
101413  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101414  if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
101415    DbMaskSet(pToplevel->cookieMask, iDb);
101416    pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
101417    if( !OMIT_TEMPDB && iDb==1 ){
101418      sqlite3OpenTempDatabase(pToplevel);
101419    }
101420  }
101421}
101422
101423/*
101424** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
101425** attached database. Otherwise, invoke it for the database named zDb only.
101426*/
101427SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
101428  sqlite3 *db = pParse->db;
101429  int i;
101430  for(i=0; i<db->nDb; i++){
101431    Db *pDb = &db->aDb[i];
101432    if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
101433      sqlite3CodeVerifySchema(pParse, i);
101434    }
101435  }
101436}
101437
101438/*
101439** Generate VDBE code that prepares for doing an operation that
101440** might change the database.
101441**
101442** This routine starts a new transaction if we are not already within
101443** a transaction.  If we are already within a transaction, then a checkpoint
101444** is set if the setStatement parameter is true.  A checkpoint should
101445** be set for operations that might fail (due to a constraint) part of
101446** the way through and which will need to undo some writes without having to
101447** rollback the whole transaction.  For operations where all constraints
101448** can be checked before any changes are made to the database, it is never
101449** necessary to undo a write and the checkpoint should not be set.
101450*/
101451SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
101452  Parse *pToplevel = sqlite3ParseToplevel(pParse);
101453  sqlite3CodeVerifySchema(pParse, iDb);
101454  DbMaskSet(pToplevel->writeMask, iDb);
101455  pToplevel->isMultiWrite |= setStatement;
101456}
101457
101458/*
101459** Indicate that the statement currently under construction might write
101460** more than one entry (example: deleting one row then inserting another,
101461** inserting multiple rows in a table, or inserting a row and index entries.)
101462** If an abort occurs after some of these writes have completed, then it will
101463** be necessary to undo the completed writes.
101464*/
101465SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
101466  Parse *pToplevel = sqlite3ParseToplevel(pParse);
101467  pToplevel->isMultiWrite = 1;
101468}
101469
101470/*
101471** The code generator calls this routine if is discovers that it is
101472** possible to abort a statement prior to completion.  In order to
101473** perform this abort without corrupting the database, we need to make
101474** sure that the statement is protected by a statement transaction.
101475**
101476** Technically, we only need to set the mayAbort flag if the
101477** isMultiWrite flag was previously set.  There is a time dependency
101478** such that the abort must occur after the multiwrite.  This makes
101479** some statements involving the REPLACE conflict resolution algorithm
101480** go a little faster.  But taking advantage of this time dependency
101481** makes it more difficult to prove that the code is correct (in
101482** particular, it prevents us from writing an effective
101483** implementation of sqlite3AssertMayAbort()) and so we have chosen
101484** to take the safe route and skip the optimization.
101485*/
101486SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
101487  Parse *pToplevel = sqlite3ParseToplevel(pParse);
101488  pToplevel->mayAbort = 1;
101489}
101490
101491/*
101492** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
101493** error. The onError parameter determines which (if any) of the statement
101494** and/or current transaction is rolled back.
101495*/
101496SQLITE_PRIVATE void sqlite3HaltConstraint(
101497  Parse *pParse,    /* Parsing context */
101498  int errCode,      /* extended error code */
101499  int onError,      /* Constraint type */
101500  char *p4,         /* Error message */
101501  i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
101502  u8 p5Errmsg       /* P5_ErrMsg type */
101503){
101504  Vdbe *v = sqlite3GetVdbe(pParse);
101505  assert( (errCode&0xff)==SQLITE_CONSTRAINT );
101506  if( onError==OE_Abort ){
101507    sqlite3MayAbort(pParse);
101508  }
101509  sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
101510  sqlite3VdbeChangeP5(v, p5Errmsg);
101511}
101512
101513/*
101514** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
101515*/
101516SQLITE_PRIVATE void sqlite3UniqueConstraint(
101517  Parse *pParse,    /* Parsing context */
101518  int onError,      /* Constraint type */
101519  Index *pIdx       /* The index that triggers the constraint */
101520){
101521  char *zErr;
101522  int j;
101523  StrAccum errMsg;
101524  Table *pTab = pIdx->pTable;
101525
101526  sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
101527  if( pIdx->aColExpr ){
101528    sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName);
101529  }else{
101530    for(j=0; j<pIdx->nKeyCol; j++){
101531      char *zCol;
101532      assert( pIdx->aiColumn[j]>=0 );
101533      zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
101534      if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
101535      sqlite3XPrintf(&errMsg, "%s.%s", pTab->zName, zCol);
101536    }
101537  }
101538  zErr = sqlite3StrAccumFinish(&errMsg);
101539  sqlite3HaltConstraint(pParse,
101540    IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
101541                            : SQLITE_CONSTRAINT_UNIQUE,
101542    onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
101543}
101544
101545
101546/*
101547** Code an OP_Halt due to non-unique rowid.
101548*/
101549SQLITE_PRIVATE void sqlite3RowidConstraint(
101550  Parse *pParse,    /* Parsing context */
101551  int onError,      /* Conflict resolution algorithm */
101552  Table *pTab       /* The table with the non-unique rowid */
101553){
101554  char *zMsg;
101555  int rc;
101556  if( pTab->iPKey>=0 ){
101557    zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
101558                          pTab->aCol[pTab->iPKey].zName);
101559    rc = SQLITE_CONSTRAINT_PRIMARYKEY;
101560  }else{
101561    zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
101562    rc = SQLITE_CONSTRAINT_ROWID;
101563  }
101564  sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
101565                        P5_ConstraintUnique);
101566}
101567
101568/*
101569** Check to see if pIndex uses the collating sequence pColl.  Return
101570** true if it does and false if it does not.
101571*/
101572#ifndef SQLITE_OMIT_REINDEX
101573static int collationMatch(const char *zColl, Index *pIndex){
101574  int i;
101575  assert( zColl!=0 );
101576  for(i=0; i<pIndex->nColumn; i++){
101577    const char *z = pIndex->azColl[i];
101578    assert( z!=0 || pIndex->aiColumn[i]<0 );
101579    if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
101580      return 1;
101581    }
101582  }
101583  return 0;
101584}
101585#endif
101586
101587/*
101588** Recompute all indices of pTab that use the collating sequence pColl.
101589** If pColl==0 then recompute all indices of pTab.
101590*/
101591#ifndef SQLITE_OMIT_REINDEX
101592static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
101593  Index *pIndex;              /* An index associated with pTab */
101594
101595  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
101596    if( zColl==0 || collationMatch(zColl, pIndex) ){
101597      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
101598      sqlite3BeginWriteOperation(pParse, 0, iDb);
101599      sqlite3RefillIndex(pParse, pIndex, -1);
101600    }
101601  }
101602}
101603#endif
101604
101605/*
101606** Recompute all indices of all tables in all databases where the
101607** indices use the collating sequence pColl.  If pColl==0 then recompute
101608** all indices everywhere.
101609*/
101610#ifndef SQLITE_OMIT_REINDEX
101611static void reindexDatabases(Parse *pParse, char const *zColl){
101612  Db *pDb;                    /* A single database */
101613  int iDb;                    /* The database index number */
101614  sqlite3 *db = pParse->db;   /* The database connection */
101615  HashElem *k;                /* For looping over tables in pDb */
101616  Table *pTab;                /* A table in the database */
101617
101618  assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
101619  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
101620    assert( pDb!=0 );
101621    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
101622      pTab = (Table*)sqliteHashData(k);
101623      reindexTable(pParse, pTab, zColl);
101624    }
101625  }
101626}
101627#endif
101628
101629/*
101630** Generate code for the REINDEX command.
101631**
101632**        REINDEX                            -- 1
101633**        REINDEX  <collation>               -- 2
101634**        REINDEX  ?<database>.?<tablename>  -- 3
101635**        REINDEX  ?<database>.?<indexname>  -- 4
101636**
101637** Form 1 causes all indices in all attached databases to be rebuilt.
101638** Form 2 rebuilds all indices in all databases that use the named
101639** collating function.  Forms 3 and 4 rebuild the named index or all
101640** indices associated with the named table.
101641*/
101642#ifndef SQLITE_OMIT_REINDEX
101643SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
101644  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
101645  char *z;                    /* Name of a table or index */
101646  const char *zDb;            /* Name of the database */
101647  Table *pTab;                /* A table in the database */
101648  Index *pIndex;              /* An index associated with pTab */
101649  int iDb;                    /* The database index number */
101650  sqlite3 *db = pParse->db;   /* The database connection */
101651  Token *pObjName;            /* Name of the table or index to be reindexed */
101652
101653  /* Read the database schema. If an error occurs, leave an error message
101654  ** and code in pParse and return NULL. */
101655  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
101656    return;
101657  }
101658
101659  if( pName1==0 ){
101660    reindexDatabases(pParse, 0);
101661    return;
101662  }else if( NEVER(pName2==0) || pName2->z==0 ){
101663    char *zColl;
101664    assert( pName1->z );
101665    zColl = sqlite3NameFromToken(pParse->db, pName1);
101666    if( !zColl ) return;
101667    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
101668    if( pColl ){
101669      reindexDatabases(pParse, zColl);
101670      sqlite3DbFree(db, zColl);
101671      return;
101672    }
101673    sqlite3DbFree(db, zColl);
101674  }
101675  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
101676  if( iDb<0 ) return;
101677  z = sqlite3NameFromToken(db, pObjName);
101678  if( z==0 ) return;
101679  zDb = db->aDb[iDb].zName;
101680  pTab = sqlite3FindTable(db, z, zDb);
101681  if( pTab ){
101682    reindexTable(pParse, pTab, 0);
101683    sqlite3DbFree(db, z);
101684    return;
101685  }
101686  pIndex = sqlite3FindIndex(db, z, zDb);
101687  sqlite3DbFree(db, z);
101688  if( pIndex ){
101689    sqlite3BeginWriteOperation(pParse, 0, iDb);
101690    sqlite3RefillIndex(pParse, pIndex, -1);
101691    return;
101692  }
101693  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
101694}
101695#endif
101696
101697/*
101698** Return a KeyInfo structure that is appropriate for the given Index.
101699**
101700** The caller should invoke sqlite3KeyInfoUnref() on the returned object
101701** when it has finished using it.
101702*/
101703SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
101704  int i;
101705  int nCol = pIdx->nColumn;
101706  int nKey = pIdx->nKeyCol;
101707  KeyInfo *pKey;
101708  if( pParse->nErr ) return 0;
101709  if( pIdx->uniqNotNull ){
101710    pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
101711  }else{
101712    pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
101713  }
101714  if( pKey ){
101715    assert( sqlite3KeyInfoIsWriteable(pKey) );
101716    for(i=0; i<nCol; i++){
101717      const char *zColl = pIdx->azColl[i];
101718      pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
101719                        sqlite3LocateCollSeq(pParse, zColl);
101720      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
101721    }
101722    if( pParse->nErr ){
101723      sqlite3KeyInfoUnref(pKey);
101724      pKey = 0;
101725    }
101726  }
101727  return pKey;
101728}
101729
101730#ifndef SQLITE_OMIT_CTE
101731/*
101732** This routine is invoked once per CTE by the parser while parsing a
101733** WITH clause.
101734*/
101735SQLITE_PRIVATE With *sqlite3WithAdd(
101736  Parse *pParse,          /* Parsing context */
101737  With *pWith,            /* Existing WITH clause, or NULL */
101738  Token *pName,           /* Name of the common-table */
101739  ExprList *pArglist,     /* Optional column name list for the table */
101740  Select *pQuery          /* Query used to initialize the table */
101741){
101742  sqlite3 *db = pParse->db;
101743  With *pNew;
101744  char *zName;
101745
101746  /* Check that the CTE name is unique within this WITH clause. If
101747  ** not, store an error in the Parse structure. */
101748  zName = sqlite3NameFromToken(pParse->db, pName);
101749  if( zName && pWith ){
101750    int i;
101751    for(i=0; i<pWith->nCte; i++){
101752      if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
101753        sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
101754      }
101755    }
101756  }
101757
101758  if( pWith ){
101759    int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
101760    pNew = sqlite3DbRealloc(db, pWith, nByte);
101761  }else{
101762    pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
101763  }
101764  assert( (pNew!=0 && zName!=0) || db->mallocFailed );
101765
101766  if( db->mallocFailed ){
101767    sqlite3ExprListDelete(db, pArglist);
101768    sqlite3SelectDelete(db, pQuery);
101769    sqlite3DbFree(db, zName);
101770    pNew = pWith;
101771  }else{
101772    pNew->a[pNew->nCte].pSelect = pQuery;
101773    pNew->a[pNew->nCte].pCols = pArglist;
101774    pNew->a[pNew->nCte].zName = zName;
101775    pNew->a[pNew->nCte].zCteErr = 0;
101776    pNew->nCte++;
101777  }
101778
101779  return pNew;
101780}
101781
101782/*
101783** Free the contents of the With object passed as the second argument.
101784*/
101785SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
101786  if( pWith ){
101787    int i;
101788    for(i=0; i<pWith->nCte; i++){
101789      struct Cte *pCte = &pWith->a[i];
101790      sqlite3ExprListDelete(db, pCte->pCols);
101791      sqlite3SelectDelete(db, pCte->pSelect);
101792      sqlite3DbFree(db, pCte->zName);
101793    }
101794    sqlite3DbFree(db, pWith);
101795  }
101796}
101797#endif /* !defined(SQLITE_OMIT_CTE) */
101798
101799/************** End of build.c ***********************************************/
101800/************** Begin file callback.c ****************************************/
101801/*
101802** 2005 May 23
101803**
101804** The author disclaims copyright to this source code.  In place of
101805** a legal notice, here is a blessing:
101806**
101807**    May you do good and not evil.
101808**    May you find forgiveness for yourself and forgive others.
101809**    May you share freely, never taking more than you give.
101810**
101811*************************************************************************
101812**
101813** This file contains functions used to access the internal hash tables
101814** of user defined functions and collation sequences.
101815*/
101816
101817/* #include "sqliteInt.h" */
101818
101819/*
101820** Invoke the 'collation needed' callback to request a collation sequence
101821** in the encoding enc of name zName, length nName.
101822*/
101823static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
101824  assert( !db->xCollNeeded || !db->xCollNeeded16 );
101825  if( db->xCollNeeded ){
101826    char *zExternal = sqlite3DbStrDup(db, zName);
101827    if( !zExternal ) return;
101828    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
101829    sqlite3DbFree(db, zExternal);
101830  }
101831#ifndef SQLITE_OMIT_UTF16
101832  if( db->xCollNeeded16 ){
101833    char const *zExternal;
101834    sqlite3_value *pTmp = sqlite3ValueNew(db);
101835    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
101836    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
101837    if( zExternal ){
101838      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
101839    }
101840    sqlite3ValueFree(pTmp);
101841  }
101842#endif
101843}
101844
101845/*
101846** This routine is called if the collation factory fails to deliver a
101847** collation function in the best encoding but there may be other versions
101848** of this collation function (for other text encodings) available. Use one
101849** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
101850** possible.
101851*/
101852static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
101853  CollSeq *pColl2;
101854  char *z = pColl->zName;
101855  int i;
101856  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
101857  for(i=0; i<3; i++){
101858    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
101859    if( pColl2->xCmp!=0 ){
101860      memcpy(pColl, pColl2, sizeof(CollSeq));
101861      pColl->xDel = 0;         /* Do not copy the destructor */
101862      return SQLITE_OK;
101863    }
101864  }
101865  return SQLITE_ERROR;
101866}
101867
101868/*
101869** This function is responsible for invoking the collation factory callback
101870** or substituting a collation sequence of a different encoding when the
101871** requested collation sequence is not available in the desired encoding.
101872**
101873** If it is not NULL, then pColl must point to the database native encoding
101874** collation sequence with name zName, length nName.
101875**
101876** The return value is either the collation sequence to be used in database
101877** db for collation type name zName, length nName, or NULL, if no collation
101878** sequence can be found.  If no collation is found, leave an error message.
101879**
101880** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
101881*/
101882SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
101883  Parse *pParse,        /* Parsing context */
101884  u8 enc,               /* The desired encoding for the collating sequence */
101885  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
101886  const char *zName     /* Collating sequence name */
101887){
101888  CollSeq *p;
101889  sqlite3 *db = pParse->db;
101890
101891  p = pColl;
101892  if( !p ){
101893    p = sqlite3FindCollSeq(db, enc, zName, 0);
101894  }
101895  if( !p || !p->xCmp ){
101896    /* No collation sequence of this type for this encoding is registered.
101897    ** Call the collation factory to see if it can supply us with one.
101898    */
101899    callCollNeeded(db, enc, zName);
101900    p = sqlite3FindCollSeq(db, enc, zName, 0);
101901  }
101902  if( p && !p->xCmp && synthCollSeq(db, p) ){
101903    p = 0;
101904  }
101905  assert( !p || p->xCmp );
101906  if( p==0 ){
101907    sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
101908  }
101909  return p;
101910}
101911
101912/*
101913** This routine is called on a collation sequence before it is used to
101914** check that it is defined. An undefined collation sequence exists when
101915** a database is loaded that contains references to collation sequences
101916** that have not been defined by sqlite3_create_collation() etc.
101917**
101918** If required, this routine calls the 'collation needed' callback to
101919** request a definition of the collating sequence. If this doesn't work,
101920** an equivalent collating sequence that uses a text encoding different
101921** from the main database is substituted, if one is available.
101922*/
101923SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
101924  if( pColl ){
101925    const char *zName = pColl->zName;
101926    sqlite3 *db = pParse->db;
101927    CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
101928    if( !p ){
101929      return SQLITE_ERROR;
101930    }
101931    assert( p==pColl );
101932  }
101933  return SQLITE_OK;
101934}
101935
101936
101937
101938/*
101939** Locate and return an entry from the db.aCollSeq hash table. If the entry
101940** specified by zName and nName is not found and parameter 'create' is
101941** true, then create a new entry. Otherwise return NULL.
101942**
101943** Each pointer stored in the sqlite3.aCollSeq hash table contains an
101944** array of three CollSeq structures. The first is the collation sequence
101945** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
101946**
101947** Stored immediately after the three collation sequences is a copy of
101948** the collation sequence name. A pointer to this string is stored in
101949** each collation sequence structure.
101950*/
101951static CollSeq *findCollSeqEntry(
101952  sqlite3 *db,          /* Database connection */
101953  const char *zName,    /* Name of the collating sequence */
101954  int create            /* Create a new entry if true */
101955){
101956  CollSeq *pColl;
101957  pColl = sqlite3HashFind(&db->aCollSeq, zName);
101958
101959  if( 0==pColl && create ){
101960    int nName = sqlite3Strlen30(zName);
101961    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
101962    if( pColl ){
101963      CollSeq *pDel = 0;
101964      pColl[0].zName = (char*)&pColl[3];
101965      pColl[0].enc = SQLITE_UTF8;
101966      pColl[1].zName = (char*)&pColl[3];
101967      pColl[1].enc = SQLITE_UTF16LE;
101968      pColl[2].zName = (char*)&pColl[3];
101969      pColl[2].enc = SQLITE_UTF16BE;
101970      memcpy(pColl[0].zName, zName, nName);
101971      pColl[0].zName[nName] = 0;
101972      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
101973
101974      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
101975      ** return the pColl pointer to be deleted (because it wasn't added
101976      ** to the hash table).
101977      */
101978      assert( pDel==0 || pDel==pColl );
101979      if( pDel!=0 ){
101980        sqlite3OomFault(db);
101981        sqlite3DbFree(db, pDel);
101982        pColl = 0;
101983      }
101984    }
101985  }
101986  return pColl;
101987}
101988
101989/*
101990** Parameter zName points to a UTF-8 encoded string nName bytes long.
101991** Return the CollSeq* pointer for the collation sequence named zName
101992** for the encoding 'enc' from the database 'db'.
101993**
101994** If the entry specified is not found and 'create' is true, then create a
101995** new entry.  Otherwise return NULL.
101996**
101997** A separate function sqlite3LocateCollSeq() is a wrapper around
101998** this routine.  sqlite3LocateCollSeq() invokes the collation factory
101999** if necessary and generates an error message if the collating sequence
102000** cannot be found.
102001**
102002** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
102003*/
102004SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
102005  sqlite3 *db,
102006  u8 enc,
102007  const char *zName,
102008  int create
102009){
102010  CollSeq *pColl;
102011  if( zName ){
102012    pColl = findCollSeqEntry(db, zName, create);
102013  }else{
102014    pColl = db->pDfltColl;
102015  }
102016  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
102017  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
102018  if( pColl ) pColl += enc-1;
102019  return pColl;
102020}
102021
102022/* During the search for the best function definition, this procedure
102023** is called to test how well the function passed as the first argument
102024** matches the request for a function with nArg arguments in a system
102025** that uses encoding enc. The value returned indicates how well the
102026** request is matched. A higher value indicates a better match.
102027**
102028** If nArg is -1 that means to only return a match (non-zero) if p->nArg
102029** is also -1.  In other words, we are searching for a function that
102030** takes a variable number of arguments.
102031**
102032** If nArg is -2 that means that we are searching for any function
102033** regardless of the number of arguments it uses, so return a positive
102034** match score for any
102035**
102036** The returned value is always between 0 and 6, as follows:
102037**
102038** 0: Not a match.
102039** 1: UTF8/16 conversion required and function takes any number of arguments.
102040** 2: UTF16 byte order change required and function takes any number of args.
102041** 3: encoding matches and function takes any number of arguments
102042** 4: UTF8/16 conversion required - argument count matches exactly
102043** 5: UTF16 byte order conversion required - argument count matches exactly
102044** 6: Perfect match:  encoding and argument count match exactly.
102045**
102046** If nArg==(-2) then any function with a non-null xSFunc is
102047** a perfect match and any function with xSFunc NULL is
102048** a non-match.
102049*/
102050#define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
102051static int matchQuality(
102052  FuncDef *p,     /* The function we are evaluating for match quality */
102053  int nArg,       /* Desired number of arguments.  (-1)==any */
102054  u8 enc          /* Desired text encoding */
102055){
102056  int match;
102057
102058  /* nArg of -2 is a special case */
102059  if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
102060
102061  /* Wrong number of arguments means "no match" */
102062  if( p->nArg!=nArg && p->nArg>=0 ) return 0;
102063
102064  /* Give a better score to a function with a specific number of arguments
102065  ** than to function that accepts any number of arguments. */
102066  if( p->nArg==nArg ){
102067    match = 4;
102068  }else{
102069    match = 1;
102070  }
102071
102072  /* Bonus points if the text encoding matches */
102073  if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
102074    match += 2;  /* Exact encoding match */
102075  }else if( (enc & p->funcFlags & 2)!=0 ){
102076    match += 1;  /* Both are UTF16, but with different byte orders */
102077  }
102078
102079  return match;
102080}
102081
102082/*
102083** Search a FuncDefHash for a function with the given name.  Return
102084** a pointer to the matching FuncDef if found, or 0 if there is no match.
102085*/
102086static FuncDef *functionSearch(
102087  int h,               /* Hash of the name */
102088  const char *zFunc    /* Name of function */
102089){
102090  FuncDef *p;
102091  for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
102092    if( sqlite3StrICmp(p->zName, zFunc)==0 ){
102093      return p;
102094    }
102095  }
102096  return 0;
102097}
102098
102099/*
102100** Insert a new FuncDef into a FuncDefHash hash table.
102101*/
102102SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
102103  FuncDef *aDef,      /* List of global functions to be inserted */
102104  int nDef            /* Length of the apDef[] list */
102105){
102106  int i;
102107  for(i=0; i<nDef; i++){
102108    FuncDef *pOther;
102109    const char *zName = aDef[i].zName;
102110    int nName = sqlite3Strlen30(zName);
102111    int h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
102112    pOther = functionSearch(h, zName);
102113    if( pOther ){
102114      assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
102115      aDef[i].pNext = pOther->pNext;
102116      pOther->pNext = &aDef[i];
102117    }else{
102118      aDef[i].pNext = 0;
102119      aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
102120      sqlite3BuiltinFunctions.a[h] = &aDef[i];
102121    }
102122  }
102123}
102124
102125
102126
102127/*
102128** Locate a user function given a name, a number of arguments and a flag
102129** indicating whether the function prefers UTF-16 over UTF-8.  Return a
102130** pointer to the FuncDef structure that defines that function, or return
102131** NULL if the function does not exist.
102132**
102133** If the createFlag argument is true, then a new (blank) FuncDef
102134** structure is created and liked into the "db" structure if a
102135** no matching function previously existed.
102136**
102137** If nArg is -2, then the first valid function found is returned.  A
102138** function is valid if xSFunc is non-zero.  The nArg==(-2)
102139** case is used to see if zName is a valid function name for some number
102140** of arguments.  If nArg is -2, then createFlag must be 0.
102141**
102142** If createFlag is false, then a function with the required name and
102143** number of arguments may be returned even if the eTextRep flag does not
102144** match that requested.
102145*/
102146SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
102147  sqlite3 *db,       /* An open database */
102148  const char *zName, /* Name of the function.  zero-terminated */
102149  int nArg,          /* Number of arguments.  -1 means any number */
102150  u8 enc,            /* Preferred text encoding */
102151  u8 createFlag      /* Create new entry if true and does not otherwise exist */
102152){
102153  FuncDef *p;         /* Iterator variable */
102154  FuncDef *pBest = 0; /* Best match found so far */
102155  int bestScore = 0;  /* Score of best match */
102156  int h;              /* Hash value */
102157  int nName;          /* Length of the name */
102158
102159  assert( nArg>=(-2) );
102160  assert( nArg>=(-1) || createFlag==0 );
102161  nName = sqlite3Strlen30(zName);
102162
102163  /* First search for a match amongst the application-defined functions.
102164  */
102165  p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
102166  while( p ){
102167    int score = matchQuality(p, nArg, enc);
102168    if( score>bestScore ){
102169      pBest = p;
102170      bestScore = score;
102171    }
102172    p = p->pNext;
102173  }
102174
102175  /* If no match is found, search the built-in functions.
102176  **
102177  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
102178  ** functions even if a prior app-defined function was found.  And give
102179  ** priority to built-in functions.
102180  **
102181  ** Except, if createFlag is true, that means that we are trying to
102182  ** install a new function.  Whatever FuncDef structure is returned it will
102183  ** have fields overwritten with new information appropriate for the
102184  ** new function.  But the FuncDefs for built-in functions are read-only.
102185  ** So we must not search for built-ins when creating a new function.
102186  */
102187  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
102188    bestScore = 0;
102189    h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
102190    p = functionSearch(h, zName);
102191    while( p ){
102192      int score = matchQuality(p, nArg, enc);
102193      if( score>bestScore ){
102194        pBest = p;
102195        bestScore = score;
102196      }
102197      p = p->pNext;
102198    }
102199  }
102200
102201  /* If the createFlag parameter is true and the search did not reveal an
102202  ** exact match for the name, number of arguments and encoding, then add a
102203  ** new entry to the hash table and return it.
102204  */
102205  if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
102206      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
102207    FuncDef *pOther;
102208    pBest->zName = (const char*)&pBest[1];
102209    pBest->nArg = (u16)nArg;
102210    pBest->funcFlags = enc;
102211    memcpy((char*)&pBest[1], zName, nName+1);
102212    pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
102213    if( pOther==pBest ){
102214      sqlite3DbFree(db, pBest);
102215      sqlite3OomFault(db);
102216      return 0;
102217    }else{
102218      pBest->pNext = pOther;
102219    }
102220  }
102221
102222  if( pBest && (pBest->xSFunc || createFlag) ){
102223    return pBest;
102224  }
102225  return 0;
102226}
102227
102228/*
102229** Free all resources held by the schema structure. The void* argument points
102230** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
102231** pointer itself, it just cleans up subsidiary resources (i.e. the contents
102232** of the schema hash tables).
102233**
102234** The Schema.cache_size variable is not cleared.
102235*/
102236SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
102237  Hash temp1;
102238  Hash temp2;
102239  HashElem *pElem;
102240  Schema *pSchema = (Schema *)p;
102241
102242  temp1 = pSchema->tblHash;
102243  temp2 = pSchema->trigHash;
102244  sqlite3HashInit(&pSchema->trigHash);
102245  sqlite3HashClear(&pSchema->idxHash);
102246  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
102247    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
102248  }
102249  sqlite3HashClear(&temp2);
102250  sqlite3HashInit(&pSchema->tblHash);
102251  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
102252    Table *pTab = sqliteHashData(pElem);
102253    sqlite3DeleteTable(0, pTab);
102254  }
102255  sqlite3HashClear(&temp1);
102256  sqlite3HashClear(&pSchema->fkeyHash);
102257  pSchema->pSeqTab = 0;
102258  if( pSchema->schemaFlags & DB_SchemaLoaded ){
102259    pSchema->iGeneration++;
102260    pSchema->schemaFlags &= ~DB_SchemaLoaded;
102261  }
102262}
102263
102264/*
102265** Find and return the schema associated with a BTree.  Create
102266** a new one if necessary.
102267*/
102268SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
102269  Schema * p;
102270  if( pBt ){
102271    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
102272  }else{
102273    p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
102274  }
102275  if( !p ){
102276    sqlite3OomFault(db);
102277  }else if ( 0==p->file_format ){
102278    sqlite3HashInit(&p->tblHash);
102279    sqlite3HashInit(&p->idxHash);
102280    sqlite3HashInit(&p->trigHash);
102281    sqlite3HashInit(&p->fkeyHash);
102282    p->enc = SQLITE_UTF8;
102283  }
102284  return p;
102285}
102286
102287/************** End of callback.c ********************************************/
102288/************** Begin file delete.c ******************************************/
102289/*
102290** 2001 September 15
102291**
102292** The author disclaims copyright to this source code.  In place of
102293** a legal notice, here is a blessing:
102294**
102295**    May you do good and not evil.
102296**    May you find forgiveness for yourself and forgive others.
102297**    May you share freely, never taking more than you give.
102298**
102299*************************************************************************
102300** This file contains C code routines that are called by the parser
102301** in order to generate code for DELETE FROM statements.
102302*/
102303/* #include "sqliteInt.h" */
102304
102305/*
102306** While a SrcList can in general represent multiple tables and subqueries
102307** (as in the FROM clause of a SELECT statement) in this case it contains
102308** the name of a single table, as one might find in an INSERT, DELETE,
102309** or UPDATE statement.  Look up that table in the symbol table and
102310** return a pointer.  Set an error message and return NULL if the table
102311** name is not found or if any other error occurs.
102312**
102313** The following fields are initialized appropriate in pSrc:
102314**
102315**    pSrc->a[0].pTab       Pointer to the Table object
102316**    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
102317**
102318*/
102319SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
102320  struct SrcList_item *pItem = pSrc->a;
102321  Table *pTab;
102322  assert( pItem && pSrc->nSrc==1 );
102323  pTab = sqlite3LocateTableItem(pParse, 0, pItem);
102324  sqlite3DeleteTable(pParse->db, pItem->pTab);
102325  pItem->pTab = pTab;
102326  if( pTab ){
102327    pTab->nRef++;
102328  }
102329  if( sqlite3IndexedByLookup(pParse, pItem) ){
102330    pTab = 0;
102331  }
102332  return pTab;
102333}
102334
102335/*
102336** Check to make sure the given table is writable.  If it is not
102337** writable, generate an error message and return 1.  If it is
102338** writable return 0;
102339*/
102340SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
102341  /* A table is not writable under the following circumstances:
102342  **
102343  **   1) It is a virtual table and no implementation of the xUpdate method
102344  **      has been provided, or
102345  **   2) It is a system table (i.e. sqlite_master), this call is not
102346  **      part of a nested parse and writable_schema pragma has not
102347  **      been specified.
102348  **
102349  ** In either case leave an error message in pParse and return non-zero.
102350  */
102351  if( ( IsVirtual(pTab)
102352     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
102353   || ( (pTab->tabFlags & TF_Readonly)!=0
102354     && (pParse->db->flags & SQLITE_WriteSchema)==0
102355     && pParse->nested==0 )
102356  ){
102357    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
102358    return 1;
102359  }
102360
102361#ifndef SQLITE_OMIT_VIEW
102362  if( !viewOk && pTab->pSelect ){
102363    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
102364    return 1;
102365  }
102366#endif
102367  return 0;
102368}
102369
102370
102371#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
102372/*
102373** Evaluate a view and store its result in an ephemeral table.  The
102374** pWhere argument is an optional WHERE clause that restricts the
102375** set of rows in the view that are to be added to the ephemeral table.
102376*/
102377SQLITE_PRIVATE void sqlite3MaterializeView(
102378  Parse *pParse,       /* Parsing context */
102379  Table *pView,        /* View definition */
102380  Expr *pWhere,        /* Optional WHERE clause to be added */
102381  int iCur             /* Cursor number for ephemeral table */
102382){
102383  SelectDest dest;
102384  Select *pSel;
102385  SrcList *pFrom;
102386  sqlite3 *db = pParse->db;
102387  int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
102388  pWhere = sqlite3ExprDup(db, pWhere, 0);
102389  pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
102390  if( pFrom ){
102391    assert( pFrom->nSrc==1 );
102392    pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
102393    pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
102394    assert( pFrom->a[0].pOn==0 );
102395    assert( pFrom->a[0].pUsing==0 );
102396  }
102397  pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0,
102398                          SF_IncludeHidden, 0, 0);
102399  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
102400  sqlite3Select(pParse, pSel, &dest);
102401  sqlite3SelectDelete(db, pSel);
102402}
102403#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
102404
102405#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
102406/*
102407** Generate an expression tree to implement the WHERE, ORDER BY,
102408** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
102409**
102410**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
102411**                            \__________________________/
102412**                               pLimitWhere (pInClause)
102413*/
102414SQLITE_PRIVATE Expr *sqlite3LimitWhere(
102415  Parse *pParse,               /* The parser context */
102416  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
102417  Expr *pWhere,                /* The WHERE clause.  May be null */
102418  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
102419  Expr *pLimit,                /* The LIMIT clause.  May be null */
102420  Expr *pOffset,               /* The OFFSET clause.  May be null */
102421  char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
102422){
102423  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
102424  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
102425  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
102426  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
102427  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
102428  Select *pSelect = NULL;      /* Complete SELECT tree */
102429
102430  /* Check that there isn't an ORDER BY without a LIMIT clause.
102431  */
102432  if( pOrderBy && (pLimit == 0) ) {
102433    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
102434    goto limit_where_cleanup;
102435  }
102436
102437  /* We only need to generate a select expression if there
102438  ** is a limit/offset term to enforce.
102439  */
102440  if( pLimit == 0 ) {
102441    /* if pLimit is null, pOffset will always be null as well. */
102442    assert( pOffset == 0 );
102443    return pWhere;
102444  }
102445
102446  /* Generate a select expression tree to enforce the limit/offset
102447  ** term for the DELETE or UPDATE statement.  For example:
102448  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
102449  ** becomes:
102450  **   DELETE FROM table_a WHERE rowid IN (
102451  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
102452  **   );
102453  */
102454
102455  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
102456  if( pSelectRowid == 0 ) goto limit_where_cleanup;
102457  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
102458  if( pEList == 0 ) goto limit_where_cleanup;
102459
102460  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
102461  ** and the SELECT subtree. */
102462  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
102463  if( pSelectSrc == 0 ) {
102464    sqlite3ExprListDelete(pParse->db, pEList);
102465    goto limit_where_cleanup;
102466  }
102467
102468  /* generate the SELECT expression tree. */
102469  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
102470                             pOrderBy,0,pLimit,pOffset);
102471  if( pSelect == 0 ) return 0;
102472
102473  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
102474  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
102475  pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0) : 0;
102476  sqlite3PExprAddSelect(pParse, pInClause, pSelect);
102477  return pInClause;
102478
102479limit_where_cleanup:
102480  sqlite3ExprDelete(pParse->db, pWhere);
102481  sqlite3ExprListDelete(pParse->db, pOrderBy);
102482  sqlite3ExprDelete(pParse->db, pLimit);
102483  sqlite3ExprDelete(pParse->db, pOffset);
102484  return 0;
102485}
102486#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
102487       /*      && !defined(SQLITE_OMIT_SUBQUERY) */
102488
102489/*
102490** Generate code for a DELETE FROM statement.
102491**
102492**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
102493**                 \________/       \________________/
102494**                  pTabList              pWhere
102495*/
102496SQLITE_PRIVATE void sqlite3DeleteFrom(
102497  Parse *pParse,         /* The parser context */
102498  SrcList *pTabList,     /* The table from which we should delete things */
102499  Expr *pWhere           /* The WHERE clause.  May be null */
102500){
102501  Vdbe *v;               /* The virtual database engine */
102502  Table *pTab;           /* The table from which records will be deleted */
102503  const char *zDb;       /* Name of database holding pTab */
102504  int i;                 /* Loop counter */
102505  WhereInfo *pWInfo;     /* Information about the WHERE clause */
102506  Index *pIdx;           /* For looping over indices of the table */
102507  int iTabCur;           /* Cursor number for the table */
102508  int iDataCur = 0;      /* VDBE cursor for the canonical data source */
102509  int iIdxCur = 0;       /* Cursor number of the first index */
102510  int nIdx;              /* Number of indices */
102511  sqlite3 *db;           /* Main database structure */
102512  AuthContext sContext;  /* Authorization context */
102513  NameContext sNC;       /* Name context to resolve expressions in */
102514  int iDb;               /* Database number */
102515  int memCnt = -1;       /* Memory cell used for change counting */
102516  int rcauth;            /* Value returned by authorization callback */
102517  int eOnePass;          /* ONEPASS_OFF or _SINGLE or _MULTI */
102518  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
102519  u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
102520  Index *pPk;            /* The PRIMARY KEY index on the table */
102521  int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
102522  i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
102523  int iKey;              /* Memory cell holding key of row to be deleted */
102524  i16 nKey;              /* Number of memory cells in the row key */
102525  int iEphCur = 0;       /* Ephemeral table holding all primary key values */
102526  int iRowSet = 0;       /* Register for rowset of rows to delete */
102527  int addrBypass = 0;    /* Address of jump over the delete logic */
102528  int addrLoop = 0;      /* Top of the delete loop */
102529  int addrEphOpen = 0;   /* Instruction to open the Ephemeral table */
102530  int bComplex;          /* True if there are triggers or FKs or
102531                         ** subqueries in the WHERE clause */
102532
102533#ifndef SQLITE_OMIT_TRIGGER
102534  int isView;                  /* True if attempting to delete from a view */
102535  Trigger *pTrigger;           /* List of table triggers, if required */
102536#endif
102537
102538  memset(&sContext, 0, sizeof(sContext));
102539  db = pParse->db;
102540  if( pParse->nErr || db->mallocFailed ){
102541    goto delete_from_cleanup;
102542  }
102543  assert( pTabList->nSrc==1 );
102544
102545  /* Locate the table which we want to delete.  This table has to be
102546  ** put in an SrcList structure because some of the subroutines we
102547  ** will be calling are designed to work with multiple tables and expect
102548  ** an SrcList* parameter instead of just a Table* parameter.
102549  */
102550  pTab = sqlite3SrcListLookup(pParse, pTabList);
102551  if( pTab==0 )  goto delete_from_cleanup;
102552
102553  /* Figure out if we have any triggers and if the table being
102554  ** deleted from is a view
102555  */
102556#ifndef SQLITE_OMIT_TRIGGER
102557  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
102558  isView = pTab->pSelect!=0;
102559  bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
102560#else
102561# define pTrigger 0
102562# define isView 0
102563#endif
102564#ifdef SQLITE_OMIT_VIEW
102565# undef isView
102566# define isView 0
102567#endif
102568
102569  /* If pTab is really a view, make sure it has been initialized.
102570  */
102571  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
102572    goto delete_from_cleanup;
102573  }
102574
102575  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
102576    goto delete_from_cleanup;
102577  }
102578  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102579  assert( iDb<db->nDb );
102580  zDb = db->aDb[iDb].zName;
102581  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
102582  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
102583  if( rcauth==SQLITE_DENY ){
102584    goto delete_from_cleanup;
102585  }
102586  assert(!isView || pTrigger);
102587
102588  /* Assign cursor numbers to the table and all its indices.
102589  */
102590  assert( pTabList->nSrc==1 );
102591  iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
102592  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
102593    pParse->nTab++;
102594  }
102595
102596  /* Start the view context
102597  */
102598  if( isView ){
102599    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
102600  }
102601
102602  /* Begin generating code.
102603  */
102604  v = sqlite3GetVdbe(pParse);
102605  if( v==0 ){
102606    goto delete_from_cleanup;
102607  }
102608  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
102609  sqlite3BeginWriteOperation(pParse, 1, iDb);
102610
102611  /* If we are trying to delete from a view, realize that view into
102612  ** an ephemeral table.
102613  */
102614#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
102615  if( isView ){
102616    sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
102617    iDataCur = iIdxCur = iTabCur;
102618  }
102619#endif
102620
102621  /* Resolve the column names in the WHERE clause.
102622  */
102623  memset(&sNC, 0, sizeof(sNC));
102624  sNC.pParse = pParse;
102625  sNC.pSrcList = pTabList;
102626  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
102627    goto delete_from_cleanup;
102628  }
102629
102630  /* Initialize the counter of the number of rows deleted, if
102631  ** we are counting rows.
102632  */
102633  if( db->flags & SQLITE_CountRows ){
102634    memCnt = ++pParse->nMem;
102635    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
102636  }
102637
102638#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
102639  /* Special case: A DELETE without a WHERE clause deletes everything.
102640  ** It is easier just to erase the whole table. Prior to version 3.6.5,
102641  ** this optimization caused the row change count (the value returned by
102642  ** API function sqlite3_count_changes) to be set incorrectly.  */
102643  if( rcauth==SQLITE_OK
102644   && pWhere==0
102645   && !bComplex
102646   && !IsVirtual(pTab)
102647#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
102648   && db->xPreUpdateCallback==0
102649#endif
102650  ){
102651    assert( !isView );
102652    sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
102653    if( HasRowid(pTab) ){
102654      sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
102655                        pTab->zName, P4_STATIC);
102656    }
102657    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102658      assert( pIdx->pSchema==pTab->pSchema );
102659      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
102660    }
102661  }else
102662#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
102663  {
102664    u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
102665    if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
102666    wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
102667    if( HasRowid(pTab) ){
102668      /* For a rowid table, initialize the RowSet to an empty set */
102669      pPk = 0;
102670      nPk = 1;
102671      iRowSet = ++pParse->nMem;
102672      sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
102673    }else{
102674      /* For a WITHOUT ROWID table, create an ephemeral table used to
102675      ** hold all primary keys for rows to be deleted. */
102676      pPk = sqlite3PrimaryKeyIndex(pTab);
102677      assert( pPk!=0 );
102678      nPk = pPk->nKeyCol;
102679      iPk = pParse->nMem+1;
102680      pParse->nMem += nPk;
102681      iEphCur = pParse->nTab++;
102682      addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
102683      sqlite3VdbeSetP4KeyInfo(pParse, pPk);
102684    }
102685
102686    /* Construct a query to find the rowid or primary key for every row
102687    ** to be deleted, based on the WHERE clause. Set variable eOnePass
102688    ** to indicate the strategy used to implement this delete:
102689    **
102690    **  ONEPASS_OFF:    Two-pass approach - use a FIFO for rowids/PK values.
102691    **  ONEPASS_SINGLE: One-pass approach - at most one row deleted.
102692    **  ONEPASS_MULTI:  One-pass approach - any number of rows may be deleted.
102693    */
102694    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
102695    if( pWInfo==0 ) goto delete_from_cleanup;
102696    eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
102697    assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
102698    assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
102699
102700    /* Keep track of the number of rows to be deleted */
102701    if( db->flags & SQLITE_CountRows ){
102702      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
102703    }
102704
102705    /* Extract the rowid or primary key for the current row */
102706    if( pPk ){
102707      for(i=0; i<nPk; i++){
102708        assert( pPk->aiColumn[i]>=0 );
102709        sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
102710                                        pPk->aiColumn[i], iPk+i);
102711      }
102712      iKey = iPk;
102713    }else{
102714      iKey = pParse->nMem + 1;
102715      iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
102716      if( iKey>pParse->nMem ) pParse->nMem = iKey;
102717    }
102718
102719    if( eOnePass!=ONEPASS_OFF ){
102720      /* For ONEPASS, no need to store the rowid/primary-key. There is only
102721      ** one, so just keep it in its register(s) and fall through to the
102722      ** delete code.  */
102723      nKey = nPk; /* OP_Found will use an unpacked key */
102724      aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
102725      if( aToOpen==0 ){
102726        sqlite3WhereEnd(pWInfo);
102727        goto delete_from_cleanup;
102728      }
102729      memset(aToOpen, 1, nIdx+1);
102730      aToOpen[nIdx+1] = 0;
102731      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
102732      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
102733      if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
102734    }else{
102735      if( pPk ){
102736        /* Add the PK key for this row to the temporary table */
102737        iKey = ++pParse->nMem;
102738        nKey = 0;   /* Zero tells OP_Found to use a composite key */
102739        sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
102740            sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
102741        sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
102742      }else{
102743        /* Add the rowid of the row to be deleted to the RowSet */
102744        nKey = 1;  /* OP_Seek always uses a single rowid */
102745        sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
102746      }
102747    }
102748
102749    /* If this DELETE cannot use the ONEPASS strategy, this is the
102750    ** end of the WHERE loop */
102751    if( eOnePass!=ONEPASS_OFF ){
102752      addrBypass = sqlite3VdbeMakeLabel(v);
102753    }else{
102754      sqlite3WhereEnd(pWInfo);
102755    }
102756
102757    /* Unless this is a view, open cursors for the table we are
102758    ** deleting from and all its indices. If this is a view, then the
102759    ** only effect this statement has is to fire the INSTEAD OF
102760    ** triggers.
102761    */
102762    if( !isView ){
102763      int iAddrOnce = 0;
102764      if( eOnePass==ONEPASS_MULTI ){
102765        iAddrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
102766      }
102767      testcase( IsVirtual(pTab) );
102768      sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
102769                                 iTabCur, aToOpen, &iDataCur, &iIdxCur);
102770      assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
102771      assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
102772      if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
102773    }
102774
102775    /* Set up a loop over the rowids/primary-keys that were found in the
102776    ** where-clause loop above.
102777    */
102778    if( eOnePass!=ONEPASS_OFF ){
102779      assert( nKey==nPk );  /* OP_Found will use an unpacked key */
102780      if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
102781        assert( pPk!=0 || pTab->pSelect!=0 );
102782        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
102783        VdbeCoverage(v);
102784      }
102785    }else if( pPk ){
102786      addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
102787      sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
102788      assert( nKey==0 );  /* OP_Found will use a composite key */
102789    }else{
102790      addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
102791      VdbeCoverage(v);
102792      assert( nKey==1 );
102793    }
102794
102795    /* Delete the row */
102796#ifndef SQLITE_OMIT_VIRTUALTABLE
102797    if( IsVirtual(pTab) ){
102798      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
102799      sqlite3VtabMakeWritable(pParse, pTab);
102800      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
102801      sqlite3VdbeChangeP5(v, OE_Abort);
102802      assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
102803      sqlite3MayAbort(pParse);
102804      if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
102805        pParse->isMultiWrite = 0;
102806      }
102807    }else
102808#endif
102809    {
102810      int count = (pParse->nested==0);    /* True to count changes */
102811      int iIdxNoSeek = -1;
102812      if( bComplex==0 && aiCurOnePass[1]!=iDataCur ){
102813        iIdxNoSeek = aiCurOnePass[1];
102814      }
102815      sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
102816          iKey, nKey, count, OE_Default, eOnePass, iIdxNoSeek);
102817    }
102818
102819    /* End of the loop over all rowids/primary-keys. */
102820    if( eOnePass!=ONEPASS_OFF ){
102821      sqlite3VdbeResolveLabel(v, addrBypass);
102822      sqlite3WhereEnd(pWInfo);
102823    }else if( pPk ){
102824      sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
102825      sqlite3VdbeJumpHere(v, addrLoop);
102826    }else{
102827      sqlite3VdbeGoto(v, addrLoop);
102828      sqlite3VdbeJumpHere(v, addrLoop);
102829    }
102830
102831    /* Close the cursors open on the table and its indexes. */
102832    if( !isView && !IsVirtual(pTab) ){
102833      if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
102834      for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
102835        sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
102836      }
102837    }
102838  } /* End non-truncate path */
102839
102840  /* Update the sqlite_sequence table by storing the content of the
102841  ** maximum rowid counter values recorded while inserting into
102842  ** autoincrement tables.
102843  */
102844  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
102845    sqlite3AutoincrementEnd(pParse);
102846  }
102847
102848  /* Return the number of rows that were deleted. If this routine is
102849  ** generating code because of a call to sqlite3NestedParse(), do not
102850  ** invoke the callback function.
102851  */
102852  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
102853    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
102854    sqlite3VdbeSetNumCols(v, 1);
102855    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
102856  }
102857
102858delete_from_cleanup:
102859  sqlite3AuthContextPop(&sContext);
102860  sqlite3SrcListDelete(db, pTabList);
102861  sqlite3ExprDelete(db, pWhere);
102862  sqlite3DbFree(db, aToOpen);
102863  return;
102864}
102865/* Make sure "isView" and other macros defined above are undefined. Otherwise
102866** they may interfere with compilation of other functions in this file
102867** (or in another file, if this file becomes part of the amalgamation).  */
102868#ifdef isView
102869 #undef isView
102870#endif
102871#ifdef pTrigger
102872 #undef pTrigger
102873#endif
102874
102875/*
102876** This routine generates VDBE code that causes a single row of a
102877** single table to be deleted.  Both the original table entry and
102878** all indices are removed.
102879**
102880** Preconditions:
102881**
102882**   1.  iDataCur is an open cursor on the btree that is the canonical data
102883**       store for the table.  (This will be either the table itself,
102884**       in the case of a rowid table, or the PRIMARY KEY index in the case
102885**       of a WITHOUT ROWID table.)
102886**
102887**   2.  Read/write cursors for all indices of pTab must be open as
102888**       cursor number iIdxCur+i for the i-th index.
102889**
102890**   3.  The primary key for the row to be deleted must be stored in a
102891**       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
102892**       that a search record formed from OP_MakeRecord is contained in the
102893**       single memory location iPk.
102894**
102895** eMode:
102896**   Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
102897**   ONEPASS_MULTI.  If eMode is not ONEPASS_OFF, then the cursor
102898**   iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
102899**   then this function must seek iDataCur to the entry identified by iPk
102900**   and nPk before reading from it.
102901**
102902**   If eMode is ONEPASS_MULTI, then this call is being made as part
102903**   of a ONEPASS delete that affects multiple rows. In this case, if
102904**   iIdxNoSeek is a valid cursor number (>=0), then its position should
102905**   be preserved following the delete operation. Or, if iIdxNoSeek is not
102906**   a valid cursor number, the position of iDataCur should be preserved
102907**   instead.
102908**
102909** iIdxNoSeek:
102910**   If iIdxNoSeek is a valid cursor number (>=0), then it identifies an
102911**   index cursor (from within array of cursors starting at iIdxCur) that
102912**   already points to the index entry to be deleted.
102913*/
102914SQLITE_PRIVATE void sqlite3GenerateRowDelete(
102915  Parse *pParse,     /* Parsing context */
102916  Table *pTab,       /* Table containing the row to be deleted */
102917  Trigger *pTrigger, /* List of triggers to (potentially) fire */
102918  int iDataCur,      /* Cursor from which column data is extracted */
102919  int iIdxCur,       /* First index cursor */
102920  int iPk,           /* First memory cell containing the PRIMARY KEY */
102921  i16 nPk,           /* Number of PRIMARY KEY memory cells */
102922  u8 count,          /* If non-zero, increment the row change counter */
102923  u8 onconf,         /* Default ON CONFLICT policy for triggers */
102924  u8 eMode,          /* ONEPASS_OFF, _SINGLE, or _MULTI.  See above */
102925  int iIdxNoSeek     /* Cursor number of cursor that does not need seeking */
102926){
102927  Vdbe *v = pParse->pVdbe;        /* Vdbe */
102928  int iOld = 0;                   /* First register in OLD.* array */
102929  int iLabel;                     /* Label resolved to end of generated code */
102930  u8 opSeek;                      /* Seek opcode */
102931
102932  /* Vdbe is guaranteed to have been allocated by this stage. */
102933  assert( v );
102934  VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
102935                         iDataCur, iIdxCur, iPk, (int)nPk));
102936
102937  /* Seek cursor iCur to the row to delete. If this row no longer exists
102938  ** (this can happen if a trigger program has already deleted it), do
102939  ** not attempt to delete it or fire any DELETE triggers.  */
102940  iLabel = sqlite3VdbeMakeLabel(v);
102941  opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
102942  if( eMode==ONEPASS_OFF ){
102943    sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
102944    VdbeCoverageIf(v, opSeek==OP_NotExists);
102945    VdbeCoverageIf(v, opSeek==OP_NotFound);
102946  }
102947
102948  /* If there are any triggers to fire, allocate a range of registers to
102949  ** use for the old.* references in the triggers.  */
102950  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
102951    u32 mask;                     /* Mask of OLD.* columns in use */
102952    int iCol;                     /* Iterator used while populating OLD.* */
102953    int addrStart;                /* Start of BEFORE trigger programs */
102954
102955    /* TODO: Could use temporary registers here. Also could attempt to
102956    ** avoid copying the contents of the rowid register.  */
102957    mask = sqlite3TriggerColmask(
102958        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
102959    );
102960    mask |= sqlite3FkOldmask(pParse, pTab);
102961    iOld = pParse->nMem+1;
102962    pParse->nMem += (1 + pTab->nCol);
102963
102964    /* Populate the OLD.* pseudo-table register array. These values will be
102965    ** used by any BEFORE and AFTER triggers that exist.  */
102966    sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
102967    for(iCol=0; iCol<pTab->nCol; iCol++){
102968      testcase( mask!=0xffffffff && iCol==31 );
102969      testcase( mask!=0xffffffff && iCol==32 );
102970      if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
102971        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
102972      }
102973    }
102974
102975    /* Invoke BEFORE DELETE trigger programs. */
102976    addrStart = sqlite3VdbeCurrentAddr(v);
102977    sqlite3CodeRowTrigger(pParse, pTrigger,
102978        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
102979    );
102980
102981    /* If any BEFORE triggers were coded, then seek the cursor to the
102982    ** row to be deleted again. It may be that the BEFORE triggers moved
102983    ** the cursor or of already deleted the row that the cursor was
102984    ** pointing to.
102985    */
102986    if( addrStart<sqlite3VdbeCurrentAddr(v) ){
102987      sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
102988      VdbeCoverageIf(v, opSeek==OP_NotExists);
102989      VdbeCoverageIf(v, opSeek==OP_NotFound);
102990    }
102991
102992    /* Do FK processing. This call checks that any FK constraints that
102993    ** refer to this table (i.e. constraints attached to other tables)
102994    ** are not violated by deleting this row.  */
102995    sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
102996  }
102997
102998  /* Delete the index and table entries. Skip this step if pTab is really
102999  ** a view (in which case the only effect of the DELETE statement is to
103000  ** fire the INSTEAD OF triggers).
103001  **
103002  ** If variable 'count' is non-zero, then this OP_Delete instruction should
103003  ** invoke the update-hook. The pre-update-hook, on the other hand should
103004  ** be invoked unless table pTab is a system table. The difference is that
103005  ** the update-hook is not invoked for rows removed by REPLACE, but the
103006  ** pre-update-hook is.
103007  */
103008  if( pTab->pSelect==0 ){
103009    u8 p5 = 0;
103010    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
103011    sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
103012    sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE);
103013    if( eMode!=ONEPASS_OFF ){
103014      sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
103015    }
103016    if( iIdxNoSeek>=0 ){
103017      sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
103018    }
103019    if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
103020    sqlite3VdbeChangeP5(v, p5);
103021  }
103022
103023  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
103024  ** handle rows (possibly in other tables) that refer via a foreign key
103025  ** to the row just deleted. */
103026  sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
103027
103028  /* Invoke AFTER DELETE trigger programs. */
103029  sqlite3CodeRowTrigger(pParse, pTrigger,
103030      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
103031  );
103032
103033  /* Jump here if the row had already been deleted before any BEFORE
103034  ** trigger programs were invoked. Or if a trigger program throws a
103035  ** RAISE(IGNORE) exception.  */
103036  sqlite3VdbeResolveLabel(v, iLabel);
103037  VdbeModuleComment((v, "END: GenRowDel()"));
103038}
103039
103040/*
103041** This routine generates VDBE code that causes the deletion of all
103042** index entries associated with a single row of a single table, pTab
103043**
103044** Preconditions:
103045**
103046**   1.  A read/write cursor "iDataCur" must be open on the canonical storage
103047**       btree for the table pTab.  (This will be either the table itself
103048**       for rowid tables or to the primary key index for WITHOUT ROWID
103049**       tables.)
103050**
103051**   2.  Read/write cursors for all indices of pTab must be open as
103052**       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
103053**       index is the 0-th index.)
103054**
103055**   3.  The "iDataCur" cursor must be already be positioned on the row
103056**       that is to be deleted.
103057*/
103058SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
103059  Parse *pParse,     /* Parsing and code generating context */
103060  Table *pTab,       /* Table containing the row to be deleted */
103061  int iDataCur,      /* Cursor of table holding data. */
103062  int iIdxCur,       /* First index cursor */
103063  int *aRegIdx,      /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
103064  int iIdxNoSeek     /* Do not delete from this cursor */
103065){
103066  int i;             /* Index loop counter */
103067  int r1 = -1;       /* Register holding an index key */
103068  int iPartIdxLabel; /* Jump destination for skipping partial index entries */
103069  Index *pIdx;       /* Current index */
103070  Index *pPrior = 0; /* Prior index */
103071  Vdbe *v;           /* The prepared statement under construction */
103072  Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
103073
103074  v = pParse->pVdbe;
103075  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
103076  for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
103077    assert( iIdxCur+i!=iDataCur || pPk==pIdx );
103078    if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
103079    if( pIdx==pPk ) continue;
103080    if( iIdxCur+i==iIdxNoSeek ) continue;
103081    VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
103082    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
103083        &iPartIdxLabel, pPrior, r1);
103084    sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
103085        pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
103086    sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
103087    pPrior = pIdx;
103088  }
103089}
103090
103091/*
103092** Generate code that will assemble an index key and stores it in register
103093** regOut.  The key with be for index pIdx which is an index on pTab.
103094** iCur is the index of a cursor open on the pTab table and pointing to
103095** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
103096** iCur must be the cursor of the PRIMARY KEY index.
103097**
103098** Return a register number which is the first in a block of
103099** registers that holds the elements of the index key.  The
103100** block of registers has already been deallocated by the time
103101** this routine returns.
103102**
103103** If *piPartIdxLabel is not NULL, fill it in with a label and jump
103104** to that label if pIdx is a partial index that should be skipped.
103105** The label should be resolved using sqlite3ResolvePartIdxLabel().
103106** A partial index should be skipped if its WHERE clause evaluates
103107** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
103108** will be set to zero which is an empty label that is ignored by
103109** sqlite3ResolvePartIdxLabel().
103110**
103111** The pPrior and regPrior parameters are used to implement a cache to
103112** avoid unnecessary register loads.  If pPrior is not NULL, then it is
103113** a pointer to a different index for which an index key has just been
103114** computed into register regPrior.  If the current pIdx index is generating
103115** its key into the same sequence of registers and if pPrior and pIdx share
103116** a column in common, then the register corresponding to that column already
103117** holds the correct value and the loading of that register is skipped.
103118** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
103119** on a table with multiple indices, and especially with the ROWID or
103120** PRIMARY KEY columns of the index.
103121*/
103122SQLITE_PRIVATE int sqlite3GenerateIndexKey(
103123  Parse *pParse,       /* Parsing context */
103124  Index *pIdx,         /* The index for which to generate a key */
103125  int iDataCur,        /* Cursor number from which to take column data */
103126  int regOut,          /* Put the new key into this register if not 0 */
103127  int prefixOnly,      /* Compute only a unique prefix of the key */
103128  int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
103129  Index *pPrior,       /* Previously generated index key */
103130  int regPrior         /* Register holding previous generated key */
103131){
103132  Vdbe *v = pParse->pVdbe;
103133  int j;
103134  int regBase;
103135  int nCol;
103136
103137  if( piPartIdxLabel ){
103138    if( pIdx->pPartIdxWhere ){
103139      *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
103140      pParse->iSelfTab = iDataCur;
103141      sqlite3ExprCachePush(pParse);
103142      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
103143                            SQLITE_JUMPIFNULL);
103144    }else{
103145      *piPartIdxLabel = 0;
103146    }
103147  }
103148  nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
103149  regBase = sqlite3GetTempRange(pParse, nCol);
103150  if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
103151  for(j=0; j<nCol; j++){
103152    if( pPrior
103153     && pPrior->aiColumn[j]==pIdx->aiColumn[j]
103154     && pPrior->aiColumn[j]!=XN_EXPR
103155    ){
103156      /* This column was already computed by the previous index */
103157      continue;
103158    }
103159    sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
103160    /* If the column affinity is REAL but the number is an integer, then it
103161    ** might be stored in the table as an integer (using a compact
103162    ** representation) then converted to REAL by an OP_RealAffinity opcode.
103163    ** But we are getting ready to store this value back into an index, where
103164    ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
103165    ** opcode if it is present */
103166    sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
103167  }
103168  if( regOut ){
103169    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
103170  }
103171  sqlite3ReleaseTempRange(pParse, regBase, nCol);
103172  return regBase;
103173}
103174
103175/*
103176** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
103177** because it was a partial index, then this routine should be called to
103178** resolve that label.
103179*/
103180SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
103181  if( iLabel ){
103182    sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
103183    sqlite3ExprCachePop(pParse);
103184  }
103185}
103186
103187/************** End of delete.c **********************************************/
103188/************** Begin file func.c ********************************************/
103189/*
103190** 2002 February 23
103191**
103192** The author disclaims copyright to this source code.  In place of
103193** a legal notice, here is a blessing:
103194**
103195**    May you do good and not evil.
103196**    May you find forgiveness for yourself and forgive others.
103197**    May you share freely, never taking more than you give.
103198**
103199*************************************************************************
103200** This file contains the C-language implementations for many of the SQL
103201** functions of SQLite.  (Some function, and in particular the date and
103202** time functions, are implemented separately.)
103203*/
103204/* #include "sqliteInt.h" */
103205/* #include <stdlib.h> */
103206/* #include <assert.h> */
103207/* #include "vdbeInt.h" */
103208
103209/*
103210** Return the collating function associated with a function.
103211*/
103212static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
103213  VdbeOp *pOp;
103214  assert( context->pVdbe!=0 );
103215  pOp = &context->pVdbe->aOp[context->iOp-1];
103216  assert( pOp->opcode==OP_CollSeq );
103217  assert( pOp->p4type==P4_COLLSEQ );
103218  return pOp->p4.pColl;
103219}
103220
103221/*
103222** Indicate that the accumulator load should be skipped on this
103223** iteration of the aggregate loop.
103224*/
103225static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
103226  context->skipFlag = 1;
103227}
103228
103229/*
103230** Implementation of the non-aggregate min() and max() functions
103231*/
103232static void minmaxFunc(
103233  sqlite3_context *context,
103234  int argc,
103235  sqlite3_value **argv
103236){
103237  int i;
103238  int mask;    /* 0 for min() or 0xffffffff for max() */
103239  int iBest;
103240  CollSeq *pColl;
103241
103242  assert( argc>1 );
103243  mask = sqlite3_user_data(context)==0 ? 0 : -1;
103244  pColl = sqlite3GetFuncCollSeq(context);
103245  assert( pColl );
103246  assert( mask==-1 || mask==0 );
103247  iBest = 0;
103248  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
103249  for(i=1; i<argc; i++){
103250    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
103251    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
103252      testcase( mask==0 );
103253      iBest = i;
103254    }
103255  }
103256  sqlite3_result_value(context, argv[iBest]);
103257}
103258
103259/*
103260** Return the type of the argument.
103261*/
103262static void typeofFunc(
103263  sqlite3_context *context,
103264  int NotUsed,
103265  sqlite3_value **argv
103266){
103267  const char *z = 0;
103268  UNUSED_PARAMETER(NotUsed);
103269  switch( sqlite3_value_type(argv[0]) ){
103270    case SQLITE_INTEGER: z = "integer"; break;
103271    case SQLITE_TEXT:    z = "text";    break;
103272    case SQLITE_FLOAT:   z = "real";    break;
103273    case SQLITE_BLOB:    z = "blob";    break;
103274    default:             z = "null";    break;
103275  }
103276  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
103277}
103278
103279
103280/*
103281** Implementation of the length() function
103282*/
103283static void lengthFunc(
103284  sqlite3_context *context,
103285  int argc,
103286  sqlite3_value **argv
103287){
103288  int len;
103289
103290  assert( argc==1 );
103291  UNUSED_PARAMETER(argc);
103292  switch( sqlite3_value_type(argv[0]) ){
103293    case SQLITE_BLOB:
103294    case SQLITE_INTEGER:
103295    case SQLITE_FLOAT: {
103296      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
103297      break;
103298    }
103299    case SQLITE_TEXT: {
103300      const unsigned char *z = sqlite3_value_text(argv[0]);
103301      if( z==0 ) return;
103302      len = 0;
103303      while( *z ){
103304        len++;
103305        SQLITE_SKIP_UTF8(z);
103306      }
103307      sqlite3_result_int(context, len);
103308      break;
103309    }
103310    default: {
103311      sqlite3_result_null(context);
103312      break;
103313    }
103314  }
103315}
103316
103317/*
103318** Implementation of the abs() function.
103319**
103320** IMP: R-23979-26855 The abs(X) function returns the absolute value of
103321** the numeric argument X.
103322*/
103323static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
103324  assert( argc==1 );
103325  UNUSED_PARAMETER(argc);
103326  switch( sqlite3_value_type(argv[0]) ){
103327    case SQLITE_INTEGER: {
103328      i64 iVal = sqlite3_value_int64(argv[0]);
103329      if( iVal<0 ){
103330        if( iVal==SMALLEST_INT64 ){
103331          /* IMP: R-31676-45509 If X is the integer -9223372036854775808
103332          ** then abs(X) throws an integer overflow error since there is no
103333          ** equivalent positive 64-bit two complement value. */
103334          sqlite3_result_error(context, "integer overflow", -1);
103335          return;
103336        }
103337        iVal = -iVal;
103338      }
103339      sqlite3_result_int64(context, iVal);
103340      break;
103341    }
103342    case SQLITE_NULL: {
103343      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
103344      sqlite3_result_null(context);
103345      break;
103346    }
103347    default: {
103348      /* Because sqlite3_value_double() returns 0.0 if the argument is not
103349      ** something that can be converted into a number, we have:
103350      ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
103351      ** that cannot be converted to a numeric value.
103352      */
103353      double rVal = sqlite3_value_double(argv[0]);
103354      if( rVal<0 ) rVal = -rVal;
103355      sqlite3_result_double(context, rVal);
103356      break;
103357    }
103358  }
103359}
103360
103361/*
103362** Implementation of the instr() function.
103363**
103364** instr(haystack,needle) finds the first occurrence of needle
103365** in haystack and returns the number of previous characters plus 1,
103366** or 0 if needle does not occur within haystack.
103367**
103368** If both haystack and needle are BLOBs, then the result is one more than
103369** the number of bytes in haystack prior to the first occurrence of needle,
103370** or 0 if needle never occurs in haystack.
103371*/
103372static void instrFunc(
103373  sqlite3_context *context,
103374  int argc,
103375  sqlite3_value **argv
103376){
103377  const unsigned char *zHaystack;
103378  const unsigned char *zNeedle;
103379  int nHaystack;
103380  int nNeedle;
103381  int typeHaystack, typeNeedle;
103382  int N = 1;
103383  int isText;
103384
103385  UNUSED_PARAMETER(argc);
103386  typeHaystack = sqlite3_value_type(argv[0]);
103387  typeNeedle = sqlite3_value_type(argv[1]);
103388  if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
103389  nHaystack = sqlite3_value_bytes(argv[0]);
103390  nNeedle = sqlite3_value_bytes(argv[1]);
103391  if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
103392    zHaystack = sqlite3_value_blob(argv[0]);
103393    zNeedle = sqlite3_value_blob(argv[1]);
103394    isText = 0;
103395  }else{
103396    zHaystack = sqlite3_value_text(argv[0]);
103397    zNeedle = sqlite3_value_text(argv[1]);
103398    isText = 1;
103399  }
103400  while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
103401    N++;
103402    do{
103403      nHaystack--;
103404      zHaystack++;
103405    }while( isText && (zHaystack[0]&0xc0)==0x80 );
103406  }
103407  if( nNeedle>nHaystack ) N = 0;
103408  sqlite3_result_int(context, N);
103409}
103410
103411/*
103412** Implementation of the printf() function.
103413*/
103414static void printfFunc(
103415  sqlite3_context *context,
103416  int argc,
103417  sqlite3_value **argv
103418){
103419  PrintfArguments x;
103420  StrAccum str;
103421  const char *zFormat;
103422  int n;
103423  sqlite3 *db = sqlite3_context_db_handle(context);
103424
103425  if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
103426    x.nArg = argc-1;
103427    x.nUsed = 0;
103428    x.apArg = argv+1;
103429    sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
103430    str.printfFlags = SQLITE_PRINTF_SQLFUNC;
103431    sqlite3XPrintf(&str, zFormat, &x);
103432    n = str.nChar;
103433    sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
103434                        SQLITE_DYNAMIC);
103435  }
103436}
103437
103438/*
103439** Implementation of the substr() function.
103440**
103441** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
103442** p1 is 1-indexed.  So substr(x,1,1) returns the first character
103443** of x.  If x is text, then we actually count UTF-8 characters.
103444** If x is a blob, then we count bytes.
103445**
103446** If p1 is negative, then we begin abs(p1) from the end of x[].
103447**
103448** If p2 is negative, return the p2 characters preceding p1.
103449*/
103450static void substrFunc(
103451  sqlite3_context *context,
103452  int argc,
103453  sqlite3_value **argv
103454){
103455  const unsigned char *z;
103456  const unsigned char *z2;
103457  int len;
103458  int p0type;
103459  i64 p1, p2;
103460  int negP2 = 0;
103461
103462  assert( argc==3 || argc==2 );
103463  if( sqlite3_value_type(argv[1])==SQLITE_NULL
103464   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
103465  ){
103466    return;
103467  }
103468  p0type = sqlite3_value_type(argv[0]);
103469  p1 = sqlite3_value_int(argv[1]);
103470  if( p0type==SQLITE_BLOB ){
103471    len = sqlite3_value_bytes(argv[0]);
103472    z = sqlite3_value_blob(argv[0]);
103473    if( z==0 ) return;
103474    assert( len==sqlite3_value_bytes(argv[0]) );
103475  }else{
103476    z = sqlite3_value_text(argv[0]);
103477    if( z==0 ) return;
103478    len = 0;
103479    if( p1<0 ){
103480      for(z2=z; *z2; len++){
103481        SQLITE_SKIP_UTF8(z2);
103482      }
103483    }
103484  }
103485#ifdef SQLITE_SUBSTR_COMPATIBILITY
103486  /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
103487  ** as substr(X,1,N) - it returns the first N characters of X.  This
103488  ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
103489  ** from 2009-02-02 for compatibility of applications that exploited the
103490  ** old buggy behavior. */
103491  if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
103492#endif
103493  if( argc==3 ){
103494    p2 = sqlite3_value_int(argv[2]);
103495    if( p2<0 ){
103496      p2 = -p2;
103497      negP2 = 1;
103498    }
103499  }else{
103500    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
103501  }
103502  if( p1<0 ){
103503    p1 += len;
103504    if( p1<0 ){
103505      p2 += p1;
103506      if( p2<0 ) p2 = 0;
103507      p1 = 0;
103508    }
103509  }else if( p1>0 ){
103510    p1--;
103511  }else if( p2>0 ){
103512    p2--;
103513  }
103514  if( negP2 ){
103515    p1 -= p2;
103516    if( p1<0 ){
103517      p2 += p1;
103518      p1 = 0;
103519    }
103520  }
103521  assert( p1>=0 && p2>=0 );
103522  if( p0type!=SQLITE_BLOB ){
103523    while( *z && p1 ){
103524      SQLITE_SKIP_UTF8(z);
103525      p1--;
103526    }
103527    for(z2=z; *z2 && p2; p2--){
103528      SQLITE_SKIP_UTF8(z2);
103529    }
103530    sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
103531                          SQLITE_UTF8);
103532  }else{
103533    if( p1+p2>len ){
103534      p2 = len-p1;
103535      if( p2<0 ) p2 = 0;
103536    }
103537    sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
103538  }
103539}
103540
103541/*
103542** Implementation of the round() function
103543*/
103544#ifndef SQLITE_OMIT_FLOATING_POINT
103545static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
103546  int n = 0;
103547  double r;
103548  char *zBuf;
103549  assert( argc==1 || argc==2 );
103550  if( argc==2 ){
103551    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
103552    n = sqlite3_value_int(argv[1]);
103553    if( n>30 ) n = 30;
103554    if( n<0 ) n = 0;
103555  }
103556  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
103557  r = sqlite3_value_double(argv[0]);
103558  /* If Y==0 and X will fit in a 64-bit int,
103559  ** handle the rounding directly,
103560  ** otherwise use printf.
103561  */
103562  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
103563    r = (double)((sqlite_int64)(r+0.5));
103564  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
103565    r = -(double)((sqlite_int64)((-r)+0.5));
103566  }else{
103567    zBuf = sqlite3_mprintf("%.*f",n,r);
103568    if( zBuf==0 ){
103569      sqlite3_result_error_nomem(context);
103570      return;
103571    }
103572    sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
103573    sqlite3_free(zBuf);
103574  }
103575  sqlite3_result_double(context, r);
103576}
103577#endif
103578
103579/*
103580** Allocate nByte bytes of space using sqlite3Malloc(). If the
103581** allocation fails, call sqlite3_result_error_nomem() to notify
103582** the database handle that malloc() has failed and return NULL.
103583** If nByte is larger than the maximum string or blob length, then
103584** raise an SQLITE_TOOBIG exception and return NULL.
103585*/
103586static void *contextMalloc(sqlite3_context *context, i64 nByte){
103587  char *z;
103588  sqlite3 *db = sqlite3_context_db_handle(context);
103589  assert( nByte>0 );
103590  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
103591  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
103592  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
103593    sqlite3_result_error_toobig(context);
103594    z = 0;
103595  }else{
103596    z = sqlite3Malloc(nByte);
103597    if( !z ){
103598      sqlite3_result_error_nomem(context);
103599    }
103600  }
103601  return z;
103602}
103603
103604/*
103605** Implementation of the upper() and lower() SQL functions.
103606*/
103607static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
103608  char *z1;
103609  const char *z2;
103610  int i, n;
103611  UNUSED_PARAMETER(argc);
103612  z2 = (char*)sqlite3_value_text(argv[0]);
103613  n = sqlite3_value_bytes(argv[0]);
103614  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
103615  assert( z2==(char*)sqlite3_value_text(argv[0]) );
103616  if( z2 ){
103617    z1 = contextMalloc(context, ((i64)n)+1);
103618    if( z1 ){
103619      for(i=0; i<n; i++){
103620        z1[i] = (char)sqlite3Toupper(z2[i]);
103621      }
103622      sqlite3_result_text(context, z1, n, sqlite3_free);
103623    }
103624  }
103625}
103626static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
103627  char *z1;
103628  const char *z2;
103629  int i, n;
103630  UNUSED_PARAMETER(argc);
103631  z2 = (char*)sqlite3_value_text(argv[0]);
103632  n = sqlite3_value_bytes(argv[0]);
103633  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
103634  assert( z2==(char*)sqlite3_value_text(argv[0]) );
103635  if( z2 ){
103636    z1 = contextMalloc(context, ((i64)n)+1);
103637    if( z1 ){
103638      for(i=0; i<n; i++){
103639        z1[i] = sqlite3Tolower(z2[i]);
103640      }
103641      sqlite3_result_text(context, z1, n, sqlite3_free);
103642    }
103643  }
103644}
103645
103646/*
103647** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
103648** as VDBE code so that unused argument values do not have to be computed.
103649** However, we still need some kind of function implementation for this
103650** routines in the function table.  The noopFunc macro provides this.
103651** noopFunc will never be called so it doesn't matter what the implementation
103652** is.  We might as well use the "version()" function as a substitute.
103653*/
103654#define noopFunc versionFunc   /* Substitute function - never called */
103655
103656/*
103657** Implementation of random().  Return a random integer.
103658*/
103659static void randomFunc(
103660  sqlite3_context *context,
103661  int NotUsed,
103662  sqlite3_value **NotUsed2
103663){
103664  sqlite_int64 r;
103665  UNUSED_PARAMETER2(NotUsed, NotUsed2);
103666  sqlite3_randomness(sizeof(r), &r);
103667  if( r<0 ){
103668    /* We need to prevent a random number of 0x8000000000000000
103669    ** (or -9223372036854775808) since when you do abs() of that
103670    ** number of you get the same value back again.  To do this
103671    ** in a way that is testable, mask the sign bit off of negative
103672    ** values, resulting in a positive value.  Then take the
103673    ** 2s complement of that positive value.  The end result can
103674    ** therefore be no less than -9223372036854775807.
103675    */
103676    r = -(r & LARGEST_INT64);
103677  }
103678  sqlite3_result_int64(context, r);
103679}
103680
103681/*
103682** Implementation of randomblob(N).  Return a random blob
103683** that is N bytes long.
103684*/
103685static void randomBlob(
103686  sqlite3_context *context,
103687  int argc,
103688  sqlite3_value **argv
103689){
103690  int n;
103691  unsigned char *p;
103692  assert( argc==1 );
103693  UNUSED_PARAMETER(argc);
103694  n = sqlite3_value_int(argv[0]);
103695  if( n<1 ){
103696    n = 1;
103697  }
103698  p = contextMalloc(context, n);
103699  if( p ){
103700    sqlite3_randomness(n, p);
103701    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
103702  }
103703}
103704
103705/*
103706** Implementation of the last_insert_rowid() SQL function.  The return
103707** value is the same as the sqlite3_last_insert_rowid() API function.
103708*/
103709static void last_insert_rowid(
103710  sqlite3_context *context,
103711  int NotUsed,
103712  sqlite3_value **NotUsed2
103713){
103714  sqlite3 *db = sqlite3_context_db_handle(context);
103715  UNUSED_PARAMETER2(NotUsed, NotUsed2);
103716  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
103717  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
103718  ** function. */
103719  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
103720}
103721
103722/*
103723** Implementation of the changes() SQL function.
103724**
103725** IMP: R-62073-11209 The changes() SQL function is a wrapper
103726** around the sqlite3_changes() C/C++ function and hence follows the same
103727** rules for counting changes.
103728*/
103729static void changes(
103730  sqlite3_context *context,
103731  int NotUsed,
103732  sqlite3_value **NotUsed2
103733){
103734  sqlite3 *db = sqlite3_context_db_handle(context);
103735  UNUSED_PARAMETER2(NotUsed, NotUsed2);
103736  sqlite3_result_int(context, sqlite3_changes(db));
103737}
103738
103739/*
103740** Implementation of the total_changes() SQL function.  The return value is
103741** the same as the sqlite3_total_changes() API function.
103742*/
103743static void total_changes(
103744  sqlite3_context *context,
103745  int NotUsed,
103746  sqlite3_value **NotUsed2
103747){
103748  sqlite3 *db = sqlite3_context_db_handle(context);
103749  UNUSED_PARAMETER2(NotUsed, NotUsed2);
103750  /* IMP: R-52756-41993 This function is a wrapper around the
103751  ** sqlite3_total_changes() C/C++ interface. */
103752  sqlite3_result_int(context, sqlite3_total_changes(db));
103753}
103754
103755/*
103756** A structure defining how to do GLOB-style comparisons.
103757*/
103758struct compareInfo {
103759  u8 matchAll;          /* "*" or "%" */
103760  u8 matchOne;          /* "?" or "_" */
103761  u8 matchSet;          /* "[" or 0 */
103762  u8 noCase;            /* true to ignore case differences */
103763};
103764
103765/*
103766** For LIKE and GLOB matching on EBCDIC machines, assume that every
103767** character is exactly one byte in size.  Also, provde the Utf8Read()
103768** macro for fast reading of the next character in the common case where
103769** the next character is ASCII.
103770*/
103771#if defined(SQLITE_EBCDIC)
103772# define sqlite3Utf8Read(A)        (*((*A)++))
103773# define Utf8Read(A)               (*(A++))
103774#else
103775# define Utf8Read(A)               (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
103776#endif
103777
103778static const struct compareInfo globInfo = { '*', '?', '[', 0 };
103779/* The correct SQL-92 behavior is for the LIKE operator to ignore
103780** case.  Thus  'a' LIKE 'A' would be true. */
103781static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
103782/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
103783** is case sensitive causing 'a' LIKE 'A' to be false */
103784static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
103785
103786/*
103787** Compare two UTF-8 strings for equality where the first string can
103788** potentially be a "glob" or "like" expression.  Return true (1) if they
103789** are the same and false (0) if they are different.
103790**
103791** Globbing rules:
103792**
103793**      '*'       Matches any sequence of zero or more characters.
103794**
103795**      '?'       Matches exactly one character.
103796**
103797**     [...]      Matches one character from the enclosed list of
103798**                characters.
103799**
103800**     [^...]     Matches one character not in the enclosed list.
103801**
103802** With the [...] and [^...] matching, a ']' character can be included
103803** in the list by making it the first character after '[' or '^'.  A
103804** range of characters can be specified using '-'.  Example:
103805** "[a-z]" matches any single lower-case letter.  To match a '-', make
103806** it the last character in the list.
103807**
103808** Like matching rules:
103809**
103810**      '%'       Matches any sequence of zero or more characters
103811**
103812***     '_'       Matches any one character
103813**
103814**      Ec        Where E is the "esc" character and c is any other
103815**                character, including '%', '_', and esc, match exactly c.
103816**
103817** The comments within this routine usually assume glob matching.
103818**
103819** This routine is usually quick, but can be N**2 in the worst case.
103820*/
103821static int patternCompare(
103822  const u8 *zPattern,              /* The glob pattern */
103823  const u8 *zString,               /* The string to compare against the glob */
103824  const struct compareInfo *pInfo, /* Information about how to do the compare */
103825  u32 matchOther                   /* The escape char (LIKE) or '[' (GLOB) */
103826){
103827  u32 c, c2;                       /* Next pattern and input string chars */
103828  u32 matchOne = pInfo->matchOne;  /* "?" or "_" */
103829  u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
103830  u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
103831  const u8 *zEscaped = 0;          /* One past the last escaped input char */
103832
103833  while( (c = Utf8Read(zPattern))!=0 ){
103834    if( c==matchAll ){  /* Match "*" */
103835      /* Skip over multiple "*" characters in the pattern.  If there
103836      ** are also "?" characters, skip those as well, but consume a
103837      ** single character of the input string for each "?" skipped */
103838      while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
103839        if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
103840          return 0;
103841        }
103842      }
103843      if( c==0 ){
103844        return 1;   /* "*" at the end of the pattern matches */
103845      }else if( c==matchOther ){
103846        if( pInfo->matchSet==0 ){
103847          c = sqlite3Utf8Read(&zPattern);
103848          if( c==0 ) return 0;
103849        }else{
103850          /* "[...]" immediately follows the "*".  We have to do a slow
103851          ** recursive search in this case, but it is an unusual case. */
103852          assert( matchOther<0x80 );  /* '[' is a single-byte character */
103853          while( *zString
103854                 && patternCompare(&zPattern[-1],zString,pInfo,matchOther)==0 ){
103855            SQLITE_SKIP_UTF8(zString);
103856          }
103857          return *zString!=0;
103858        }
103859      }
103860
103861      /* At this point variable c contains the first character of the
103862      ** pattern string past the "*".  Search in the input string for the
103863      ** first matching character and recursively contine the match from
103864      ** that point.
103865      **
103866      ** For a case-insensitive search, set variable cx to be the same as
103867      ** c but in the other case and search the input string for either
103868      ** c or cx.
103869      */
103870      if( c<=0x80 ){
103871        u32 cx;
103872        if( noCase ){
103873          cx = sqlite3Toupper(c);
103874          c = sqlite3Tolower(c);
103875        }else{
103876          cx = c;
103877        }
103878        while( (c2 = *(zString++))!=0 ){
103879          if( c2!=c && c2!=cx ) continue;
103880          if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1;
103881        }
103882      }else{
103883        while( (c2 = Utf8Read(zString))!=0 ){
103884          if( c2!=c ) continue;
103885          if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1;
103886        }
103887      }
103888      return 0;
103889    }
103890    if( c==matchOther ){
103891      if( pInfo->matchSet==0 ){
103892        c = sqlite3Utf8Read(&zPattern);
103893        if( c==0 ) return 0;
103894        zEscaped = zPattern;
103895      }else{
103896        u32 prior_c = 0;
103897        int seen = 0;
103898        int invert = 0;
103899        c = sqlite3Utf8Read(&zString);
103900        if( c==0 ) return 0;
103901        c2 = sqlite3Utf8Read(&zPattern);
103902        if( c2=='^' ){
103903          invert = 1;
103904          c2 = sqlite3Utf8Read(&zPattern);
103905        }
103906        if( c2==']' ){
103907          if( c==']' ) seen = 1;
103908          c2 = sqlite3Utf8Read(&zPattern);
103909        }
103910        while( c2 && c2!=']' ){
103911          if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
103912            c2 = sqlite3Utf8Read(&zPattern);
103913            if( c>=prior_c && c<=c2 ) seen = 1;
103914            prior_c = 0;
103915          }else{
103916            if( c==c2 ){
103917              seen = 1;
103918            }
103919            prior_c = c2;
103920          }
103921          c2 = sqlite3Utf8Read(&zPattern);
103922        }
103923        if( c2==0 || (seen ^ invert)==0 ){
103924          return 0;
103925        }
103926        continue;
103927      }
103928    }
103929    c2 = Utf8Read(zString);
103930    if( c==c2 ) continue;
103931    if( noCase  && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
103932      continue;
103933    }
103934    if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
103935    return 0;
103936  }
103937  return *zString==0;
103938}
103939
103940/*
103941** The sqlite3_strglob() interface.
103942*/
103943SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlobPattern, const char *zString){
103944  return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[')==0;
103945}
103946
103947/*
103948** The sqlite3_strlike() interface.
103949*/
103950SQLITE_API int SQLITE_STDCALL sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
103951  return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc)==0;
103952}
103953
103954/*
103955** Count the number of times that the LIKE operator (or GLOB which is
103956** just a variation of LIKE) gets called.  This is used for testing
103957** only.
103958*/
103959#ifdef SQLITE_TEST
103960SQLITE_API int sqlite3_like_count = 0;
103961#endif
103962
103963
103964/*
103965** Implementation of the like() SQL function.  This function implements
103966** the build-in LIKE operator.  The first argument to the function is the
103967** pattern and the second argument is the string.  So, the SQL statements:
103968**
103969**       A LIKE B
103970**
103971** is implemented as like(B,A).
103972**
103973** This same function (with a different compareInfo structure) computes
103974** the GLOB operator.
103975*/
103976static void likeFunc(
103977  sqlite3_context *context,
103978  int argc,
103979  sqlite3_value **argv
103980){
103981  const unsigned char *zA, *zB;
103982  u32 escape;
103983  int nPat;
103984  sqlite3 *db = sqlite3_context_db_handle(context);
103985  struct compareInfo *pInfo = sqlite3_user_data(context);
103986
103987#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
103988  if( sqlite3_value_type(argv[0])==SQLITE_BLOB
103989   || sqlite3_value_type(argv[1])==SQLITE_BLOB
103990  ){
103991#ifdef SQLITE_TEST
103992    sqlite3_like_count++;
103993#endif
103994    sqlite3_result_int(context, 0);
103995    return;
103996  }
103997#endif
103998  zB = sqlite3_value_text(argv[0]);
103999  zA = sqlite3_value_text(argv[1]);
104000
104001  /* Limit the length of the LIKE or GLOB pattern to avoid problems
104002  ** of deep recursion and N*N behavior in patternCompare().
104003  */
104004  nPat = sqlite3_value_bytes(argv[0]);
104005  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
104006  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
104007  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
104008    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
104009    return;
104010  }
104011  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
104012
104013  if( argc==3 ){
104014    /* The escape character string must consist of a single UTF-8 character.
104015    ** Otherwise, return an error.
104016    */
104017    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
104018    if( zEsc==0 ) return;
104019    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
104020      sqlite3_result_error(context,
104021          "ESCAPE expression must be a single character", -1);
104022      return;
104023    }
104024    escape = sqlite3Utf8Read(&zEsc);
104025  }else{
104026    escape = pInfo->matchSet;
104027  }
104028  if( zA && zB ){
104029#ifdef SQLITE_TEST
104030    sqlite3_like_count++;
104031#endif
104032    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
104033  }
104034}
104035
104036/*
104037** Implementation of the NULLIF(x,y) function.  The result is the first
104038** argument if the arguments are different.  The result is NULL if the
104039** arguments are equal to each other.
104040*/
104041static void nullifFunc(
104042  sqlite3_context *context,
104043  int NotUsed,
104044  sqlite3_value **argv
104045){
104046  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
104047  UNUSED_PARAMETER(NotUsed);
104048  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
104049    sqlite3_result_value(context, argv[0]);
104050  }
104051}
104052
104053/*
104054** Implementation of the sqlite_version() function.  The result is the version
104055** of the SQLite library that is running.
104056*/
104057static void versionFunc(
104058  sqlite3_context *context,
104059  int NotUsed,
104060  sqlite3_value **NotUsed2
104061){
104062  UNUSED_PARAMETER2(NotUsed, NotUsed2);
104063  /* IMP: R-48699-48617 This function is an SQL wrapper around the
104064  ** sqlite3_libversion() C-interface. */
104065  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
104066}
104067
104068/*
104069** Implementation of the sqlite_source_id() function. The result is a string
104070** that identifies the particular version of the source code used to build
104071** SQLite.
104072*/
104073static void sourceidFunc(
104074  sqlite3_context *context,
104075  int NotUsed,
104076  sqlite3_value **NotUsed2
104077){
104078  UNUSED_PARAMETER2(NotUsed, NotUsed2);
104079  /* IMP: R-24470-31136 This function is an SQL wrapper around the
104080  ** sqlite3_sourceid() C interface. */
104081  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
104082}
104083
104084/*
104085** Implementation of the sqlite_log() function.  This is a wrapper around
104086** sqlite3_log().  The return value is NULL.  The function exists purely for
104087** its side-effects.
104088*/
104089static void errlogFunc(
104090  sqlite3_context *context,
104091  int argc,
104092  sqlite3_value **argv
104093){
104094  UNUSED_PARAMETER(argc);
104095  UNUSED_PARAMETER(context);
104096  sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
104097}
104098
104099/*
104100** Implementation of the sqlite_compileoption_used() function.
104101** The result is an integer that identifies if the compiler option
104102** was used to build SQLite.
104103*/
104104#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
104105static void compileoptionusedFunc(
104106  sqlite3_context *context,
104107  int argc,
104108  sqlite3_value **argv
104109){
104110  const char *zOptName;
104111  assert( argc==1 );
104112  UNUSED_PARAMETER(argc);
104113  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
104114  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
104115  ** function.
104116  */
104117  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
104118    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
104119  }
104120}
104121#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
104122
104123/*
104124** Implementation of the sqlite_compileoption_get() function.
104125** The result is a string that identifies the compiler options
104126** used to build SQLite.
104127*/
104128#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
104129static void compileoptiongetFunc(
104130  sqlite3_context *context,
104131  int argc,
104132  sqlite3_value **argv
104133){
104134  int n;
104135  assert( argc==1 );
104136  UNUSED_PARAMETER(argc);
104137  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
104138  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
104139  */
104140  n = sqlite3_value_int(argv[0]);
104141  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
104142}
104143#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
104144
104145/* Array for converting from half-bytes (nybbles) into ASCII hex
104146** digits. */
104147static const char hexdigits[] = {
104148  '0', '1', '2', '3', '4', '5', '6', '7',
104149  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
104150};
104151
104152/*
104153** Implementation of the QUOTE() function.  This function takes a single
104154** argument.  If the argument is numeric, the return value is the same as
104155** the argument.  If the argument is NULL, the return value is the string
104156** "NULL".  Otherwise, the argument is enclosed in single quotes with
104157** single-quote escapes.
104158*/
104159static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
104160  assert( argc==1 );
104161  UNUSED_PARAMETER(argc);
104162  switch( sqlite3_value_type(argv[0]) ){
104163    case SQLITE_FLOAT: {
104164      double r1, r2;
104165      char zBuf[50];
104166      r1 = sqlite3_value_double(argv[0]);
104167      sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
104168      sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
104169      if( r1!=r2 ){
104170        sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
104171      }
104172      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
104173      break;
104174    }
104175    case SQLITE_INTEGER: {
104176      sqlite3_result_value(context, argv[0]);
104177      break;
104178    }
104179    case SQLITE_BLOB: {
104180      char *zText = 0;
104181      char const *zBlob = sqlite3_value_blob(argv[0]);
104182      int nBlob = sqlite3_value_bytes(argv[0]);
104183      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
104184      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
104185      if( zText ){
104186        int i;
104187        for(i=0; i<nBlob; i++){
104188          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
104189          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
104190        }
104191        zText[(nBlob*2)+2] = '\'';
104192        zText[(nBlob*2)+3] = '\0';
104193        zText[0] = 'X';
104194        zText[1] = '\'';
104195        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
104196        sqlite3_free(zText);
104197      }
104198      break;
104199    }
104200    case SQLITE_TEXT: {
104201      int i,j;
104202      u64 n;
104203      const unsigned char *zArg = sqlite3_value_text(argv[0]);
104204      char *z;
104205
104206      if( zArg==0 ) return;
104207      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
104208      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
104209      if( z ){
104210        z[0] = '\'';
104211        for(i=0, j=1; zArg[i]; i++){
104212          z[j++] = zArg[i];
104213          if( zArg[i]=='\'' ){
104214            z[j++] = '\'';
104215          }
104216        }
104217        z[j++] = '\'';
104218        z[j] = 0;
104219        sqlite3_result_text(context, z, j, sqlite3_free);
104220      }
104221      break;
104222    }
104223    default: {
104224      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
104225      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
104226      break;
104227    }
104228  }
104229}
104230
104231/*
104232** The unicode() function.  Return the integer unicode code-point value
104233** for the first character of the input string.
104234*/
104235static void unicodeFunc(
104236  sqlite3_context *context,
104237  int argc,
104238  sqlite3_value **argv
104239){
104240  const unsigned char *z = sqlite3_value_text(argv[0]);
104241  (void)argc;
104242  if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
104243}
104244
104245/*
104246** The char() function takes zero or more arguments, each of which is
104247** an integer.  It constructs a string where each character of the string
104248** is the unicode character for the corresponding integer argument.
104249*/
104250static void charFunc(
104251  sqlite3_context *context,
104252  int argc,
104253  sqlite3_value **argv
104254){
104255  unsigned char *z, *zOut;
104256  int i;
104257  zOut = z = sqlite3_malloc64( argc*4+1 );
104258  if( z==0 ){
104259    sqlite3_result_error_nomem(context);
104260    return;
104261  }
104262  for(i=0; i<argc; i++){
104263    sqlite3_int64 x;
104264    unsigned c;
104265    x = sqlite3_value_int64(argv[i]);
104266    if( x<0 || x>0x10ffff ) x = 0xfffd;
104267    c = (unsigned)(x & 0x1fffff);
104268    if( c<0x00080 ){
104269      *zOut++ = (u8)(c&0xFF);
104270    }else if( c<0x00800 ){
104271      *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
104272      *zOut++ = 0x80 + (u8)(c & 0x3F);
104273    }else if( c<0x10000 ){
104274      *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
104275      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
104276      *zOut++ = 0x80 + (u8)(c & 0x3F);
104277    }else{
104278      *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
104279      *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
104280      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
104281      *zOut++ = 0x80 + (u8)(c & 0x3F);
104282    }                                                    \
104283  }
104284  sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
104285}
104286
104287/*
104288** The hex() function.  Interpret the argument as a blob.  Return
104289** a hexadecimal rendering as text.
104290*/
104291static void hexFunc(
104292  sqlite3_context *context,
104293  int argc,
104294  sqlite3_value **argv
104295){
104296  int i, n;
104297  const unsigned char *pBlob;
104298  char *zHex, *z;
104299  assert( argc==1 );
104300  UNUSED_PARAMETER(argc);
104301  pBlob = sqlite3_value_blob(argv[0]);
104302  n = sqlite3_value_bytes(argv[0]);
104303  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
104304  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
104305  if( zHex ){
104306    for(i=0; i<n; i++, pBlob++){
104307      unsigned char c = *pBlob;
104308      *(z++) = hexdigits[(c>>4)&0xf];
104309      *(z++) = hexdigits[c&0xf];
104310    }
104311    *z = 0;
104312    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
104313  }
104314}
104315
104316/*
104317** The zeroblob(N) function returns a zero-filled blob of size N bytes.
104318*/
104319static void zeroblobFunc(
104320  sqlite3_context *context,
104321  int argc,
104322  sqlite3_value **argv
104323){
104324  i64 n;
104325  int rc;
104326  assert( argc==1 );
104327  UNUSED_PARAMETER(argc);
104328  n = sqlite3_value_int64(argv[0]);
104329  if( n<0 ) n = 0;
104330  rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
104331  if( rc ){
104332    sqlite3_result_error_code(context, rc);
104333  }
104334}
104335
104336/*
104337** The replace() function.  Three arguments are all strings: call
104338** them A, B, and C. The result is also a string which is derived
104339** from A by replacing every occurrence of B with C.  The match
104340** must be exact.  Collating sequences are not used.
104341*/
104342static void replaceFunc(
104343  sqlite3_context *context,
104344  int argc,
104345  sqlite3_value **argv
104346){
104347  const unsigned char *zStr;        /* The input string A */
104348  const unsigned char *zPattern;    /* The pattern string B */
104349  const unsigned char *zRep;        /* The replacement string C */
104350  unsigned char *zOut;              /* The output */
104351  int nStr;                /* Size of zStr */
104352  int nPattern;            /* Size of zPattern */
104353  int nRep;                /* Size of zRep */
104354  i64 nOut;                /* Maximum size of zOut */
104355  int loopLimit;           /* Last zStr[] that might match zPattern[] */
104356  int i, j;                /* Loop counters */
104357
104358  assert( argc==3 );
104359  UNUSED_PARAMETER(argc);
104360  zStr = sqlite3_value_text(argv[0]);
104361  if( zStr==0 ) return;
104362  nStr = sqlite3_value_bytes(argv[0]);
104363  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
104364  zPattern = sqlite3_value_text(argv[1]);
104365  if( zPattern==0 ){
104366    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
104367            || sqlite3_context_db_handle(context)->mallocFailed );
104368    return;
104369  }
104370  if( zPattern[0]==0 ){
104371    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
104372    sqlite3_result_value(context, argv[0]);
104373    return;
104374  }
104375  nPattern = sqlite3_value_bytes(argv[1]);
104376  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
104377  zRep = sqlite3_value_text(argv[2]);
104378  if( zRep==0 ) return;
104379  nRep = sqlite3_value_bytes(argv[2]);
104380  assert( zRep==sqlite3_value_text(argv[2]) );
104381  nOut = nStr + 1;
104382  assert( nOut<SQLITE_MAX_LENGTH );
104383  zOut = contextMalloc(context, (i64)nOut);
104384  if( zOut==0 ){
104385    return;
104386  }
104387  loopLimit = nStr - nPattern;
104388  for(i=j=0; i<=loopLimit; i++){
104389    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
104390      zOut[j++] = zStr[i];
104391    }else{
104392      u8 *zOld;
104393      sqlite3 *db = sqlite3_context_db_handle(context);
104394      nOut += nRep - nPattern;
104395      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
104396      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
104397      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
104398        sqlite3_result_error_toobig(context);
104399        sqlite3_free(zOut);
104400        return;
104401      }
104402      zOld = zOut;
104403      zOut = sqlite3_realloc64(zOut, (int)nOut);
104404      if( zOut==0 ){
104405        sqlite3_result_error_nomem(context);
104406        sqlite3_free(zOld);
104407        return;
104408      }
104409      memcpy(&zOut[j], zRep, nRep);
104410      j += nRep;
104411      i += nPattern-1;
104412    }
104413  }
104414  assert( j+nStr-i+1==nOut );
104415  memcpy(&zOut[j], &zStr[i], nStr-i);
104416  j += nStr - i;
104417  assert( j<=nOut );
104418  zOut[j] = 0;
104419  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
104420}
104421
104422/*
104423** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
104424** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
104425*/
104426static void trimFunc(
104427  sqlite3_context *context,
104428  int argc,
104429  sqlite3_value **argv
104430){
104431  const unsigned char *zIn;         /* Input string */
104432  const unsigned char *zCharSet;    /* Set of characters to trim */
104433  int nIn;                          /* Number of bytes in input */
104434  int flags;                        /* 1: trimleft  2: trimright  3: trim */
104435  int i;                            /* Loop counter */
104436  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
104437  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
104438  int nChar;                        /* Number of characters in zCharSet */
104439
104440  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
104441    return;
104442  }
104443  zIn = sqlite3_value_text(argv[0]);
104444  if( zIn==0 ) return;
104445  nIn = sqlite3_value_bytes(argv[0]);
104446  assert( zIn==sqlite3_value_text(argv[0]) );
104447  if( argc==1 ){
104448    static const unsigned char lenOne[] = { 1 };
104449    static unsigned char * const azOne[] = { (u8*)" " };
104450    nChar = 1;
104451    aLen = (u8*)lenOne;
104452    azChar = (unsigned char **)azOne;
104453    zCharSet = 0;
104454  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
104455    return;
104456  }else{
104457    const unsigned char *z;
104458    for(z=zCharSet, nChar=0; *z; nChar++){
104459      SQLITE_SKIP_UTF8(z);
104460    }
104461    if( nChar>0 ){
104462      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
104463      if( azChar==0 ){
104464        return;
104465      }
104466      aLen = (unsigned char*)&azChar[nChar];
104467      for(z=zCharSet, nChar=0; *z; nChar++){
104468        azChar[nChar] = (unsigned char *)z;
104469        SQLITE_SKIP_UTF8(z);
104470        aLen[nChar] = (u8)(z - azChar[nChar]);
104471      }
104472    }
104473  }
104474  if( nChar>0 ){
104475    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
104476    if( flags & 1 ){
104477      while( nIn>0 ){
104478        int len = 0;
104479        for(i=0; i<nChar; i++){
104480          len = aLen[i];
104481          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
104482        }
104483        if( i>=nChar ) break;
104484        zIn += len;
104485        nIn -= len;
104486      }
104487    }
104488    if( flags & 2 ){
104489      while( nIn>0 ){
104490        int len = 0;
104491        for(i=0; i<nChar; i++){
104492          len = aLen[i];
104493          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
104494        }
104495        if( i>=nChar ) break;
104496        nIn -= len;
104497      }
104498    }
104499    if( zCharSet ){
104500      sqlite3_free(azChar);
104501    }
104502  }
104503  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
104504}
104505
104506
104507#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
104508/*
104509** The "unknown" function is automatically substituted in place of
104510** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
104511** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
104512** When the "sqlite3" command-line shell is built using this functionality,
104513** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
104514** involving application-defined functions to be examined in a generic
104515** sqlite3 shell.
104516*/
104517static void unknownFunc(
104518  sqlite3_context *context,
104519  int argc,
104520  sqlite3_value **argv
104521){
104522  /* no-op */
104523}
104524#endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
104525
104526
104527/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
104528** is only available if the SQLITE_SOUNDEX compile-time option is used
104529** when SQLite is built.
104530*/
104531#ifdef SQLITE_SOUNDEX
104532/*
104533** Compute the soundex encoding of a word.
104534**
104535** IMP: R-59782-00072 The soundex(X) function returns a string that is the
104536** soundex encoding of the string X.
104537*/
104538static void soundexFunc(
104539  sqlite3_context *context,
104540  int argc,
104541  sqlite3_value **argv
104542){
104543  char zResult[8];
104544  const u8 *zIn;
104545  int i, j;
104546  static const unsigned char iCode[] = {
104547    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
104548    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
104549    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
104550    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
104551    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
104552    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
104553    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
104554    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
104555  };
104556  assert( argc==1 );
104557  zIn = (u8*)sqlite3_value_text(argv[0]);
104558  if( zIn==0 ) zIn = (u8*)"";
104559  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
104560  if( zIn[i] ){
104561    u8 prevcode = iCode[zIn[i]&0x7f];
104562    zResult[0] = sqlite3Toupper(zIn[i]);
104563    for(j=1; j<4 && zIn[i]; i++){
104564      int code = iCode[zIn[i]&0x7f];
104565      if( code>0 ){
104566        if( code!=prevcode ){
104567          prevcode = code;
104568          zResult[j++] = code + '0';
104569        }
104570      }else{
104571        prevcode = 0;
104572      }
104573    }
104574    while( j<4 ){
104575      zResult[j++] = '0';
104576    }
104577    zResult[j] = 0;
104578    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
104579  }else{
104580    /* IMP: R-64894-50321 The string "?000" is returned if the argument
104581    ** is NULL or contains no ASCII alphabetic characters. */
104582    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
104583  }
104584}
104585#endif /* SQLITE_SOUNDEX */
104586
104587#ifndef SQLITE_OMIT_LOAD_EXTENSION
104588/*
104589** A function that loads a shared-library extension then returns NULL.
104590*/
104591static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
104592  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
104593  const char *zProc;
104594  sqlite3 *db = sqlite3_context_db_handle(context);
104595  char *zErrMsg = 0;
104596
104597  /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
104598  ** flag is set.  See the sqlite3_enable_load_extension() API.
104599  */
104600  if( (db->flags & SQLITE_LoadExtFunc)==0 ){
104601    sqlite3_result_error(context, "not authorized", -1);
104602    return;
104603  }
104604
104605  if( argc==2 ){
104606    zProc = (const char *)sqlite3_value_text(argv[1]);
104607  }else{
104608    zProc = 0;
104609  }
104610  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
104611    sqlite3_result_error(context, zErrMsg, -1);
104612    sqlite3_free(zErrMsg);
104613  }
104614}
104615#endif
104616
104617
104618/*
104619** An instance of the following structure holds the context of a
104620** sum() or avg() aggregate computation.
104621*/
104622typedef struct SumCtx SumCtx;
104623struct SumCtx {
104624  double rSum;      /* Floating point sum */
104625  i64 iSum;         /* Integer sum */
104626  i64 cnt;          /* Number of elements summed */
104627  u8 overflow;      /* True if integer overflow seen */
104628  u8 approx;        /* True if non-integer value was input to the sum */
104629};
104630
104631/*
104632** Routines used to compute the sum, average, and total.
104633**
104634** The SUM() function follows the (broken) SQL standard which means
104635** that it returns NULL if it sums over no inputs.  TOTAL returns
104636** 0.0 in that case.  In addition, TOTAL always returns a float where
104637** SUM might return an integer if it never encounters a floating point
104638** value.  TOTAL never fails, but SUM might through an exception if
104639** it overflows an integer.
104640*/
104641static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
104642  SumCtx *p;
104643  int type;
104644  assert( argc==1 );
104645  UNUSED_PARAMETER(argc);
104646  p = sqlite3_aggregate_context(context, sizeof(*p));
104647  type = sqlite3_value_numeric_type(argv[0]);
104648  if( p && type!=SQLITE_NULL ){
104649    p->cnt++;
104650    if( type==SQLITE_INTEGER ){
104651      i64 v = sqlite3_value_int64(argv[0]);
104652      p->rSum += v;
104653      if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
104654        p->overflow = 1;
104655      }
104656    }else{
104657      p->rSum += sqlite3_value_double(argv[0]);
104658      p->approx = 1;
104659    }
104660  }
104661}
104662static void sumFinalize(sqlite3_context *context){
104663  SumCtx *p;
104664  p = sqlite3_aggregate_context(context, 0);
104665  if( p && p->cnt>0 ){
104666    if( p->overflow ){
104667      sqlite3_result_error(context,"integer overflow",-1);
104668    }else if( p->approx ){
104669      sqlite3_result_double(context, p->rSum);
104670    }else{
104671      sqlite3_result_int64(context, p->iSum);
104672    }
104673  }
104674}
104675static void avgFinalize(sqlite3_context *context){
104676  SumCtx *p;
104677  p = sqlite3_aggregate_context(context, 0);
104678  if( p && p->cnt>0 ){
104679    sqlite3_result_double(context, p->rSum/(double)p->cnt);
104680  }
104681}
104682static void totalFinalize(sqlite3_context *context){
104683  SumCtx *p;
104684  p = sqlite3_aggregate_context(context, 0);
104685  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
104686  sqlite3_result_double(context, p ? p->rSum : (double)0);
104687}
104688
104689/*
104690** The following structure keeps track of state information for the
104691** count() aggregate function.
104692*/
104693typedef struct CountCtx CountCtx;
104694struct CountCtx {
104695  i64 n;
104696};
104697
104698/*
104699** Routines to implement the count() aggregate function.
104700*/
104701static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
104702  CountCtx *p;
104703  p = sqlite3_aggregate_context(context, sizeof(*p));
104704  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
104705    p->n++;
104706  }
104707
104708#ifndef SQLITE_OMIT_DEPRECATED
104709  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
104710  ** sure it still operates correctly, verify that its count agrees with our
104711  ** internal count when using count(*) and when the total count can be
104712  ** expressed as a 32-bit integer. */
104713  assert( argc==1 || p==0 || p->n>0x7fffffff
104714          || p->n==sqlite3_aggregate_count(context) );
104715#endif
104716}
104717static void countFinalize(sqlite3_context *context){
104718  CountCtx *p;
104719  p = sqlite3_aggregate_context(context, 0);
104720  sqlite3_result_int64(context, p ? p->n : 0);
104721}
104722
104723/*
104724** Routines to implement min() and max() aggregate functions.
104725*/
104726static void minmaxStep(
104727  sqlite3_context *context,
104728  int NotUsed,
104729  sqlite3_value **argv
104730){
104731  Mem *pArg  = (Mem *)argv[0];
104732  Mem *pBest;
104733  UNUSED_PARAMETER(NotUsed);
104734
104735  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
104736  if( !pBest ) return;
104737
104738  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
104739    if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
104740  }else if( pBest->flags ){
104741    int max;
104742    int cmp;
104743    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
104744    /* This step function is used for both the min() and max() aggregates,
104745    ** the only difference between the two being that the sense of the
104746    ** comparison is inverted. For the max() aggregate, the
104747    ** sqlite3_user_data() function returns (void *)-1. For min() it
104748    ** returns (void *)db, where db is the sqlite3* database pointer.
104749    ** Therefore the next statement sets variable 'max' to 1 for the max()
104750    ** aggregate, or 0 for min().
104751    */
104752    max = sqlite3_user_data(context)!=0;
104753    cmp = sqlite3MemCompare(pBest, pArg, pColl);
104754    if( (max && cmp<0) || (!max && cmp>0) ){
104755      sqlite3VdbeMemCopy(pBest, pArg);
104756    }else{
104757      sqlite3SkipAccumulatorLoad(context);
104758    }
104759  }else{
104760    pBest->db = sqlite3_context_db_handle(context);
104761    sqlite3VdbeMemCopy(pBest, pArg);
104762  }
104763}
104764static void minMaxFinalize(sqlite3_context *context){
104765  sqlite3_value *pRes;
104766  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
104767  if( pRes ){
104768    if( pRes->flags ){
104769      sqlite3_result_value(context, pRes);
104770    }
104771    sqlite3VdbeMemRelease(pRes);
104772  }
104773}
104774
104775/*
104776** group_concat(EXPR, ?SEPARATOR?)
104777*/
104778static void groupConcatStep(
104779  sqlite3_context *context,
104780  int argc,
104781  sqlite3_value **argv
104782){
104783  const char *zVal;
104784  StrAccum *pAccum;
104785  const char *zSep;
104786  int nVal, nSep;
104787  assert( argc==1 || argc==2 );
104788  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
104789  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
104790
104791  if( pAccum ){
104792    sqlite3 *db = sqlite3_context_db_handle(context);
104793    int firstTerm = pAccum->mxAlloc==0;
104794    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
104795    if( !firstTerm ){
104796      if( argc==2 ){
104797        zSep = (char*)sqlite3_value_text(argv[1]);
104798        nSep = sqlite3_value_bytes(argv[1]);
104799      }else{
104800        zSep = ",";
104801        nSep = 1;
104802      }
104803      if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
104804    }
104805    zVal = (char*)sqlite3_value_text(argv[0]);
104806    nVal = sqlite3_value_bytes(argv[0]);
104807    if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
104808  }
104809}
104810static void groupConcatFinalize(sqlite3_context *context){
104811  StrAccum *pAccum;
104812  pAccum = sqlite3_aggregate_context(context, 0);
104813  if( pAccum ){
104814    if( pAccum->accError==STRACCUM_TOOBIG ){
104815      sqlite3_result_error_toobig(context);
104816    }else if( pAccum->accError==STRACCUM_NOMEM ){
104817      sqlite3_result_error_nomem(context);
104818    }else{
104819      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
104820                          sqlite3_free);
104821    }
104822  }
104823}
104824
104825/*
104826** This routine does per-connection function registration.  Most
104827** of the built-in functions above are part of the global function set.
104828** This routine only deals with those that are not global.
104829*/
104830SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
104831  int rc = sqlite3_overload_function(db, "MATCH", 2);
104832  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
104833  if( rc==SQLITE_NOMEM ){
104834    sqlite3OomFault(db);
104835  }
104836}
104837
104838/*
104839** Set the LIKEOPT flag on the 2-argument function with the given name.
104840*/
104841static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
104842  FuncDef *pDef;
104843  pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
104844  if( ALWAYS(pDef) ){
104845    pDef->funcFlags |= flagVal;
104846  }
104847}
104848
104849/*
104850** Register the built-in LIKE and GLOB functions.  The caseSensitive
104851** parameter determines whether or not the LIKE operator is case
104852** sensitive.  GLOB is always case sensitive.
104853*/
104854SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
104855  struct compareInfo *pInfo;
104856  if( caseSensitive ){
104857    pInfo = (struct compareInfo*)&likeInfoAlt;
104858  }else{
104859    pInfo = (struct compareInfo*)&likeInfoNorm;
104860  }
104861  sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
104862  sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
104863  sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
104864      (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
104865  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
104866  setLikeOptFlag(db, "like",
104867      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
104868}
104869
104870/*
104871** pExpr points to an expression which implements a function.  If
104872** it is appropriate to apply the LIKE optimization to that function
104873** then set aWc[0] through aWc[2] to the wildcard characters and
104874** return TRUE.  If the function is not a LIKE-style function then
104875** return FALSE.
104876**
104877** *pIsNocase is set to true if uppercase and lowercase are equivalent for
104878** the function (default for LIKE).  If the function makes the distinction
104879** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
104880** false.
104881*/
104882SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
104883  FuncDef *pDef;
104884  if( pExpr->op!=TK_FUNCTION
104885   || !pExpr->x.pList
104886   || pExpr->x.pList->nExpr!=2
104887  ){
104888    return 0;
104889  }
104890  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
104891  pDef = sqlite3FindFunction(db, pExpr->u.zToken, 2, SQLITE_UTF8, 0);
104892  if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
104893    return 0;
104894  }
104895
104896  /* The memcpy() statement assumes that the wildcard characters are
104897  ** the first three statements in the compareInfo structure.  The
104898  ** asserts() that follow verify that assumption
104899  */
104900  memcpy(aWc, pDef->pUserData, 3);
104901  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
104902  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
104903  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
104904  *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
104905  return 1;
104906}
104907
104908/*
104909** All of the FuncDef structures in the aBuiltinFunc[] array above
104910** to the global function hash table.  This occurs at start-time (as
104911** a consequence of calling sqlite3_initialize()).
104912**
104913** After this routine runs
104914*/
104915SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
104916  /*
104917  ** The following array holds FuncDef structures for all of the functions
104918  ** defined in this file.
104919  **
104920  ** The array cannot be constant since changes are made to the
104921  ** FuncDef.pHash elements at start-time.  The elements of this array
104922  ** are read-only after initialization is complete.
104923  **
104924  ** For peak efficiency, put the most frequently used function last.
104925  */
104926  static FuncDef aBuiltinFunc[] = {
104927#ifdef SQLITE_SOUNDEX
104928    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
104929#endif
104930#ifndef SQLITE_OMIT_LOAD_EXTENSION
104931    VFUNCTION(load_extension,    1, 0, 0, loadExt          ),
104932    VFUNCTION(load_extension,    2, 0, 0, loadExt          ),
104933#endif
104934#if SQLITE_USER_AUTHENTICATION
104935    FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
104936#endif
104937#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
104938    DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
104939    DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
104940#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
104941    FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
104942    FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
104943    FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
104944    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
104945    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
104946    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
104947    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
104948    FUNCTION(trim,               1, 3, 0, trimFunc         ),
104949    FUNCTION(trim,               2, 3, 0, trimFunc         ),
104950    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
104951    FUNCTION(min,                0, 0, 1, 0                ),
104952    AGGREGATE2(min,              1, 0, 1, minmaxStep,      minMaxFinalize,
104953                                          SQLITE_FUNC_MINMAX ),
104954    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
104955    FUNCTION(max,                0, 1, 1, 0                ),
104956    AGGREGATE2(max,              1, 1, 1, minmaxStep,      minMaxFinalize,
104957                                          SQLITE_FUNC_MINMAX ),
104958    FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
104959    FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
104960    FUNCTION(instr,              2, 0, 0, instrFunc        ),
104961    FUNCTION(printf,            -1, 0, 0, printfFunc       ),
104962    FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
104963    FUNCTION(char,              -1, 0, 0, charFunc         ),
104964    FUNCTION(abs,                1, 0, 0, absFunc          ),
104965#ifndef SQLITE_OMIT_FLOATING_POINT
104966    FUNCTION(round,              1, 0, 0, roundFunc        ),
104967    FUNCTION(round,              2, 0, 0, roundFunc        ),
104968#endif
104969    FUNCTION(upper,              1, 0, 0, upperFunc        ),
104970    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
104971    FUNCTION(hex,                1, 0, 0, hexFunc          ),
104972    FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
104973    VFUNCTION(random,            0, 0, 0, randomFunc       ),
104974    VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
104975    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
104976    DFUNCTION(sqlite_version,    0, 0, 0, versionFunc      ),
104977    DFUNCTION(sqlite_source_id,  0, 0, 0, sourceidFunc     ),
104978    FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
104979    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
104980    VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
104981    VFUNCTION(changes,           0, 0, 0, changes          ),
104982    VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
104983    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
104984    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
104985    FUNCTION(substr,             2, 0, 0, substrFunc       ),
104986    FUNCTION(substr,             3, 0, 0, substrFunc       ),
104987    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
104988    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
104989    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
104990    AGGREGATE2(count,            0, 0, 0, countStep,       countFinalize,
104991               SQLITE_FUNC_COUNT  ),
104992    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
104993    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
104994    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
104995
104996    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
104997#ifdef SQLITE_CASE_SENSITIVE_LIKE
104998    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
104999    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
105000#else
105001    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
105002    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
105003#endif
105004#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
105005    FUNCTION(unknown,           -1, 0, 0, unknownFunc      ),
105006#endif
105007    FUNCTION(coalesce,           1, 0, 0, 0                ),
105008    FUNCTION(coalesce,           0, 0, 0, 0                ),
105009    FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
105010  };
105011#ifndef SQLITE_OMIT_ALTERTABLE
105012  sqlite3AlterFunctions();
105013#endif
105014#if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
105015  sqlite3AnalyzeFunctions();
105016#endif
105017  sqlite3RegisterDateTimeFunctions();
105018  sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
105019
105020#if 0  /* Enable to print out how the built-in functions are hashed */
105021  {
105022    int i;
105023    FuncDef *p;
105024    for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
105025      printf("FUNC-HASH %02d:", i);
105026      for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
105027        int n = sqlite3Strlen30(p->zName);
105028        int h = p->zName[0] + n;
105029        printf(" %s(%d)", p->zName, h);
105030      }
105031      printf("\n");
105032    }
105033  }
105034#endif
105035}
105036
105037/************** End of func.c ************************************************/
105038/************** Begin file fkey.c ********************************************/
105039/*
105040**
105041** The author disclaims copyright to this source code.  In place of
105042** a legal notice, here is a blessing:
105043**
105044**    May you do good and not evil.
105045**    May you find forgiveness for yourself and forgive others.
105046**    May you share freely, never taking more than you give.
105047**
105048*************************************************************************
105049** This file contains code used by the compiler to add foreign key
105050** support to compiled SQL statements.
105051*/
105052/* #include "sqliteInt.h" */
105053
105054#ifndef SQLITE_OMIT_FOREIGN_KEY
105055#ifndef SQLITE_OMIT_TRIGGER
105056
105057/*
105058** Deferred and Immediate FKs
105059** --------------------------
105060**
105061** Foreign keys in SQLite come in two flavours: deferred and immediate.
105062** If an immediate foreign key constraint is violated,
105063** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
105064** statement transaction rolled back. If a
105065** deferred foreign key constraint is violated, no action is taken
105066** immediately. However if the application attempts to commit the
105067** transaction before fixing the constraint violation, the attempt fails.
105068**
105069** Deferred constraints are implemented using a simple counter associated
105070** with the database handle. The counter is set to zero each time a
105071** database transaction is opened. Each time a statement is executed
105072** that causes a foreign key violation, the counter is incremented. Each
105073** time a statement is executed that removes an existing violation from
105074** the database, the counter is decremented. When the transaction is
105075** committed, the commit fails if the current value of the counter is
105076** greater than zero. This scheme has two big drawbacks:
105077**
105078**   * When a commit fails due to a deferred foreign key constraint,
105079**     there is no way to tell which foreign constraint is not satisfied,
105080**     or which row it is not satisfied for.
105081**
105082**   * If the database contains foreign key violations when the
105083**     transaction is opened, this may cause the mechanism to malfunction.
105084**
105085** Despite these problems, this approach is adopted as it seems simpler
105086** than the alternatives.
105087**
105088** INSERT operations:
105089**
105090**   I.1) For each FK for which the table is the child table, search
105091**        the parent table for a match. If none is found increment the
105092**        constraint counter.
105093**
105094**   I.2) For each FK for which the table is the parent table,
105095**        search the child table for rows that correspond to the new
105096**        row in the parent table. Decrement the counter for each row
105097**        found (as the constraint is now satisfied).
105098**
105099** DELETE operations:
105100**
105101**   D.1) For each FK for which the table is the child table,
105102**        search the parent table for a row that corresponds to the
105103**        deleted row in the child table. If such a row is not found,
105104**        decrement the counter.
105105**
105106**   D.2) For each FK for which the table is the parent table, search
105107**        the child table for rows that correspond to the deleted row
105108**        in the parent table. For each found increment the counter.
105109**
105110** UPDATE operations:
105111**
105112**   An UPDATE command requires that all 4 steps above are taken, but only
105113**   for FK constraints for which the affected columns are actually
105114**   modified (values must be compared at runtime).
105115**
105116** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
105117** This simplifies the implementation a bit.
105118**
105119** For the purposes of immediate FK constraints, the OR REPLACE conflict
105120** resolution is considered to delete rows before the new row is inserted.
105121** If a delete caused by OR REPLACE violates an FK constraint, an exception
105122** is thrown, even if the FK constraint would be satisfied after the new
105123** row is inserted.
105124**
105125** Immediate constraints are usually handled similarly. The only difference
105126** is that the counter used is stored as part of each individual statement
105127** object (struct Vdbe). If, after the statement has run, its immediate
105128** constraint counter is greater than zero,
105129** it returns SQLITE_CONSTRAINT_FOREIGNKEY
105130** and the statement transaction is rolled back. An exception is an INSERT
105131** statement that inserts a single row only (no triggers). In this case,
105132** instead of using a counter, an exception is thrown immediately if the
105133** INSERT violates a foreign key constraint. This is necessary as such
105134** an INSERT does not open a statement transaction.
105135**
105136** TODO: How should dropping a table be handled? How should renaming a
105137** table be handled?
105138**
105139**
105140** Query API Notes
105141** ---------------
105142**
105143** Before coding an UPDATE or DELETE row operation, the code-generator
105144** for those two operations needs to know whether or not the operation
105145** requires any FK processing and, if so, which columns of the original
105146** row are required by the FK processing VDBE code (i.e. if FKs were
105147** implemented using triggers, which of the old.* columns would be
105148** accessed). No information is required by the code-generator before
105149** coding an INSERT operation. The functions used by the UPDATE/DELETE
105150** generation code to query for this information are:
105151**
105152**   sqlite3FkRequired() - Test to see if FK processing is required.
105153**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
105154**
105155**
105156** Externally accessible module functions
105157** --------------------------------------
105158**
105159**   sqlite3FkCheck()    - Check for foreign key violations.
105160**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
105161**   sqlite3FkDelete()   - Delete an FKey structure.
105162*/
105163
105164/*
105165** VDBE Calling Convention
105166** -----------------------
105167**
105168** Example:
105169**
105170**   For the following INSERT statement:
105171**
105172**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
105173**     INSERT INTO t1 VALUES(1, 2, 3.1);
105174**
105175**   Register (x):        2    (type integer)
105176**   Register (x+1):      1    (type integer)
105177**   Register (x+2):      NULL (type NULL)
105178**   Register (x+3):      3.1  (type real)
105179*/
105180
105181/*
105182** A foreign key constraint requires that the key columns in the parent
105183** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
105184** Given that pParent is the parent table for foreign key constraint pFKey,
105185** search the schema for a unique index on the parent key columns.
105186**
105187** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
105188** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
105189** is set to point to the unique index.
105190**
105191** If the parent key consists of a single column (the foreign key constraint
105192** is not a composite foreign key), output variable *paiCol is set to NULL.
105193** Otherwise, it is set to point to an allocated array of size N, where
105194** N is the number of columns in the parent key. The first element of the
105195** array is the index of the child table column that is mapped by the FK
105196** constraint to the parent table column stored in the left-most column
105197** of index *ppIdx. The second element of the array is the index of the
105198** child table column that corresponds to the second left-most column of
105199** *ppIdx, and so on.
105200**
105201** If the required index cannot be found, either because:
105202**
105203**   1) The named parent key columns do not exist, or
105204**
105205**   2) The named parent key columns do exist, but are not subject to a
105206**      UNIQUE or PRIMARY KEY constraint, or
105207**
105208**   3) No parent key columns were provided explicitly as part of the
105209**      foreign key definition, and the parent table does not have a
105210**      PRIMARY KEY, or
105211**
105212**   4) No parent key columns were provided explicitly as part of the
105213**      foreign key definition, and the PRIMARY KEY of the parent table
105214**      consists of a different number of columns to the child key in
105215**      the child table.
105216**
105217** then non-zero is returned, and a "foreign key mismatch" error loaded
105218** into pParse. If an OOM error occurs, non-zero is returned and the
105219** pParse->db->mallocFailed flag is set.
105220*/
105221SQLITE_PRIVATE int sqlite3FkLocateIndex(
105222  Parse *pParse,                  /* Parse context to store any error in */
105223  Table *pParent,                 /* Parent table of FK constraint pFKey */
105224  FKey *pFKey,                    /* Foreign key to find index for */
105225  Index **ppIdx,                  /* OUT: Unique index on parent table */
105226  int **paiCol                    /* OUT: Map of index columns in pFKey */
105227){
105228  Index *pIdx = 0;                    /* Value to return via *ppIdx */
105229  int *aiCol = 0;                     /* Value to return via *paiCol */
105230  int nCol = pFKey->nCol;             /* Number of columns in parent key */
105231  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
105232
105233  /* The caller is responsible for zeroing output parameters. */
105234  assert( ppIdx && *ppIdx==0 );
105235  assert( !paiCol || *paiCol==0 );
105236  assert( pParse );
105237
105238  /* If this is a non-composite (single column) foreign key, check if it
105239  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
105240  ** and *paiCol set to zero and return early.
105241  **
105242  ** Otherwise, for a composite foreign key (more than one column), allocate
105243  ** space for the aiCol array (returned via output parameter *paiCol).
105244  ** Non-composite foreign keys do not require the aiCol array.
105245  */
105246  if( nCol==1 ){
105247    /* The FK maps to the IPK if any of the following are true:
105248    **
105249    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
105250    **      mapped to the primary key of table pParent, or
105251    **   2) The FK is explicitly mapped to a column declared as INTEGER
105252    **      PRIMARY KEY.
105253    */
105254    if( pParent->iPKey>=0 ){
105255      if( !zKey ) return 0;
105256      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
105257    }
105258  }else if( paiCol ){
105259    assert( nCol>1 );
105260    aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
105261    if( !aiCol ) return 1;
105262    *paiCol = aiCol;
105263  }
105264
105265  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
105266    if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
105267      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
105268      ** of columns. If each indexed column corresponds to a foreign key
105269      ** column of pFKey, then this index is a winner.  */
105270
105271      if( zKey==0 ){
105272        /* If zKey is NULL, then this foreign key is implicitly mapped to
105273        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
105274        ** identified by the test.  */
105275        if( IsPrimaryKeyIndex(pIdx) ){
105276          if( aiCol ){
105277            int i;
105278            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
105279          }
105280          break;
105281        }
105282      }else{
105283        /* If zKey is non-NULL, then this foreign key was declared to
105284        ** map to an explicit list of columns in table pParent. Check if this
105285        ** index matches those columns. Also, check that the index uses
105286        ** the default collation sequences for each column. */
105287        int i, j;
105288        for(i=0; i<nCol; i++){
105289          i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
105290          const char *zDfltColl;            /* Def. collation for column */
105291          char *zIdxCol;                    /* Name of indexed column */
105292
105293          if( iCol<0 ) break; /* No foreign keys against expression indexes */
105294
105295          /* If the index uses a collation sequence that is different from
105296          ** the default collation sequence for the column, this index is
105297          ** unusable. Bail out early in this case.  */
105298          zDfltColl = pParent->aCol[iCol].zColl;
105299          if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
105300          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
105301
105302          zIdxCol = pParent->aCol[iCol].zName;
105303          for(j=0; j<nCol; j++){
105304            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
105305              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
105306              break;
105307            }
105308          }
105309          if( j==nCol ) break;
105310        }
105311        if( i==nCol ) break;      /* pIdx is usable */
105312      }
105313    }
105314  }
105315
105316  if( !pIdx ){
105317    if( !pParse->disableTriggers ){
105318      sqlite3ErrorMsg(pParse,
105319           "foreign key mismatch - \"%w\" referencing \"%w\"",
105320           pFKey->pFrom->zName, pFKey->zTo);
105321    }
105322    sqlite3DbFree(pParse->db, aiCol);
105323    return 1;
105324  }
105325
105326  *ppIdx = pIdx;
105327  return 0;
105328}
105329
105330/*
105331** This function is called when a row is inserted into or deleted from the
105332** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
105333** on the child table of pFKey, this function is invoked twice for each row
105334** affected - once to "delete" the old row, and then again to "insert" the
105335** new row.
105336**
105337** Each time it is called, this function generates VDBE code to locate the
105338** row in the parent table that corresponds to the row being inserted into
105339** or deleted from the child table. If the parent row can be found, no
105340** special action is taken. Otherwise, if the parent row can *not* be
105341** found in the parent table:
105342**
105343**   Operation | FK type   | Action taken
105344**   --------------------------------------------------------------------------
105345**   INSERT      immediate   Increment the "immediate constraint counter".
105346**
105347**   DELETE      immediate   Decrement the "immediate constraint counter".
105348**
105349**   INSERT      deferred    Increment the "deferred constraint counter".
105350**
105351**   DELETE      deferred    Decrement the "deferred constraint counter".
105352**
105353** These operations are identified in the comment at the top of this file
105354** (fkey.c) as "I.1" and "D.1".
105355*/
105356static void fkLookupParent(
105357  Parse *pParse,        /* Parse context */
105358  int iDb,              /* Index of database housing pTab */
105359  Table *pTab,          /* Parent table of FK pFKey */
105360  Index *pIdx,          /* Unique index on parent key columns in pTab */
105361  FKey *pFKey,          /* Foreign key constraint */
105362  int *aiCol,           /* Map from parent key columns to child table columns */
105363  int regData,          /* Address of array containing child table row */
105364  int nIncr,            /* Increment constraint counter by this */
105365  int isIgnore          /* If true, pretend pTab contains all NULL values */
105366){
105367  int i;                                    /* Iterator variable */
105368  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
105369  int iCur = pParse->nTab - 1;              /* Cursor number to use */
105370  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
105371
105372  /* If nIncr is less than zero, then check at runtime if there are any
105373  ** outstanding constraints to resolve. If there are not, there is no need
105374  ** to check if deleting this row resolves any outstanding violations.
105375  **
105376  ** Check if any of the key columns in the child table row are NULL. If
105377  ** any are, then the constraint is considered satisfied. No need to
105378  ** search for a matching row in the parent table.  */
105379  if( nIncr<0 ){
105380    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
105381    VdbeCoverage(v);
105382  }
105383  for(i=0; i<pFKey->nCol; i++){
105384    int iReg = aiCol[i] + regData + 1;
105385    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
105386  }
105387
105388  if( isIgnore==0 ){
105389    if( pIdx==0 ){
105390      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
105391      ** column of the parent table (table pTab).  */
105392      int iMustBeInt;               /* Address of MustBeInt instruction */
105393      int regTemp = sqlite3GetTempReg(pParse);
105394
105395      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
105396      ** apply the affinity of the parent key). If this fails, then there
105397      ** is no matching parent key. Before using MustBeInt, make a copy of
105398      ** the value. Otherwise, the value inserted into the child key column
105399      ** will have INTEGER affinity applied to it, which may not be correct.  */
105400      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
105401      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
105402      VdbeCoverage(v);
105403
105404      /* If the parent table is the same as the child table, and we are about
105405      ** to increment the constraint-counter (i.e. this is an INSERT operation),
105406      ** then check if the row being inserted matches itself. If so, do not
105407      ** increment the constraint-counter.  */
105408      if( pTab==pFKey->pFrom && nIncr==1 ){
105409        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
105410        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
105411      }
105412
105413      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
105414      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
105415      sqlite3VdbeGoto(v, iOk);
105416      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
105417      sqlite3VdbeJumpHere(v, iMustBeInt);
105418      sqlite3ReleaseTempReg(pParse, regTemp);
105419    }else{
105420      int nCol = pFKey->nCol;
105421      int regTemp = sqlite3GetTempRange(pParse, nCol);
105422      int regRec = sqlite3GetTempReg(pParse);
105423
105424      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
105425      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
105426      for(i=0; i<nCol; i++){
105427        sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
105428      }
105429
105430      /* If the parent table is the same as the child table, and we are about
105431      ** to increment the constraint-counter (i.e. this is an INSERT operation),
105432      ** then check if the row being inserted matches itself. If so, do not
105433      ** increment the constraint-counter.
105434      **
105435      ** If any of the parent-key values are NULL, then the row cannot match
105436      ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
105437      ** of the parent-key values are NULL (at this point it is known that
105438      ** none of the child key values are).
105439      */
105440      if( pTab==pFKey->pFrom && nIncr==1 ){
105441        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
105442        for(i=0; i<nCol; i++){
105443          int iChild = aiCol[i]+1+regData;
105444          int iParent = pIdx->aiColumn[i]+1+regData;
105445          assert( pIdx->aiColumn[i]>=0 );
105446          assert( aiCol[i]!=pTab->iPKey );
105447          if( pIdx->aiColumn[i]==pTab->iPKey ){
105448            /* The parent key is a composite key that includes the IPK column */
105449            iParent = regData;
105450          }
105451          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
105452          sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
105453        }
105454        sqlite3VdbeGoto(v, iOk);
105455      }
105456
105457      sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
105458                        sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
105459      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
105460
105461      sqlite3ReleaseTempReg(pParse, regRec);
105462      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
105463    }
105464  }
105465
105466  if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
105467   && !pParse->pToplevel
105468   && !pParse->isMultiWrite
105469  ){
105470    /* Special case: If this is an INSERT statement that will insert exactly
105471    ** one row into the table, raise a constraint immediately instead of
105472    ** incrementing a counter. This is necessary as the VM code is being
105473    ** generated for will not open a statement transaction.  */
105474    assert( nIncr==1 );
105475    sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
105476        OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
105477  }else{
105478    if( nIncr>0 && pFKey->isDeferred==0 ){
105479      sqlite3MayAbort(pParse);
105480    }
105481    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
105482  }
105483
105484  sqlite3VdbeResolveLabel(v, iOk);
105485  sqlite3VdbeAddOp1(v, OP_Close, iCur);
105486}
105487
105488
105489/*
105490** Return an Expr object that refers to a memory register corresponding
105491** to column iCol of table pTab.
105492**
105493** regBase is the first of an array of register that contains the data
105494** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
105495** column.  regBase+2 holds the second column, and so forth.
105496*/
105497static Expr *exprTableRegister(
105498  Parse *pParse,     /* Parsing and code generating context */
105499  Table *pTab,       /* The table whose content is at r[regBase]... */
105500  int regBase,       /* Contents of table pTab */
105501  i16 iCol           /* Which column of pTab is desired */
105502){
105503  Expr *pExpr;
105504  Column *pCol;
105505  const char *zColl;
105506  sqlite3 *db = pParse->db;
105507
105508  pExpr = sqlite3Expr(db, TK_REGISTER, 0);
105509  if( pExpr ){
105510    if( iCol>=0 && iCol!=pTab->iPKey ){
105511      pCol = &pTab->aCol[iCol];
105512      pExpr->iTable = regBase + iCol + 1;
105513      pExpr->affinity = pCol->affinity;
105514      zColl = pCol->zColl;
105515      if( zColl==0 ) zColl = db->pDfltColl->zName;
105516      pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
105517    }else{
105518      pExpr->iTable = regBase;
105519      pExpr->affinity = SQLITE_AFF_INTEGER;
105520    }
105521  }
105522  return pExpr;
105523}
105524
105525/*
105526** Return an Expr object that refers to column iCol of table pTab which
105527** has cursor iCur.
105528*/
105529static Expr *exprTableColumn(
105530  sqlite3 *db,      /* The database connection */
105531  Table *pTab,      /* The table whose column is desired */
105532  int iCursor,      /* The open cursor on the table */
105533  i16 iCol          /* The column that is wanted */
105534){
105535  Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
105536  if( pExpr ){
105537    pExpr->pTab = pTab;
105538    pExpr->iTable = iCursor;
105539    pExpr->iColumn = iCol;
105540  }
105541  return pExpr;
105542}
105543
105544/*
105545** This function is called to generate code executed when a row is deleted
105546** from the parent table of foreign key constraint pFKey and, if pFKey is
105547** deferred, when a row is inserted into the same table. When generating
105548** code for an SQL UPDATE operation, this function may be called twice -
105549** once to "delete" the old row and once to "insert" the new row.
105550**
105551** Parameter nIncr is passed -1 when inserting a row (as this may decrease
105552** the number of FK violations in the db) or +1 when deleting one (as this
105553** may increase the number of FK constraint problems).
105554**
105555** The code generated by this function scans through the rows in the child
105556** table that correspond to the parent table row being deleted or inserted.
105557** For each child row found, one of the following actions is taken:
105558**
105559**   Operation | FK type   | Action taken
105560**   --------------------------------------------------------------------------
105561**   DELETE      immediate   Increment the "immediate constraint counter".
105562**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
105563**                           throw a "FOREIGN KEY constraint failed" exception.
105564**
105565**   INSERT      immediate   Decrement the "immediate constraint counter".
105566**
105567**   DELETE      deferred    Increment the "deferred constraint counter".
105568**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
105569**                           throw a "FOREIGN KEY constraint failed" exception.
105570**
105571**   INSERT      deferred    Decrement the "deferred constraint counter".
105572**
105573** These operations are identified in the comment at the top of this file
105574** (fkey.c) as "I.2" and "D.2".
105575*/
105576static void fkScanChildren(
105577  Parse *pParse,                  /* Parse context */
105578  SrcList *pSrc,                  /* The child table to be scanned */
105579  Table *pTab,                    /* The parent table */
105580  Index *pIdx,                    /* Index on parent covering the foreign key */
105581  FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
105582  int *aiCol,                     /* Map from pIdx cols to child table cols */
105583  int regData,                    /* Parent row data starts here */
105584  int nIncr                       /* Amount to increment deferred counter by */
105585){
105586  sqlite3 *db = pParse->db;       /* Database handle */
105587  int i;                          /* Iterator variable */
105588  Expr *pWhere = 0;               /* WHERE clause to scan with */
105589  NameContext sNameContext;       /* Context used to resolve WHERE clause */
105590  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
105591  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
105592  Vdbe *v = sqlite3GetVdbe(pParse);
105593
105594  assert( pIdx==0 || pIdx->pTable==pTab );
105595  assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
105596  assert( pIdx!=0 || pFKey->nCol==1 );
105597  assert( pIdx!=0 || HasRowid(pTab) );
105598
105599  if( nIncr<0 ){
105600    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
105601    VdbeCoverage(v);
105602  }
105603
105604  /* Create an Expr object representing an SQL expression like:
105605  **
105606  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
105607  **
105608  ** The collation sequence used for the comparison should be that of
105609  ** the parent key columns. The affinity of the parent key column should
105610  ** be applied to each child key value before the comparison takes place.
105611  */
105612  for(i=0; i<pFKey->nCol; i++){
105613    Expr *pLeft;                  /* Value from parent table row */
105614    Expr *pRight;                 /* Column ref to child table */
105615    Expr *pEq;                    /* Expression (pLeft = pRight) */
105616    i16 iCol;                     /* Index of column in child table */
105617    const char *zCol;             /* Name of column in child table */
105618
105619    iCol = pIdx ? pIdx->aiColumn[i] : -1;
105620    pLeft = exprTableRegister(pParse, pTab, regData, iCol);
105621    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
105622    assert( iCol>=0 );
105623    zCol = pFKey->pFrom->aCol[iCol].zName;
105624    pRight = sqlite3Expr(db, TK_ID, zCol);
105625    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
105626    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
105627  }
105628
105629  /* If the child table is the same as the parent table, then add terms
105630  ** to the WHERE clause that prevent this entry from being scanned.
105631  ** The added WHERE clause terms are like this:
105632  **
105633  **     $current_rowid!=rowid
105634  **     NOT( $current_a==a AND $current_b==b AND ... )
105635  **
105636  ** The first form is used for rowid tables.  The second form is used
105637  ** for WITHOUT ROWID tables.  In the second form, the primary key is
105638  ** (a,b,...)
105639  */
105640  if( pTab==pFKey->pFrom && nIncr>0 ){
105641    Expr *pNe;                    /* Expression (pLeft != pRight) */
105642    Expr *pLeft;                  /* Value from parent table row */
105643    Expr *pRight;                 /* Column ref to child table */
105644    if( HasRowid(pTab) ){
105645      pLeft = exprTableRegister(pParse, pTab, regData, -1);
105646      pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
105647      pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
105648    }else{
105649      Expr *pEq, *pAll = 0;
105650      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
105651      assert( pIdx!=0 );
105652      for(i=0; i<pPk->nKeyCol; i++){
105653        i16 iCol = pIdx->aiColumn[i];
105654        assert( iCol>=0 );
105655        pLeft = exprTableRegister(pParse, pTab, regData, iCol);
105656        pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
105657        pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
105658        pAll = sqlite3ExprAnd(db, pAll, pEq);
105659      }
105660      pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
105661    }
105662    pWhere = sqlite3ExprAnd(db, pWhere, pNe);
105663  }
105664
105665  /* Resolve the references in the WHERE clause. */
105666  memset(&sNameContext, 0, sizeof(NameContext));
105667  sNameContext.pSrcList = pSrc;
105668  sNameContext.pParse = pParse;
105669  sqlite3ResolveExprNames(&sNameContext, pWhere);
105670
105671  /* Create VDBE to loop through the entries in pSrc that match the WHERE
105672  ** clause. For each row found, increment either the deferred or immediate
105673  ** foreign key constraint counter. */
105674  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
105675  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
105676  if( pWInfo ){
105677    sqlite3WhereEnd(pWInfo);
105678  }
105679
105680  /* Clean up the WHERE clause constructed above. */
105681  sqlite3ExprDelete(db, pWhere);
105682  if( iFkIfZero ){
105683    sqlite3VdbeJumpHere(v, iFkIfZero);
105684  }
105685}
105686
105687/*
105688** This function returns a linked list of FKey objects (connected by
105689** FKey.pNextTo) holding all children of table pTab.  For example,
105690** given the following schema:
105691**
105692**   CREATE TABLE t1(a PRIMARY KEY);
105693**   CREATE TABLE t2(b REFERENCES t1(a);
105694**
105695** Calling this function with table "t1" as an argument returns a pointer
105696** to the FKey structure representing the foreign key constraint on table
105697** "t2". Calling this function with "t2" as the argument would return a
105698** NULL pointer (as there are no FK constraints for which t2 is the parent
105699** table).
105700*/
105701SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
105702  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
105703}
105704
105705/*
105706** The second argument is a Trigger structure allocated by the
105707** fkActionTrigger() routine. This function deletes the Trigger structure
105708** and all of its sub-components.
105709**
105710** The Trigger structure or any of its sub-components may be allocated from
105711** the lookaside buffer belonging to database handle dbMem.
105712*/
105713static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
105714  if( p ){
105715    TriggerStep *pStep = p->step_list;
105716    sqlite3ExprDelete(dbMem, pStep->pWhere);
105717    sqlite3ExprListDelete(dbMem, pStep->pExprList);
105718    sqlite3SelectDelete(dbMem, pStep->pSelect);
105719    sqlite3ExprDelete(dbMem, p->pWhen);
105720    sqlite3DbFree(dbMem, p);
105721  }
105722}
105723
105724/*
105725** This function is called to generate code that runs when table pTab is
105726** being dropped from the database. The SrcList passed as the second argument
105727** to this function contains a single entry guaranteed to resolve to
105728** table pTab.
105729**
105730** Normally, no code is required. However, if either
105731**
105732**   (a) The table is the parent table of a FK constraint, or
105733**   (b) The table is the child table of a deferred FK constraint and it is
105734**       determined at runtime that there are outstanding deferred FK
105735**       constraint violations in the database,
105736**
105737** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
105738** the table from the database. Triggers are disabled while running this
105739** DELETE, but foreign key actions are not.
105740*/
105741SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
105742  sqlite3 *db = pParse->db;
105743  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
105744    int iSkip = 0;
105745    Vdbe *v = sqlite3GetVdbe(pParse);
105746
105747    assert( v );                  /* VDBE has already been allocated */
105748    if( sqlite3FkReferences(pTab)==0 ){
105749      /* Search for a deferred foreign key constraint for which this table
105750      ** is the child table. If one cannot be found, return without
105751      ** generating any VDBE code. If one can be found, then jump over
105752      ** the entire DELETE if there are no outstanding deferred constraints
105753      ** when this statement is run.  */
105754      FKey *p;
105755      for(p=pTab->pFKey; p; p=p->pNextFrom){
105756        if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
105757      }
105758      if( !p ) return;
105759      iSkip = sqlite3VdbeMakeLabel(v);
105760      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
105761    }
105762
105763    pParse->disableTriggers = 1;
105764    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
105765    pParse->disableTriggers = 0;
105766
105767    /* If the DELETE has generated immediate foreign key constraint
105768    ** violations, halt the VDBE and return an error at this point, before
105769    ** any modifications to the schema are made. This is because statement
105770    ** transactions are not able to rollback schema changes.
105771    **
105772    ** If the SQLITE_DeferFKs flag is set, then this is not required, as
105773    ** the statement transaction will not be rolled back even if FK
105774    ** constraints are violated.
105775    */
105776    if( (db->flags & SQLITE_DeferFKs)==0 ){
105777      sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
105778      VdbeCoverage(v);
105779      sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
105780          OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
105781    }
105782
105783    if( iSkip ){
105784      sqlite3VdbeResolveLabel(v, iSkip);
105785    }
105786  }
105787}
105788
105789
105790/*
105791** The second argument points to an FKey object representing a foreign key
105792** for which pTab is the child table. An UPDATE statement against pTab
105793** is currently being processed. For each column of the table that is
105794** actually updated, the corresponding element in the aChange[] array
105795** is zero or greater (if a column is unmodified the corresponding element
105796** is set to -1). If the rowid column is modified by the UPDATE statement
105797** the bChngRowid argument is non-zero.
105798**
105799** This function returns true if any of the columns that are part of the
105800** child key for FK constraint *p are modified.
105801*/
105802static int fkChildIsModified(
105803  Table *pTab,                    /* Table being updated */
105804  FKey *p,                        /* Foreign key for which pTab is the child */
105805  int *aChange,                   /* Array indicating modified columns */
105806  int bChngRowid                  /* True if rowid is modified by this update */
105807){
105808  int i;
105809  for(i=0; i<p->nCol; i++){
105810    int iChildKey = p->aCol[i].iFrom;
105811    if( aChange[iChildKey]>=0 ) return 1;
105812    if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
105813  }
105814  return 0;
105815}
105816
105817/*
105818** The second argument points to an FKey object representing a foreign key
105819** for which pTab is the parent table. An UPDATE statement against pTab
105820** is currently being processed. For each column of the table that is
105821** actually updated, the corresponding element in the aChange[] array
105822** is zero or greater (if a column is unmodified the corresponding element
105823** is set to -1). If the rowid column is modified by the UPDATE statement
105824** the bChngRowid argument is non-zero.
105825**
105826** This function returns true if any of the columns that are part of the
105827** parent key for FK constraint *p are modified.
105828*/
105829static int fkParentIsModified(
105830  Table *pTab,
105831  FKey *p,
105832  int *aChange,
105833  int bChngRowid
105834){
105835  int i;
105836  for(i=0; i<p->nCol; i++){
105837    char *zKey = p->aCol[i].zCol;
105838    int iKey;
105839    for(iKey=0; iKey<pTab->nCol; iKey++){
105840      if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
105841        Column *pCol = &pTab->aCol[iKey];
105842        if( zKey ){
105843          if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
105844        }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
105845          return 1;
105846        }
105847      }
105848    }
105849  }
105850  return 0;
105851}
105852
105853/*
105854** Return true if the parser passed as the first argument is being
105855** used to code a trigger that is really a "SET NULL" action belonging
105856** to trigger pFKey.
105857*/
105858static int isSetNullAction(Parse *pParse, FKey *pFKey){
105859  Parse *pTop = sqlite3ParseToplevel(pParse);
105860  if( pTop->pTriggerPrg ){
105861    Trigger *p = pTop->pTriggerPrg->pTrigger;
105862    if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
105863     || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
105864    ){
105865      return 1;
105866    }
105867  }
105868  return 0;
105869}
105870
105871/*
105872** This function is called when inserting, deleting or updating a row of
105873** table pTab to generate VDBE code to perform foreign key constraint
105874** processing for the operation.
105875**
105876** For a DELETE operation, parameter regOld is passed the index of the
105877** first register in an array of (pTab->nCol+1) registers containing the
105878** rowid of the row being deleted, followed by each of the column values
105879** of the row being deleted, from left to right. Parameter regNew is passed
105880** zero in this case.
105881**
105882** For an INSERT operation, regOld is passed zero and regNew is passed the
105883** first register of an array of (pTab->nCol+1) registers containing the new
105884** row data.
105885**
105886** For an UPDATE operation, this function is called twice. Once before
105887** the original record is deleted from the table using the calling convention
105888** described for DELETE. Then again after the original record is deleted
105889** but before the new record is inserted using the INSERT convention.
105890*/
105891SQLITE_PRIVATE void sqlite3FkCheck(
105892  Parse *pParse,                  /* Parse context */
105893  Table *pTab,                    /* Row is being deleted from this table */
105894  int regOld,                     /* Previous row data is stored here */
105895  int regNew,                     /* New row data is stored here */
105896  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
105897  int bChngRowid                  /* True if rowid is UPDATEd */
105898){
105899  sqlite3 *db = pParse->db;       /* Database handle */
105900  FKey *pFKey;                    /* Used to iterate through FKs */
105901  int iDb;                        /* Index of database containing pTab */
105902  const char *zDb;                /* Name of database containing pTab */
105903  int isIgnoreErrors = pParse->disableTriggers;
105904
105905  /* Exactly one of regOld and regNew should be non-zero. */
105906  assert( (regOld==0)!=(regNew==0) );
105907
105908  /* If foreign-keys are disabled, this function is a no-op. */
105909  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
105910
105911  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
105912  zDb = db->aDb[iDb].zName;
105913
105914  /* Loop through all the foreign key constraints for which pTab is the
105915  ** child table (the table that the foreign key definition is part of).  */
105916  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
105917    Table *pTo;                   /* Parent table of foreign key pFKey */
105918    Index *pIdx = 0;              /* Index on key columns in pTo */
105919    int *aiFree = 0;
105920    int *aiCol;
105921    int iCol;
105922    int i;
105923    int bIgnore = 0;
105924
105925    if( aChange
105926     && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
105927     && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
105928    ){
105929      continue;
105930    }
105931
105932    /* Find the parent table of this foreign key. Also find a unique index
105933    ** on the parent key columns in the parent table. If either of these
105934    ** schema items cannot be located, set an error in pParse and return
105935    ** early.  */
105936    if( pParse->disableTriggers ){
105937      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
105938    }else{
105939      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
105940    }
105941    if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
105942      assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
105943      if( !isIgnoreErrors || db->mallocFailed ) return;
105944      if( pTo==0 ){
105945        /* If isIgnoreErrors is true, then a table is being dropped. In this
105946        ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
105947        ** before actually dropping it in order to check FK constraints.
105948        ** If the parent table of an FK constraint on the current table is
105949        ** missing, behave as if it is empty. i.e. decrement the relevant
105950        ** FK counter for each row of the current table with non-NULL keys.
105951        */
105952        Vdbe *v = sqlite3GetVdbe(pParse);
105953        int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
105954        for(i=0; i<pFKey->nCol; i++){
105955          int iReg = pFKey->aCol[i].iFrom + regOld + 1;
105956          sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
105957        }
105958        sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
105959      }
105960      continue;
105961    }
105962    assert( pFKey->nCol==1 || (aiFree && pIdx) );
105963
105964    if( aiFree ){
105965      aiCol = aiFree;
105966    }else{
105967      iCol = pFKey->aCol[0].iFrom;
105968      aiCol = &iCol;
105969    }
105970    for(i=0; i<pFKey->nCol; i++){
105971      if( aiCol[i]==pTab->iPKey ){
105972        aiCol[i] = -1;
105973      }
105974      assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
105975#ifndef SQLITE_OMIT_AUTHORIZATION
105976      /* Request permission to read the parent key columns. If the
105977      ** authorization callback returns SQLITE_IGNORE, behave as if any
105978      ** values read from the parent table are NULL. */
105979      if( db->xAuth ){
105980        int rcauth;
105981        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
105982        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
105983        bIgnore = (rcauth==SQLITE_IGNORE);
105984      }
105985#endif
105986    }
105987
105988    /* Take a shared-cache advisory read-lock on the parent table. Allocate
105989    ** a cursor to use to search the unique index on the parent key columns
105990    ** in the parent table.  */
105991    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
105992    pParse->nTab++;
105993
105994    if( regOld!=0 ){
105995      /* A row is being removed from the child table. Search for the parent.
105996      ** If the parent does not exist, removing the child row resolves an
105997      ** outstanding foreign key constraint violation. */
105998      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
105999    }
106000    if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
106001      /* A row is being added to the child table. If a parent row cannot
106002      ** be found, adding the child row has violated the FK constraint.
106003      **
106004      ** If this operation is being performed as part of a trigger program
106005      ** that is actually a "SET NULL" action belonging to this very
106006      ** foreign key, then omit this scan altogether. As all child key
106007      ** values are guaranteed to be NULL, it is not possible for adding
106008      ** this row to cause an FK violation.  */
106009      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
106010    }
106011
106012    sqlite3DbFree(db, aiFree);
106013  }
106014
106015  /* Loop through all the foreign key constraints that refer to this table.
106016  ** (the "child" constraints) */
106017  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
106018    Index *pIdx = 0;              /* Foreign key index for pFKey */
106019    SrcList *pSrc;
106020    int *aiCol = 0;
106021
106022    if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
106023      continue;
106024    }
106025
106026    if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
106027     && !pParse->pToplevel && !pParse->isMultiWrite
106028    ){
106029      assert( regOld==0 && regNew!=0 );
106030      /* Inserting a single row into a parent table cannot cause (or fix)
106031      ** an immediate foreign key violation. So do nothing in this case.  */
106032      continue;
106033    }
106034
106035    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
106036      if( !isIgnoreErrors || db->mallocFailed ) return;
106037      continue;
106038    }
106039    assert( aiCol || pFKey->nCol==1 );
106040
106041    /* Create a SrcList structure containing the child table.  We need the
106042    ** child table as a SrcList for sqlite3WhereBegin() */
106043    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
106044    if( pSrc ){
106045      struct SrcList_item *pItem = pSrc->a;
106046      pItem->pTab = pFKey->pFrom;
106047      pItem->zName = pFKey->pFrom->zName;
106048      pItem->pTab->nRef++;
106049      pItem->iCursor = pParse->nTab++;
106050
106051      if( regNew!=0 ){
106052        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
106053      }
106054      if( regOld!=0 ){
106055        int eAction = pFKey->aAction[aChange!=0];
106056        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
106057        /* If this is a deferred FK constraint, or a CASCADE or SET NULL
106058        ** action applies, then any foreign key violations caused by
106059        ** removing the parent key will be rectified by the action trigger.
106060        ** So do not set the "may-abort" flag in this case.
106061        **
106062        ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
106063        ** may-abort flag will eventually be set on this statement anyway
106064        ** (when this function is called as part of processing the UPDATE
106065        ** within the action trigger).
106066        **
106067        ** Note 2: At first glance it may seem like SQLite could simply omit
106068        ** all OP_FkCounter related scans when either CASCADE or SET NULL
106069        ** applies. The trouble starts if the CASCADE or SET NULL action
106070        ** trigger causes other triggers or action rules attached to the
106071        ** child table to fire. In these cases the fk constraint counters
106072        ** might be set incorrectly if any OP_FkCounter related scans are
106073        ** omitted.  */
106074        if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
106075          sqlite3MayAbort(pParse);
106076        }
106077      }
106078      pItem->zName = 0;
106079      sqlite3SrcListDelete(db, pSrc);
106080    }
106081    sqlite3DbFree(db, aiCol);
106082  }
106083}
106084
106085#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
106086
106087/*
106088** This function is called before generating code to update or delete a
106089** row contained in table pTab.
106090*/
106091SQLITE_PRIVATE u32 sqlite3FkOldmask(
106092  Parse *pParse,                  /* Parse context */
106093  Table *pTab                     /* Table being modified */
106094){
106095  u32 mask = 0;
106096  if( pParse->db->flags&SQLITE_ForeignKeys ){
106097    FKey *p;
106098    int i;
106099    for(p=pTab->pFKey; p; p=p->pNextFrom){
106100      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
106101    }
106102    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
106103      Index *pIdx = 0;
106104      sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
106105      if( pIdx ){
106106        for(i=0; i<pIdx->nKeyCol; i++){
106107          assert( pIdx->aiColumn[i]>=0 );
106108          mask |= COLUMN_MASK(pIdx->aiColumn[i]);
106109        }
106110      }
106111    }
106112  }
106113  return mask;
106114}
106115
106116
106117/*
106118** This function is called before generating code to update or delete a
106119** row contained in table pTab. If the operation is a DELETE, then
106120** parameter aChange is passed a NULL value. For an UPDATE, aChange points
106121** to an array of size N, where N is the number of columns in table pTab.
106122** If the i'th column is not modified by the UPDATE, then the corresponding
106123** entry in the aChange[] array is set to -1. If the column is modified,
106124** the value is 0 or greater. Parameter chngRowid is set to true if the
106125** UPDATE statement modifies the rowid fields of the table.
106126**
106127** If any foreign key processing will be required, this function returns
106128** true. If there is no foreign key related processing, this function
106129** returns false.
106130*/
106131SQLITE_PRIVATE int sqlite3FkRequired(
106132  Parse *pParse,                  /* Parse context */
106133  Table *pTab,                    /* Table being modified */
106134  int *aChange,                   /* Non-NULL for UPDATE operations */
106135  int chngRowid                   /* True for UPDATE that affects rowid */
106136){
106137  if( pParse->db->flags&SQLITE_ForeignKeys ){
106138    if( !aChange ){
106139      /* A DELETE operation. Foreign key processing is required if the
106140      ** table in question is either the child or parent table for any
106141      ** foreign key constraint.  */
106142      return (sqlite3FkReferences(pTab) || pTab->pFKey);
106143    }else{
106144      /* This is an UPDATE. Foreign key processing is only required if the
106145      ** operation modifies one or more child or parent key columns. */
106146      FKey *p;
106147
106148      /* Check if any child key columns are being modified. */
106149      for(p=pTab->pFKey; p; p=p->pNextFrom){
106150        if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
106151      }
106152
106153      /* Check if any parent key columns are being modified. */
106154      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
106155        if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
106156      }
106157    }
106158  }
106159  return 0;
106160}
106161
106162/*
106163** This function is called when an UPDATE or DELETE operation is being
106164** compiled on table pTab, which is the parent table of foreign-key pFKey.
106165** If the current operation is an UPDATE, then the pChanges parameter is
106166** passed a pointer to the list of columns being modified. If it is a
106167** DELETE, pChanges is passed a NULL pointer.
106168**
106169** It returns a pointer to a Trigger structure containing a trigger
106170** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
106171** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
106172** returned (these actions require no special handling by the triggers
106173** sub-system, code for them is created by fkScanChildren()).
106174**
106175** For example, if pFKey is the foreign key and pTab is table "p" in
106176** the following schema:
106177**
106178**   CREATE TABLE p(pk PRIMARY KEY);
106179**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
106180**
106181** then the returned trigger structure is equivalent to:
106182**
106183**   CREATE TRIGGER ... DELETE ON p BEGIN
106184**     DELETE FROM c WHERE ck = old.pk;
106185**   END;
106186**
106187** The returned pointer is cached as part of the foreign key object. It
106188** is eventually freed along with the rest of the foreign key object by
106189** sqlite3FkDelete().
106190*/
106191static Trigger *fkActionTrigger(
106192  Parse *pParse,                  /* Parse context */
106193  Table *pTab,                    /* Table being updated or deleted from */
106194  FKey *pFKey,                    /* Foreign key to get action for */
106195  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
106196){
106197  sqlite3 *db = pParse->db;       /* Database handle */
106198  int action;                     /* One of OE_None, OE_Cascade etc. */
106199  Trigger *pTrigger;              /* Trigger definition to return */
106200  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
106201
106202  action = pFKey->aAction[iAction];
106203  if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
106204    return 0;
106205  }
106206  pTrigger = pFKey->apTrigger[iAction];
106207
106208  if( action!=OE_None && !pTrigger ){
106209    char const *zFrom;            /* Name of child table */
106210    int nFrom;                    /* Length in bytes of zFrom */
106211    Index *pIdx = 0;              /* Parent key index for this FK */
106212    int *aiCol = 0;               /* child table cols -> parent key cols */
106213    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
106214    Expr *pWhere = 0;             /* WHERE clause of trigger step */
106215    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
106216    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
106217    int i;                        /* Iterator variable */
106218    Expr *pWhen = 0;              /* WHEN clause for the trigger */
106219
106220    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
106221    assert( aiCol || pFKey->nCol==1 );
106222
106223    for(i=0; i<pFKey->nCol; i++){
106224      Token tOld = { "old", 3 };  /* Literal "old" token */
106225      Token tNew = { "new", 3 };  /* Literal "new" token */
106226      Token tFromCol;             /* Name of column in child table */
106227      Token tToCol;               /* Name of column in parent table */
106228      int iFromCol;               /* Idx of column in child table */
106229      Expr *pEq;                  /* tFromCol = OLD.tToCol */
106230
106231      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
106232      assert( iFromCol>=0 );
106233      assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
106234      assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
106235      sqlite3TokenInit(&tToCol,
106236                   pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
106237      sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
106238
106239      /* Create the expression "OLD.zToCol = zFromCol". It is important
106240      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
106241      ** that the affinity and collation sequence associated with the
106242      ** parent table are used for the comparison. */
106243      pEq = sqlite3PExpr(pParse, TK_EQ,
106244          sqlite3PExpr(pParse, TK_DOT,
106245            sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
106246            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
106247          , 0),
106248          sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
106249      , 0);
106250      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
106251
106252      /* For ON UPDATE, construct the next term of the WHEN clause.
106253      ** The final WHEN clause will be like this:
106254      **
106255      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
106256      */
106257      if( pChanges ){
106258        pEq = sqlite3PExpr(pParse, TK_IS,
106259            sqlite3PExpr(pParse, TK_DOT,
106260              sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
106261              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
106262              0),
106263            sqlite3PExpr(pParse, TK_DOT,
106264              sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
106265              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
106266              0),
106267            0);
106268        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
106269      }
106270
106271      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
106272        Expr *pNew;
106273        if( action==OE_Cascade ){
106274          pNew = sqlite3PExpr(pParse, TK_DOT,
106275            sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
106276            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
106277          , 0);
106278        }else if( action==OE_SetDflt ){
106279          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
106280          if( pDflt ){
106281            pNew = sqlite3ExprDup(db, pDflt, 0);
106282          }else{
106283            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
106284          }
106285        }else{
106286          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
106287        }
106288        pList = sqlite3ExprListAppend(pParse, pList, pNew);
106289        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
106290      }
106291    }
106292    sqlite3DbFree(db, aiCol);
106293
106294    zFrom = pFKey->pFrom->zName;
106295    nFrom = sqlite3Strlen30(zFrom);
106296
106297    if( action==OE_Restrict ){
106298      Token tFrom;
106299      Expr *pRaise;
106300
106301      tFrom.z = zFrom;
106302      tFrom.n = nFrom;
106303      pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
106304      if( pRaise ){
106305        pRaise->affinity = OE_Abort;
106306      }
106307      pSelect = sqlite3SelectNew(pParse,
106308          sqlite3ExprListAppend(pParse, 0, pRaise),
106309          sqlite3SrcListAppend(db, 0, &tFrom, 0),
106310          pWhere,
106311          0, 0, 0, 0, 0, 0
106312      );
106313      pWhere = 0;
106314    }
106315
106316    /* Disable lookaside memory allocation */
106317    db->lookaside.bDisable++;
106318
106319    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
106320        sizeof(Trigger) +         /* struct Trigger */
106321        sizeof(TriggerStep) +     /* Single step in trigger program */
106322        nFrom + 1                 /* Space for pStep->zTarget */
106323    );
106324    if( pTrigger ){
106325      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
106326      pStep->zTarget = (char *)&pStep[1];
106327      memcpy((char *)pStep->zTarget, zFrom, nFrom);
106328
106329      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
106330      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
106331      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
106332      if( pWhen ){
106333        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
106334        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
106335      }
106336    }
106337
106338    /* Re-enable the lookaside buffer, if it was disabled earlier. */
106339    db->lookaside.bDisable--;
106340
106341    sqlite3ExprDelete(db, pWhere);
106342    sqlite3ExprDelete(db, pWhen);
106343    sqlite3ExprListDelete(db, pList);
106344    sqlite3SelectDelete(db, pSelect);
106345    if( db->mallocFailed==1 ){
106346      fkTriggerDelete(db, pTrigger);
106347      return 0;
106348    }
106349    assert( pStep!=0 );
106350
106351    switch( action ){
106352      case OE_Restrict:
106353        pStep->op = TK_SELECT;
106354        break;
106355      case OE_Cascade:
106356        if( !pChanges ){
106357          pStep->op = TK_DELETE;
106358          break;
106359        }
106360      default:
106361        pStep->op = TK_UPDATE;
106362    }
106363    pStep->pTrig = pTrigger;
106364    pTrigger->pSchema = pTab->pSchema;
106365    pTrigger->pTabSchema = pTab->pSchema;
106366    pFKey->apTrigger[iAction] = pTrigger;
106367    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
106368  }
106369
106370  return pTrigger;
106371}
106372
106373/*
106374** This function is called when deleting or updating a row to implement
106375** any required CASCADE, SET NULL or SET DEFAULT actions.
106376*/
106377SQLITE_PRIVATE void sqlite3FkActions(
106378  Parse *pParse,                  /* Parse context */
106379  Table *pTab,                    /* Table being updated or deleted from */
106380  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
106381  int regOld,                     /* Address of array containing old row */
106382  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
106383  int bChngRowid                  /* True if rowid is UPDATEd */
106384){
106385  /* If foreign-key support is enabled, iterate through all FKs that
106386  ** refer to table pTab. If there is an action associated with the FK
106387  ** for this operation (either update or delete), invoke the associated
106388  ** trigger sub-program.  */
106389  if( pParse->db->flags&SQLITE_ForeignKeys ){
106390    FKey *pFKey;                  /* Iterator variable */
106391    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
106392      if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
106393        Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
106394        if( pAct ){
106395          sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
106396        }
106397      }
106398    }
106399  }
106400}
106401
106402#endif /* ifndef SQLITE_OMIT_TRIGGER */
106403
106404/*
106405** Free all memory associated with foreign key definitions attached to
106406** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
106407** hash table.
106408*/
106409SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
106410  FKey *pFKey;                    /* Iterator variable */
106411  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
106412
106413  assert( db==0 || IsVirtual(pTab)
106414         || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
106415  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
106416
106417    /* Remove the FK from the fkeyHash hash table. */
106418    if( !db || db->pnBytesFreed==0 ){
106419      if( pFKey->pPrevTo ){
106420        pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
106421      }else{
106422        void *p = (void *)pFKey->pNextTo;
106423        const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
106424        sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
106425      }
106426      if( pFKey->pNextTo ){
106427        pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
106428      }
106429    }
106430
106431    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
106432    ** classified as either immediate or deferred.
106433    */
106434    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
106435
106436    /* Delete any triggers created to implement actions for this FK. */
106437#ifndef SQLITE_OMIT_TRIGGER
106438    fkTriggerDelete(db, pFKey->apTrigger[0]);
106439    fkTriggerDelete(db, pFKey->apTrigger[1]);
106440#endif
106441
106442    pNext = pFKey->pNextFrom;
106443    sqlite3DbFree(db, pFKey);
106444  }
106445}
106446#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
106447
106448/************** End of fkey.c ************************************************/
106449/************** Begin file insert.c ******************************************/
106450/*
106451** 2001 September 15
106452**
106453** The author disclaims copyright to this source code.  In place of
106454** a legal notice, here is a blessing:
106455**
106456**    May you do good and not evil.
106457**    May you find forgiveness for yourself and forgive others.
106458**    May you share freely, never taking more than you give.
106459**
106460*************************************************************************
106461** This file contains C code routines that are called by the parser
106462** to handle INSERT statements in SQLite.
106463*/
106464/* #include "sqliteInt.h" */
106465
106466/*
106467** Generate code that will
106468**
106469**   (1) acquire a lock for table pTab then
106470**   (2) open pTab as cursor iCur.
106471**
106472** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
106473** for that table that is actually opened.
106474*/
106475SQLITE_PRIVATE void sqlite3OpenTable(
106476  Parse *pParse,  /* Generate code into this VDBE */
106477  int iCur,       /* The cursor number of the table */
106478  int iDb,        /* The database index in sqlite3.aDb[] */
106479  Table *pTab,    /* The table to be opened */
106480  int opcode      /* OP_OpenRead or OP_OpenWrite */
106481){
106482  Vdbe *v;
106483  assert( !IsVirtual(pTab) );
106484  v = sqlite3GetVdbe(pParse);
106485  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
106486  sqlite3TableLock(pParse, iDb, pTab->tnum,
106487                   (opcode==OP_OpenWrite)?1:0, pTab->zName);
106488  if( HasRowid(pTab) ){
106489    sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
106490    VdbeComment((v, "%s", pTab->zName));
106491  }else{
106492    Index *pPk = sqlite3PrimaryKeyIndex(pTab);
106493    assert( pPk!=0 );
106494    assert( pPk->tnum==pTab->tnum );
106495    sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
106496    sqlite3VdbeSetP4KeyInfo(pParse, pPk);
106497    VdbeComment((v, "%s", pTab->zName));
106498  }
106499}
106500
106501/*
106502** Return a pointer to the column affinity string associated with index
106503** pIdx. A column affinity string has one character for each column in
106504** the table, according to the affinity of the column:
106505**
106506**  Character      Column affinity
106507**  ------------------------------
106508**  'A'            BLOB
106509**  'B'            TEXT
106510**  'C'            NUMERIC
106511**  'D'            INTEGER
106512**  'F'            REAL
106513**
106514** An extra 'D' is appended to the end of the string to cover the
106515** rowid that appears as the last column in every index.
106516**
106517** Memory for the buffer containing the column index affinity string
106518** is managed along with the rest of the Index structure. It will be
106519** released when sqlite3DeleteIndex() is called.
106520*/
106521SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
106522  if( !pIdx->zColAff ){
106523    /* The first time a column affinity string for a particular index is
106524    ** required, it is allocated and populated here. It is then stored as
106525    ** a member of the Index structure for subsequent use.
106526    **
106527    ** The column affinity string will eventually be deleted by
106528    ** sqliteDeleteIndex() when the Index structure itself is cleaned
106529    ** up.
106530    */
106531    int n;
106532    Table *pTab = pIdx->pTable;
106533    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
106534    if( !pIdx->zColAff ){
106535      sqlite3OomFault(db);
106536      return 0;
106537    }
106538    for(n=0; n<pIdx->nColumn; n++){
106539      i16 x = pIdx->aiColumn[n];
106540      if( x>=0 ){
106541        pIdx->zColAff[n] = pTab->aCol[x].affinity;
106542      }else if( x==XN_ROWID ){
106543        pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
106544      }else{
106545        char aff;
106546        assert( x==XN_EXPR );
106547        assert( pIdx->aColExpr!=0 );
106548        aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
106549        if( aff==0 ) aff = SQLITE_AFF_BLOB;
106550        pIdx->zColAff[n] = aff;
106551      }
106552    }
106553    pIdx->zColAff[n] = 0;
106554  }
106555
106556  return pIdx->zColAff;
106557}
106558
106559/*
106560** Compute the affinity string for table pTab, if it has not already been
106561** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
106562**
106563** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
106564** if iReg>0 then code an OP_Affinity opcode that will set the affinities
106565** for register iReg and following.  Or if affinities exists and iReg==0,
106566** then just set the P4 operand of the previous opcode (which should  be
106567** an OP_MakeRecord) to the affinity string.
106568**
106569** A column affinity string has one character per column:
106570**
106571**  Character      Column affinity
106572**  ------------------------------
106573**  'A'            BLOB
106574**  'B'            TEXT
106575**  'C'            NUMERIC
106576**  'D'            INTEGER
106577**  'E'            REAL
106578*/
106579SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
106580  int i;
106581  char *zColAff = pTab->zColAff;
106582  if( zColAff==0 ){
106583    sqlite3 *db = sqlite3VdbeDb(v);
106584    zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
106585    if( !zColAff ){
106586      sqlite3OomFault(db);
106587      return;
106588    }
106589
106590    for(i=0; i<pTab->nCol; i++){
106591      zColAff[i] = pTab->aCol[i].affinity;
106592    }
106593    do{
106594      zColAff[i--] = 0;
106595    }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
106596    pTab->zColAff = zColAff;
106597  }
106598  i = sqlite3Strlen30(zColAff);
106599  if( i ){
106600    if( iReg ){
106601      sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
106602    }else{
106603      sqlite3VdbeChangeP4(v, -1, zColAff, i);
106604    }
106605  }
106606}
106607
106608/*
106609** Return non-zero if the table pTab in database iDb or any of its indices
106610** have been opened at any point in the VDBE program. This is used to see if
106611** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
106612** run without using a temporary table for the results of the SELECT.
106613*/
106614static int readsTable(Parse *p, int iDb, Table *pTab){
106615  Vdbe *v = sqlite3GetVdbe(p);
106616  int i;
106617  int iEnd = sqlite3VdbeCurrentAddr(v);
106618#ifndef SQLITE_OMIT_VIRTUALTABLE
106619  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
106620#endif
106621
106622  for(i=1; i<iEnd; i++){
106623    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
106624    assert( pOp!=0 );
106625    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
106626      Index *pIndex;
106627      int tnum = pOp->p2;
106628      if( tnum==pTab->tnum ){
106629        return 1;
106630      }
106631      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
106632        if( tnum==pIndex->tnum ){
106633          return 1;
106634        }
106635      }
106636    }
106637#ifndef SQLITE_OMIT_VIRTUALTABLE
106638    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
106639      assert( pOp->p4.pVtab!=0 );
106640      assert( pOp->p4type==P4_VTAB );
106641      return 1;
106642    }
106643#endif
106644  }
106645  return 0;
106646}
106647
106648#ifndef SQLITE_OMIT_AUTOINCREMENT
106649/*
106650** Locate or create an AutoincInfo structure associated with table pTab
106651** which is in database iDb.  Return the register number for the register
106652** that holds the maximum rowid.
106653**
106654** There is at most one AutoincInfo structure per table even if the
106655** same table is autoincremented multiple times due to inserts within
106656** triggers.  A new AutoincInfo structure is created if this is the
106657** first use of table pTab.  On 2nd and subsequent uses, the original
106658** AutoincInfo structure is used.
106659**
106660** Three memory locations are allocated:
106661**
106662**   (1)  Register to hold the name of the pTab table.
106663**   (2)  Register to hold the maximum ROWID of pTab.
106664**   (3)  Register to hold the rowid in sqlite_sequence of pTab
106665**
106666** The 2nd register is the one that is returned.  That is all the
106667** insert routine needs to know about.
106668*/
106669static int autoIncBegin(
106670  Parse *pParse,      /* Parsing context */
106671  int iDb,            /* Index of the database holding pTab */
106672  Table *pTab         /* The table we are writing to */
106673){
106674  int memId = 0;      /* Register holding maximum rowid */
106675  if( pTab->tabFlags & TF_Autoincrement ){
106676    Parse *pToplevel = sqlite3ParseToplevel(pParse);
106677    AutoincInfo *pInfo;
106678
106679    pInfo = pToplevel->pAinc;
106680    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
106681    if( pInfo==0 ){
106682      pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
106683      if( pInfo==0 ) return 0;
106684      pInfo->pNext = pToplevel->pAinc;
106685      pToplevel->pAinc = pInfo;
106686      pInfo->pTab = pTab;
106687      pInfo->iDb = iDb;
106688      pToplevel->nMem++;                  /* Register to hold name of table */
106689      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
106690      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
106691    }
106692    memId = pInfo->regCtr;
106693  }
106694  return memId;
106695}
106696
106697/*
106698** This routine generates code that will initialize all of the
106699** register used by the autoincrement tracker.
106700*/
106701SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
106702  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
106703  sqlite3 *db = pParse->db;  /* The database connection */
106704  Db *pDb;                   /* Database only autoinc table */
106705  int memId;                 /* Register holding max rowid */
106706  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
106707
106708  /* This routine is never called during trigger-generation.  It is
106709  ** only called from the top-level */
106710  assert( pParse->pTriggerTab==0 );
106711  assert( sqlite3IsToplevel(pParse) );
106712
106713  assert( v );   /* We failed long ago if this is not so */
106714  for(p = pParse->pAinc; p; p = p->pNext){
106715    static const int iLn = VDBE_OFFSET_LINENO(2);
106716    static const VdbeOpList autoInc[] = {
106717      /* 0  */ {OP_Null,    0,  0, 0},
106718      /* 1  */ {OP_Rewind,  0,  9, 0},
106719      /* 2  */ {OP_Column,  0,  0, 0},
106720      /* 3  */ {OP_Ne,      0,  7, 0},
106721      /* 4  */ {OP_Rowid,   0,  0, 0},
106722      /* 5  */ {OP_Column,  0,  1, 0},
106723      /* 6  */ {OP_Goto,    0,  9, 0},
106724      /* 7  */ {OP_Next,    0,  2, 0},
106725      /* 8  */ {OP_Integer, 0,  0, 0},
106726      /* 9  */ {OP_Close,   0,  0, 0}
106727    };
106728    VdbeOp *aOp;
106729    pDb = &db->aDb[p->iDb];
106730    memId = p->regCtr;
106731    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
106732    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
106733    sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
106734    aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
106735    if( aOp==0 ) break;
106736    aOp[0].p2 = memId;
106737    aOp[0].p3 = memId+1;
106738    aOp[2].p3 = memId;
106739    aOp[3].p1 = memId-1;
106740    aOp[3].p3 = memId;
106741    aOp[3].p5 = SQLITE_JUMPIFNULL;
106742    aOp[4].p2 = memId+1;
106743    aOp[5].p3 = memId;
106744    aOp[8].p2 = memId;
106745  }
106746}
106747
106748/*
106749** Update the maximum rowid for an autoincrement calculation.
106750**
106751** This routine should be called when the regRowid register holds a
106752** new rowid that is about to be inserted.  If that new rowid is
106753** larger than the maximum rowid in the memId memory cell, then the
106754** memory cell is updated.
106755*/
106756static void autoIncStep(Parse *pParse, int memId, int regRowid){
106757  if( memId>0 ){
106758    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
106759  }
106760}
106761
106762/*
106763** This routine generates the code needed to write autoincrement
106764** maximum rowid values back into the sqlite_sequence register.
106765** Every statement that might do an INSERT into an autoincrement
106766** table (either directly or through triggers) needs to call this
106767** routine just before the "exit" code.
106768*/
106769static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
106770  AutoincInfo *p;
106771  Vdbe *v = pParse->pVdbe;
106772  sqlite3 *db = pParse->db;
106773
106774  assert( v );
106775  for(p = pParse->pAinc; p; p = p->pNext){
106776    static const int iLn = VDBE_OFFSET_LINENO(2);
106777    static const VdbeOpList autoIncEnd[] = {
106778      /* 0 */ {OP_NotNull,     0, 2, 0},
106779      /* 1 */ {OP_NewRowid,    0, 0, 0},
106780      /* 2 */ {OP_MakeRecord,  0, 2, 0},
106781      /* 3 */ {OP_Insert,      0, 0, 0},
106782      /* 4 */ {OP_Close,       0, 0, 0}
106783    };
106784    VdbeOp *aOp;
106785    Db *pDb = &db->aDb[p->iDb];
106786    int iRec;
106787    int memId = p->regCtr;
106788
106789    iRec = sqlite3GetTempReg(pParse);
106790    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
106791    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
106792    aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
106793    if( aOp==0 ) break;
106794    aOp[0].p1 = memId+1;
106795    aOp[1].p2 = memId+1;
106796    aOp[2].p1 = memId-1;
106797    aOp[2].p3 = iRec;
106798    aOp[3].p2 = iRec;
106799    aOp[3].p3 = memId+1;
106800    aOp[3].p5 = OPFLAG_APPEND;
106801    sqlite3ReleaseTempReg(pParse, iRec);
106802  }
106803}
106804SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
106805  if( pParse->pAinc ) autoIncrementEnd(pParse);
106806}
106807#else
106808/*
106809** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
106810** above are all no-ops
106811*/
106812# define autoIncBegin(A,B,C) (0)
106813# define autoIncStep(A,B,C)
106814#endif /* SQLITE_OMIT_AUTOINCREMENT */
106815
106816
106817/* Forward declaration */
106818static int xferOptimization(
106819  Parse *pParse,        /* Parser context */
106820  Table *pDest,         /* The table we are inserting into */
106821  Select *pSelect,      /* A SELECT statement to use as the data source */
106822  int onError,          /* How to handle constraint errors */
106823  int iDbDest           /* The database of pDest */
106824);
106825
106826/*
106827** This routine is called to handle SQL of the following forms:
106828**
106829**    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
106830**    insert into TABLE (IDLIST) select
106831**    insert into TABLE (IDLIST) default values
106832**
106833** The IDLIST following the table name is always optional.  If omitted,
106834** then a list of all (non-hidden) columns for the table is substituted.
106835** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
106836** is omitted.
106837**
106838** For the pSelect parameter holds the values to be inserted for the
106839** first two forms shown above.  A VALUES clause is really just short-hand
106840** for a SELECT statement that omits the FROM clause and everything else
106841** that follows.  If the pSelect parameter is NULL, that means that the
106842** DEFAULT VALUES form of the INSERT statement is intended.
106843**
106844** The code generated follows one of four templates.  For a simple
106845** insert with data coming from a single-row VALUES clause, the code executes
106846** once straight down through.  Pseudo-code follows (we call this
106847** the "1st template"):
106848**
106849**         open write cursor to <table> and its indices
106850**         put VALUES clause expressions into registers
106851**         write the resulting record into <table>
106852**         cleanup
106853**
106854** The three remaining templates assume the statement is of the form
106855**
106856**   INSERT INTO <table> SELECT ...
106857**
106858** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
106859** in other words if the SELECT pulls all columns from a single table
106860** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
106861** if <table2> and <table1> are distinct tables but have identical
106862** schemas, including all the same indices, then a special optimization
106863** is invoked that copies raw records from <table2> over to <table1>.
106864** See the xferOptimization() function for the implementation of this
106865** template.  This is the 2nd template.
106866**
106867**         open a write cursor to <table>
106868**         open read cursor on <table2>
106869**         transfer all records in <table2> over to <table>
106870**         close cursors
106871**         foreach index on <table>
106872**           open a write cursor on the <table> index
106873**           open a read cursor on the corresponding <table2> index
106874**           transfer all records from the read to the write cursors
106875**           close cursors
106876**         end foreach
106877**
106878** The 3rd template is for when the second template does not apply
106879** and the SELECT clause does not read from <table> at any time.
106880** The generated code follows this template:
106881**
106882**         X <- A
106883**         goto B
106884**      A: setup for the SELECT
106885**         loop over the rows in the SELECT
106886**           load values into registers R..R+n
106887**           yield X
106888**         end loop
106889**         cleanup after the SELECT
106890**         end-coroutine X
106891**      B: open write cursor to <table> and its indices
106892**      C: yield X, at EOF goto D
106893**         insert the select result into <table> from R..R+n
106894**         goto C
106895**      D: cleanup
106896**
106897** The 4th template is used if the insert statement takes its
106898** values from a SELECT but the data is being inserted into a table
106899** that is also read as part of the SELECT.  In the third form,
106900** we have to use an intermediate table to store the results of
106901** the select.  The template is like this:
106902**
106903**         X <- A
106904**         goto B
106905**      A: setup for the SELECT
106906**         loop over the tables in the SELECT
106907**           load value into register R..R+n
106908**           yield X
106909**         end loop
106910**         cleanup after the SELECT
106911**         end co-routine R
106912**      B: open temp table
106913**      L: yield X, at EOF goto M
106914**         insert row from R..R+n into temp table
106915**         goto L
106916**      M: open write cursor to <table> and its indices
106917**         rewind temp table
106918**      C: loop over rows of intermediate table
106919**           transfer values form intermediate table into <table>
106920**         end loop
106921**      D: cleanup
106922*/
106923SQLITE_PRIVATE void sqlite3Insert(
106924  Parse *pParse,        /* Parser context */
106925  SrcList *pTabList,    /* Name of table into which we are inserting */
106926  Select *pSelect,      /* A SELECT statement to use as the data source */
106927  IdList *pColumn,      /* Column names corresponding to IDLIST. */
106928  int onError           /* How to handle constraint errors */
106929){
106930  sqlite3 *db;          /* The main database structure */
106931  Table *pTab;          /* The table to insert into.  aka TABLE */
106932  char *zTab;           /* Name of the table into which we are inserting */
106933  const char *zDb;      /* Name of the database holding this table */
106934  int i, j, idx;        /* Loop counters */
106935  Vdbe *v;              /* Generate code into this virtual machine */
106936  Index *pIdx;          /* For looping over indices of the table */
106937  int nColumn;          /* Number of columns in the data */
106938  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
106939  int iDataCur = 0;     /* VDBE cursor that is the main data repository */
106940  int iIdxCur = 0;      /* First index cursor */
106941  int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
106942  int endOfLoop;        /* Label for the end of the insertion loop */
106943  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
106944  int addrInsTop = 0;   /* Jump to label "D" */
106945  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
106946  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
106947  int iDb;              /* Index of database holding TABLE */
106948  Db *pDb;              /* The database containing table being inserted into */
106949  u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
106950  u8 appendFlag = 0;    /* True if the insert is likely to be an append */
106951  u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
106952  u8 bIdListInOrder;    /* True if IDLIST is in table order */
106953  ExprList *pList = 0;  /* List of VALUES() to be inserted  */
106954
106955  /* Register allocations */
106956  int regFromSelect = 0;/* Base register for data coming from SELECT */
106957  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
106958  int regRowCount = 0;  /* Memory cell used for the row counter */
106959  int regIns;           /* Block of regs holding rowid+data being inserted */
106960  int regRowid;         /* registers holding insert rowid */
106961  int regData;          /* register holding first column to insert */
106962  int *aRegIdx = 0;     /* One register allocated to each index */
106963
106964#ifndef SQLITE_OMIT_TRIGGER
106965  int isView;                 /* True if attempting to insert into a view */
106966  Trigger *pTrigger;          /* List of triggers on pTab, if required */
106967  int tmask;                  /* Mask of trigger times */
106968#endif
106969
106970  db = pParse->db;
106971  memset(&dest, 0, sizeof(dest));
106972  if( pParse->nErr || db->mallocFailed ){
106973    goto insert_cleanup;
106974  }
106975
106976  /* If the Select object is really just a simple VALUES() list with a
106977  ** single row (the common case) then keep that one row of values
106978  ** and discard the other (unused) parts of the pSelect object
106979  */
106980  if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
106981    pList = pSelect->pEList;
106982    pSelect->pEList = 0;
106983    sqlite3SelectDelete(db, pSelect);
106984    pSelect = 0;
106985  }
106986
106987  /* Locate the table into which we will be inserting new information.
106988  */
106989  assert( pTabList->nSrc==1 );
106990  zTab = pTabList->a[0].zName;
106991  if( NEVER(zTab==0) ) goto insert_cleanup;
106992  pTab = sqlite3SrcListLookup(pParse, pTabList);
106993  if( pTab==0 ){
106994    goto insert_cleanup;
106995  }
106996  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
106997  assert( iDb<db->nDb );
106998  pDb = &db->aDb[iDb];
106999  zDb = pDb->zName;
107000  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
107001    goto insert_cleanup;
107002  }
107003  withoutRowid = !HasRowid(pTab);
107004
107005  /* Figure out if we have any triggers and if the table being
107006  ** inserted into is a view
107007  */
107008#ifndef SQLITE_OMIT_TRIGGER
107009  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
107010  isView = pTab->pSelect!=0;
107011#else
107012# define pTrigger 0
107013# define tmask 0
107014# define isView 0
107015#endif
107016#ifdef SQLITE_OMIT_VIEW
107017# undef isView
107018# define isView 0
107019#endif
107020  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
107021
107022  /* If pTab is really a view, make sure it has been initialized.
107023  ** ViewGetColumnNames() is a no-op if pTab is not a view.
107024  */
107025  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
107026    goto insert_cleanup;
107027  }
107028
107029  /* Cannot insert into a read-only table.
107030  */
107031  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
107032    goto insert_cleanup;
107033  }
107034
107035  /* Allocate a VDBE
107036  */
107037  v = sqlite3GetVdbe(pParse);
107038  if( v==0 ) goto insert_cleanup;
107039  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
107040  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
107041
107042#ifndef SQLITE_OMIT_XFER_OPT
107043  /* If the statement is of the form
107044  **
107045  **       INSERT INTO <table1> SELECT * FROM <table2>;
107046  **
107047  ** Then special optimizations can be applied that make the transfer
107048  ** very fast and which reduce fragmentation of indices.
107049  **
107050  ** This is the 2nd template.
107051  */
107052  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
107053    assert( !pTrigger );
107054    assert( pList==0 );
107055    goto insert_end;
107056  }
107057#endif /* SQLITE_OMIT_XFER_OPT */
107058
107059  /* If this is an AUTOINCREMENT table, look up the sequence number in the
107060  ** sqlite_sequence table and store it in memory cell regAutoinc.
107061  */
107062  regAutoinc = autoIncBegin(pParse, iDb, pTab);
107063
107064  /* Allocate registers for holding the rowid of the new row,
107065  ** the content of the new row, and the assembled row record.
107066  */
107067  regRowid = regIns = pParse->nMem+1;
107068  pParse->nMem += pTab->nCol + 1;
107069  if( IsVirtual(pTab) ){
107070    regRowid++;
107071    pParse->nMem++;
107072  }
107073  regData = regRowid+1;
107074
107075  /* If the INSERT statement included an IDLIST term, then make sure
107076  ** all elements of the IDLIST really are columns of the table and
107077  ** remember the column indices.
107078  **
107079  ** If the table has an INTEGER PRIMARY KEY column and that column
107080  ** is named in the IDLIST, then record in the ipkColumn variable
107081  ** the index into IDLIST of the primary key column.  ipkColumn is
107082  ** the index of the primary key as it appears in IDLIST, not as
107083  ** is appears in the original table.  (The index of the INTEGER
107084  ** PRIMARY KEY in the original table is pTab->iPKey.)
107085  */
107086  bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
107087  if( pColumn ){
107088    for(i=0; i<pColumn->nId; i++){
107089      pColumn->a[i].idx = -1;
107090    }
107091    for(i=0; i<pColumn->nId; i++){
107092      for(j=0; j<pTab->nCol; j++){
107093        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
107094          pColumn->a[i].idx = j;
107095          if( i!=j ) bIdListInOrder = 0;
107096          if( j==pTab->iPKey ){
107097            ipkColumn = i;  assert( !withoutRowid );
107098          }
107099          break;
107100        }
107101      }
107102      if( j>=pTab->nCol ){
107103        if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
107104          ipkColumn = i;
107105          bIdListInOrder = 0;
107106        }else{
107107          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
107108              pTabList, 0, pColumn->a[i].zName);
107109          pParse->checkSchema = 1;
107110          goto insert_cleanup;
107111        }
107112      }
107113    }
107114  }
107115
107116  /* Figure out how many columns of data are supplied.  If the data
107117  ** is coming from a SELECT statement, then generate a co-routine that
107118  ** produces a single row of the SELECT on each invocation.  The
107119  ** co-routine is the common header to the 3rd and 4th templates.
107120  */
107121  if( pSelect ){
107122    /* Data is coming from a SELECT or from a multi-row VALUES clause.
107123    ** Generate a co-routine to run the SELECT. */
107124    int regYield;       /* Register holding co-routine entry-point */
107125    int addrTop;        /* Top of the co-routine */
107126    int rc;             /* Result code */
107127
107128    regYield = ++pParse->nMem;
107129    addrTop = sqlite3VdbeCurrentAddr(v) + 1;
107130    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
107131    sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
107132    dest.iSdst = bIdListInOrder ? regData : 0;
107133    dest.nSdst = pTab->nCol;
107134    rc = sqlite3Select(pParse, pSelect, &dest);
107135    regFromSelect = dest.iSdst;
107136    if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
107137    sqlite3VdbeEndCoroutine(v, regYield);
107138    sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
107139    assert( pSelect->pEList );
107140    nColumn = pSelect->pEList->nExpr;
107141
107142    /* Set useTempTable to TRUE if the result of the SELECT statement
107143    ** should be written into a temporary table (template 4).  Set to
107144    ** FALSE if each output row of the SELECT can be written directly into
107145    ** the destination table (template 3).
107146    **
107147    ** A temp table must be used if the table being updated is also one
107148    ** of the tables being read by the SELECT statement.  Also use a
107149    ** temp table in the case of row triggers.
107150    */
107151    if( pTrigger || readsTable(pParse, iDb, pTab) ){
107152      useTempTable = 1;
107153    }
107154
107155    if( useTempTable ){
107156      /* Invoke the coroutine to extract information from the SELECT
107157      ** and add it to a transient table srcTab.  The code generated
107158      ** here is from the 4th template:
107159      **
107160      **      B: open temp table
107161      **      L: yield X, goto M at EOF
107162      **         insert row from R..R+n into temp table
107163      **         goto L
107164      **      M: ...
107165      */
107166      int regRec;          /* Register to hold packed record */
107167      int regTempRowid;    /* Register to hold temp table ROWID */
107168      int addrL;           /* Label "L" */
107169
107170      srcTab = pParse->nTab++;
107171      regRec = sqlite3GetTempReg(pParse);
107172      regTempRowid = sqlite3GetTempReg(pParse);
107173      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
107174      addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
107175      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
107176      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
107177      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
107178      sqlite3VdbeGoto(v, addrL);
107179      sqlite3VdbeJumpHere(v, addrL);
107180      sqlite3ReleaseTempReg(pParse, regRec);
107181      sqlite3ReleaseTempReg(pParse, regTempRowid);
107182    }
107183  }else{
107184    /* This is the case if the data for the INSERT is coming from a
107185    ** single-row VALUES clause
107186    */
107187    NameContext sNC;
107188    memset(&sNC, 0, sizeof(sNC));
107189    sNC.pParse = pParse;
107190    srcTab = -1;
107191    assert( useTempTable==0 );
107192    if( pList ){
107193      nColumn = pList->nExpr;
107194      if( sqlite3ResolveExprListNames(&sNC, pList) ){
107195        goto insert_cleanup;
107196      }
107197    }else{
107198      nColumn = 0;
107199    }
107200  }
107201
107202  /* If there is no IDLIST term but the table has an integer primary
107203  ** key, the set the ipkColumn variable to the integer primary key
107204  ** column index in the original table definition.
107205  */
107206  if( pColumn==0 && nColumn>0 ){
107207    ipkColumn = pTab->iPKey;
107208  }
107209
107210  /* Make sure the number of columns in the source data matches the number
107211  ** of columns to be inserted into the table.
107212  */
107213  for(i=0; i<pTab->nCol; i++){
107214    nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
107215  }
107216  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
107217    sqlite3ErrorMsg(pParse,
107218       "table %S has %d columns but %d values were supplied",
107219       pTabList, 0, pTab->nCol-nHidden, nColumn);
107220    goto insert_cleanup;
107221  }
107222  if( pColumn!=0 && nColumn!=pColumn->nId ){
107223    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
107224    goto insert_cleanup;
107225  }
107226
107227  /* Initialize the count of rows to be inserted
107228  */
107229  if( db->flags & SQLITE_CountRows ){
107230    regRowCount = ++pParse->nMem;
107231    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
107232  }
107233
107234  /* If this is not a view, open the table and and all indices */
107235  if( !isView ){
107236    int nIdx;
107237    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
107238                                      &iDataCur, &iIdxCur);
107239    aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
107240    if( aRegIdx==0 ){
107241      goto insert_cleanup;
107242    }
107243    for(i=0; i<nIdx; i++){
107244      aRegIdx[i] = ++pParse->nMem;
107245    }
107246  }
107247
107248  /* This is the top of the main insertion loop */
107249  if( useTempTable ){
107250    /* This block codes the top of loop only.  The complete loop is the
107251    ** following pseudocode (template 4):
107252    **
107253    **         rewind temp table, if empty goto D
107254    **      C: loop over rows of intermediate table
107255    **           transfer values form intermediate table into <table>
107256    **         end loop
107257    **      D: ...
107258    */
107259    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
107260    addrCont = sqlite3VdbeCurrentAddr(v);
107261  }else if( pSelect ){
107262    /* This block codes the top of loop only.  The complete loop is the
107263    ** following pseudocode (template 3):
107264    **
107265    **      C: yield X, at EOF goto D
107266    **         insert the select result into <table> from R..R+n
107267    **         goto C
107268    **      D: ...
107269    */
107270    addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
107271    VdbeCoverage(v);
107272  }
107273
107274  /* Run the BEFORE and INSTEAD OF triggers, if there are any
107275  */
107276  endOfLoop = sqlite3VdbeMakeLabel(v);
107277  if( tmask & TRIGGER_BEFORE ){
107278    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
107279
107280    /* build the NEW.* reference row.  Note that if there is an INTEGER
107281    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
107282    ** translated into a unique ID for the row.  But on a BEFORE trigger,
107283    ** we do not know what the unique ID will be (because the insert has
107284    ** not happened yet) so we substitute a rowid of -1
107285    */
107286    if( ipkColumn<0 ){
107287      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
107288    }else{
107289      int addr1;
107290      assert( !withoutRowid );
107291      if( useTempTable ){
107292        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
107293      }else{
107294        assert( pSelect==0 );  /* Otherwise useTempTable is true */
107295        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
107296      }
107297      addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
107298      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
107299      sqlite3VdbeJumpHere(v, addr1);
107300      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
107301    }
107302
107303    /* Cannot have triggers on a virtual table. If it were possible,
107304    ** this block would have to account for hidden column.
107305    */
107306    assert( !IsVirtual(pTab) );
107307
107308    /* Create the new column data
107309    */
107310    for(i=j=0; i<pTab->nCol; i++){
107311      if( pColumn ){
107312        for(j=0; j<pColumn->nId; j++){
107313          if( pColumn->a[j].idx==i ) break;
107314        }
107315      }
107316      if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
107317            || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
107318        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
107319      }else if( useTempTable ){
107320        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
107321      }else{
107322        assert( pSelect==0 ); /* Otherwise useTempTable is true */
107323        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
107324      }
107325      if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
107326    }
107327
107328    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
107329    ** do not attempt any conversions before assembling the record.
107330    ** If this is a real table, attempt conversions as required by the
107331    ** table column affinities.
107332    */
107333    if( !isView ){
107334      sqlite3TableAffinity(v, pTab, regCols+1);
107335    }
107336
107337    /* Fire BEFORE or INSTEAD OF triggers */
107338    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
107339        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
107340
107341    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
107342  }
107343
107344  /* Compute the content of the next row to insert into a range of
107345  ** registers beginning at regIns.
107346  */
107347  if( !isView ){
107348    if( IsVirtual(pTab) ){
107349      /* The row that the VUpdate opcode will delete: none */
107350      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
107351    }
107352    if( ipkColumn>=0 ){
107353      if( useTempTable ){
107354        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
107355      }else if( pSelect ){
107356        sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
107357      }else{
107358        VdbeOp *pOp;
107359        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
107360        pOp = sqlite3VdbeGetOp(v, -1);
107361        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
107362          appendFlag = 1;
107363          pOp->opcode = OP_NewRowid;
107364          pOp->p1 = iDataCur;
107365          pOp->p2 = regRowid;
107366          pOp->p3 = regAutoinc;
107367        }
107368      }
107369      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
107370      ** to generate a unique primary key value.
107371      */
107372      if( !appendFlag ){
107373        int addr1;
107374        if( !IsVirtual(pTab) ){
107375          addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
107376          sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
107377          sqlite3VdbeJumpHere(v, addr1);
107378        }else{
107379          addr1 = sqlite3VdbeCurrentAddr(v);
107380          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
107381        }
107382        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
107383      }
107384    }else if( IsVirtual(pTab) || withoutRowid ){
107385      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
107386    }else{
107387      sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
107388      appendFlag = 1;
107389    }
107390    autoIncStep(pParse, regAutoinc, regRowid);
107391
107392    /* Compute data for all columns of the new entry, beginning
107393    ** with the first column.
107394    */
107395    nHidden = 0;
107396    for(i=0; i<pTab->nCol; i++){
107397      int iRegStore = regRowid+1+i;
107398      if( i==pTab->iPKey ){
107399        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
107400        ** Whenever this column is read, the rowid will be substituted
107401        ** in its place.  Hence, fill this column with a NULL to avoid
107402        ** taking up data space with information that will never be used.
107403        ** As there may be shallow copies of this value, make it a soft-NULL */
107404        sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
107405        continue;
107406      }
107407      if( pColumn==0 ){
107408        if( IsHiddenColumn(&pTab->aCol[i]) ){
107409          j = -1;
107410          nHidden++;
107411        }else{
107412          j = i - nHidden;
107413        }
107414      }else{
107415        for(j=0; j<pColumn->nId; j++){
107416          if( pColumn->a[j].idx==i ) break;
107417        }
107418      }
107419      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
107420        sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
107421      }else if( useTempTable ){
107422        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
107423      }else if( pSelect ){
107424        if( regFromSelect!=regData ){
107425          sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
107426        }
107427      }else{
107428        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
107429      }
107430    }
107431
107432    /* Generate code to check constraints and generate index keys and
107433    ** do the insertion.
107434    */
107435#ifndef SQLITE_OMIT_VIRTUALTABLE
107436    if( IsVirtual(pTab) ){
107437      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
107438      sqlite3VtabMakeWritable(pParse, pTab);
107439      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
107440      sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
107441      sqlite3MayAbort(pParse);
107442    }else
107443#endif
107444    {
107445      int isReplace;    /* Set to true if constraints may cause a replace */
107446      sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
107447          regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
107448      );
107449      sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
107450      sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
107451                               regIns, aRegIdx, 0, appendFlag, isReplace==0);
107452    }
107453  }
107454
107455  /* Update the count of rows that are inserted
107456  */
107457  if( (db->flags & SQLITE_CountRows)!=0 ){
107458    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
107459  }
107460
107461  if( pTrigger ){
107462    /* Code AFTER triggers */
107463    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
107464        pTab, regData-2-pTab->nCol, onError, endOfLoop);
107465  }
107466
107467  /* The bottom of the main insertion loop, if the data source
107468  ** is a SELECT statement.
107469  */
107470  sqlite3VdbeResolveLabel(v, endOfLoop);
107471  if( useTempTable ){
107472    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
107473    sqlite3VdbeJumpHere(v, addrInsTop);
107474    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
107475  }else if( pSelect ){
107476    sqlite3VdbeGoto(v, addrCont);
107477    sqlite3VdbeJumpHere(v, addrInsTop);
107478  }
107479
107480  if( !IsVirtual(pTab) && !isView ){
107481    /* Close all tables opened */
107482    if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
107483    for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
107484      sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
107485    }
107486  }
107487
107488insert_end:
107489  /* Update the sqlite_sequence table by storing the content of the
107490  ** maximum rowid counter values recorded while inserting into
107491  ** autoincrement tables.
107492  */
107493  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
107494    sqlite3AutoincrementEnd(pParse);
107495  }
107496
107497  /*
107498  ** Return the number of rows inserted. If this routine is
107499  ** generating code because of a call to sqlite3NestedParse(), do not
107500  ** invoke the callback function.
107501  */
107502  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
107503    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
107504    sqlite3VdbeSetNumCols(v, 1);
107505    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
107506  }
107507
107508insert_cleanup:
107509  sqlite3SrcListDelete(db, pTabList);
107510  sqlite3ExprListDelete(db, pList);
107511  sqlite3SelectDelete(db, pSelect);
107512  sqlite3IdListDelete(db, pColumn);
107513  sqlite3DbFree(db, aRegIdx);
107514}
107515
107516/* Make sure "isView" and other macros defined above are undefined. Otherwise
107517** they may interfere with compilation of other functions in this file
107518** (or in another file, if this file becomes part of the amalgamation).  */
107519#ifdef isView
107520 #undef isView
107521#endif
107522#ifdef pTrigger
107523 #undef pTrigger
107524#endif
107525#ifdef tmask
107526 #undef tmask
107527#endif
107528
107529/*
107530** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
107531*/
107532#define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
107533#define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
107534
107535/* This is the Walker callback from checkConstraintUnchanged().  Set
107536** bit 0x01 of pWalker->eCode if
107537** pWalker->eCode to 0 if this expression node references any of the
107538** columns that are being modifed by an UPDATE statement.
107539*/
107540static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
107541  if( pExpr->op==TK_COLUMN ){
107542    assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
107543    if( pExpr->iColumn>=0 ){
107544      if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
107545        pWalker->eCode |= CKCNSTRNT_COLUMN;
107546      }
107547    }else{
107548      pWalker->eCode |= CKCNSTRNT_ROWID;
107549    }
107550  }
107551  return WRC_Continue;
107552}
107553
107554/*
107555** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
107556** only columns that are modified by the UPDATE are those for which
107557** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
107558**
107559** Return true if CHECK constraint pExpr does not use any of the
107560** changing columns (or the rowid if it is changing).  In other words,
107561** return true if this CHECK constraint can be skipped when validating
107562** the new row in the UPDATE statement.
107563*/
107564static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
107565  Walker w;
107566  memset(&w, 0, sizeof(w));
107567  w.eCode = 0;
107568  w.xExprCallback = checkConstraintExprNode;
107569  w.u.aiCol = aiChng;
107570  sqlite3WalkExpr(&w, pExpr);
107571  if( !chngRowid ){
107572    testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
107573    w.eCode &= ~CKCNSTRNT_ROWID;
107574  }
107575  testcase( w.eCode==0 );
107576  testcase( w.eCode==CKCNSTRNT_COLUMN );
107577  testcase( w.eCode==CKCNSTRNT_ROWID );
107578  testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
107579  return !w.eCode;
107580}
107581
107582/*
107583** Generate code to do constraint checks prior to an INSERT or an UPDATE
107584** on table pTab.
107585**
107586** The regNewData parameter is the first register in a range that contains
107587** the data to be inserted or the data after the update.  There will be
107588** pTab->nCol+1 registers in this range.  The first register (the one
107589** that regNewData points to) will contain the new rowid, or NULL in the
107590** case of a WITHOUT ROWID table.  The second register in the range will
107591** contain the content of the first table column.  The third register will
107592** contain the content of the second table column.  And so forth.
107593**
107594** The regOldData parameter is similar to regNewData except that it contains
107595** the data prior to an UPDATE rather than afterwards.  regOldData is zero
107596** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
107597** checking regOldData for zero.
107598**
107599** For an UPDATE, the pkChng boolean is true if the true primary key (the
107600** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
107601** might be modified by the UPDATE.  If pkChng is false, then the key of
107602** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
107603**
107604** For an INSERT, the pkChng boolean indicates whether or not the rowid
107605** was explicitly specified as part of the INSERT statement.  If pkChng
107606** is zero, it means that the either rowid is computed automatically or
107607** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
107608** pkChng will only be true if the INSERT statement provides an integer
107609** value for either the rowid column or its INTEGER PRIMARY KEY alias.
107610**
107611** The code generated by this routine will store new index entries into
107612** registers identified by aRegIdx[].  No index entry is created for
107613** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
107614** the same as the order of indices on the linked list of indices
107615** at pTab->pIndex.
107616**
107617** The caller must have already opened writeable cursors on the main
107618** table and all applicable indices (that is to say, all indices for which
107619** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
107620** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
107621** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
107622** for the first index in the pTab->pIndex list.  Cursors for other indices
107623** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
107624**
107625** This routine also generates code to check constraints.  NOT NULL,
107626** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
107627** then the appropriate action is performed.  There are five possible
107628** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
107629**
107630**  Constraint type  Action       What Happens
107631**  ---------------  ----------   ----------------------------------------
107632**  any              ROLLBACK     The current transaction is rolled back and
107633**                                sqlite3_step() returns immediately with a
107634**                                return code of SQLITE_CONSTRAINT.
107635**
107636**  any              ABORT        Back out changes from the current command
107637**                                only (do not do a complete rollback) then
107638**                                cause sqlite3_step() to return immediately
107639**                                with SQLITE_CONSTRAINT.
107640**
107641**  any              FAIL         Sqlite3_step() returns immediately with a
107642**                                return code of SQLITE_CONSTRAINT.  The
107643**                                transaction is not rolled back and any
107644**                                changes to prior rows are retained.
107645**
107646**  any              IGNORE       The attempt in insert or update the current
107647**                                row is skipped, without throwing an error.
107648**                                Processing continues with the next row.
107649**                                (There is an immediate jump to ignoreDest.)
107650**
107651**  NOT NULL         REPLACE      The NULL value is replace by the default
107652**                                value for that column.  If the default value
107653**                                is NULL, the action is the same as ABORT.
107654**
107655**  UNIQUE           REPLACE      The other row that conflicts with the row
107656**                                being inserted is removed.
107657**
107658**  CHECK            REPLACE      Illegal.  The results in an exception.
107659**
107660** Which action to take is determined by the overrideError parameter.
107661** Or if overrideError==OE_Default, then the pParse->onError parameter
107662** is used.  Or if pParse->onError==OE_Default then the onError value
107663** for the constraint is used.
107664*/
107665SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
107666  Parse *pParse,       /* The parser context */
107667  Table *pTab,         /* The table being inserted or updated */
107668  int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
107669  int iDataCur,        /* Canonical data cursor (main table or PK index) */
107670  int iIdxCur,         /* First index cursor */
107671  int regNewData,      /* First register in a range holding values to insert */
107672  int regOldData,      /* Previous content.  0 for INSERTs */
107673  u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
107674  u8 overrideError,    /* Override onError to this if not OE_Default */
107675  int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
107676  int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
107677  int *aiChng          /* column i is unchanged if aiChng[i]<0 */
107678){
107679  Vdbe *v;             /* VDBE under constrution */
107680  Index *pIdx;         /* Pointer to one of the indices */
107681  Index *pPk = 0;      /* The PRIMARY KEY index */
107682  sqlite3 *db;         /* Database connection */
107683  int i;               /* loop counter */
107684  int ix;              /* Index loop counter */
107685  int nCol;            /* Number of columns */
107686  int onError;         /* Conflict resolution strategy */
107687  int addr1;           /* Address of jump instruction */
107688  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
107689  int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
107690  int ipkTop = 0;      /* Top of the rowid change constraint check */
107691  int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
107692  u8 isUpdate;         /* True if this is an UPDATE operation */
107693  u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
107694  int regRowid = -1;   /* Register holding ROWID value */
107695
107696  isUpdate = regOldData!=0;
107697  db = pParse->db;
107698  v = sqlite3GetVdbe(pParse);
107699  assert( v!=0 );
107700  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
107701  nCol = pTab->nCol;
107702
107703  /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
107704  ** normal rowid tables.  nPkField is the number of key fields in the
107705  ** pPk index or 1 for a rowid table.  In other words, nPkField is the
107706  ** number of fields in the true primary key of the table. */
107707  if( HasRowid(pTab) ){
107708    pPk = 0;
107709    nPkField = 1;
107710  }else{
107711    pPk = sqlite3PrimaryKeyIndex(pTab);
107712    nPkField = pPk->nKeyCol;
107713  }
107714
107715  /* Record that this module has started */
107716  VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
107717                     iDataCur, iIdxCur, regNewData, regOldData, pkChng));
107718
107719  /* Test all NOT NULL constraints.
107720  */
107721  for(i=0; i<nCol; i++){
107722    if( i==pTab->iPKey ){
107723      continue;        /* ROWID is never NULL */
107724    }
107725    if( aiChng && aiChng[i]<0 ){
107726      /* Don't bother checking for NOT NULL on columns that do not change */
107727      continue;
107728    }
107729    onError = pTab->aCol[i].notNull;
107730    if( onError==OE_None ) continue;  /* This column is allowed to be NULL */
107731    if( overrideError!=OE_Default ){
107732      onError = overrideError;
107733    }else if( onError==OE_Default ){
107734      onError = OE_Abort;
107735    }
107736    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
107737      onError = OE_Abort;
107738    }
107739    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
107740        || onError==OE_Ignore || onError==OE_Replace );
107741    switch( onError ){
107742      case OE_Abort:
107743        sqlite3MayAbort(pParse);
107744        /* Fall through */
107745      case OE_Rollback:
107746      case OE_Fail: {
107747        char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
107748                                    pTab->aCol[i].zName);
107749        sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
107750                          regNewData+1+i, zMsg, P4_DYNAMIC);
107751        sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
107752        VdbeCoverage(v);
107753        break;
107754      }
107755      case OE_Ignore: {
107756        sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
107757        VdbeCoverage(v);
107758        break;
107759      }
107760      default: {
107761        assert( onError==OE_Replace );
107762        addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
107763           VdbeCoverage(v);
107764        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
107765        sqlite3VdbeJumpHere(v, addr1);
107766        break;
107767      }
107768    }
107769  }
107770
107771  /* Test all CHECK constraints
107772  */
107773#ifndef SQLITE_OMIT_CHECK
107774  if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
107775    ExprList *pCheck = pTab->pCheck;
107776    pParse->ckBase = regNewData+1;
107777    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
107778    for(i=0; i<pCheck->nExpr; i++){
107779      int allOk;
107780      Expr *pExpr = pCheck->a[i].pExpr;
107781      if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
107782      allOk = sqlite3VdbeMakeLabel(v);
107783      sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
107784      if( onError==OE_Ignore ){
107785        sqlite3VdbeGoto(v, ignoreDest);
107786      }else{
107787        char *zName = pCheck->a[i].zName;
107788        if( zName==0 ) zName = pTab->zName;
107789        if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
107790        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
107791                              onError, zName, P4_TRANSIENT,
107792                              P5_ConstraintCheck);
107793      }
107794      sqlite3VdbeResolveLabel(v, allOk);
107795    }
107796  }
107797#endif /* !defined(SQLITE_OMIT_CHECK) */
107798
107799  /* If rowid is changing, make sure the new rowid does not previously
107800  ** exist in the table.
107801  */
107802  if( pkChng && pPk==0 ){
107803    int addrRowidOk = sqlite3VdbeMakeLabel(v);
107804
107805    /* Figure out what action to take in case of a rowid collision */
107806    onError = pTab->keyConf;
107807    if( overrideError!=OE_Default ){
107808      onError = overrideError;
107809    }else if( onError==OE_Default ){
107810      onError = OE_Abort;
107811    }
107812
107813    if( isUpdate ){
107814      /* pkChng!=0 does not mean that the rowid has change, only that
107815      ** it might have changed.  Skip the conflict logic below if the rowid
107816      ** is unchanged. */
107817      sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
107818      sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
107819      VdbeCoverage(v);
107820    }
107821
107822    /* If the response to a rowid conflict is REPLACE but the response
107823    ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
107824    ** to defer the running of the rowid conflict checking until after
107825    ** the UNIQUE constraints have run.
107826    */
107827    if( onError==OE_Replace && overrideError!=OE_Replace ){
107828      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
107829        if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
107830          ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
107831          break;
107832        }
107833      }
107834    }
107835
107836    /* Check to see if the new rowid already exists in the table.  Skip
107837    ** the following conflict logic if it does not. */
107838    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
107839    VdbeCoverage(v);
107840
107841    /* Generate code that deals with a rowid collision */
107842    switch( onError ){
107843      default: {
107844        onError = OE_Abort;
107845        /* Fall thru into the next case */
107846      }
107847      case OE_Rollback:
107848      case OE_Abort:
107849      case OE_Fail: {
107850        sqlite3RowidConstraint(pParse, onError, pTab);
107851        break;
107852      }
107853      case OE_Replace: {
107854        /* If there are DELETE triggers on this table and the
107855        ** recursive-triggers flag is set, call GenerateRowDelete() to
107856        ** remove the conflicting row from the table. This will fire
107857        ** the triggers and remove both the table and index b-tree entries.
107858        **
107859        ** Otherwise, if there are no triggers or the recursive-triggers
107860        ** flag is not set, but the table has one or more indexes, call
107861        ** GenerateRowIndexDelete(). This removes the index b-tree entries
107862        ** only. The table b-tree entry will be replaced by the new entry
107863        ** when it is inserted.
107864        **
107865        ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
107866        ** also invoke MultiWrite() to indicate that this VDBE may require
107867        ** statement rollback (if the statement is aborted after the delete
107868        ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
107869        ** but being more selective here allows statements like:
107870        **
107871        **   REPLACE INTO t(rowid) VALUES($newrowid)
107872        **
107873        ** to run without a statement journal if there are no indexes on the
107874        ** table.
107875        */
107876        Trigger *pTrigger = 0;
107877        if( db->flags&SQLITE_RecTriggers ){
107878          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
107879        }
107880        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
107881          sqlite3MultiWrite(pParse);
107882          sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
107883                                   regNewData, 1, 0, OE_Replace, 1, -1);
107884        }else{
107885#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
107886          if( HasRowid(pTab) ){
107887            /* This OP_Delete opcode fires the pre-update-hook only. It does
107888            ** not modify the b-tree. It is more efficient to let the coming
107889            ** OP_Insert replace the existing entry than it is to delete the
107890            ** existing entry and then insert a new one. */
107891            sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
107892            sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
107893          }
107894#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
107895          if( pTab->pIndex ){
107896            sqlite3MultiWrite(pParse);
107897            sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
107898          }
107899        }
107900        seenReplace = 1;
107901        break;
107902      }
107903      case OE_Ignore: {
107904        /*assert( seenReplace==0 );*/
107905        sqlite3VdbeGoto(v, ignoreDest);
107906        break;
107907      }
107908    }
107909    sqlite3VdbeResolveLabel(v, addrRowidOk);
107910    if( ipkTop ){
107911      ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
107912      sqlite3VdbeJumpHere(v, ipkTop);
107913    }
107914  }
107915
107916  /* Test all UNIQUE constraints by creating entries for each UNIQUE
107917  ** index and making sure that duplicate entries do not already exist.
107918  ** Compute the revised record entries for indices as we go.
107919  **
107920  ** This loop also handles the case of the PRIMARY KEY index for a
107921  ** WITHOUT ROWID table.
107922  */
107923  for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
107924    int regIdx;          /* Range of registers hold conent for pIdx */
107925    int regR;            /* Range of registers holding conflicting PK */
107926    int iThisCur;        /* Cursor for this UNIQUE index */
107927    int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
107928
107929    if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
107930    if( bAffinityDone==0 ){
107931      sqlite3TableAffinity(v, pTab, regNewData+1);
107932      bAffinityDone = 1;
107933    }
107934    iThisCur = iIdxCur+ix;
107935    addrUniqueOk = sqlite3VdbeMakeLabel(v);
107936
107937    /* Skip partial indices for which the WHERE clause is not true */
107938    if( pIdx->pPartIdxWhere ){
107939      sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
107940      pParse->ckBase = regNewData+1;
107941      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
107942                            SQLITE_JUMPIFNULL);
107943      pParse->ckBase = 0;
107944    }
107945
107946    /* Create a record for this index entry as it should appear after
107947    ** the insert or update.  Store that record in the aRegIdx[ix] register
107948    */
107949    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
107950    for(i=0; i<pIdx->nColumn; i++){
107951      int iField = pIdx->aiColumn[i];
107952      int x;
107953      if( iField==XN_EXPR ){
107954        pParse->ckBase = regNewData+1;
107955        sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
107956        pParse->ckBase = 0;
107957        VdbeComment((v, "%s column %d", pIdx->zName, i));
107958      }else{
107959        if( iField==XN_ROWID || iField==pTab->iPKey ){
107960          if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
107961          x = regNewData;
107962          regRowid =  pIdx->pPartIdxWhere ? -1 : regIdx+i;
107963        }else{
107964          x = iField + regNewData + 1;
107965        }
107966        sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
107967        VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
107968      }
107969    }
107970    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
107971    VdbeComment((v, "for %s", pIdx->zName));
107972    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
107973
107974    /* In an UPDATE operation, if this index is the PRIMARY KEY index
107975    ** of a WITHOUT ROWID table and there has been no change the
107976    ** primary key, then no collision is possible.  The collision detection
107977    ** logic below can all be skipped. */
107978    if( isUpdate && pPk==pIdx && pkChng==0 ){
107979      sqlite3VdbeResolveLabel(v, addrUniqueOk);
107980      continue;
107981    }
107982
107983    /* Find out what action to take in case there is a uniqueness conflict */
107984    onError = pIdx->onError;
107985    if( onError==OE_None ){
107986      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
107987      sqlite3VdbeResolveLabel(v, addrUniqueOk);
107988      continue;  /* pIdx is not a UNIQUE index */
107989    }
107990    if( overrideError!=OE_Default ){
107991      onError = overrideError;
107992    }else if( onError==OE_Default ){
107993      onError = OE_Abort;
107994    }
107995
107996    /* Check to see if the new index entry will be unique */
107997    sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
107998                         regIdx, pIdx->nKeyCol); VdbeCoverage(v);
107999
108000    /* Generate code to handle collisions */
108001    regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
108002    if( isUpdate || onError==OE_Replace ){
108003      if( HasRowid(pTab) ){
108004        sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
108005        /* Conflict only if the rowid of the existing index entry
108006        ** is different from old-rowid */
108007        if( isUpdate ){
108008          sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
108009          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
108010          VdbeCoverage(v);
108011        }
108012      }else{
108013        int x;
108014        /* Extract the PRIMARY KEY from the end of the index entry and
108015        ** store it in registers regR..regR+nPk-1 */
108016        if( pIdx!=pPk ){
108017          for(i=0; i<pPk->nKeyCol; i++){
108018            assert( pPk->aiColumn[i]>=0 );
108019            x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
108020            sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
108021            VdbeComment((v, "%s.%s", pTab->zName,
108022                         pTab->aCol[pPk->aiColumn[i]].zName));
108023          }
108024        }
108025        if( isUpdate ){
108026          /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
108027          ** table, only conflict if the new PRIMARY KEY values are actually
108028          ** different from the old.
108029          **
108030          ** For a UNIQUE index, only conflict if the PRIMARY KEY values
108031          ** of the matched index row are different from the original PRIMARY
108032          ** KEY values of this row before the update.  */
108033          int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
108034          int op = OP_Ne;
108035          int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
108036
108037          for(i=0; i<pPk->nKeyCol; i++){
108038            char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
108039            x = pPk->aiColumn[i];
108040            assert( x>=0 );
108041            if( i==(pPk->nKeyCol-1) ){
108042              addrJump = addrUniqueOk;
108043              op = OP_Eq;
108044            }
108045            sqlite3VdbeAddOp4(v, op,
108046                regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
108047            );
108048            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
108049            VdbeCoverageIf(v, op==OP_Eq);
108050            VdbeCoverageIf(v, op==OP_Ne);
108051          }
108052        }
108053      }
108054    }
108055
108056    /* Generate code that executes if the new index entry is not unique */
108057    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
108058        || onError==OE_Ignore || onError==OE_Replace );
108059    switch( onError ){
108060      case OE_Rollback:
108061      case OE_Abort:
108062      case OE_Fail: {
108063        sqlite3UniqueConstraint(pParse, onError, pIdx);
108064        break;
108065      }
108066      case OE_Ignore: {
108067        sqlite3VdbeGoto(v, ignoreDest);
108068        break;
108069      }
108070      default: {
108071        Trigger *pTrigger = 0;
108072        assert( onError==OE_Replace );
108073        sqlite3MultiWrite(pParse);
108074        if( db->flags&SQLITE_RecTriggers ){
108075          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
108076        }
108077        sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
108078            regR, nPkField, 0, OE_Replace,
108079            (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1);
108080        seenReplace = 1;
108081        break;
108082      }
108083    }
108084    sqlite3VdbeResolveLabel(v, addrUniqueOk);
108085    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
108086    if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
108087  }
108088  if( ipkTop ){
108089    sqlite3VdbeGoto(v, ipkTop+1);
108090    sqlite3VdbeJumpHere(v, ipkBottom);
108091  }
108092
108093  *pbMayReplace = seenReplace;
108094  VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
108095}
108096
108097/*
108098** This routine generates code to finish the INSERT or UPDATE operation
108099** that was started by a prior call to sqlite3GenerateConstraintChecks.
108100** A consecutive range of registers starting at regNewData contains the
108101** rowid and the content to be inserted.
108102**
108103** The arguments to this routine should be the same as the first six
108104** arguments to sqlite3GenerateConstraintChecks.
108105*/
108106SQLITE_PRIVATE void sqlite3CompleteInsertion(
108107  Parse *pParse,      /* The parser context */
108108  Table *pTab,        /* the table into which we are inserting */
108109  int iDataCur,       /* Cursor of the canonical data source */
108110  int iIdxCur,        /* First index cursor */
108111  int regNewData,     /* Range of content */
108112  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
108113  int isUpdate,       /* True for UPDATE, False for INSERT */
108114  int appendBias,     /* True if this is likely to be an append */
108115  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
108116){
108117  Vdbe *v;            /* Prepared statements under construction */
108118  Index *pIdx;        /* An index being inserted or updated */
108119  u8 pik_flags;       /* flag values passed to the btree insert */
108120  int regData;        /* Content registers (after the rowid) */
108121  int regRec;         /* Register holding assembled record for the table */
108122  int i;              /* Loop counter */
108123  u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
108124
108125  v = sqlite3GetVdbe(pParse);
108126  assert( v!=0 );
108127  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
108128  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
108129    if( aRegIdx[i]==0 ) continue;
108130    bAffinityDone = 1;
108131    if( pIdx->pPartIdxWhere ){
108132      sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
108133      VdbeCoverage(v);
108134    }
108135    sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
108136    pik_flags = 0;
108137    if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
108138    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
108139      assert( pParse->nested==0 );
108140      pik_flags |= OPFLAG_NCHANGE;
108141    }
108142    sqlite3VdbeChangeP5(v, pik_flags);
108143  }
108144  if( !HasRowid(pTab) ) return;
108145  regData = regNewData + 1;
108146  regRec = sqlite3GetTempReg(pParse);
108147  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
108148  if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
108149  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
108150  if( pParse->nested ){
108151    pik_flags = 0;
108152  }else{
108153    pik_flags = OPFLAG_NCHANGE;
108154    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
108155  }
108156  if( appendBias ){
108157    pik_flags |= OPFLAG_APPEND;
108158  }
108159  if( useSeekResult ){
108160    pik_flags |= OPFLAG_USESEEKRESULT;
108161  }
108162  sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
108163  if( !pParse->nested ){
108164    sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
108165  }
108166  sqlite3VdbeChangeP5(v, pik_flags);
108167}
108168
108169/*
108170** Allocate cursors for the pTab table and all its indices and generate
108171** code to open and initialized those cursors.
108172**
108173** The cursor for the object that contains the complete data (normally
108174** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
108175** ROWID table) is returned in *piDataCur.  The first index cursor is
108176** returned in *piIdxCur.  The number of indices is returned.
108177**
108178** Use iBase as the first cursor (either the *piDataCur for rowid tables
108179** or the first index for WITHOUT ROWID tables) if it is non-negative.
108180** If iBase is negative, then allocate the next available cursor.
108181**
108182** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
108183** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
108184** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
108185** pTab->pIndex list.
108186**
108187** If pTab is a virtual table, then this routine is a no-op and the
108188** *piDataCur and *piIdxCur values are left uninitialized.
108189*/
108190SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
108191  Parse *pParse,   /* Parsing context */
108192  Table *pTab,     /* Table to be opened */
108193  int op,          /* OP_OpenRead or OP_OpenWrite */
108194  u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
108195  int iBase,       /* Use this for the table cursor, if there is one */
108196  u8 *aToOpen,     /* If not NULL: boolean for each table and index */
108197  int *piDataCur,  /* Write the database source cursor number here */
108198  int *piIdxCur    /* Write the first index cursor number here */
108199){
108200  int i;
108201  int iDb;
108202  int iDataCur;
108203  Index *pIdx;
108204  Vdbe *v;
108205
108206  assert( op==OP_OpenRead || op==OP_OpenWrite );
108207  assert( op==OP_OpenWrite || p5==0 );
108208  if( IsVirtual(pTab) ){
108209    /* This routine is a no-op for virtual tables. Leave the output
108210    ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
108211    ** can detect if they are used by mistake in the caller. */
108212    return 0;
108213  }
108214  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
108215  v = sqlite3GetVdbe(pParse);
108216  assert( v!=0 );
108217  if( iBase<0 ) iBase = pParse->nTab;
108218  iDataCur = iBase++;
108219  if( piDataCur ) *piDataCur = iDataCur;
108220  if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
108221    sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
108222  }else{
108223    sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
108224  }
108225  if( piIdxCur ) *piIdxCur = iBase;
108226  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
108227    int iIdxCur = iBase++;
108228    assert( pIdx->pSchema==pTab->pSchema );
108229    if( aToOpen==0 || aToOpen[i+1] ){
108230      sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
108231      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
108232      VdbeComment((v, "%s", pIdx->zName));
108233    }
108234    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
108235      if( piDataCur ) *piDataCur = iIdxCur;
108236    }else{
108237      sqlite3VdbeChangeP5(v, p5);
108238    }
108239  }
108240  if( iBase>pParse->nTab ) pParse->nTab = iBase;
108241  return i;
108242}
108243
108244
108245#ifdef SQLITE_TEST
108246/*
108247** The following global variable is incremented whenever the
108248** transfer optimization is used.  This is used for testing
108249** purposes only - to make sure the transfer optimization really
108250** is happening when it is supposed to.
108251*/
108252SQLITE_API int sqlite3_xferopt_count;
108253#endif /* SQLITE_TEST */
108254
108255
108256#ifndef SQLITE_OMIT_XFER_OPT
108257/*
108258** Check to see if index pSrc is compatible as a source of data
108259** for index pDest in an insert transfer optimization.  The rules
108260** for a compatible index:
108261**
108262**    *   The index is over the same set of columns
108263**    *   The same DESC and ASC markings occurs on all columns
108264**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
108265**    *   The same collating sequence on each column
108266**    *   The index has the exact same WHERE clause
108267*/
108268static int xferCompatibleIndex(Index *pDest, Index *pSrc){
108269  int i;
108270  assert( pDest && pSrc );
108271  assert( pDest->pTable!=pSrc->pTable );
108272  if( pDest->nKeyCol!=pSrc->nKeyCol ){
108273    return 0;   /* Different number of columns */
108274  }
108275  if( pDest->onError!=pSrc->onError ){
108276    return 0;   /* Different conflict resolution strategies */
108277  }
108278  for(i=0; i<pSrc->nKeyCol; i++){
108279    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
108280      return 0;   /* Different columns indexed */
108281    }
108282    if( pSrc->aiColumn[i]==XN_EXPR ){
108283      assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
108284      if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr,
108285                             pDest->aColExpr->a[i].pExpr, -1)!=0 ){
108286        return 0;   /* Different expressions in the index */
108287      }
108288    }
108289    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
108290      return 0;   /* Different sort orders */
108291    }
108292    if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
108293      return 0;   /* Different collating sequences */
108294    }
108295  }
108296  if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
108297    return 0;     /* Different WHERE clauses */
108298  }
108299
108300  /* If no test above fails then the indices must be compatible */
108301  return 1;
108302}
108303
108304/*
108305** Attempt the transfer optimization on INSERTs of the form
108306**
108307**     INSERT INTO tab1 SELECT * FROM tab2;
108308**
108309** The xfer optimization transfers raw records from tab2 over to tab1.
108310** Columns are not decoded and reassembled, which greatly improves
108311** performance.  Raw index records are transferred in the same way.
108312**
108313** The xfer optimization is only attempted if tab1 and tab2 are compatible.
108314** There are lots of rules for determining compatibility - see comments
108315** embedded in the code for details.
108316**
108317** This routine returns TRUE if the optimization is guaranteed to be used.
108318** Sometimes the xfer optimization will only work if the destination table
108319** is empty - a factor that can only be determined at run-time.  In that
108320** case, this routine generates code for the xfer optimization but also
108321** does a test to see if the destination table is empty and jumps over the
108322** xfer optimization code if the test fails.  In that case, this routine
108323** returns FALSE so that the caller will know to go ahead and generate
108324** an unoptimized transfer.  This routine also returns FALSE if there
108325** is no chance that the xfer optimization can be applied.
108326**
108327** This optimization is particularly useful at making VACUUM run faster.
108328*/
108329static int xferOptimization(
108330  Parse *pParse,        /* Parser context */
108331  Table *pDest,         /* The table we are inserting into */
108332  Select *pSelect,      /* A SELECT statement to use as the data source */
108333  int onError,          /* How to handle constraint errors */
108334  int iDbDest           /* The database of pDest */
108335){
108336  sqlite3 *db = pParse->db;
108337  ExprList *pEList;                /* The result set of the SELECT */
108338  Table *pSrc;                     /* The table in the FROM clause of SELECT */
108339  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
108340  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
108341  int i;                           /* Loop counter */
108342  int iDbSrc;                      /* The database of pSrc */
108343  int iSrc, iDest;                 /* Cursors from source and destination */
108344  int addr1, addr2;                /* Loop addresses */
108345  int emptyDestTest = 0;           /* Address of test for empty pDest */
108346  int emptySrcTest = 0;            /* Address of test for empty pSrc */
108347  Vdbe *v;                         /* The VDBE we are building */
108348  int regAutoinc;                  /* Memory register used by AUTOINC */
108349  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
108350  int regData, regRowid;           /* Registers holding data and rowid */
108351
108352  if( pSelect==0 ){
108353    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
108354  }
108355  if( pParse->pWith || pSelect->pWith ){
108356    /* Do not attempt to process this query if there are an WITH clauses
108357    ** attached to it. Proceeding may generate a false "no such table: xxx"
108358    ** error if pSelect reads from a CTE named "xxx".  */
108359    return 0;
108360  }
108361  if( sqlite3TriggerList(pParse, pDest) ){
108362    return 0;   /* tab1 must not have triggers */
108363  }
108364#ifndef SQLITE_OMIT_VIRTUALTABLE
108365  if( pDest->tabFlags & TF_Virtual ){
108366    return 0;   /* tab1 must not be a virtual table */
108367  }
108368#endif
108369  if( onError==OE_Default ){
108370    if( pDest->iPKey>=0 ) onError = pDest->keyConf;
108371    if( onError==OE_Default ) onError = OE_Abort;
108372  }
108373  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
108374  if( pSelect->pSrc->nSrc!=1 ){
108375    return 0;   /* FROM clause must have exactly one term */
108376  }
108377  if( pSelect->pSrc->a[0].pSelect ){
108378    return 0;   /* FROM clause cannot contain a subquery */
108379  }
108380  if( pSelect->pWhere ){
108381    return 0;   /* SELECT may not have a WHERE clause */
108382  }
108383  if( pSelect->pOrderBy ){
108384    return 0;   /* SELECT may not have an ORDER BY clause */
108385  }
108386  /* Do not need to test for a HAVING clause.  If HAVING is present but
108387  ** there is no ORDER BY, we will get an error. */
108388  if( pSelect->pGroupBy ){
108389    return 0;   /* SELECT may not have a GROUP BY clause */
108390  }
108391  if( pSelect->pLimit ){
108392    return 0;   /* SELECT may not have a LIMIT clause */
108393  }
108394  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
108395  if( pSelect->pPrior ){
108396    return 0;   /* SELECT may not be a compound query */
108397  }
108398  if( pSelect->selFlags & SF_Distinct ){
108399    return 0;   /* SELECT may not be DISTINCT */
108400  }
108401  pEList = pSelect->pEList;
108402  assert( pEList!=0 );
108403  if( pEList->nExpr!=1 ){
108404    return 0;   /* The result set must have exactly one column */
108405  }
108406  assert( pEList->a[0].pExpr );
108407  if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
108408    return 0;   /* The result set must be the special operator "*" */
108409  }
108410
108411  /* At this point we have established that the statement is of the
108412  ** correct syntactic form to participate in this optimization.  Now
108413  ** we have to check the semantics.
108414  */
108415  pItem = pSelect->pSrc->a;
108416  pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
108417  if( pSrc==0 ){
108418    return 0;   /* FROM clause does not contain a real table */
108419  }
108420  if( pSrc==pDest ){
108421    return 0;   /* tab1 and tab2 may not be the same table */
108422  }
108423  if( HasRowid(pDest)!=HasRowid(pSrc) ){
108424    return 0;   /* source and destination must both be WITHOUT ROWID or not */
108425  }
108426#ifndef SQLITE_OMIT_VIRTUALTABLE
108427  if( pSrc->tabFlags & TF_Virtual ){
108428    return 0;   /* tab2 must not be a virtual table */
108429  }
108430#endif
108431  if( pSrc->pSelect ){
108432    return 0;   /* tab2 may not be a view */
108433  }
108434  if( pDest->nCol!=pSrc->nCol ){
108435    return 0;   /* Number of columns must be the same in tab1 and tab2 */
108436  }
108437  if( pDest->iPKey!=pSrc->iPKey ){
108438    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
108439  }
108440  for(i=0; i<pDest->nCol; i++){
108441    Column *pDestCol = &pDest->aCol[i];
108442    Column *pSrcCol = &pSrc->aCol[i];
108443#ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
108444    if( (db->flags & SQLITE_Vacuum)==0
108445     && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
108446    ){
108447      return 0;    /* Neither table may have __hidden__ columns */
108448    }
108449#endif
108450    if( pDestCol->affinity!=pSrcCol->affinity ){
108451      return 0;    /* Affinity must be the same on all columns */
108452    }
108453    if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
108454      return 0;    /* Collating sequence must be the same on all columns */
108455    }
108456    if( pDestCol->notNull && !pSrcCol->notNull ){
108457      return 0;    /* tab2 must be NOT NULL if tab1 is */
108458    }
108459    /* Default values for second and subsequent columns need to match. */
108460    if( i>0 ){
108461      assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
108462      assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
108463      if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
108464       || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
108465                                       pSrcCol->pDflt->u.zToken)!=0)
108466      ){
108467        return 0;    /* Default values must be the same for all columns */
108468      }
108469    }
108470  }
108471  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
108472    if( IsUniqueIndex(pDestIdx) ){
108473      destHasUniqueIdx = 1;
108474    }
108475    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
108476      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
108477    }
108478    if( pSrcIdx==0 ){
108479      return 0;    /* pDestIdx has no corresponding index in pSrc */
108480    }
108481  }
108482#ifndef SQLITE_OMIT_CHECK
108483  if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
108484    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
108485  }
108486#endif
108487#ifndef SQLITE_OMIT_FOREIGN_KEY
108488  /* Disallow the transfer optimization if the destination table constains
108489  ** any foreign key constraints.  This is more restrictive than necessary.
108490  ** But the main beneficiary of the transfer optimization is the VACUUM
108491  ** command, and the VACUUM command disables foreign key constraints.  So
108492  ** the extra complication to make this rule less restrictive is probably
108493  ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
108494  */
108495  if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
108496    return 0;
108497  }
108498#endif
108499  if( (db->flags & SQLITE_CountRows)!=0 ){
108500    return 0;  /* xfer opt does not play well with PRAGMA count_changes */
108501  }
108502
108503  /* If we get this far, it means that the xfer optimization is at
108504  ** least a possibility, though it might only work if the destination
108505  ** table (tab1) is initially empty.
108506  */
108507#ifdef SQLITE_TEST
108508  sqlite3_xferopt_count++;
108509#endif
108510  iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
108511  v = sqlite3GetVdbe(pParse);
108512  sqlite3CodeVerifySchema(pParse, iDbSrc);
108513  iSrc = pParse->nTab++;
108514  iDest = pParse->nTab++;
108515  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
108516  regData = sqlite3GetTempReg(pParse);
108517  regRowid = sqlite3GetTempReg(pParse);
108518  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
108519  assert( HasRowid(pDest) || destHasUniqueIdx );
108520  if( (db->flags & SQLITE_Vacuum)==0 && (
108521      (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
108522   || destHasUniqueIdx                              /* (2) */
108523   || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
108524  )){
108525    /* In some circumstances, we are able to run the xfer optimization
108526    ** only if the destination table is initially empty. Unless the
108527    ** SQLITE_Vacuum flag is set, this block generates code to make
108528    ** that determination. If SQLITE_Vacuum is set, then the destination
108529    ** table is always empty.
108530    **
108531    ** Conditions under which the destination must be empty:
108532    **
108533    ** (1) There is no INTEGER PRIMARY KEY but there are indices.
108534    **     (If the destination is not initially empty, the rowid fields
108535    **     of index entries might need to change.)
108536    **
108537    ** (2) The destination has a unique index.  (The xfer optimization
108538    **     is unable to test uniqueness.)
108539    **
108540    ** (3) onError is something other than OE_Abort and OE_Rollback.
108541    */
108542    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
108543    emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
108544    sqlite3VdbeJumpHere(v, addr1);
108545  }
108546  if( HasRowid(pSrc) ){
108547    sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
108548    emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
108549    if( pDest->iPKey>=0 ){
108550      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
108551      addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
108552      VdbeCoverage(v);
108553      sqlite3RowidConstraint(pParse, onError, pDest);
108554      sqlite3VdbeJumpHere(v, addr2);
108555      autoIncStep(pParse, regAutoinc, regRowid);
108556    }else if( pDest->pIndex==0 ){
108557      addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
108558    }else{
108559      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
108560      assert( (pDest->tabFlags & TF_Autoincrement)==0 );
108561    }
108562    sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
108563    sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
108564                      (char*)pDest, P4_TABLE);
108565    sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
108566    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
108567    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
108568    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
108569  }else{
108570    sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
108571    sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
108572  }
108573  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
108574    u8 idxInsFlags = 0;
108575    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
108576      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
108577    }
108578    assert( pSrcIdx );
108579    sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
108580    sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
108581    VdbeComment((v, "%s", pSrcIdx->zName));
108582    sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
108583    sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
108584    sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
108585    VdbeComment((v, "%s", pDestIdx->zName));
108586    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
108587    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
108588    if( db->flags & SQLITE_Vacuum ){
108589      /* This INSERT command is part of a VACUUM operation, which guarantees
108590      ** that the destination table is empty. If all indexed columns use
108591      ** collation sequence BINARY, then it can also be assumed that the
108592      ** index will be populated by inserting keys in strictly sorted
108593      ** order. In this case, instead of seeking within the b-tree as part
108594      ** of every OP_IdxInsert opcode, an OP_Last is added before the
108595      ** OP_IdxInsert to seek to the point within the b-tree where each key
108596      ** should be inserted. This is faster.
108597      **
108598      ** If any of the indexed columns use a collation sequence other than
108599      ** BINARY, this optimization is disabled. This is because the user
108600      ** might change the definition of a collation sequence and then run
108601      ** a VACUUM command. In that case keys may not be written in strictly
108602      ** sorted order.  */
108603      for(i=0; i<pSrcIdx->nColumn; i++){
108604        const char *zColl = pSrcIdx->azColl[i];
108605        assert( sqlite3_stricmp(sqlite3StrBINARY, zColl)!=0
108606                    || sqlite3StrBINARY==zColl );
108607        if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
108608      }
108609      if( i==pSrcIdx->nColumn ){
108610        idxInsFlags = OPFLAG_USESEEKRESULT;
108611        sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
108612      }
108613    }
108614    if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
108615      idxInsFlags |= OPFLAG_NCHANGE;
108616    }
108617    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
108618    sqlite3VdbeChangeP5(v, idxInsFlags);
108619    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
108620    sqlite3VdbeJumpHere(v, addr1);
108621    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
108622    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
108623  }
108624  if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
108625  sqlite3ReleaseTempReg(pParse, regRowid);
108626  sqlite3ReleaseTempReg(pParse, regData);
108627  if( emptyDestTest ){
108628    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
108629    sqlite3VdbeJumpHere(v, emptyDestTest);
108630    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
108631    return 0;
108632  }else{
108633    return 1;
108634  }
108635}
108636#endif /* SQLITE_OMIT_XFER_OPT */
108637
108638/************** End of insert.c **********************************************/
108639/************** Begin file legacy.c ******************************************/
108640/*
108641** 2001 September 15
108642**
108643** The author disclaims copyright to this source code.  In place of
108644** a legal notice, here is a blessing:
108645**
108646**    May you do good and not evil.
108647**    May you find forgiveness for yourself and forgive others.
108648**    May you share freely, never taking more than you give.
108649**
108650*************************************************************************
108651** Main file for the SQLite library.  The routines in this file
108652** implement the programmer interface to the library.  Routines in
108653** other files are for internal use by SQLite and should not be
108654** accessed by users of the library.
108655*/
108656
108657/* #include "sqliteInt.h" */
108658
108659/*
108660** Execute SQL code.  Return one of the SQLITE_ success/failure
108661** codes.  Also write an error message into memory obtained from
108662** malloc() and make *pzErrMsg point to that message.
108663**
108664** If the SQL is a query, then for each row in the query result
108665** the xCallback() function is called.  pArg becomes the first
108666** argument to xCallback().  If xCallback=NULL then no callback
108667** is invoked, even for queries.
108668*/
108669SQLITE_API int SQLITE_STDCALL sqlite3_exec(
108670  sqlite3 *db,                /* The database on which the SQL executes */
108671  const char *zSql,           /* The SQL to be executed */
108672  sqlite3_callback xCallback, /* Invoke this callback routine */
108673  void *pArg,                 /* First argument to xCallback() */
108674  char **pzErrMsg             /* Write error messages here */
108675){
108676  int rc = SQLITE_OK;         /* Return code */
108677  const char *zLeftover;      /* Tail of unprocessed SQL */
108678  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
108679  char **azCols = 0;          /* Names of result columns */
108680  int callbackIsInit;         /* True if callback data is initialized */
108681
108682  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
108683  if( zSql==0 ) zSql = "";
108684
108685  sqlite3_mutex_enter(db->mutex);
108686  sqlite3Error(db, SQLITE_OK);
108687  while( rc==SQLITE_OK && zSql[0] ){
108688    int nCol;
108689    char **azVals = 0;
108690
108691    pStmt = 0;
108692    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
108693    assert( rc==SQLITE_OK || pStmt==0 );
108694    if( rc!=SQLITE_OK ){
108695      continue;
108696    }
108697    if( !pStmt ){
108698      /* this happens for a comment or white-space */
108699      zSql = zLeftover;
108700      continue;
108701    }
108702
108703    callbackIsInit = 0;
108704    nCol = sqlite3_column_count(pStmt);
108705
108706    while( 1 ){
108707      int i;
108708      rc = sqlite3_step(pStmt);
108709
108710      /* Invoke the callback function if required */
108711      if( xCallback && (SQLITE_ROW==rc ||
108712          (SQLITE_DONE==rc && !callbackIsInit
108713                           && db->flags&SQLITE_NullCallback)) ){
108714        if( !callbackIsInit ){
108715          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
108716          if( azCols==0 ){
108717            goto exec_out;
108718          }
108719          for(i=0; i<nCol; i++){
108720            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
108721            /* sqlite3VdbeSetColName() installs column names as UTF8
108722            ** strings so there is no way for sqlite3_column_name() to fail. */
108723            assert( azCols[i]!=0 );
108724          }
108725          callbackIsInit = 1;
108726        }
108727        if( rc==SQLITE_ROW ){
108728          azVals = &azCols[nCol];
108729          for(i=0; i<nCol; i++){
108730            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
108731            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
108732              sqlite3OomFault(db);
108733              goto exec_out;
108734            }
108735          }
108736        }
108737        if( xCallback(pArg, nCol, azVals, azCols) ){
108738          /* EVIDENCE-OF: R-38229-40159 If the callback function to
108739          ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
108740          ** return SQLITE_ABORT. */
108741          rc = SQLITE_ABORT;
108742          sqlite3VdbeFinalize((Vdbe *)pStmt);
108743          pStmt = 0;
108744          sqlite3Error(db, SQLITE_ABORT);
108745          goto exec_out;
108746        }
108747      }
108748
108749      if( rc!=SQLITE_ROW ){
108750        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
108751        pStmt = 0;
108752        zSql = zLeftover;
108753        while( sqlite3Isspace(zSql[0]) ) zSql++;
108754        break;
108755      }
108756    }
108757
108758    sqlite3DbFree(db, azCols);
108759    azCols = 0;
108760  }
108761
108762exec_out:
108763  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
108764  sqlite3DbFree(db, azCols);
108765
108766  rc = sqlite3ApiExit(db, rc);
108767  if( rc!=SQLITE_OK && pzErrMsg ){
108768    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
108769    *pzErrMsg = sqlite3Malloc(nErrMsg);
108770    if( *pzErrMsg ){
108771      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
108772    }else{
108773      rc = SQLITE_NOMEM_BKPT;
108774      sqlite3Error(db, SQLITE_NOMEM);
108775    }
108776  }else if( pzErrMsg ){
108777    *pzErrMsg = 0;
108778  }
108779
108780  assert( (rc&db->errMask)==rc );
108781  sqlite3_mutex_leave(db->mutex);
108782  return rc;
108783}
108784
108785/************** End of legacy.c **********************************************/
108786/************** Begin file loadext.c *****************************************/
108787/*
108788** 2006 June 7
108789**
108790** The author disclaims copyright to this source code.  In place of
108791** a legal notice, here is a blessing:
108792**
108793**    May you do good and not evil.
108794**    May you find forgiveness for yourself and forgive others.
108795**    May you share freely, never taking more than you give.
108796**
108797*************************************************************************
108798** This file contains code used to dynamically load extensions into
108799** the SQLite library.
108800*/
108801
108802#ifndef SQLITE_CORE
108803  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
108804#endif
108805/************** Include sqlite3ext.h in the middle of loadext.c **************/
108806/************** Begin file sqlite3ext.h **************************************/
108807/*
108808** 2006 June 7
108809**
108810** The author disclaims copyright to this source code.  In place of
108811** a legal notice, here is a blessing:
108812**
108813**    May you do good and not evil.
108814**    May you find forgiveness for yourself and forgive others.
108815**    May you share freely, never taking more than you give.
108816**
108817*************************************************************************
108818** This header file defines the SQLite interface for use by
108819** shared libraries that want to be imported as extensions into
108820** an SQLite instance.  Shared libraries that intend to be loaded
108821** as extensions by SQLite should #include this file instead of
108822** sqlite3.h.
108823*/
108824#ifndef SQLITE3EXT_H
108825#define SQLITE3EXT_H
108826/* #include "sqlite3.h" */
108827
108828/*
108829** The following structure holds pointers to all of the SQLite API
108830** routines.
108831**
108832** WARNING:  In order to maintain backwards compatibility, add new
108833** interfaces to the end of this structure only.  If you insert new
108834** interfaces in the middle of this structure, then older different
108835** versions of SQLite will not be able to load each other's shared
108836** libraries!
108837*/
108838struct sqlite3_api_routines {
108839  void * (*aggregate_context)(sqlite3_context*,int nBytes);
108840  int  (*aggregate_count)(sqlite3_context*);
108841  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
108842  int  (*bind_double)(sqlite3_stmt*,int,double);
108843  int  (*bind_int)(sqlite3_stmt*,int,int);
108844  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
108845  int  (*bind_null)(sqlite3_stmt*,int);
108846  int  (*bind_parameter_count)(sqlite3_stmt*);
108847  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
108848  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
108849  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
108850  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
108851  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
108852  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
108853  int  (*busy_timeout)(sqlite3*,int ms);
108854  int  (*changes)(sqlite3*);
108855  int  (*close)(sqlite3*);
108856  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
108857                           int eTextRep,const char*));
108858  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
108859                             int eTextRep,const void*));
108860  const void * (*column_blob)(sqlite3_stmt*,int iCol);
108861  int  (*column_bytes)(sqlite3_stmt*,int iCol);
108862  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
108863  int  (*column_count)(sqlite3_stmt*pStmt);
108864  const char * (*column_database_name)(sqlite3_stmt*,int);
108865  const void * (*column_database_name16)(sqlite3_stmt*,int);
108866  const char * (*column_decltype)(sqlite3_stmt*,int i);
108867  const void * (*column_decltype16)(sqlite3_stmt*,int);
108868  double  (*column_double)(sqlite3_stmt*,int iCol);
108869  int  (*column_int)(sqlite3_stmt*,int iCol);
108870  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
108871  const char * (*column_name)(sqlite3_stmt*,int);
108872  const void * (*column_name16)(sqlite3_stmt*,int);
108873  const char * (*column_origin_name)(sqlite3_stmt*,int);
108874  const void * (*column_origin_name16)(sqlite3_stmt*,int);
108875  const char * (*column_table_name)(sqlite3_stmt*,int);
108876  const void * (*column_table_name16)(sqlite3_stmt*,int);
108877  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
108878  const void * (*column_text16)(sqlite3_stmt*,int iCol);
108879  int  (*column_type)(sqlite3_stmt*,int iCol);
108880  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
108881  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
108882  int  (*complete)(const char*sql);
108883  int  (*complete16)(const void*sql);
108884  int  (*create_collation)(sqlite3*,const char*,int,void*,
108885                           int(*)(void*,int,const void*,int,const void*));
108886  int  (*create_collation16)(sqlite3*,const void*,int,void*,
108887                             int(*)(void*,int,const void*,int,const void*));
108888  int  (*create_function)(sqlite3*,const char*,int,int,void*,
108889                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
108890                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),
108891                          void (*xFinal)(sqlite3_context*));
108892  int  (*create_function16)(sqlite3*,const void*,int,int,void*,
108893                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
108894                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
108895                            void (*xFinal)(sqlite3_context*));
108896  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
108897  int  (*data_count)(sqlite3_stmt*pStmt);
108898  sqlite3 * (*db_handle)(sqlite3_stmt*);
108899  int (*declare_vtab)(sqlite3*,const char*);
108900  int  (*enable_shared_cache)(int);
108901  int  (*errcode)(sqlite3*db);
108902  const char * (*errmsg)(sqlite3*);
108903  const void * (*errmsg16)(sqlite3*);
108904  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
108905  int  (*expired)(sqlite3_stmt*);
108906  int  (*finalize)(sqlite3_stmt*pStmt);
108907  void  (*free)(void*);
108908  void  (*free_table)(char**result);
108909  int  (*get_autocommit)(sqlite3*);
108910  void * (*get_auxdata)(sqlite3_context*,int);
108911  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
108912  int  (*global_recover)(void);
108913  void  (*interruptx)(sqlite3*);
108914  sqlite_int64  (*last_insert_rowid)(sqlite3*);
108915  const char * (*libversion)(void);
108916  int  (*libversion_number)(void);
108917  void *(*malloc)(int);
108918  char * (*mprintf)(const char*,...);
108919  int  (*open)(const char*,sqlite3**);
108920  int  (*open16)(const void*,sqlite3**);
108921  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
108922  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
108923  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
108924  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
108925  void *(*realloc)(void*,int);
108926  int  (*reset)(sqlite3_stmt*pStmt);
108927  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
108928  void  (*result_double)(sqlite3_context*,double);
108929  void  (*result_error)(sqlite3_context*,const char*,int);
108930  void  (*result_error16)(sqlite3_context*,const void*,int);
108931  void  (*result_int)(sqlite3_context*,int);
108932  void  (*result_int64)(sqlite3_context*,sqlite_int64);
108933  void  (*result_null)(sqlite3_context*);
108934  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
108935  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
108936  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
108937  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
108938  void  (*result_value)(sqlite3_context*,sqlite3_value*);
108939  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
108940  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
108941                         const char*,const char*),void*);
108942  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
108943  char * (*snprintf)(int,char*,const char*,...);
108944  int  (*step)(sqlite3_stmt*);
108945  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
108946                                char const**,char const**,int*,int*,int*);
108947  void  (*thread_cleanup)(void);
108948  int  (*total_changes)(sqlite3*);
108949  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
108950  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
108951  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
108952                                         sqlite_int64),void*);
108953  void * (*user_data)(sqlite3_context*);
108954  const void * (*value_blob)(sqlite3_value*);
108955  int  (*value_bytes)(sqlite3_value*);
108956  int  (*value_bytes16)(sqlite3_value*);
108957  double  (*value_double)(sqlite3_value*);
108958  int  (*value_int)(sqlite3_value*);
108959  sqlite_int64  (*value_int64)(sqlite3_value*);
108960  int  (*value_numeric_type)(sqlite3_value*);
108961  const unsigned char * (*value_text)(sqlite3_value*);
108962  const void * (*value_text16)(sqlite3_value*);
108963  const void * (*value_text16be)(sqlite3_value*);
108964  const void * (*value_text16le)(sqlite3_value*);
108965  int  (*value_type)(sqlite3_value*);
108966  char *(*vmprintf)(const char*,va_list);
108967  /* Added ??? */
108968  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
108969  /* Added by 3.3.13 */
108970  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
108971  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
108972  int (*clear_bindings)(sqlite3_stmt*);
108973  /* Added by 3.4.1 */
108974  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
108975                          void (*xDestroy)(void *));
108976  /* Added by 3.5.0 */
108977  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
108978  int (*blob_bytes)(sqlite3_blob*);
108979  int (*blob_close)(sqlite3_blob*);
108980  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
108981                   int,sqlite3_blob**);
108982  int (*blob_read)(sqlite3_blob*,void*,int,int);
108983  int (*blob_write)(sqlite3_blob*,const void*,int,int);
108984  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
108985                             int(*)(void*,int,const void*,int,const void*),
108986                             void(*)(void*));
108987  int (*file_control)(sqlite3*,const char*,int,void*);
108988  sqlite3_int64 (*memory_highwater)(int);
108989  sqlite3_int64 (*memory_used)(void);
108990  sqlite3_mutex *(*mutex_alloc)(int);
108991  void (*mutex_enter)(sqlite3_mutex*);
108992  void (*mutex_free)(sqlite3_mutex*);
108993  void (*mutex_leave)(sqlite3_mutex*);
108994  int (*mutex_try)(sqlite3_mutex*);
108995  int (*open_v2)(const char*,sqlite3**,int,const char*);
108996  int (*release_memory)(int);
108997  void (*result_error_nomem)(sqlite3_context*);
108998  void (*result_error_toobig)(sqlite3_context*);
108999  int (*sleep)(int);
109000  void (*soft_heap_limit)(int);
109001  sqlite3_vfs *(*vfs_find)(const char*);
109002  int (*vfs_register)(sqlite3_vfs*,int);
109003  int (*vfs_unregister)(sqlite3_vfs*);
109004  int (*xthreadsafe)(void);
109005  void (*result_zeroblob)(sqlite3_context*,int);
109006  void (*result_error_code)(sqlite3_context*,int);
109007  int (*test_control)(int, ...);
109008  void (*randomness)(int,void*);
109009  sqlite3 *(*context_db_handle)(sqlite3_context*);
109010  int (*extended_result_codes)(sqlite3*,int);
109011  int (*limit)(sqlite3*,int,int);
109012  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
109013  const char *(*sql)(sqlite3_stmt*);
109014  int (*status)(int,int*,int*,int);
109015  int (*backup_finish)(sqlite3_backup*);
109016  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
109017  int (*backup_pagecount)(sqlite3_backup*);
109018  int (*backup_remaining)(sqlite3_backup*);
109019  int (*backup_step)(sqlite3_backup*,int);
109020  const char *(*compileoption_get)(int);
109021  int (*compileoption_used)(const char*);
109022  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
109023                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
109024                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
109025                            void (*xFinal)(sqlite3_context*),
109026                            void(*xDestroy)(void*));
109027  int (*db_config)(sqlite3*,int,...);
109028  sqlite3_mutex *(*db_mutex)(sqlite3*);
109029  int (*db_status)(sqlite3*,int,int*,int*,int);
109030  int (*extended_errcode)(sqlite3*);
109031  void (*log)(int,const char*,...);
109032  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
109033  const char *(*sourceid)(void);
109034  int (*stmt_status)(sqlite3_stmt*,int,int);
109035  int (*strnicmp)(const char*,const char*,int);
109036  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
109037  int (*wal_autocheckpoint)(sqlite3*,int);
109038  int (*wal_checkpoint)(sqlite3*,const char*);
109039  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
109040  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
109041  int (*vtab_config)(sqlite3*,int op,...);
109042  int (*vtab_on_conflict)(sqlite3*);
109043  /* Version 3.7.16 and later */
109044  int (*close_v2)(sqlite3*);
109045  const char *(*db_filename)(sqlite3*,const char*);
109046  int (*db_readonly)(sqlite3*,const char*);
109047  int (*db_release_memory)(sqlite3*);
109048  const char *(*errstr)(int);
109049  int (*stmt_busy)(sqlite3_stmt*);
109050  int (*stmt_readonly)(sqlite3_stmt*);
109051  int (*stricmp)(const char*,const char*);
109052  int (*uri_boolean)(const char*,const char*,int);
109053  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
109054  const char *(*uri_parameter)(const char*,const char*);
109055  char *(*vsnprintf)(int,char*,const char*,va_list);
109056  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
109057  /* Version 3.8.7 and later */
109058  int (*auto_extension)(void(*)(void));
109059  int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
109060                     void(*)(void*));
109061  int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
109062                      void(*)(void*),unsigned char);
109063  int (*cancel_auto_extension)(void(*)(void));
109064  int (*load_extension)(sqlite3*,const char*,const char*,char**);
109065  void *(*malloc64)(sqlite3_uint64);
109066  sqlite3_uint64 (*msize)(void*);
109067  void *(*realloc64)(void*,sqlite3_uint64);
109068  void (*reset_auto_extension)(void);
109069  void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
109070                        void(*)(void*));
109071  void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
109072                         void(*)(void*), unsigned char);
109073  int (*strglob)(const char*,const char*);
109074  /* Version 3.8.11 and later */
109075  sqlite3_value *(*value_dup)(const sqlite3_value*);
109076  void (*value_free)(sqlite3_value*);
109077  int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
109078  int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
109079  /* Version 3.9.0 and later */
109080  unsigned int (*value_subtype)(sqlite3_value*);
109081  void (*result_subtype)(sqlite3_context*,unsigned int);
109082  /* Version 3.10.0 and later */
109083  int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
109084  int (*strlike)(const char*,const char*,unsigned int);
109085  int (*db_cacheflush)(sqlite3*);
109086  /* Version 3.12.0 and later */
109087  int (*system_errno)(sqlite3*);
109088  /* Version 3.14.0 and later */
109089  int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
109090  char *(*expanded_sql)(sqlite3_stmt*);
109091};
109092
109093/*
109094** This is the function signature used for all extension entry points.  It
109095** is also defined in the file "loadext.c".
109096*/
109097typedef int (*sqlite3_loadext_entry)(
109098  sqlite3 *db,                       /* Handle to the database. */
109099  char **pzErrMsg,                   /* Used to set error string on failure. */
109100  const sqlite3_api_routines *pThunk /* Extension API function pointers. */
109101);
109102
109103/*
109104** The following macros redefine the API routines so that they are
109105** redirected through the global sqlite3_api structure.
109106**
109107** This header file is also used by the loadext.c source file
109108** (part of the main SQLite library - not an extension) so that
109109** it can get access to the sqlite3_api_routines structure
109110** definition.  But the main library does not want to redefine
109111** the API.  So the redefinition macros are only valid if the
109112** SQLITE_CORE macros is undefined.
109113*/
109114#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
109115#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
109116#ifndef SQLITE_OMIT_DEPRECATED
109117#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
109118#endif
109119#define sqlite3_bind_blob              sqlite3_api->bind_blob
109120#define sqlite3_bind_double            sqlite3_api->bind_double
109121#define sqlite3_bind_int               sqlite3_api->bind_int
109122#define sqlite3_bind_int64             sqlite3_api->bind_int64
109123#define sqlite3_bind_null              sqlite3_api->bind_null
109124#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
109125#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
109126#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
109127#define sqlite3_bind_text              sqlite3_api->bind_text
109128#define sqlite3_bind_text16            sqlite3_api->bind_text16
109129#define sqlite3_bind_value             sqlite3_api->bind_value
109130#define sqlite3_busy_handler           sqlite3_api->busy_handler
109131#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
109132#define sqlite3_changes                sqlite3_api->changes
109133#define sqlite3_close                  sqlite3_api->close
109134#define sqlite3_collation_needed       sqlite3_api->collation_needed
109135#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
109136#define sqlite3_column_blob            sqlite3_api->column_blob
109137#define sqlite3_column_bytes           sqlite3_api->column_bytes
109138#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
109139#define sqlite3_column_count           sqlite3_api->column_count
109140#define sqlite3_column_database_name   sqlite3_api->column_database_name
109141#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
109142#define sqlite3_column_decltype        sqlite3_api->column_decltype
109143#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
109144#define sqlite3_column_double          sqlite3_api->column_double
109145#define sqlite3_column_int             sqlite3_api->column_int
109146#define sqlite3_column_int64           sqlite3_api->column_int64
109147#define sqlite3_column_name            sqlite3_api->column_name
109148#define sqlite3_column_name16          sqlite3_api->column_name16
109149#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
109150#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
109151#define sqlite3_column_table_name      sqlite3_api->column_table_name
109152#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
109153#define sqlite3_column_text            sqlite3_api->column_text
109154#define sqlite3_column_text16          sqlite3_api->column_text16
109155#define sqlite3_column_type            sqlite3_api->column_type
109156#define sqlite3_column_value           sqlite3_api->column_value
109157#define sqlite3_commit_hook            sqlite3_api->commit_hook
109158#define sqlite3_complete               sqlite3_api->complete
109159#define sqlite3_complete16             sqlite3_api->complete16
109160#define sqlite3_create_collation       sqlite3_api->create_collation
109161#define sqlite3_create_collation16     sqlite3_api->create_collation16
109162#define sqlite3_create_function        sqlite3_api->create_function
109163#define sqlite3_create_function16      sqlite3_api->create_function16
109164#define sqlite3_create_module          sqlite3_api->create_module
109165#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
109166#define sqlite3_data_count             sqlite3_api->data_count
109167#define sqlite3_db_handle              sqlite3_api->db_handle
109168#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
109169#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
109170#define sqlite3_errcode                sqlite3_api->errcode
109171#define sqlite3_errmsg                 sqlite3_api->errmsg
109172#define sqlite3_errmsg16               sqlite3_api->errmsg16
109173#define sqlite3_exec                   sqlite3_api->exec
109174#ifndef SQLITE_OMIT_DEPRECATED
109175#define sqlite3_expired                sqlite3_api->expired
109176#endif
109177#define sqlite3_finalize               sqlite3_api->finalize
109178#define sqlite3_free                   sqlite3_api->free
109179#define sqlite3_free_table             sqlite3_api->free_table
109180#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
109181#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
109182#define sqlite3_get_table              sqlite3_api->get_table
109183#ifndef SQLITE_OMIT_DEPRECATED
109184#define sqlite3_global_recover         sqlite3_api->global_recover
109185#endif
109186#define sqlite3_interrupt              sqlite3_api->interruptx
109187#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
109188#define sqlite3_libversion             sqlite3_api->libversion
109189#define sqlite3_libversion_number      sqlite3_api->libversion_number
109190#define sqlite3_malloc                 sqlite3_api->malloc
109191#define sqlite3_mprintf                sqlite3_api->mprintf
109192#define sqlite3_open                   sqlite3_api->open
109193#define sqlite3_open16                 sqlite3_api->open16
109194#define sqlite3_prepare                sqlite3_api->prepare
109195#define sqlite3_prepare16              sqlite3_api->prepare16
109196#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
109197#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
109198#define sqlite3_profile                sqlite3_api->profile
109199#define sqlite3_progress_handler       sqlite3_api->progress_handler
109200#define sqlite3_realloc                sqlite3_api->realloc
109201#define sqlite3_reset                  sqlite3_api->reset
109202#define sqlite3_result_blob            sqlite3_api->result_blob
109203#define sqlite3_result_double          sqlite3_api->result_double
109204#define sqlite3_result_error           sqlite3_api->result_error
109205#define sqlite3_result_error16         sqlite3_api->result_error16
109206#define sqlite3_result_int             sqlite3_api->result_int
109207#define sqlite3_result_int64           sqlite3_api->result_int64
109208#define sqlite3_result_null            sqlite3_api->result_null
109209#define sqlite3_result_text            sqlite3_api->result_text
109210#define sqlite3_result_text16          sqlite3_api->result_text16
109211#define sqlite3_result_text16be        sqlite3_api->result_text16be
109212#define sqlite3_result_text16le        sqlite3_api->result_text16le
109213#define sqlite3_result_value           sqlite3_api->result_value
109214#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
109215#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
109216#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
109217#define sqlite3_snprintf               sqlite3_api->snprintf
109218#define sqlite3_step                   sqlite3_api->step
109219#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
109220#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
109221#define sqlite3_total_changes          sqlite3_api->total_changes
109222#define sqlite3_trace                  sqlite3_api->trace
109223#ifndef SQLITE_OMIT_DEPRECATED
109224#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
109225#endif
109226#define sqlite3_update_hook            sqlite3_api->update_hook
109227#define sqlite3_user_data              sqlite3_api->user_data
109228#define sqlite3_value_blob             sqlite3_api->value_blob
109229#define sqlite3_value_bytes            sqlite3_api->value_bytes
109230#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
109231#define sqlite3_value_double           sqlite3_api->value_double
109232#define sqlite3_value_int              sqlite3_api->value_int
109233#define sqlite3_value_int64            sqlite3_api->value_int64
109234#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
109235#define sqlite3_value_text             sqlite3_api->value_text
109236#define sqlite3_value_text16           sqlite3_api->value_text16
109237#define sqlite3_value_text16be         sqlite3_api->value_text16be
109238#define sqlite3_value_text16le         sqlite3_api->value_text16le
109239#define sqlite3_value_type             sqlite3_api->value_type
109240#define sqlite3_vmprintf               sqlite3_api->vmprintf
109241#define sqlite3_vsnprintf              sqlite3_api->vsnprintf
109242#define sqlite3_overload_function      sqlite3_api->overload_function
109243#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
109244#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
109245#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
109246#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
109247#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
109248#define sqlite3_blob_close             sqlite3_api->blob_close
109249#define sqlite3_blob_open              sqlite3_api->blob_open
109250#define sqlite3_blob_read              sqlite3_api->blob_read
109251#define sqlite3_blob_write             sqlite3_api->blob_write
109252#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
109253#define sqlite3_file_control           sqlite3_api->file_control
109254#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
109255#define sqlite3_memory_used            sqlite3_api->memory_used
109256#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
109257#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
109258#define sqlite3_mutex_free             sqlite3_api->mutex_free
109259#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
109260#define sqlite3_mutex_try              sqlite3_api->mutex_try
109261#define sqlite3_open_v2                sqlite3_api->open_v2
109262#define sqlite3_release_memory         sqlite3_api->release_memory
109263#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
109264#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
109265#define sqlite3_sleep                  sqlite3_api->sleep
109266#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
109267#define sqlite3_vfs_find               sqlite3_api->vfs_find
109268#define sqlite3_vfs_register           sqlite3_api->vfs_register
109269#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
109270#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
109271#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
109272#define sqlite3_result_error_code      sqlite3_api->result_error_code
109273#define sqlite3_test_control           sqlite3_api->test_control
109274#define sqlite3_randomness             sqlite3_api->randomness
109275#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
109276#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
109277#define sqlite3_limit                  sqlite3_api->limit
109278#define sqlite3_next_stmt              sqlite3_api->next_stmt
109279#define sqlite3_sql                    sqlite3_api->sql
109280#define sqlite3_status                 sqlite3_api->status
109281#define sqlite3_backup_finish          sqlite3_api->backup_finish
109282#define sqlite3_backup_init            sqlite3_api->backup_init
109283#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
109284#define sqlite3_backup_remaining       sqlite3_api->backup_remaining
109285#define sqlite3_backup_step            sqlite3_api->backup_step
109286#define sqlite3_compileoption_get      sqlite3_api->compileoption_get
109287#define sqlite3_compileoption_used     sqlite3_api->compileoption_used
109288#define sqlite3_create_function_v2     sqlite3_api->create_function_v2
109289#define sqlite3_db_config              sqlite3_api->db_config
109290#define sqlite3_db_mutex               sqlite3_api->db_mutex
109291#define sqlite3_db_status              sqlite3_api->db_status
109292#define sqlite3_extended_errcode       sqlite3_api->extended_errcode
109293#define sqlite3_log                    sqlite3_api->log
109294#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
109295#define sqlite3_sourceid               sqlite3_api->sourceid
109296#define sqlite3_stmt_status            sqlite3_api->stmt_status
109297#define sqlite3_strnicmp               sqlite3_api->strnicmp
109298#define sqlite3_unlock_notify          sqlite3_api->unlock_notify
109299#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
109300#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
109301#define sqlite3_wal_hook               sqlite3_api->wal_hook
109302#define sqlite3_blob_reopen            sqlite3_api->blob_reopen
109303#define sqlite3_vtab_config            sqlite3_api->vtab_config
109304#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
109305/* Version 3.7.16 and later */
109306#define sqlite3_close_v2               sqlite3_api->close_v2
109307#define sqlite3_db_filename            sqlite3_api->db_filename
109308#define sqlite3_db_readonly            sqlite3_api->db_readonly
109309#define sqlite3_db_release_memory      sqlite3_api->db_release_memory
109310#define sqlite3_errstr                 sqlite3_api->errstr
109311#define sqlite3_stmt_busy              sqlite3_api->stmt_busy
109312#define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
109313#define sqlite3_stricmp                sqlite3_api->stricmp
109314#define sqlite3_uri_boolean            sqlite3_api->uri_boolean
109315#define sqlite3_uri_int64              sqlite3_api->uri_int64
109316#define sqlite3_uri_parameter          sqlite3_api->uri_parameter
109317#define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
109318#define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
109319/* Version 3.8.7 and later */
109320#define sqlite3_auto_extension         sqlite3_api->auto_extension
109321#define sqlite3_bind_blob64            sqlite3_api->bind_blob64
109322#define sqlite3_bind_text64            sqlite3_api->bind_text64
109323#define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension
109324#define sqlite3_load_extension         sqlite3_api->load_extension
109325#define sqlite3_malloc64               sqlite3_api->malloc64
109326#define sqlite3_msize                  sqlite3_api->msize
109327#define sqlite3_realloc64              sqlite3_api->realloc64
109328#define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension
109329#define sqlite3_result_blob64          sqlite3_api->result_blob64
109330#define sqlite3_result_text64          sqlite3_api->result_text64
109331#define sqlite3_strglob                sqlite3_api->strglob
109332/* Version 3.8.11 and later */
109333#define sqlite3_value_dup              sqlite3_api->value_dup
109334#define sqlite3_value_free             sqlite3_api->value_free
109335#define sqlite3_result_zeroblob64      sqlite3_api->result_zeroblob64
109336#define sqlite3_bind_zeroblob64        sqlite3_api->bind_zeroblob64
109337/* Version 3.9.0 and later */
109338#define sqlite3_value_subtype          sqlite3_api->value_subtype
109339#define sqlite3_result_subtype         sqlite3_api->result_subtype
109340/* Version 3.10.0 and later */
109341#define sqlite3_status64               sqlite3_api->status64
109342#define sqlite3_strlike                sqlite3_api->strlike
109343#define sqlite3_db_cacheflush          sqlite3_api->db_cacheflush
109344/* Version 3.12.0 and later */
109345#define sqlite3_system_errno           sqlite3_api->system_errno
109346/* Version 3.14.0 and later */
109347#define sqlite3_trace_v2               sqlite3_api->trace_v2
109348#define sqlite3_expanded_sql           sqlite3_api->expanded_sql
109349#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
109350
109351#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
109352  /* This case when the file really is being compiled as a loadable
109353  ** extension */
109354# define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
109355# define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
109356# define SQLITE_EXTENSION_INIT3     \
109357    extern const sqlite3_api_routines *sqlite3_api;
109358#else
109359  /* This case when the file is being statically linked into the
109360  ** application */
109361# define SQLITE_EXTENSION_INIT1     /*no-op*/
109362# define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
109363# define SQLITE_EXTENSION_INIT3     /*no-op*/
109364#endif
109365
109366#endif /* SQLITE3EXT_H */
109367
109368/************** End of sqlite3ext.h ******************************************/
109369/************** Continuing where we left off in loadext.c ********************/
109370/* #include "sqliteInt.h" */
109371/* #include <string.h> */
109372
109373#ifndef SQLITE_OMIT_LOAD_EXTENSION
109374/*
109375** Some API routines are omitted when various features are
109376** excluded from a build of SQLite.  Substitute a NULL pointer
109377** for any missing APIs.
109378*/
109379#ifndef SQLITE_ENABLE_COLUMN_METADATA
109380# define sqlite3_column_database_name   0
109381# define sqlite3_column_database_name16 0
109382# define sqlite3_column_table_name      0
109383# define sqlite3_column_table_name16    0
109384# define sqlite3_column_origin_name     0
109385# define sqlite3_column_origin_name16   0
109386#endif
109387
109388#ifdef SQLITE_OMIT_AUTHORIZATION
109389# define sqlite3_set_authorizer         0
109390#endif
109391
109392#ifdef SQLITE_OMIT_UTF16
109393# define sqlite3_bind_text16            0
109394# define sqlite3_collation_needed16     0
109395# define sqlite3_column_decltype16      0
109396# define sqlite3_column_name16          0
109397# define sqlite3_column_text16          0
109398# define sqlite3_complete16             0
109399# define sqlite3_create_collation16     0
109400# define sqlite3_create_function16      0
109401# define sqlite3_errmsg16               0
109402# define sqlite3_open16                 0
109403# define sqlite3_prepare16              0
109404# define sqlite3_prepare16_v2           0
109405# define sqlite3_result_error16         0
109406# define sqlite3_result_text16          0
109407# define sqlite3_result_text16be        0
109408# define sqlite3_result_text16le        0
109409# define sqlite3_value_text16           0
109410# define sqlite3_value_text16be         0
109411# define sqlite3_value_text16le         0
109412# define sqlite3_column_database_name16 0
109413# define sqlite3_column_table_name16    0
109414# define sqlite3_column_origin_name16   0
109415#endif
109416
109417#ifdef SQLITE_OMIT_COMPLETE
109418# define sqlite3_complete 0
109419# define sqlite3_complete16 0
109420#endif
109421
109422#ifdef SQLITE_OMIT_DECLTYPE
109423# define sqlite3_column_decltype16      0
109424# define sqlite3_column_decltype        0
109425#endif
109426
109427#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
109428# define sqlite3_progress_handler 0
109429#endif
109430
109431#ifdef SQLITE_OMIT_VIRTUALTABLE
109432# define sqlite3_create_module 0
109433# define sqlite3_create_module_v2 0
109434# define sqlite3_declare_vtab 0
109435# define sqlite3_vtab_config 0
109436# define sqlite3_vtab_on_conflict 0
109437#endif
109438
109439#ifdef SQLITE_OMIT_SHARED_CACHE
109440# define sqlite3_enable_shared_cache 0
109441#endif
109442
109443#if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
109444# define sqlite3_profile       0
109445# define sqlite3_trace         0
109446#endif
109447
109448#ifdef SQLITE_OMIT_GET_TABLE
109449# define sqlite3_free_table    0
109450# define sqlite3_get_table     0
109451#endif
109452
109453#ifdef SQLITE_OMIT_INCRBLOB
109454#define sqlite3_bind_zeroblob  0
109455#define sqlite3_blob_bytes     0
109456#define sqlite3_blob_close     0
109457#define sqlite3_blob_open      0
109458#define sqlite3_blob_read      0
109459#define sqlite3_blob_write     0
109460#define sqlite3_blob_reopen    0
109461#endif
109462
109463#if defined(SQLITE_OMIT_TRACE)
109464# define sqlite3_trace_v2      0
109465#endif
109466
109467/*
109468** The following structure contains pointers to all SQLite API routines.
109469** A pointer to this structure is passed into extensions when they are
109470** loaded so that the extension can make calls back into the SQLite
109471** library.
109472**
109473** When adding new APIs, add them to the bottom of this structure
109474** in order to preserve backwards compatibility.
109475**
109476** Extensions that use newer APIs should first call the
109477** sqlite3_libversion_number() to make sure that the API they
109478** intend to use is supported by the library.  Extensions should
109479** also check to make sure that the pointer to the function is
109480** not NULL before calling it.
109481*/
109482static const sqlite3_api_routines sqlite3Apis = {
109483  sqlite3_aggregate_context,
109484#ifndef SQLITE_OMIT_DEPRECATED
109485  sqlite3_aggregate_count,
109486#else
109487  0,
109488#endif
109489  sqlite3_bind_blob,
109490  sqlite3_bind_double,
109491  sqlite3_bind_int,
109492  sqlite3_bind_int64,
109493  sqlite3_bind_null,
109494  sqlite3_bind_parameter_count,
109495  sqlite3_bind_parameter_index,
109496  sqlite3_bind_parameter_name,
109497  sqlite3_bind_text,
109498  sqlite3_bind_text16,
109499  sqlite3_bind_value,
109500  sqlite3_busy_handler,
109501  sqlite3_busy_timeout,
109502  sqlite3_changes,
109503  sqlite3_close,
109504  sqlite3_collation_needed,
109505  sqlite3_collation_needed16,
109506  sqlite3_column_blob,
109507  sqlite3_column_bytes,
109508  sqlite3_column_bytes16,
109509  sqlite3_column_count,
109510  sqlite3_column_database_name,
109511  sqlite3_column_database_name16,
109512  sqlite3_column_decltype,
109513  sqlite3_column_decltype16,
109514  sqlite3_column_double,
109515  sqlite3_column_int,
109516  sqlite3_column_int64,
109517  sqlite3_column_name,
109518  sqlite3_column_name16,
109519  sqlite3_column_origin_name,
109520  sqlite3_column_origin_name16,
109521  sqlite3_column_table_name,
109522  sqlite3_column_table_name16,
109523  sqlite3_column_text,
109524  sqlite3_column_text16,
109525  sqlite3_column_type,
109526  sqlite3_column_value,
109527  sqlite3_commit_hook,
109528  sqlite3_complete,
109529  sqlite3_complete16,
109530  sqlite3_create_collation,
109531  sqlite3_create_collation16,
109532  sqlite3_create_function,
109533  sqlite3_create_function16,
109534  sqlite3_create_module,
109535  sqlite3_data_count,
109536  sqlite3_db_handle,
109537  sqlite3_declare_vtab,
109538  sqlite3_enable_shared_cache,
109539  sqlite3_errcode,
109540  sqlite3_errmsg,
109541  sqlite3_errmsg16,
109542  sqlite3_exec,
109543#ifndef SQLITE_OMIT_DEPRECATED
109544  sqlite3_expired,
109545#else
109546  0,
109547#endif
109548  sqlite3_finalize,
109549  sqlite3_free,
109550  sqlite3_free_table,
109551  sqlite3_get_autocommit,
109552  sqlite3_get_auxdata,
109553  sqlite3_get_table,
109554  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
109555  sqlite3_interrupt,
109556  sqlite3_last_insert_rowid,
109557  sqlite3_libversion,
109558  sqlite3_libversion_number,
109559  sqlite3_malloc,
109560  sqlite3_mprintf,
109561  sqlite3_open,
109562  sqlite3_open16,
109563  sqlite3_prepare,
109564  sqlite3_prepare16,
109565  sqlite3_profile,
109566  sqlite3_progress_handler,
109567  sqlite3_realloc,
109568  sqlite3_reset,
109569  sqlite3_result_blob,
109570  sqlite3_result_double,
109571  sqlite3_result_error,
109572  sqlite3_result_error16,
109573  sqlite3_result_int,
109574  sqlite3_result_int64,
109575  sqlite3_result_null,
109576  sqlite3_result_text,
109577  sqlite3_result_text16,
109578  sqlite3_result_text16be,
109579  sqlite3_result_text16le,
109580  sqlite3_result_value,
109581  sqlite3_rollback_hook,
109582  sqlite3_set_authorizer,
109583  sqlite3_set_auxdata,
109584  sqlite3_snprintf,
109585  sqlite3_step,
109586  sqlite3_table_column_metadata,
109587#ifndef SQLITE_OMIT_DEPRECATED
109588  sqlite3_thread_cleanup,
109589#else
109590  0,
109591#endif
109592  sqlite3_total_changes,
109593  sqlite3_trace,
109594#ifndef SQLITE_OMIT_DEPRECATED
109595  sqlite3_transfer_bindings,
109596#else
109597  0,
109598#endif
109599  sqlite3_update_hook,
109600  sqlite3_user_data,
109601  sqlite3_value_blob,
109602  sqlite3_value_bytes,
109603  sqlite3_value_bytes16,
109604  sqlite3_value_double,
109605  sqlite3_value_int,
109606  sqlite3_value_int64,
109607  sqlite3_value_numeric_type,
109608  sqlite3_value_text,
109609  sqlite3_value_text16,
109610  sqlite3_value_text16be,
109611  sqlite3_value_text16le,
109612  sqlite3_value_type,
109613  sqlite3_vmprintf,
109614  /*
109615  ** The original API set ends here.  All extensions can call any
109616  ** of the APIs above provided that the pointer is not NULL.  But
109617  ** before calling APIs that follow, extension should check the
109618  ** sqlite3_libversion_number() to make sure they are dealing with
109619  ** a library that is new enough to support that API.
109620  *************************************************************************
109621  */
109622  sqlite3_overload_function,
109623
109624  /*
109625  ** Added after 3.3.13
109626  */
109627  sqlite3_prepare_v2,
109628  sqlite3_prepare16_v2,
109629  sqlite3_clear_bindings,
109630
109631  /*
109632  ** Added for 3.4.1
109633  */
109634  sqlite3_create_module_v2,
109635
109636  /*
109637  ** Added for 3.5.0
109638  */
109639  sqlite3_bind_zeroblob,
109640  sqlite3_blob_bytes,
109641  sqlite3_blob_close,
109642  sqlite3_blob_open,
109643  sqlite3_blob_read,
109644  sqlite3_blob_write,
109645  sqlite3_create_collation_v2,
109646  sqlite3_file_control,
109647  sqlite3_memory_highwater,
109648  sqlite3_memory_used,
109649#ifdef SQLITE_MUTEX_OMIT
109650  0,
109651  0,
109652  0,
109653  0,
109654  0,
109655#else
109656  sqlite3_mutex_alloc,
109657  sqlite3_mutex_enter,
109658  sqlite3_mutex_free,
109659  sqlite3_mutex_leave,
109660  sqlite3_mutex_try,
109661#endif
109662  sqlite3_open_v2,
109663  sqlite3_release_memory,
109664  sqlite3_result_error_nomem,
109665  sqlite3_result_error_toobig,
109666  sqlite3_sleep,
109667  sqlite3_soft_heap_limit,
109668  sqlite3_vfs_find,
109669  sqlite3_vfs_register,
109670  sqlite3_vfs_unregister,
109671
109672  /*
109673  ** Added for 3.5.8
109674  */
109675  sqlite3_threadsafe,
109676  sqlite3_result_zeroblob,
109677  sqlite3_result_error_code,
109678  sqlite3_test_control,
109679  sqlite3_randomness,
109680  sqlite3_context_db_handle,
109681
109682  /*
109683  ** Added for 3.6.0
109684  */
109685  sqlite3_extended_result_codes,
109686  sqlite3_limit,
109687  sqlite3_next_stmt,
109688  sqlite3_sql,
109689  sqlite3_status,
109690
109691  /*
109692  ** Added for 3.7.4
109693  */
109694  sqlite3_backup_finish,
109695  sqlite3_backup_init,
109696  sqlite3_backup_pagecount,
109697  sqlite3_backup_remaining,
109698  sqlite3_backup_step,
109699#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
109700  sqlite3_compileoption_get,
109701  sqlite3_compileoption_used,
109702#else
109703  0,
109704  0,
109705#endif
109706  sqlite3_create_function_v2,
109707  sqlite3_db_config,
109708  sqlite3_db_mutex,
109709  sqlite3_db_status,
109710  sqlite3_extended_errcode,
109711  sqlite3_log,
109712  sqlite3_soft_heap_limit64,
109713  sqlite3_sourceid,
109714  sqlite3_stmt_status,
109715  sqlite3_strnicmp,
109716#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
109717  sqlite3_unlock_notify,
109718#else
109719  0,
109720#endif
109721#ifndef SQLITE_OMIT_WAL
109722  sqlite3_wal_autocheckpoint,
109723  sqlite3_wal_checkpoint,
109724  sqlite3_wal_hook,
109725#else
109726  0,
109727  0,
109728  0,
109729#endif
109730  sqlite3_blob_reopen,
109731  sqlite3_vtab_config,
109732  sqlite3_vtab_on_conflict,
109733  sqlite3_close_v2,
109734  sqlite3_db_filename,
109735  sqlite3_db_readonly,
109736  sqlite3_db_release_memory,
109737  sqlite3_errstr,
109738  sqlite3_stmt_busy,
109739  sqlite3_stmt_readonly,
109740  sqlite3_stricmp,
109741  sqlite3_uri_boolean,
109742  sqlite3_uri_int64,
109743  sqlite3_uri_parameter,
109744  sqlite3_vsnprintf,
109745  sqlite3_wal_checkpoint_v2,
109746  /* Version 3.8.7 and later */
109747  sqlite3_auto_extension,
109748  sqlite3_bind_blob64,
109749  sqlite3_bind_text64,
109750  sqlite3_cancel_auto_extension,
109751  sqlite3_load_extension,
109752  sqlite3_malloc64,
109753  sqlite3_msize,
109754  sqlite3_realloc64,
109755  sqlite3_reset_auto_extension,
109756  sqlite3_result_blob64,
109757  sqlite3_result_text64,
109758  sqlite3_strglob,
109759  /* Version 3.8.11 and later */
109760  (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
109761  sqlite3_value_free,
109762  sqlite3_result_zeroblob64,
109763  sqlite3_bind_zeroblob64,
109764  /* Version 3.9.0 and later */
109765  sqlite3_value_subtype,
109766  sqlite3_result_subtype,
109767  /* Version 3.10.0 and later */
109768  sqlite3_status64,
109769  sqlite3_strlike,
109770  sqlite3_db_cacheflush,
109771  /* Version 3.12.0 and later */
109772  sqlite3_system_errno,
109773  /* Version 3.14.0 and later */
109774  sqlite3_trace_v2,
109775  sqlite3_expanded_sql
109776};
109777
109778/*
109779** Attempt to load an SQLite extension library contained in the file
109780** zFile.  The entry point is zProc.  zProc may be 0 in which case a
109781** default entry point name (sqlite3_extension_init) is used.  Use
109782** of the default name is recommended.
109783**
109784** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
109785**
109786** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
109787** error message text.  The calling function should free this memory
109788** by calling sqlite3DbFree(db, ).
109789*/
109790static int sqlite3LoadExtension(
109791  sqlite3 *db,          /* Load the extension into this database connection */
109792  const char *zFile,    /* Name of the shared library containing extension */
109793  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
109794  char **pzErrMsg       /* Put error message here if not 0 */
109795){
109796  sqlite3_vfs *pVfs = db->pVfs;
109797  void *handle;
109798  sqlite3_loadext_entry xInit;
109799  char *zErrmsg = 0;
109800  const char *zEntry;
109801  char *zAltEntry = 0;
109802  void **aHandle;
109803  u64 nMsg = 300 + sqlite3Strlen30(zFile);
109804  int ii;
109805  int rc;
109806
109807  /* Shared library endings to try if zFile cannot be loaded as written */
109808  static const char *azEndings[] = {
109809#if SQLITE_OS_WIN
109810     "dll"
109811#elif defined(__APPLE__)
109812     "dylib"
109813#else
109814     "so"
109815#endif
109816  };
109817
109818
109819  if( pzErrMsg ) *pzErrMsg = 0;
109820
109821  /* Ticket #1863.  To avoid a creating security problems for older
109822  ** applications that relink against newer versions of SQLite, the
109823  ** ability to run load_extension is turned off by default.  One
109824  ** must call either sqlite3_enable_load_extension(db) or
109825  ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
109826  ** to turn on extension loading.
109827  */
109828  if( (db->flags & SQLITE_LoadExtension)==0 ){
109829    if( pzErrMsg ){
109830      *pzErrMsg = sqlite3_mprintf("not authorized");
109831    }
109832    return SQLITE_ERROR;
109833  }
109834
109835  zEntry = zProc ? zProc : "sqlite3_extension_init";
109836
109837  handle = sqlite3OsDlOpen(pVfs, zFile);
109838#if SQLITE_OS_UNIX || SQLITE_OS_WIN
109839  for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
109840    char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
109841    if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
109842    handle = sqlite3OsDlOpen(pVfs, zAltFile);
109843    sqlite3_free(zAltFile);
109844  }
109845#endif
109846  if( handle==0 ){
109847    if( pzErrMsg ){
109848      *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
109849      if( zErrmsg ){
109850        sqlite3_snprintf(nMsg, zErrmsg,
109851            "unable to open shared library [%s]", zFile);
109852        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
109853      }
109854    }
109855    return SQLITE_ERROR;
109856  }
109857  xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
109858
109859  /* If no entry point was specified and the default legacy
109860  ** entry point name "sqlite3_extension_init" was not found, then
109861  ** construct an entry point name "sqlite3_X_init" where the X is
109862  ** replaced by the lowercase value of every ASCII alphabetic
109863  ** character in the filename after the last "/" upto the first ".",
109864  ** and eliding the first three characters if they are "lib".
109865  ** Examples:
109866  **
109867  **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
109868  **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
109869  */
109870  if( xInit==0 && zProc==0 ){
109871    int iFile, iEntry, c;
109872    int ncFile = sqlite3Strlen30(zFile);
109873    zAltEntry = sqlite3_malloc64(ncFile+30);
109874    if( zAltEntry==0 ){
109875      sqlite3OsDlClose(pVfs, handle);
109876      return SQLITE_NOMEM_BKPT;
109877    }
109878    memcpy(zAltEntry, "sqlite3_", 8);
109879    for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
109880    iFile++;
109881    if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
109882    for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
109883      if( sqlite3Isalpha(c) ){
109884        zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
109885      }
109886    }
109887    memcpy(zAltEntry+iEntry, "_init", 6);
109888    zEntry = zAltEntry;
109889    xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
109890  }
109891  if( xInit==0 ){
109892    if( pzErrMsg ){
109893      nMsg += sqlite3Strlen30(zEntry);
109894      *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
109895      if( zErrmsg ){
109896        sqlite3_snprintf(nMsg, zErrmsg,
109897            "no entry point [%s] in shared library [%s]", zEntry, zFile);
109898        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
109899      }
109900    }
109901    sqlite3OsDlClose(pVfs, handle);
109902    sqlite3_free(zAltEntry);
109903    return SQLITE_ERROR;
109904  }
109905  sqlite3_free(zAltEntry);
109906  rc = xInit(db, &zErrmsg, &sqlite3Apis);
109907  if( rc ){
109908    if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
109909    if( pzErrMsg ){
109910      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
109911    }
109912    sqlite3_free(zErrmsg);
109913    sqlite3OsDlClose(pVfs, handle);
109914    return SQLITE_ERROR;
109915  }
109916
109917  /* Append the new shared library handle to the db->aExtension array. */
109918  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
109919  if( aHandle==0 ){
109920    return SQLITE_NOMEM_BKPT;
109921  }
109922  if( db->nExtension>0 ){
109923    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
109924  }
109925  sqlite3DbFree(db, db->aExtension);
109926  db->aExtension = aHandle;
109927
109928  db->aExtension[db->nExtension++] = handle;
109929  return SQLITE_OK;
109930}
109931SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
109932  sqlite3 *db,          /* Load the extension into this database connection */
109933  const char *zFile,    /* Name of the shared library containing extension */
109934  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
109935  char **pzErrMsg       /* Put error message here if not 0 */
109936){
109937  int rc;
109938  sqlite3_mutex_enter(db->mutex);
109939  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
109940  rc = sqlite3ApiExit(db, rc);
109941  sqlite3_mutex_leave(db->mutex);
109942  return rc;
109943}
109944
109945/*
109946** Call this routine when the database connection is closing in order
109947** to clean up loaded extensions
109948*/
109949SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
109950  int i;
109951  assert( sqlite3_mutex_held(db->mutex) );
109952  for(i=0; i<db->nExtension; i++){
109953    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
109954  }
109955  sqlite3DbFree(db, db->aExtension);
109956}
109957
109958/*
109959** Enable or disable extension loading.  Extension loading is disabled by
109960** default so as not to open security holes in older applications.
109961*/
109962SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff){
109963  sqlite3_mutex_enter(db->mutex);
109964  if( onoff ){
109965    db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
109966  }else{
109967    db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
109968  }
109969  sqlite3_mutex_leave(db->mutex);
109970  return SQLITE_OK;
109971}
109972
109973#endif /* SQLITE_OMIT_LOAD_EXTENSION */
109974
109975/*
109976** The auto-extension code added regardless of whether or not extension
109977** loading is supported.  We need a dummy sqlite3Apis pointer for that
109978** code if regular extension loading is not available.  This is that
109979** dummy pointer.
109980*/
109981#ifdef SQLITE_OMIT_LOAD_EXTENSION
109982static const sqlite3_api_routines sqlite3Apis = { 0 };
109983#endif
109984
109985
109986/*
109987** The following object holds the list of automatically loaded
109988** extensions.
109989**
109990** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
109991** mutex must be held while accessing this list.
109992*/
109993typedef struct sqlite3AutoExtList sqlite3AutoExtList;
109994static SQLITE_WSD struct sqlite3AutoExtList {
109995  u32 nExt;              /* Number of entries in aExt[] */
109996  void (**aExt)(void);   /* Pointers to the extension init functions */
109997} sqlite3Autoext = { 0, 0 };
109998
109999/* The "wsdAutoext" macro will resolve to the autoextension
110000** state vector.  If writable static data is unsupported on the target,
110001** we have to locate the state vector at run-time.  In the more common
110002** case where writable static data is supported, wsdStat can refer directly
110003** to the "sqlite3Autoext" state vector declared above.
110004*/
110005#ifdef SQLITE_OMIT_WSD
110006# define wsdAutoextInit \
110007  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
110008# define wsdAutoext x[0]
110009#else
110010# define wsdAutoextInit
110011# define wsdAutoext sqlite3Autoext
110012#endif
110013
110014
110015/*
110016** Register a statically linked extension that is automatically
110017** loaded by every new database connection.
110018*/
110019SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(
110020  void (*xInit)(void)
110021){
110022  int rc = SQLITE_OK;
110023#ifndef SQLITE_OMIT_AUTOINIT
110024  rc = sqlite3_initialize();
110025  if( rc ){
110026    return rc;
110027  }else
110028#endif
110029  {
110030    u32 i;
110031#if SQLITE_THREADSAFE
110032    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
110033#endif
110034    wsdAutoextInit;
110035    sqlite3_mutex_enter(mutex);
110036    for(i=0; i<wsdAutoext.nExt; i++){
110037      if( wsdAutoext.aExt[i]==xInit ) break;
110038    }
110039    if( i==wsdAutoext.nExt ){
110040      u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
110041      void (**aNew)(void);
110042      aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
110043      if( aNew==0 ){
110044        rc = SQLITE_NOMEM_BKPT;
110045      }else{
110046        wsdAutoext.aExt = aNew;
110047        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
110048        wsdAutoext.nExt++;
110049      }
110050    }
110051    sqlite3_mutex_leave(mutex);
110052    assert( (rc&0xff)==rc );
110053    return rc;
110054  }
110055}
110056
110057/*
110058** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
110059** set of routines that is invoked for each new database connection, if it
110060** is currently on the list.  If xInit is not on the list, then this
110061** routine is a no-op.
110062**
110063** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
110064** was not on the list.
110065*/
110066SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(
110067  void (*xInit)(void)
110068){
110069#if SQLITE_THREADSAFE
110070  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
110071#endif
110072  int i;
110073  int n = 0;
110074  wsdAutoextInit;
110075  sqlite3_mutex_enter(mutex);
110076  for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
110077    if( wsdAutoext.aExt[i]==xInit ){
110078      wsdAutoext.nExt--;
110079      wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
110080      n++;
110081      break;
110082    }
110083  }
110084  sqlite3_mutex_leave(mutex);
110085  return n;
110086}
110087
110088/*
110089** Reset the automatic extension loading mechanism.
110090*/
110091SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void){
110092#ifndef SQLITE_OMIT_AUTOINIT
110093  if( sqlite3_initialize()==SQLITE_OK )
110094#endif
110095  {
110096#if SQLITE_THREADSAFE
110097    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
110098#endif
110099    wsdAutoextInit;
110100    sqlite3_mutex_enter(mutex);
110101    sqlite3_free(wsdAutoext.aExt);
110102    wsdAutoext.aExt = 0;
110103    wsdAutoext.nExt = 0;
110104    sqlite3_mutex_leave(mutex);
110105  }
110106}
110107
110108/*
110109** Load all automatic extensions.
110110**
110111** If anything goes wrong, set an error in the database connection.
110112*/
110113SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
110114  u32 i;
110115  int go = 1;
110116  int rc;
110117  sqlite3_loadext_entry xInit;
110118
110119  wsdAutoextInit;
110120  if( wsdAutoext.nExt==0 ){
110121    /* Common case: early out without every having to acquire a mutex */
110122    return;
110123  }
110124  for(i=0; go; i++){
110125    char *zErrmsg;
110126#if SQLITE_THREADSAFE
110127    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
110128#endif
110129    sqlite3_mutex_enter(mutex);
110130    if( i>=wsdAutoext.nExt ){
110131      xInit = 0;
110132      go = 0;
110133    }else{
110134      xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
110135    }
110136    sqlite3_mutex_leave(mutex);
110137    zErrmsg = 0;
110138    if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
110139      sqlite3ErrorWithMsg(db, rc,
110140            "automatic extension loading failed: %s", zErrmsg);
110141      go = 0;
110142    }
110143    sqlite3_free(zErrmsg);
110144  }
110145}
110146
110147/************** End of loadext.c *********************************************/
110148/************** Begin file pragma.c ******************************************/
110149/*
110150** 2003 April 6
110151**
110152** The author disclaims copyright to this source code.  In place of
110153** a legal notice, here is a blessing:
110154**
110155**    May you do good and not evil.
110156**    May you find forgiveness for yourself and forgive others.
110157**    May you share freely, never taking more than you give.
110158**
110159*************************************************************************
110160** This file contains code used to implement the PRAGMA command.
110161*/
110162/* #include "sqliteInt.h" */
110163
110164#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
110165#  if defined(__APPLE__)
110166#    define SQLITE_ENABLE_LOCKING_STYLE 1
110167#  else
110168#    define SQLITE_ENABLE_LOCKING_STYLE 0
110169#  endif
110170#endif
110171
110172/***************************************************************************
110173** The "pragma.h" include file is an automatically generated file that
110174** that includes the PragType_XXXX macro definitions and the aPragmaName[]
110175** object.  This ensures that the aPragmaName[] table is arranged in
110176** lexicographical order to facility a binary search of the pragma name.
110177** Do not edit pragma.h directly.  Edit and rerun the script in at
110178** ../tool/mkpragmatab.tcl. */
110179/************** Include pragma.h in the middle of pragma.c *******************/
110180/************** Begin file pragma.h ******************************************/
110181/* DO NOT EDIT!
110182** This file is automatically generated by the script at
110183** ../tool/mkpragmatab.tcl.  To update the set of pragmas, edit
110184** that script and rerun it.
110185*/
110186#define PragTyp_HEADER_VALUE                   0
110187#define PragTyp_AUTO_VACUUM                    1
110188#define PragTyp_FLAG                           2
110189#define PragTyp_BUSY_TIMEOUT                   3
110190#define PragTyp_CACHE_SIZE                     4
110191#define PragTyp_CACHE_SPILL                    5
110192#define PragTyp_CASE_SENSITIVE_LIKE            6
110193#define PragTyp_COLLATION_LIST                 7
110194#define PragTyp_COMPILE_OPTIONS                8
110195#define PragTyp_DATA_STORE_DIRECTORY           9
110196#define PragTyp_DATABASE_LIST                 10
110197#define PragTyp_DEFAULT_CACHE_SIZE            11
110198#define PragTyp_ENCODING                      12
110199#define PragTyp_FOREIGN_KEY_CHECK             13
110200#define PragTyp_FOREIGN_KEY_LIST              14
110201#define PragTyp_INCREMENTAL_VACUUM            15
110202#define PragTyp_INDEX_INFO                    16
110203#define PragTyp_INDEX_LIST                    17
110204#define PragTyp_INTEGRITY_CHECK               18
110205#define PragTyp_JOURNAL_MODE                  19
110206#define PragTyp_JOURNAL_SIZE_LIMIT            20
110207#define PragTyp_LOCK_PROXY_FILE               21
110208#define PragTyp_LOCKING_MODE                  22
110209#define PragTyp_PAGE_COUNT                    23
110210#define PragTyp_MMAP_SIZE                     24
110211#define PragTyp_PAGE_SIZE                     25
110212#define PragTyp_SECURE_DELETE                 26
110213#define PragTyp_SHRINK_MEMORY                 27
110214#define PragTyp_SOFT_HEAP_LIMIT               28
110215#define PragTyp_STATS                         29
110216#define PragTyp_SYNCHRONOUS                   30
110217#define PragTyp_TABLE_INFO                    31
110218#define PragTyp_TEMP_STORE                    32
110219#define PragTyp_TEMP_STORE_DIRECTORY          33
110220#define PragTyp_THREADS                       34
110221#define PragTyp_WAL_AUTOCHECKPOINT            35
110222#define PragTyp_WAL_CHECKPOINT                36
110223#define PragTyp_ACTIVATE_EXTENSIONS           37
110224#define PragTyp_HEXKEY                        38
110225#define PragTyp_KEY                           39
110226#define PragTyp_REKEY                         40
110227#define PragTyp_LOCK_STATUS                   41
110228#define PragTyp_PARSER_TRACE                  42
110229#define PragFlag_NeedSchema           0x01
110230#define PragFlag_ReadOnly             0x02
110231static const struct sPragmaNames {
110232  const char *const zName;  /* Name of pragma */
110233  u8 ePragTyp;              /* PragTyp_XXX value */
110234  u8 mPragFlag;             /* Zero or more PragFlag_XXX values */
110235  u32 iArg;                 /* Extra argument */
110236} aPragmaNames[] = {
110237#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
110238  { /* zName:     */ "activate_extensions",
110239    /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
110240    /* ePragFlag: */ 0,
110241    /* iArg:      */ 0 },
110242#endif
110243#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
110244  { /* zName:     */ "application_id",
110245    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
110246    /* ePragFlag: */ 0,
110247    /* iArg:      */ BTREE_APPLICATION_ID },
110248#endif
110249#if !defined(SQLITE_OMIT_AUTOVACUUM)
110250  { /* zName:     */ "auto_vacuum",
110251    /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
110252    /* ePragFlag: */ PragFlag_NeedSchema,
110253    /* iArg:      */ 0 },
110254#endif
110255#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110256#if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
110257  { /* zName:     */ "automatic_index",
110258    /* ePragTyp:  */ PragTyp_FLAG,
110259    /* ePragFlag: */ 0,
110260    /* iArg:      */ SQLITE_AutoIndex },
110261#endif
110262#endif
110263  { /* zName:     */ "busy_timeout",
110264    /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
110265    /* ePragFlag: */ 0,
110266    /* iArg:      */ 0 },
110267#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110268  { /* zName:     */ "cache_size",
110269    /* ePragTyp:  */ PragTyp_CACHE_SIZE,
110270    /* ePragFlag: */ PragFlag_NeedSchema,
110271    /* iArg:      */ 0 },
110272#endif
110273#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110274  { /* zName:     */ "cache_spill",
110275    /* ePragTyp:  */ PragTyp_CACHE_SPILL,
110276    /* ePragFlag: */ 0,
110277    /* iArg:      */ 0 },
110278#endif
110279  { /* zName:     */ "case_sensitive_like",
110280    /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
110281    /* ePragFlag: */ 0,
110282    /* iArg:      */ 0 },
110283  { /* zName:     */ "cell_size_check",
110284    /* ePragTyp:  */ PragTyp_FLAG,
110285    /* ePragFlag: */ 0,
110286    /* iArg:      */ SQLITE_CellSizeCk },
110287#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110288  { /* zName:     */ "checkpoint_fullfsync",
110289    /* ePragTyp:  */ PragTyp_FLAG,
110290    /* ePragFlag: */ 0,
110291    /* iArg:      */ SQLITE_CkptFullFSync },
110292#endif
110293#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
110294  { /* zName:     */ "collation_list",
110295    /* ePragTyp:  */ PragTyp_COLLATION_LIST,
110296    /* ePragFlag: */ 0,
110297    /* iArg:      */ 0 },
110298#endif
110299#if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
110300  { /* zName:     */ "compile_options",
110301    /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
110302    /* ePragFlag: */ 0,
110303    /* iArg:      */ 0 },
110304#endif
110305#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110306  { /* zName:     */ "count_changes",
110307    /* ePragTyp:  */ PragTyp_FLAG,
110308    /* ePragFlag: */ 0,
110309    /* iArg:      */ SQLITE_CountRows },
110310#endif
110311#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
110312  { /* zName:     */ "data_store_directory",
110313    /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
110314    /* ePragFlag: */ 0,
110315    /* iArg:      */ 0 },
110316#endif
110317#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
110318  { /* zName:     */ "data_version",
110319    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
110320    /* ePragFlag: */ PragFlag_ReadOnly,
110321    /* iArg:      */ BTREE_DATA_VERSION },
110322#endif
110323#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
110324  { /* zName:     */ "database_list",
110325    /* ePragTyp:  */ PragTyp_DATABASE_LIST,
110326    /* ePragFlag: */ PragFlag_NeedSchema,
110327    /* iArg:      */ 0 },
110328#endif
110329#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
110330  { /* zName:     */ "default_cache_size",
110331    /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
110332    /* ePragFlag: */ PragFlag_NeedSchema,
110333    /* iArg:      */ 0 },
110334#endif
110335#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110336#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
110337  { /* zName:     */ "defer_foreign_keys",
110338    /* ePragTyp:  */ PragTyp_FLAG,
110339    /* ePragFlag: */ 0,
110340    /* iArg:      */ SQLITE_DeferFKs },
110341#endif
110342#endif
110343#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110344  { /* zName:     */ "empty_result_callbacks",
110345    /* ePragTyp:  */ PragTyp_FLAG,
110346    /* ePragFlag: */ 0,
110347    /* iArg:      */ SQLITE_NullCallback },
110348#endif
110349#if !defined(SQLITE_OMIT_UTF16)
110350  { /* zName:     */ "encoding",
110351    /* ePragTyp:  */ PragTyp_ENCODING,
110352    /* ePragFlag: */ 0,
110353    /* iArg:      */ 0 },
110354#endif
110355#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
110356  { /* zName:     */ "foreign_key_check",
110357    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
110358    /* ePragFlag: */ PragFlag_NeedSchema,
110359    /* iArg:      */ 0 },
110360#endif
110361#if !defined(SQLITE_OMIT_FOREIGN_KEY)
110362  { /* zName:     */ "foreign_key_list",
110363    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
110364    /* ePragFlag: */ PragFlag_NeedSchema,
110365    /* iArg:      */ 0 },
110366#endif
110367#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110368#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
110369  { /* zName:     */ "foreign_keys",
110370    /* ePragTyp:  */ PragTyp_FLAG,
110371    /* ePragFlag: */ 0,
110372    /* iArg:      */ SQLITE_ForeignKeys },
110373#endif
110374#endif
110375#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
110376  { /* zName:     */ "freelist_count",
110377    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
110378    /* ePragFlag: */ PragFlag_ReadOnly,
110379    /* iArg:      */ BTREE_FREE_PAGE_COUNT },
110380#endif
110381#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110382  { /* zName:     */ "full_column_names",
110383    /* ePragTyp:  */ PragTyp_FLAG,
110384    /* ePragFlag: */ 0,
110385    /* iArg:      */ SQLITE_FullColNames },
110386  { /* zName:     */ "fullfsync",
110387    /* ePragTyp:  */ PragTyp_FLAG,
110388    /* ePragFlag: */ 0,
110389    /* iArg:      */ SQLITE_FullFSync },
110390#endif
110391#if defined(SQLITE_HAS_CODEC)
110392  { /* zName:     */ "hexkey",
110393    /* ePragTyp:  */ PragTyp_HEXKEY,
110394    /* ePragFlag: */ 0,
110395    /* iArg:      */ 0 },
110396  { /* zName:     */ "hexrekey",
110397    /* ePragTyp:  */ PragTyp_HEXKEY,
110398    /* ePragFlag: */ 0,
110399    /* iArg:      */ 0 },
110400#endif
110401#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110402#if !defined(SQLITE_OMIT_CHECK)
110403  { /* zName:     */ "ignore_check_constraints",
110404    /* ePragTyp:  */ PragTyp_FLAG,
110405    /* ePragFlag: */ 0,
110406    /* iArg:      */ SQLITE_IgnoreChecks },
110407#endif
110408#endif
110409#if !defined(SQLITE_OMIT_AUTOVACUUM)
110410  { /* zName:     */ "incremental_vacuum",
110411    /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
110412    /* ePragFlag: */ PragFlag_NeedSchema,
110413    /* iArg:      */ 0 },
110414#endif
110415#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
110416  { /* zName:     */ "index_info",
110417    /* ePragTyp:  */ PragTyp_INDEX_INFO,
110418    /* ePragFlag: */ PragFlag_NeedSchema,
110419    /* iArg:      */ 0 },
110420  { /* zName:     */ "index_list",
110421    /* ePragTyp:  */ PragTyp_INDEX_LIST,
110422    /* ePragFlag: */ PragFlag_NeedSchema,
110423    /* iArg:      */ 0 },
110424  { /* zName:     */ "index_xinfo",
110425    /* ePragTyp:  */ PragTyp_INDEX_INFO,
110426    /* ePragFlag: */ PragFlag_NeedSchema,
110427    /* iArg:      */ 1 },
110428#endif
110429#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
110430  { /* zName:     */ "integrity_check",
110431    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
110432    /* ePragFlag: */ PragFlag_NeedSchema,
110433    /* iArg:      */ 0 },
110434#endif
110435#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110436  { /* zName:     */ "journal_mode",
110437    /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
110438    /* ePragFlag: */ PragFlag_NeedSchema,
110439    /* iArg:      */ 0 },
110440  { /* zName:     */ "journal_size_limit",
110441    /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
110442    /* ePragFlag: */ 0,
110443    /* iArg:      */ 0 },
110444#endif
110445#if defined(SQLITE_HAS_CODEC)
110446  { /* zName:     */ "key",
110447    /* ePragTyp:  */ PragTyp_KEY,
110448    /* ePragFlag: */ 0,
110449    /* iArg:      */ 0 },
110450#endif
110451#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110452  { /* zName:     */ "legacy_file_format",
110453    /* ePragTyp:  */ PragTyp_FLAG,
110454    /* ePragFlag: */ 0,
110455    /* iArg:      */ SQLITE_LegacyFileFmt },
110456#endif
110457#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
110458  { /* zName:     */ "lock_proxy_file",
110459    /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
110460    /* ePragFlag: */ 0,
110461    /* iArg:      */ 0 },
110462#endif
110463#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
110464  { /* zName:     */ "lock_status",
110465    /* ePragTyp:  */ PragTyp_LOCK_STATUS,
110466    /* ePragFlag: */ 0,
110467    /* iArg:      */ 0 },
110468#endif
110469#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110470  { /* zName:     */ "locking_mode",
110471    /* ePragTyp:  */ PragTyp_LOCKING_MODE,
110472    /* ePragFlag: */ 0,
110473    /* iArg:      */ 0 },
110474  { /* zName:     */ "max_page_count",
110475    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
110476    /* ePragFlag: */ PragFlag_NeedSchema,
110477    /* iArg:      */ 0 },
110478  { /* zName:     */ "mmap_size",
110479    /* ePragTyp:  */ PragTyp_MMAP_SIZE,
110480    /* ePragFlag: */ 0,
110481    /* iArg:      */ 0 },
110482  { /* zName:     */ "page_count",
110483    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
110484    /* ePragFlag: */ PragFlag_NeedSchema,
110485    /* iArg:      */ 0 },
110486  { /* zName:     */ "page_size",
110487    /* ePragTyp:  */ PragTyp_PAGE_SIZE,
110488    /* ePragFlag: */ 0,
110489    /* iArg:      */ 0 },
110490#endif
110491#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
110492  { /* zName:     */ "parser_trace",
110493    /* ePragTyp:  */ PragTyp_PARSER_TRACE,
110494    /* ePragFlag: */ 0,
110495    /* iArg:      */ 0 },
110496#endif
110497#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110498  { /* zName:     */ "query_only",
110499    /* ePragTyp:  */ PragTyp_FLAG,
110500    /* ePragFlag: */ 0,
110501    /* iArg:      */ SQLITE_QueryOnly },
110502#endif
110503#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
110504  { /* zName:     */ "quick_check",
110505    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
110506    /* ePragFlag: */ PragFlag_NeedSchema,
110507    /* iArg:      */ 0 },
110508#endif
110509#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110510  { /* zName:     */ "read_uncommitted",
110511    /* ePragTyp:  */ PragTyp_FLAG,
110512    /* ePragFlag: */ 0,
110513    /* iArg:      */ SQLITE_ReadUncommitted },
110514  { /* zName:     */ "recursive_triggers",
110515    /* ePragTyp:  */ PragTyp_FLAG,
110516    /* ePragFlag: */ 0,
110517    /* iArg:      */ SQLITE_RecTriggers },
110518#endif
110519#if defined(SQLITE_HAS_CODEC)
110520  { /* zName:     */ "rekey",
110521    /* ePragTyp:  */ PragTyp_REKEY,
110522    /* ePragFlag: */ 0,
110523    /* iArg:      */ 0 },
110524#endif
110525#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110526  { /* zName:     */ "reverse_unordered_selects",
110527    /* ePragTyp:  */ PragTyp_FLAG,
110528    /* ePragFlag: */ 0,
110529    /* iArg:      */ SQLITE_ReverseOrder },
110530#endif
110531#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
110532  { /* zName:     */ "schema_version",
110533    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
110534    /* ePragFlag: */ 0,
110535    /* iArg:      */ BTREE_SCHEMA_VERSION },
110536#endif
110537#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110538  { /* zName:     */ "secure_delete",
110539    /* ePragTyp:  */ PragTyp_SECURE_DELETE,
110540    /* ePragFlag: */ 0,
110541    /* iArg:      */ 0 },
110542#endif
110543#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110544  { /* zName:     */ "short_column_names",
110545    /* ePragTyp:  */ PragTyp_FLAG,
110546    /* ePragFlag: */ 0,
110547    /* iArg:      */ SQLITE_ShortColNames },
110548#endif
110549  { /* zName:     */ "shrink_memory",
110550    /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
110551    /* ePragFlag: */ 0,
110552    /* iArg:      */ 0 },
110553  { /* zName:     */ "soft_heap_limit",
110554    /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
110555    /* ePragFlag: */ 0,
110556    /* iArg:      */ 0 },
110557#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110558#if defined(SQLITE_DEBUG)
110559  { /* zName:     */ "sql_trace",
110560    /* ePragTyp:  */ PragTyp_FLAG,
110561    /* ePragFlag: */ 0,
110562    /* iArg:      */ SQLITE_SqlTrace },
110563#endif
110564#endif
110565#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
110566  { /* zName:     */ "stats",
110567    /* ePragTyp:  */ PragTyp_STATS,
110568    /* ePragFlag: */ PragFlag_NeedSchema,
110569    /* iArg:      */ 0 },
110570#endif
110571#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110572  { /* zName:     */ "synchronous",
110573    /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
110574    /* ePragFlag: */ PragFlag_NeedSchema,
110575    /* iArg:      */ 0 },
110576#endif
110577#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
110578  { /* zName:     */ "table_info",
110579    /* ePragTyp:  */ PragTyp_TABLE_INFO,
110580    /* ePragFlag: */ PragFlag_NeedSchema,
110581    /* iArg:      */ 0 },
110582#endif
110583#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110584  { /* zName:     */ "temp_store",
110585    /* ePragTyp:  */ PragTyp_TEMP_STORE,
110586    /* ePragFlag: */ 0,
110587    /* iArg:      */ 0 },
110588  { /* zName:     */ "temp_store_directory",
110589    /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
110590    /* ePragFlag: */ 0,
110591    /* iArg:      */ 0 },
110592#endif
110593  { /* zName:     */ "threads",
110594    /* ePragTyp:  */ PragTyp_THREADS,
110595    /* ePragFlag: */ 0,
110596    /* iArg:      */ 0 },
110597#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
110598  { /* zName:     */ "user_version",
110599    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
110600    /* ePragFlag: */ 0,
110601    /* iArg:      */ BTREE_USER_VERSION },
110602#endif
110603#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110604#if defined(SQLITE_DEBUG)
110605  { /* zName:     */ "vdbe_addoptrace",
110606    /* ePragTyp:  */ PragTyp_FLAG,
110607    /* ePragFlag: */ 0,
110608    /* iArg:      */ SQLITE_VdbeAddopTrace },
110609  { /* zName:     */ "vdbe_debug",
110610    /* ePragTyp:  */ PragTyp_FLAG,
110611    /* ePragFlag: */ 0,
110612    /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
110613  { /* zName:     */ "vdbe_eqp",
110614    /* ePragTyp:  */ PragTyp_FLAG,
110615    /* ePragFlag: */ 0,
110616    /* iArg:      */ SQLITE_VdbeEQP },
110617  { /* zName:     */ "vdbe_listing",
110618    /* ePragTyp:  */ PragTyp_FLAG,
110619    /* ePragFlag: */ 0,
110620    /* iArg:      */ SQLITE_VdbeListing },
110621  { /* zName:     */ "vdbe_trace",
110622    /* ePragTyp:  */ PragTyp_FLAG,
110623    /* ePragFlag: */ 0,
110624    /* iArg:      */ SQLITE_VdbeTrace },
110625#endif
110626#endif
110627#if !defined(SQLITE_OMIT_WAL)
110628  { /* zName:     */ "wal_autocheckpoint",
110629    /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
110630    /* ePragFlag: */ 0,
110631    /* iArg:      */ 0 },
110632  { /* zName:     */ "wal_checkpoint",
110633    /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
110634    /* ePragFlag: */ PragFlag_NeedSchema,
110635    /* iArg:      */ 0 },
110636#endif
110637#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110638  { /* zName:     */ "writable_schema",
110639    /* ePragTyp:  */ PragTyp_FLAG,
110640    /* ePragFlag: */ 0,
110641    /* iArg:      */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
110642#endif
110643};
110644/* Number of pragmas: 60 on by default, 73 total. */
110645
110646/************** End of pragma.h **********************************************/
110647/************** Continuing where we left off in pragma.c *********************/
110648
110649/*
110650** Interpret the given string as a safety level.  Return 0 for OFF,
110651** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA.  Return 1 for an empty or
110652** unrecognized string argument.  The FULL and EXTRA option is disallowed
110653** if the omitFull parameter it 1.
110654**
110655** Note that the values returned are one less that the values that
110656** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
110657** to support legacy SQL code.  The safety level used to be boolean
110658** and older scripts may have used numbers 0 for OFF and 1 for ON.
110659*/
110660static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
110661                             /* 123456789 123456789 123 */
110662  static const char zText[] = "onoffalseyestruextrafull";
110663  static const u8 iOffset[] = {0, 1, 2,  4,    9,  12,  15,   20};
110664  static const u8 iLength[] = {2, 2, 3,  5,    3,   4,   5,    4};
110665  static const u8 iValue[] =  {1, 0, 0,  0,    1,   1,   3,    2};
110666                            /* on no off false yes true extra full */
110667  int i, n;
110668  if( sqlite3Isdigit(*z) ){
110669    return (u8)sqlite3Atoi(z);
110670  }
110671  n = sqlite3Strlen30(z);
110672  for(i=0; i<ArraySize(iLength); i++){
110673    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
110674     && (!omitFull || iValue[i]<=1)
110675    ){
110676      return iValue[i];
110677    }
110678  }
110679  return dflt;
110680}
110681
110682/*
110683** Interpret the given string as a boolean value.
110684*/
110685SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
110686  return getSafetyLevel(z,1,dflt)!=0;
110687}
110688
110689/* The sqlite3GetBoolean() function is used by other modules but the
110690** remainder of this file is specific to PRAGMA processing.  So omit
110691** the rest of the file if PRAGMAs are omitted from the build.
110692*/
110693#if !defined(SQLITE_OMIT_PRAGMA)
110694
110695/*
110696** Interpret the given string as a locking mode value.
110697*/
110698static int getLockingMode(const char *z){
110699  if( z ){
110700    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
110701    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
110702  }
110703  return PAGER_LOCKINGMODE_QUERY;
110704}
110705
110706#ifndef SQLITE_OMIT_AUTOVACUUM
110707/*
110708** Interpret the given string as an auto-vacuum mode value.
110709**
110710** The following strings, "none", "full" and "incremental" are
110711** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
110712*/
110713static int getAutoVacuum(const char *z){
110714  int i;
110715  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
110716  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
110717  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
110718  i = sqlite3Atoi(z);
110719  return (u8)((i>=0&&i<=2)?i:0);
110720}
110721#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
110722
110723#ifndef SQLITE_OMIT_PAGER_PRAGMAS
110724/*
110725** Interpret the given string as a temp db location. Return 1 for file
110726** backed temporary databases, 2 for the Red-Black tree in memory database
110727** and 0 to use the compile-time default.
110728*/
110729static int getTempStore(const char *z){
110730  if( z[0]>='0' && z[0]<='2' ){
110731    return z[0] - '0';
110732  }else if( sqlite3StrICmp(z, "file")==0 ){
110733    return 1;
110734  }else if( sqlite3StrICmp(z, "memory")==0 ){
110735    return 2;
110736  }else{
110737    return 0;
110738  }
110739}
110740#endif /* SQLITE_PAGER_PRAGMAS */
110741
110742#ifndef SQLITE_OMIT_PAGER_PRAGMAS
110743/*
110744** Invalidate temp storage, either when the temp storage is changed
110745** from default, or when 'file' and the temp_store_directory has changed
110746*/
110747static int invalidateTempStorage(Parse *pParse){
110748  sqlite3 *db = pParse->db;
110749  if( db->aDb[1].pBt!=0 ){
110750    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
110751      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
110752        "from within a transaction");
110753      return SQLITE_ERROR;
110754    }
110755    sqlite3BtreeClose(db->aDb[1].pBt);
110756    db->aDb[1].pBt = 0;
110757    sqlite3ResetAllSchemasOfConnection(db);
110758  }
110759  return SQLITE_OK;
110760}
110761#endif /* SQLITE_PAGER_PRAGMAS */
110762
110763#ifndef SQLITE_OMIT_PAGER_PRAGMAS
110764/*
110765** If the TEMP database is open, close it and mark the database schema
110766** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
110767** or DEFAULT_TEMP_STORE pragmas.
110768*/
110769static int changeTempStorage(Parse *pParse, const char *zStorageType){
110770  int ts = getTempStore(zStorageType);
110771  sqlite3 *db = pParse->db;
110772  if( db->temp_store==ts ) return SQLITE_OK;
110773  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
110774    return SQLITE_ERROR;
110775  }
110776  db->temp_store = (u8)ts;
110777  return SQLITE_OK;
110778}
110779#endif /* SQLITE_PAGER_PRAGMAS */
110780
110781/*
110782** Set the names of the first N columns to the values in azCol[]
110783*/
110784static void setAllColumnNames(
110785  Vdbe *v,               /* The query under construction */
110786  int N,                 /* Number of columns */
110787  const char **azCol     /* Names of columns */
110788){
110789  int i;
110790  sqlite3VdbeSetNumCols(v, N);
110791  for(i=0; i<N; i++){
110792    sqlite3VdbeSetColName(v, i, COLNAME_NAME, azCol[i], SQLITE_STATIC);
110793  }
110794}
110795static void setOneColumnName(Vdbe *v, const char *z){
110796  setAllColumnNames(v, 1, &z);
110797}
110798
110799/*
110800** Generate code to return a single integer value.
110801*/
110802static void returnSingleInt(Vdbe *v, const char *zLabel, i64 value){
110803  sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
110804  setOneColumnName(v, zLabel);
110805  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
110806}
110807
110808/*
110809** Generate code to return a single text value.
110810*/
110811static void returnSingleText(
110812  Vdbe *v,                /* Prepared statement under construction */
110813  const char *zLabel,     /* Name of the result column */
110814  const char *zValue      /* Value to be returned */
110815){
110816  if( zValue ){
110817    sqlite3VdbeLoadString(v, 1, (const char*)zValue);
110818    setOneColumnName(v, zLabel);
110819    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
110820  }
110821}
110822
110823
110824/*
110825** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
110826** set these values for all pagers.
110827*/
110828#ifndef SQLITE_OMIT_PAGER_PRAGMAS
110829static void setAllPagerFlags(sqlite3 *db){
110830  if( db->autoCommit ){
110831    Db *pDb = db->aDb;
110832    int n = db->nDb;
110833    assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
110834    assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
110835    assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
110836    assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
110837             ==  PAGER_FLAGS_MASK );
110838    assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
110839    while( (n--) > 0 ){
110840      if( pDb->pBt ){
110841        sqlite3BtreeSetPagerFlags(pDb->pBt,
110842                 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
110843      }
110844      pDb++;
110845    }
110846  }
110847}
110848#else
110849# define setAllPagerFlags(X)  /* no-op */
110850#endif
110851
110852
110853/*
110854** Return a human-readable name for a constraint resolution action.
110855*/
110856#ifndef SQLITE_OMIT_FOREIGN_KEY
110857static const char *actionName(u8 action){
110858  const char *zName;
110859  switch( action ){
110860    case OE_SetNull:  zName = "SET NULL";        break;
110861    case OE_SetDflt:  zName = "SET DEFAULT";     break;
110862    case OE_Cascade:  zName = "CASCADE";         break;
110863    case OE_Restrict: zName = "RESTRICT";        break;
110864    default:          zName = "NO ACTION";
110865                      assert( action==OE_None ); break;
110866  }
110867  return zName;
110868}
110869#endif
110870
110871
110872/*
110873** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
110874** defined in pager.h. This function returns the associated lowercase
110875** journal-mode name.
110876*/
110877SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
110878  static char * const azModeName[] = {
110879    "delete", "persist", "off", "truncate", "memory"
110880#ifndef SQLITE_OMIT_WAL
110881     , "wal"
110882#endif
110883  };
110884  assert( PAGER_JOURNALMODE_DELETE==0 );
110885  assert( PAGER_JOURNALMODE_PERSIST==1 );
110886  assert( PAGER_JOURNALMODE_OFF==2 );
110887  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
110888  assert( PAGER_JOURNALMODE_MEMORY==4 );
110889  assert( PAGER_JOURNALMODE_WAL==5 );
110890  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
110891
110892  if( eMode==ArraySize(azModeName) ) return 0;
110893  return azModeName[eMode];
110894}
110895
110896/*
110897** Process a pragma statement.
110898**
110899** Pragmas are of this form:
110900**
110901**      PRAGMA [schema.]id [= value]
110902**
110903** The identifier might also be a string.  The value is a string, and
110904** identifier, or a number.  If minusFlag is true, then the value is
110905** a number that was preceded by a minus sign.
110906**
110907** If the left side is "database.id" then pId1 is the database name
110908** and pId2 is the id.  If the left side is just "id" then pId1 is the
110909** id and pId2 is any empty string.
110910*/
110911SQLITE_PRIVATE void sqlite3Pragma(
110912  Parse *pParse,
110913  Token *pId1,        /* First part of [schema.]id field */
110914  Token *pId2,        /* Second part of [schema.]id field, or NULL */
110915  Token *pValue,      /* Token for <value>, or NULL */
110916  int minusFlag       /* True if a '-' sign preceded <value> */
110917){
110918  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
110919  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
110920  const char *zDb = 0;   /* The database name */
110921  Token *pId;            /* Pointer to <id> token */
110922  char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
110923  int iDb;               /* Database index for <database> */
110924  int lwr, upr, mid = 0;       /* Binary search bounds */
110925  int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
110926  sqlite3 *db = pParse->db;    /* The database connection */
110927  Db *pDb;                     /* The specific database being pragmaed */
110928  Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
110929  const struct sPragmaNames *pPragma;
110930
110931  if( v==0 ) return;
110932  sqlite3VdbeRunOnlyOnce(v);
110933  pParse->nMem = 2;
110934
110935  /* Interpret the [schema.] part of the pragma statement. iDb is the
110936  ** index of the database this pragma is being applied to in db.aDb[]. */
110937  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
110938  if( iDb<0 ) return;
110939  pDb = &db->aDb[iDb];
110940
110941  /* If the temp database has been explicitly named as part of the
110942  ** pragma, make sure it is open.
110943  */
110944  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
110945    return;
110946  }
110947
110948  zLeft = sqlite3NameFromToken(db, pId);
110949  if( !zLeft ) return;
110950  if( minusFlag ){
110951    zRight = sqlite3MPrintf(db, "-%T", pValue);
110952  }else{
110953    zRight = sqlite3NameFromToken(db, pValue);
110954  }
110955
110956  assert( pId2 );
110957  zDb = pId2->n>0 ? pDb->zName : 0;
110958  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
110959    goto pragma_out;
110960  }
110961
110962  /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
110963  ** connection.  If it returns SQLITE_OK, then assume that the VFS
110964  ** handled the pragma and generate a no-op prepared statement.
110965  **
110966  ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
110967  ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
110968  ** object corresponding to the database file to which the pragma
110969  ** statement refers.
110970  **
110971  ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
110972  ** file control is an array of pointers to strings (char**) in which the
110973  ** second element of the array is the name of the pragma and the third
110974  ** element is the argument to the pragma or NULL if the pragma has no
110975  ** argument.
110976  */
110977  aFcntl[0] = 0;
110978  aFcntl[1] = zLeft;
110979  aFcntl[2] = zRight;
110980  aFcntl[3] = 0;
110981  db->busyHandler.nBusy = 0;
110982  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
110983  if( rc==SQLITE_OK ){
110984    returnSingleText(v, "result", aFcntl[0]);
110985    sqlite3_free(aFcntl[0]);
110986    goto pragma_out;
110987  }
110988  if( rc!=SQLITE_NOTFOUND ){
110989    if( aFcntl[0] ){
110990      sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
110991      sqlite3_free(aFcntl[0]);
110992    }
110993    pParse->nErr++;
110994    pParse->rc = rc;
110995    goto pragma_out;
110996  }
110997
110998  /* Locate the pragma in the lookup table */
110999  lwr = 0;
111000  upr = ArraySize(aPragmaNames)-1;
111001  while( lwr<=upr ){
111002    mid = (lwr+upr)/2;
111003    rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
111004    if( rc==0 ) break;
111005    if( rc<0 ){
111006      upr = mid - 1;
111007    }else{
111008      lwr = mid + 1;
111009    }
111010  }
111011  if( lwr>upr ) goto pragma_out;
111012  pPragma = &aPragmaNames[mid];
111013
111014  /* Make sure the database schema is loaded if the pragma requires that */
111015  if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){
111016    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
111017  }
111018
111019  /* Jump to the appropriate pragma handler */
111020  switch( pPragma->ePragTyp ){
111021
111022#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
111023  /*
111024  **  PRAGMA [schema.]default_cache_size
111025  **  PRAGMA [schema.]default_cache_size=N
111026  **
111027  ** The first form reports the current persistent setting for the
111028  ** page cache size.  The value returned is the maximum number of
111029  ** pages in the page cache.  The second form sets both the current
111030  ** page cache size value and the persistent page cache size value
111031  ** stored in the database file.
111032  **
111033  ** Older versions of SQLite would set the default cache size to a
111034  ** negative number to indicate synchronous=OFF.  These days, synchronous
111035  ** is always on by default regardless of the sign of the default cache
111036  ** size.  But continue to take the absolute value of the default cache
111037  ** size of historical compatibility.
111038  */
111039  case PragTyp_DEFAULT_CACHE_SIZE: {
111040    static const int iLn = VDBE_OFFSET_LINENO(2);
111041    static const VdbeOpList getCacheSize[] = {
111042      { OP_Transaction, 0, 0,        0},                         /* 0 */
111043      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
111044      { OP_IfPos,       1, 8,        0},
111045      { OP_Integer,     0, 2,        0},
111046      { OP_Subtract,    1, 2,        1},
111047      { OP_IfPos,       1, 8,        0},
111048      { OP_Integer,     0, 1,        0},                         /* 6 */
111049      { OP_Noop,        0, 0,        0},
111050      { OP_ResultRow,   1, 1,        0},
111051    };
111052    VdbeOp *aOp;
111053    sqlite3VdbeUsesBtree(v, iDb);
111054    if( !zRight ){
111055      setOneColumnName(v, "cache_size");
111056      pParse->nMem += 2;
111057      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
111058      aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
111059      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
111060      aOp[0].p1 = iDb;
111061      aOp[1].p1 = iDb;
111062      aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
111063    }else{
111064      int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
111065      sqlite3BeginWriteOperation(pParse, 0, iDb);
111066      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
111067      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
111068      pDb->pSchema->cache_size = size;
111069      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
111070    }
111071    break;
111072  }
111073#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
111074
111075#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
111076  /*
111077  **  PRAGMA [schema.]page_size
111078  **  PRAGMA [schema.]page_size=N
111079  **
111080  ** The first form reports the current setting for the
111081  ** database page size in bytes.  The second form sets the
111082  ** database page size value.  The value can only be set if
111083  ** the database has not yet been created.
111084  */
111085  case PragTyp_PAGE_SIZE: {
111086    Btree *pBt = pDb->pBt;
111087    assert( pBt!=0 );
111088    if( !zRight ){
111089      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
111090      returnSingleInt(v, "page_size", size);
111091    }else{
111092      /* Malloc may fail when setting the page-size, as there is an internal
111093      ** buffer that the pager module resizes using sqlite3_realloc().
111094      */
111095      db->nextPagesize = sqlite3Atoi(zRight);
111096      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
111097        sqlite3OomFault(db);
111098      }
111099    }
111100    break;
111101  }
111102
111103  /*
111104  **  PRAGMA [schema.]secure_delete
111105  **  PRAGMA [schema.]secure_delete=ON/OFF
111106  **
111107  ** The first form reports the current setting for the
111108  ** secure_delete flag.  The second form changes the secure_delete
111109  ** flag setting and reports thenew value.
111110  */
111111  case PragTyp_SECURE_DELETE: {
111112    Btree *pBt = pDb->pBt;
111113    int b = -1;
111114    assert( pBt!=0 );
111115    if( zRight ){
111116      b = sqlite3GetBoolean(zRight, 0);
111117    }
111118    if( pId2->n==0 && b>=0 ){
111119      int ii;
111120      for(ii=0; ii<db->nDb; ii++){
111121        sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
111122      }
111123    }
111124    b = sqlite3BtreeSecureDelete(pBt, b);
111125    returnSingleInt(v, "secure_delete", b);
111126    break;
111127  }
111128
111129  /*
111130  **  PRAGMA [schema.]max_page_count
111131  **  PRAGMA [schema.]max_page_count=N
111132  **
111133  ** The first form reports the current setting for the
111134  ** maximum number of pages in the database file.  The
111135  ** second form attempts to change this setting.  Both
111136  ** forms return the current setting.
111137  **
111138  ** The absolute value of N is used.  This is undocumented and might
111139  ** change.  The only purpose is to provide an easy way to test
111140  ** the sqlite3AbsInt32() function.
111141  **
111142  **  PRAGMA [schema.]page_count
111143  **
111144  ** Return the number of pages in the specified database.
111145  */
111146  case PragTyp_PAGE_COUNT: {
111147    int iReg;
111148    sqlite3CodeVerifySchema(pParse, iDb);
111149    iReg = ++pParse->nMem;
111150    if( sqlite3Tolower(zLeft[0])=='p' ){
111151      sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
111152    }else{
111153      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
111154                        sqlite3AbsInt32(sqlite3Atoi(zRight)));
111155    }
111156    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
111157    sqlite3VdbeSetNumCols(v, 1);
111158    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
111159    break;
111160  }
111161
111162  /*
111163  **  PRAGMA [schema.]locking_mode
111164  **  PRAGMA [schema.]locking_mode = (normal|exclusive)
111165  */
111166  case PragTyp_LOCKING_MODE: {
111167    const char *zRet = "normal";
111168    int eMode = getLockingMode(zRight);
111169
111170    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
111171      /* Simple "PRAGMA locking_mode;" statement. This is a query for
111172      ** the current default locking mode (which may be different to
111173      ** the locking-mode of the main database).
111174      */
111175      eMode = db->dfltLockMode;
111176    }else{
111177      Pager *pPager;
111178      if( pId2->n==0 ){
111179        /* This indicates that no database name was specified as part
111180        ** of the PRAGMA command. In this case the locking-mode must be
111181        ** set on all attached databases, as well as the main db file.
111182        **
111183        ** Also, the sqlite3.dfltLockMode variable is set so that
111184        ** any subsequently attached databases also use the specified
111185        ** locking mode.
111186        */
111187        int ii;
111188        assert(pDb==&db->aDb[0]);
111189        for(ii=2; ii<db->nDb; ii++){
111190          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
111191          sqlite3PagerLockingMode(pPager, eMode);
111192        }
111193        db->dfltLockMode = (u8)eMode;
111194      }
111195      pPager = sqlite3BtreePager(pDb->pBt);
111196      eMode = sqlite3PagerLockingMode(pPager, eMode);
111197    }
111198
111199    assert( eMode==PAGER_LOCKINGMODE_NORMAL
111200            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
111201    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
111202      zRet = "exclusive";
111203    }
111204    returnSingleText(v, "locking_mode", zRet);
111205    break;
111206  }
111207
111208  /*
111209  **  PRAGMA [schema.]journal_mode
111210  **  PRAGMA [schema.]journal_mode =
111211  **                      (delete|persist|off|truncate|memory|wal|off)
111212  */
111213  case PragTyp_JOURNAL_MODE: {
111214    int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
111215    int ii;           /* Loop counter */
111216
111217    setOneColumnName(v, "journal_mode");
111218    if( zRight==0 ){
111219      /* If there is no "=MODE" part of the pragma, do a query for the
111220      ** current mode */
111221      eMode = PAGER_JOURNALMODE_QUERY;
111222    }else{
111223      const char *zMode;
111224      int n = sqlite3Strlen30(zRight);
111225      for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
111226        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
111227      }
111228      if( !zMode ){
111229        /* If the "=MODE" part does not match any known journal mode,
111230        ** then do a query */
111231        eMode = PAGER_JOURNALMODE_QUERY;
111232      }
111233    }
111234    if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
111235      /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
111236      iDb = 0;
111237      pId2->n = 1;
111238    }
111239    for(ii=db->nDb-1; ii>=0; ii--){
111240      if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
111241        sqlite3VdbeUsesBtree(v, ii);
111242        sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
111243      }
111244    }
111245    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
111246    break;
111247  }
111248
111249  /*
111250  **  PRAGMA [schema.]journal_size_limit
111251  **  PRAGMA [schema.]journal_size_limit=N
111252  **
111253  ** Get or set the size limit on rollback journal files.
111254  */
111255  case PragTyp_JOURNAL_SIZE_LIMIT: {
111256    Pager *pPager = sqlite3BtreePager(pDb->pBt);
111257    i64 iLimit = -2;
111258    if( zRight ){
111259      sqlite3DecOrHexToI64(zRight, &iLimit);
111260      if( iLimit<-1 ) iLimit = -1;
111261    }
111262    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
111263    returnSingleInt(v, "journal_size_limit", iLimit);
111264    break;
111265  }
111266
111267#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
111268
111269  /*
111270  **  PRAGMA [schema.]auto_vacuum
111271  **  PRAGMA [schema.]auto_vacuum=N
111272  **
111273  ** Get or set the value of the database 'auto-vacuum' parameter.
111274  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
111275  */
111276#ifndef SQLITE_OMIT_AUTOVACUUM
111277  case PragTyp_AUTO_VACUUM: {
111278    Btree *pBt = pDb->pBt;
111279    assert( pBt!=0 );
111280    if( !zRight ){
111281      returnSingleInt(v, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
111282    }else{
111283      int eAuto = getAutoVacuum(zRight);
111284      assert( eAuto>=0 && eAuto<=2 );
111285      db->nextAutovac = (u8)eAuto;
111286      /* Call SetAutoVacuum() to set initialize the internal auto and
111287      ** incr-vacuum flags. This is required in case this connection
111288      ** creates the database file. It is important that it is created
111289      ** as an auto-vacuum capable db.
111290      */
111291      rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
111292      if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
111293        /* When setting the auto_vacuum mode to either "full" or
111294        ** "incremental", write the value of meta[6] in the database
111295        ** file. Before writing to meta[6], check that meta[3] indicates
111296        ** that this really is an auto-vacuum capable database.
111297        */
111298        static const int iLn = VDBE_OFFSET_LINENO(2);
111299        static const VdbeOpList setMeta6[] = {
111300          { OP_Transaction,    0,         1,                 0},    /* 0 */
111301          { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
111302          { OP_If,             1,         0,                 0},    /* 2 */
111303          { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
111304          { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 0},    /* 4 */
111305        };
111306        VdbeOp *aOp;
111307        int iAddr = sqlite3VdbeCurrentAddr(v);
111308        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
111309        aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
111310        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
111311        aOp[0].p1 = iDb;
111312        aOp[1].p1 = iDb;
111313        aOp[2].p2 = iAddr+4;
111314        aOp[4].p1 = iDb;
111315        aOp[4].p3 = eAuto - 1;
111316        sqlite3VdbeUsesBtree(v, iDb);
111317      }
111318    }
111319    break;
111320  }
111321#endif
111322
111323  /*
111324  **  PRAGMA [schema.]incremental_vacuum(N)
111325  **
111326  ** Do N steps of incremental vacuuming on a database.
111327  */
111328#ifndef SQLITE_OMIT_AUTOVACUUM
111329  case PragTyp_INCREMENTAL_VACUUM: {
111330    int iLimit, addr;
111331    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
111332      iLimit = 0x7fffffff;
111333    }
111334    sqlite3BeginWriteOperation(pParse, 0, iDb);
111335    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
111336    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
111337    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
111338    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
111339    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
111340    sqlite3VdbeJumpHere(v, addr);
111341    break;
111342  }
111343#endif
111344
111345#ifndef SQLITE_OMIT_PAGER_PRAGMAS
111346  /*
111347  **  PRAGMA [schema.]cache_size
111348  **  PRAGMA [schema.]cache_size=N
111349  **
111350  ** The first form reports the current local setting for the
111351  ** page cache size. The second form sets the local
111352  ** page cache size value.  If N is positive then that is the
111353  ** number of pages in the cache.  If N is negative, then the
111354  ** number of pages is adjusted so that the cache uses -N kibibytes
111355  ** of memory.
111356  */
111357  case PragTyp_CACHE_SIZE: {
111358    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
111359    if( !zRight ){
111360      returnSingleInt(v, "cache_size", pDb->pSchema->cache_size);
111361    }else{
111362      int size = sqlite3Atoi(zRight);
111363      pDb->pSchema->cache_size = size;
111364      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
111365    }
111366    break;
111367  }
111368
111369  /*
111370  **  PRAGMA [schema.]cache_spill
111371  **  PRAGMA cache_spill=BOOLEAN
111372  **  PRAGMA [schema.]cache_spill=N
111373  **
111374  ** The first form reports the current local setting for the
111375  ** page cache spill size. The second form turns cache spill on
111376  ** or off.  When turnning cache spill on, the size is set to the
111377  ** current cache_size.  The third form sets a spill size that
111378  ** may be different form the cache size.
111379  ** If N is positive then that is the
111380  ** number of pages in the cache.  If N is negative, then the
111381  ** number of pages is adjusted so that the cache uses -N kibibytes
111382  ** of memory.
111383  **
111384  ** If the number of cache_spill pages is less then the number of
111385  ** cache_size pages, no spilling occurs until the page count exceeds
111386  ** the number of cache_size pages.
111387  **
111388  ** The cache_spill=BOOLEAN setting applies to all attached schemas,
111389  ** not just the schema specified.
111390  */
111391  case PragTyp_CACHE_SPILL: {
111392    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
111393    if( !zRight ){
111394      returnSingleInt(v, "cache_spill",
111395         (db->flags & SQLITE_CacheSpill)==0 ? 0 :
111396            sqlite3BtreeSetSpillSize(pDb->pBt,0));
111397    }else{
111398      int size = 1;
111399      if( sqlite3GetInt32(zRight, &size) ){
111400        sqlite3BtreeSetSpillSize(pDb->pBt, size);
111401      }
111402      if( sqlite3GetBoolean(zRight, size!=0) ){
111403        db->flags |= SQLITE_CacheSpill;
111404      }else{
111405        db->flags &= ~SQLITE_CacheSpill;
111406      }
111407      setAllPagerFlags(db);
111408    }
111409    break;
111410  }
111411
111412  /*
111413  **  PRAGMA [schema.]mmap_size(N)
111414  **
111415  ** Used to set mapping size limit. The mapping size limit is
111416  ** used to limit the aggregate size of all memory mapped regions of the
111417  ** database file. If this parameter is set to zero, then memory mapping
111418  ** is not used at all.  If N is negative, then the default memory map
111419  ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
111420  ** The parameter N is measured in bytes.
111421  **
111422  ** This value is advisory.  The underlying VFS is free to memory map
111423  ** as little or as much as it wants.  Except, if N is set to 0 then the
111424  ** upper layers will never invoke the xFetch interfaces to the VFS.
111425  */
111426  case PragTyp_MMAP_SIZE: {
111427    sqlite3_int64 sz;
111428#if SQLITE_MAX_MMAP_SIZE>0
111429    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
111430    if( zRight ){
111431      int ii;
111432      sqlite3DecOrHexToI64(zRight, &sz);
111433      if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
111434      if( pId2->n==0 ) db->szMmap = sz;
111435      for(ii=db->nDb-1; ii>=0; ii--){
111436        if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
111437          sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
111438        }
111439      }
111440    }
111441    sz = -1;
111442    rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
111443#else
111444    sz = 0;
111445    rc = SQLITE_OK;
111446#endif
111447    if( rc==SQLITE_OK ){
111448      returnSingleInt(v, "mmap_size", sz);
111449    }else if( rc!=SQLITE_NOTFOUND ){
111450      pParse->nErr++;
111451      pParse->rc = rc;
111452    }
111453    break;
111454  }
111455
111456  /*
111457  **   PRAGMA temp_store
111458  **   PRAGMA temp_store = "default"|"memory"|"file"
111459  **
111460  ** Return or set the local value of the temp_store flag.  Changing
111461  ** the local value does not make changes to the disk file and the default
111462  ** value will be restored the next time the database is opened.
111463  **
111464  ** Note that it is possible for the library compile-time options to
111465  ** override this setting
111466  */
111467  case PragTyp_TEMP_STORE: {
111468    if( !zRight ){
111469      returnSingleInt(v, "temp_store", db->temp_store);
111470    }else{
111471      changeTempStorage(pParse, zRight);
111472    }
111473    break;
111474  }
111475
111476  /*
111477  **   PRAGMA temp_store_directory
111478  **   PRAGMA temp_store_directory = ""|"directory_name"
111479  **
111480  ** Return or set the local value of the temp_store_directory flag.  Changing
111481  ** the value sets a specific directory to be used for temporary files.
111482  ** Setting to a null string reverts to the default temporary directory search.
111483  ** If temporary directory is changed, then invalidateTempStorage.
111484  **
111485  */
111486  case PragTyp_TEMP_STORE_DIRECTORY: {
111487    if( !zRight ){
111488      returnSingleText(v, "temp_store_directory", sqlite3_temp_directory);
111489    }else{
111490#ifndef SQLITE_OMIT_WSD
111491      if( zRight[0] ){
111492        int res;
111493        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
111494        if( rc!=SQLITE_OK || res==0 ){
111495          sqlite3ErrorMsg(pParse, "not a writable directory");
111496          goto pragma_out;
111497        }
111498      }
111499      if( SQLITE_TEMP_STORE==0
111500       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
111501       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
111502      ){
111503        invalidateTempStorage(pParse);
111504      }
111505      sqlite3_free(sqlite3_temp_directory);
111506      if( zRight[0] ){
111507        sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
111508      }else{
111509        sqlite3_temp_directory = 0;
111510      }
111511#endif /* SQLITE_OMIT_WSD */
111512    }
111513    break;
111514  }
111515
111516#if SQLITE_OS_WIN
111517  /*
111518  **   PRAGMA data_store_directory
111519  **   PRAGMA data_store_directory = ""|"directory_name"
111520  **
111521  ** Return or set the local value of the data_store_directory flag.  Changing
111522  ** the value sets a specific directory to be used for database files that
111523  ** were specified with a relative pathname.  Setting to a null string reverts
111524  ** to the default database directory, which for database files specified with
111525  ** a relative path will probably be based on the current directory for the
111526  ** process.  Database file specified with an absolute path are not impacted
111527  ** by this setting, regardless of its value.
111528  **
111529  */
111530  case PragTyp_DATA_STORE_DIRECTORY: {
111531    if( !zRight ){
111532      returnSingleText(v, "data_store_directory", sqlite3_data_directory);
111533    }else{
111534#ifndef SQLITE_OMIT_WSD
111535      if( zRight[0] ){
111536        int res;
111537        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
111538        if( rc!=SQLITE_OK || res==0 ){
111539          sqlite3ErrorMsg(pParse, "not a writable directory");
111540          goto pragma_out;
111541        }
111542      }
111543      sqlite3_free(sqlite3_data_directory);
111544      if( zRight[0] ){
111545        sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
111546      }else{
111547        sqlite3_data_directory = 0;
111548      }
111549#endif /* SQLITE_OMIT_WSD */
111550    }
111551    break;
111552  }
111553#endif
111554
111555#if SQLITE_ENABLE_LOCKING_STYLE
111556  /*
111557  **   PRAGMA [schema.]lock_proxy_file
111558  **   PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
111559  **
111560  ** Return or set the value of the lock_proxy_file flag.  Changing
111561  ** the value sets a specific file to be used for database access locks.
111562  **
111563  */
111564  case PragTyp_LOCK_PROXY_FILE: {
111565    if( !zRight ){
111566      Pager *pPager = sqlite3BtreePager(pDb->pBt);
111567      char *proxy_file_path = NULL;
111568      sqlite3_file *pFile = sqlite3PagerFile(pPager);
111569      sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
111570                           &proxy_file_path);
111571      returnSingleText(v, "lock_proxy_file", proxy_file_path);
111572    }else{
111573      Pager *pPager = sqlite3BtreePager(pDb->pBt);
111574      sqlite3_file *pFile = sqlite3PagerFile(pPager);
111575      int res;
111576      if( zRight[0] ){
111577        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
111578                                     zRight);
111579      } else {
111580        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
111581                                     NULL);
111582      }
111583      if( res!=SQLITE_OK ){
111584        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
111585        goto pragma_out;
111586      }
111587    }
111588    break;
111589  }
111590#endif /* SQLITE_ENABLE_LOCKING_STYLE */
111591
111592  /*
111593  **   PRAGMA [schema.]synchronous
111594  **   PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
111595  **
111596  ** Return or set the local value of the synchronous flag.  Changing
111597  ** the local value does not make changes to the disk file and the
111598  ** default value will be restored the next time the database is
111599  ** opened.
111600  */
111601  case PragTyp_SYNCHRONOUS: {
111602    if( !zRight ){
111603      returnSingleInt(v, "synchronous", pDb->safety_level-1);
111604    }else{
111605      if( !db->autoCommit ){
111606        sqlite3ErrorMsg(pParse,
111607            "Safety level may not be changed inside a transaction");
111608      }else{
111609        int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
111610        if( iLevel==0 ) iLevel = 1;
111611        pDb->safety_level = iLevel;
111612        pDb->bSyncSet = 1;
111613        setAllPagerFlags(db);
111614      }
111615    }
111616    break;
111617  }
111618#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
111619
111620#ifndef SQLITE_OMIT_FLAG_PRAGMAS
111621  case PragTyp_FLAG: {
111622    if( zRight==0 ){
111623      returnSingleInt(v, pPragma->zName, (db->flags & pPragma->iArg)!=0 );
111624    }else{
111625      int mask = pPragma->iArg;    /* Mask of bits to set or clear. */
111626      if( db->autoCommit==0 ){
111627        /* Foreign key support may not be enabled or disabled while not
111628        ** in auto-commit mode.  */
111629        mask &= ~(SQLITE_ForeignKeys);
111630      }
111631#if SQLITE_USER_AUTHENTICATION
111632      if( db->auth.authLevel==UAUTH_User ){
111633        /* Do not allow non-admin users to modify the schema arbitrarily */
111634        mask &= ~(SQLITE_WriteSchema);
111635      }
111636#endif
111637
111638      if( sqlite3GetBoolean(zRight, 0) ){
111639        db->flags |= mask;
111640      }else{
111641        db->flags &= ~mask;
111642        if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
111643      }
111644
111645      /* Many of the flag-pragmas modify the code generated by the SQL
111646      ** compiler (eg. count_changes). So add an opcode to expire all
111647      ** compiled SQL statements after modifying a pragma value.
111648      */
111649      sqlite3VdbeAddOp0(v, OP_Expire);
111650      setAllPagerFlags(db);
111651    }
111652    break;
111653  }
111654#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
111655
111656#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
111657  /*
111658  **   PRAGMA table_info(<table>)
111659  **
111660  ** Return a single row for each column of the named table. The columns of
111661  ** the returned data set are:
111662  **
111663  ** cid:        Column id (numbered from left to right, starting at 0)
111664  ** name:       Column name
111665  ** type:       Column declaration type.
111666  ** notnull:    True if 'NOT NULL' is part of column declaration
111667  ** dflt_value: The default value for the column, if any.
111668  */
111669  case PragTyp_TABLE_INFO: if( zRight ){
111670    Table *pTab;
111671    pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
111672    if( pTab ){
111673      static const char *azCol[] = {
111674         "cid", "name", "type", "notnull", "dflt_value", "pk"
111675      };
111676      int i, k;
111677      int nHidden = 0;
111678      Column *pCol;
111679      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
111680      pParse->nMem = 6;
111681      sqlite3CodeVerifySchema(pParse, iDb);
111682      setAllColumnNames(v, 6, azCol); assert( 6==ArraySize(azCol) );
111683      sqlite3ViewGetColumnNames(pParse, pTab);
111684      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
111685        if( IsHiddenColumn(pCol) ){
111686          nHidden++;
111687          continue;
111688        }
111689        if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
111690          k = 0;
111691        }else if( pPk==0 ){
111692          k = 1;
111693        }else{
111694          for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
111695        }
111696        assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
111697        sqlite3VdbeMultiLoad(v, 1, "issisi",
111698               i-nHidden,
111699               pCol->zName,
111700               sqlite3ColumnType(pCol,""),
111701               pCol->notNull ? 1 : 0,
111702               pCol->pDflt ? pCol->pDflt->u.zToken : 0,
111703               k);
111704        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
111705      }
111706    }
111707  }
111708  break;
111709
111710  case PragTyp_STATS: {
111711    static const char *azCol[] = { "table", "index", "width", "height" };
111712    Index *pIdx;
111713    HashElem *i;
111714    v = sqlite3GetVdbe(pParse);
111715    pParse->nMem = 4;
111716    sqlite3CodeVerifySchema(pParse, iDb);
111717    setAllColumnNames(v, 4, azCol);  assert( 4==ArraySize(azCol) );
111718    for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
111719      Table *pTab = sqliteHashData(i);
111720      sqlite3VdbeMultiLoad(v, 1, "ssii",
111721           pTab->zName,
111722           0,
111723           pTab->szTabRow,
111724           pTab->nRowLogEst);
111725      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
111726      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
111727        sqlite3VdbeMultiLoad(v, 2, "sii",
111728           pIdx->zName,
111729           pIdx->szIdxRow,
111730           pIdx->aiRowLogEst[0]);
111731        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
111732      }
111733    }
111734  }
111735  break;
111736
111737  case PragTyp_INDEX_INFO: if( zRight ){
111738    Index *pIdx;
111739    Table *pTab;
111740    pIdx = sqlite3FindIndex(db, zRight, zDb);
111741    if( pIdx ){
111742      static const char *azCol[] = {
111743         "seqno", "cid", "name", "desc", "coll", "key"
111744      };
111745      int i;
111746      int mx;
111747      if( pPragma->iArg ){
111748        /* PRAGMA index_xinfo (newer version with more rows and columns) */
111749        mx = pIdx->nColumn;
111750        pParse->nMem = 6;
111751      }else{
111752        /* PRAGMA index_info (legacy version) */
111753        mx = pIdx->nKeyCol;
111754        pParse->nMem = 3;
111755      }
111756      pTab = pIdx->pTable;
111757      sqlite3CodeVerifySchema(pParse, iDb);
111758      assert( pParse->nMem<=ArraySize(azCol) );
111759      setAllColumnNames(v, pParse->nMem, azCol);
111760      for(i=0; i<mx; i++){
111761        i16 cnum = pIdx->aiColumn[i];
111762        sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum,
111763                             cnum<0 ? 0 : pTab->aCol[cnum].zName);
111764        if( pPragma->iArg ){
111765          sqlite3VdbeMultiLoad(v, 4, "isi",
111766            pIdx->aSortOrder[i],
111767            pIdx->azColl[i],
111768            i<pIdx->nKeyCol);
111769        }
111770        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
111771      }
111772    }
111773  }
111774  break;
111775
111776  case PragTyp_INDEX_LIST: if( zRight ){
111777    Index *pIdx;
111778    Table *pTab;
111779    int i;
111780    pTab = sqlite3FindTable(db, zRight, zDb);
111781    if( pTab ){
111782      static const char *azCol[] = {
111783        "seq", "name", "unique", "origin", "partial"
111784      };
111785      v = sqlite3GetVdbe(pParse);
111786      pParse->nMem = 5;
111787      sqlite3CodeVerifySchema(pParse, iDb);
111788      setAllColumnNames(v, 5, azCol);  assert( 5==ArraySize(azCol) );
111789      for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
111790        const char *azOrigin[] = { "c", "u", "pk" };
111791        sqlite3VdbeMultiLoad(v, 1, "isisi",
111792           i,
111793           pIdx->zName,
111794           IsUniqueIndex(pIdx),
111795           azOrigin[pIdx->idxType],
111796           pIdx->pPartIdxWhere!=0);
111797        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
111798      }
111799    }
111800  }
111801  break;
111802
111803  case PragTyp_DATABASE_LIST: {
111804    static const char *azCol[] = { "seq", "name", "file" };
111805    int i;
111806    pParse->nMem = 3;
111807    setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
111808    for(i=0; i<db->nDb; i++){
111809      if( db->aDb[i].pBt==0 ) continue;
111810      assert( db->aDb[i].zName!=0 );
111811      sqlite3VdbeMultiLoad(v, 1, "iss",
111812         i,
111813         db->aDb[i].zName,
111814         sqlite3BtreeGetFilename(db->aDb[i].pBt));
111815      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
111816    }
111817  }
111818  break;
111819
111820  case PragTyp_COLLATION_LIST: {
111821    static const char *azCol[] = { "seq", "name" };
111822    int i = 0;
111823    HashElem *p;
111824    pParse->nMem = 2;
111825    setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
111826    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
111827      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
111828      sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
111829      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
111830    }
111831  }
111832  break;
111833#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
111834
111835#ifndef SQLITE_OMIT_FOREIGN_KEY
111836  case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
111837    FKey *pFK;
111838    Table *pTab;
111839    pTab = sqlite3FindTable(db, zRight, zDb);
111840    if( pTab ){
111841      v = sqlite3GetVdbe(pParse);
111842      pFK = pTab->pFKey;
111843      if( pFK ){
111844        static const char *azCol[] = {
111845           "id", "seq", "table", "from", "to", "on_update", "on_delete",
111846           "match"
111847        };
111848        int i = 0;
111849        pParse->nMem = 8;
111850        sqlite3CodeVerifySchema(pParse, iDb);
111851        setAllColumnNames(v, 8, azCol); assert( 8==ArraySize(azCol) );
111852        while(pFK){
111853          int j;
111854          for(j=0; j<pFK->nCol; j++){
111855            sqlite3VdbeMultiLoad(v, 1, "iissssss",
111856                   i,
111857                   j,
111858                   pFK->zTo,
111859                   pTab->aCol[pFK->aCol[j].iFrom].zName,
111860                   pFK->aCol[j].zCol,
111861                   actionName(pFK->aAction[1]),  /* ON UPDATE */
111862                   actionName(pFK->aAction[0]),  /* ON DELETE */
111863                   "NONE");
111864            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
111865          }
111866          ++i;
111867          pFK = pFK->pNextFrom;
111868        }
111869      }
111870    }
111871  }
111872  break;
111873#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
111874
111875#ifndef SQLITE_OMIT_FOREIGN_KEY
111876#ifndef SQLITE_OMIT_TRIGGER
111877  case PragTyp_FOREIGN_KEY_CHECK: {
111878    FKey *pFK;             /* A foreign key constraint */
111879    Table *pTab;           /* Child table contain "REFERENCES" keyword */
111880    Table *pParent;        /* Parent table that child points to */
111881    Index *pIdx;           /* Index in the parent table */
111882    int i;                 /* Loop counter:  Foreign key number for pTab */
111883    int j;                 /* Loop counter:  Field of the foreign key */
111884    HashElem *k;           /* Loop counter:  Next table in schema */
111885    int x;                 /* result variable */
111886    int regResult;         /* 3 registers to hold a result row */
111887    int regKey;            /* Register to hold key for checking the FK */
111888    int regRow;            /* Registers to hold a row from pTab */
111889    int addrTop;           /* Top of a loop checking foreign keys */
111890    int addrOk;            /* Jump here if the key is OK */
111891    int *aiCols;           /* child to parent column mapping */
111892    static const char *azCol[] = { "table", "rowid", "parent", "fkid" };
111893
111894    regResult = pParse->nMem+1;
111895    pParse->nMem += 4;
111896    regKey = ++pParse->nMem;
111897    regRow = ++pParse->nMem;
111898    v = sqlite3GetVdbe(pParse);
111899    setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
111900    sqlite3CodeVerifySchema(pParse, iDb);
111901    k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
111902    while( k ){
111903      if( zRight ){
111904        pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
111905        k = 0;
111906      }else{
111907        pTab = (Table*)sqliteHashData(k);
111908        k = sqliteHashNext(k);
111909      }
111910      if( pTab==0 || pTab->pFKey==0 ) continue;
111911      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
111912      if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
111913      sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
111914      sqlite3VdbeLoadString(v, regResult, pTab->zName);
111915      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
111916        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
111917        if( pParent==0 ) continue;
111918        pIdx = 0;
111919        sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
111920        x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
111921        if( x==0 ){
111922          if( pIdx==0 ){
111923            sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
111924          }else{
111925            sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
111926            sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
111927          }
111928        }else{
111929          k = 0;
111930          break;
111931        }
111932      }
111933      assert( pParse->nErr>0 || pFK==0 );
111934      if( pFK ) break;
111935      if( pParse->nTab<i ) pParse->nTab = i;
111936      addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
111937      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
111938        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
111939        pIdx = 0;
111940        aiCols = 0;
111941        if( pParent ){
111942          x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
111943          assert( x==0 );
111944        }
111945        addrOk = sqlite3VdbeMakeLabel(v);
111946        if( pParent && pIdx==0 ){
111947          int iKey = pFK->aCol[0].iFrom;
111948          assert( iKey>=0 && iKey<pTab->nCol );
111949          if( iKey!=pTab->iPKey ){
111950            sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
111951            sqlite3ColumnDefault(v, pTab, iKey, regRow);
111952            sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
111953          }else{
111954            sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
111955          }
111956          sqlite3VdbeAddOp3(v, OP_SeekRowid, i, 0, regRow); VdbeCoverage(v);
111957          sqlite3VdbeGoto(v, addrOk);
111958          sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
111959        }else{
111960          for(j=0; j<pFK->nCol; j++){
111961            sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
111962                            aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
111963            sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
111964          }
111965          if( pParent ){
111966            sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
111967                              sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
111968            sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
111969            VdbeCoverage(v);
111970          }
111971        }
111972        sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
111973        sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1);
111974        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
111975        sqlite3VdbeResolveLabel(v, addrOk);
111976        sqlite3DbFree(db, aiCols);
111977      }
111978      sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
111979      sqlite3VdbeJumpHere(v, addrTop);
111980    }
111981  }
111982  break;
111983#endif /* !defined(SQLITE_OMIT_TRIGGER) */
111984#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
111985
111986#ifndef NDEBUG
111987  case PragTyp_PARSER_TRACE: {
111988    if( zRight ){
111989      if( sqlite3GetBoolean(zRight, 0) ){
111990        sqlite3ParserTrace(stdout, "parser: ");
111991      }else{
111992        sqlite3ParserTrace(0, 0);
111993      }
111994    }
111995  }
111996  break;
111997#endif
111998
111999  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
112000  ** used will be case sensitive or not depending on the RHS.
112001  */
112002  case PragTyp_CASE_SENSITIVE_LIKE: {
112003    if( zRight ){
112004      sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
112005    }
112006  }
112007  break;
112008
112009#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
112010# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
112011#endif
112012
112013#ifndef SQLITE_OMIT_INTEGRITY_CHECK
112014  /* Pragma "quick_check" is reduced version of
112015  ** integrity_check designed to detect most database corruption
112016  ** without most of the overhead of a full integrity-check.
112017  */
112018  case PragTyp_INTEGRITY_CHECK: {
112019    int i, j, addr, mxErr;
112020
112021    int isQuick = (sqlite3Tolower(zLeft[0])=='q');
112022
112023    /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
112024    ** then iDb is set to the index of the database identified by <db>.
112025    ** In this case, the integrity of database iDb only is verified by
112026    ** the VDBE created below.
112027    **
112028    ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
112029    ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
112030    ** to -1 here, to indicate that the VDBE should verify the integrity
112031    ** of all attached databases.  */
112032    assert( iDb>=0 );
112033    assert( iDb==0 || pId2->z );
112034    if( pId2->z==0 ) iDb = -1;
112035
112036    /* Initialize the VDBE program */
112037    pParse->nMem = 6;
112038    setOneColumnName(v, "integrity_check");
112039
112040    /* Set the maximum error count */
112041    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
112042    if( zRight ){
112043      sqlite3GetInt32(zRight, &mxErr);
112044      if( mxErr<=0 ){
112045        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
112046      }
112047    }
112048    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
112049
112050    /* Do an integrity check on each database file */
112051    for(i=0; i<db->nDb; i++){
112052      HashElem *x;
112053      Hash *pTbls;
112054      int *aRoot;
112055      int cnt = 0;
112056      int mxIdx = 0;
112057      int nIdx;
112058
112059      if( OMIT_TEMPDB && i==1 ) continue;
112060      if( iDb>=0 && i!=iDb ) continue;
112061
112062      sqlite3CodeVerifySchema(pParse, i);
112063      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
112064      VdbeCoverage(v);
112065      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
112066      sqlite3VdbeJumpHere(v, addr);
112067
112068      /* Do an integrity check of the B-Tree
112069      **
112070      ** Begin by finding the root pages numbers
112071      ** for all tables and indices in the database.
112072      */
112073      assert( sqlite3SchemaMutexHeld(db, i, 0) );
112074      pTbls = &db->aDb[i].pSchema->tblHash;
112075      for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
112076        Table *pTab = sqliteHashData(x);
112077        Index *pIdx;
112078        if( HasRowid(pTab) ) cnt++;
112079        for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
112080        if( nIdx>mxIdx ) mxIdx = nIdx;
112081      }
112082      aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
112083      if( aRoot==0 ) break;
112084      for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
112085        Table *pTab = sqliteHashData(x);
112086        Index *pIdx;
112087        if( HasRowid(pTab) ) aRoot[cnt++] = pTab->tnum;
112088        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
112089          aRoot[cnt++] = pIdx->tnum;
112090        }
112091      }
112092      aRoot[cnt] = 0;
112093
112094      /* Make sure sufficient number of registers have been allocated */
112095      pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
112096
112097      /* Do the b-tree integrity checks */
112098      sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
112099      sqlite3VdbeChangeP5(v, (u8)i);
112100      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
112101      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
112102         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
112103         P4_DYNAMIC);
112104      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
112105      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
112106      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
112107      sqlite3VdbeJumpHere(v, addr);
112108
112109      /* Make sure all the indices are constructed correctly.
112110      */
112111      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
112112        Table *pTab = sqliteHashData(x);
112113        Index *pIdx, *pPk;
112114        Index *pPrior = 0;
112115        int loopTop;
112116        int iDataCur, iIdxCur;
112117        int r1 = -1;
112118
112119        if( pTab->pIndex==0 ) continue;
112120        pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
112121        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
112122        VdbeCoverage(v);
112123        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
112124        sqlite3VdbeJumpHere(v, addr);
112125        sqlite3ExprCacheClear(pParse);
112126        sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
112127                                   1, 0, &iDataCur, &iIdxCur);
112128        sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
112129        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
112130          sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
112131        }
112132        assert( pParse->nMem>=8+j );
112133        assert( sqlite3NoTempsInRange(pParse,1,7+j) );
112134        sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
112135        loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
112136        /* Verify that all NOT NULL columns really are NOT NULL */
112137        for(j=0; j<pTab->nCol; j++){
112138          char *zErr;
112139          int jmp2, jmp3;
112140          if( j==pTab->iPKey ) continue;
112141          if( pTab->aCol[j].notNull==0 ) continue;
112142          sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
112143          sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
112144          jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
112145          sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
112146          zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
112147                              pTab->aCol[j].zName);
112148          sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
112149          sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
112150          jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
112151          sqlite3VdbeAddOp0(v, OP_Halt);
112152          sqlite3VdbeJumpHere(v, jmp2);
112153          sqlite3VdbeJumpHere(v, jmp3);
112154        }
112155        /* Validate index entries for the current row */
112156        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
112157          int jmp2, jmp3, jmp4, jmp5;
112158          int ckUniq = sqlite3VdbeMakeLabel(v);
112159          if( pPk==pIdx ) continue;
112160          r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
112161                                       pPrior, r1);
112162          pPrior = pIdx;
112163          sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);  /* increment entry count */
112164          /* Verify that an index entry exists for the current table row */
112165          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
112166                                      pIdx->nColumn); VdbeCoverage(v);
112167          sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
112168          sqlite3VdbeLoadString(v, 3, "row ");
112169          sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
112170          sqlite3VdbeLoadString(v, 4, " missing from index ");
112171          sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
112172          jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
112173          sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
112174          sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
112175          jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
112176          sqlite3VdbeAddOp0(v, OP_Halt);
112177          sqlite3VdbeJumpHere(v, jmp2);
112178          /* For UNIQUE indexes, verify that only one entry exists with the
112179          ** current key.  The entry is unique if (1) any column is NULL
112180          ** or (2) the next entry has a different key */
112181          if( IsUniqueIndex(pIdx) ){
112182            int uniqOk = sqlite3VdbeMakeLabel(v);
112183            int jmp6;
112184            int kk;
112185            for(kk=0; kk<pIdx->nKeyCol; kk++){
112186              int iCol = pIdx->aiColumn[kk];
112187              assert( iCol!=XN_ROWID && iCol<pTab->nCol );
112188              if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
112189              sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
112190              VdbeCoverage(v);
112191            }
112192            jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
112193            sqlite3VdbeGoto(v, uniqOk);
112194            sqlite3VdbeJumpHere(v, jmp6);
112195            sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
112196                                 pIdx->nKeyCol); VdbeCoverage(v);
112197            sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
112198            sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
112199            sqlite3VdbeGoto(v, jmp5);
112200            sqlite3VdbeResolveLabel(v, uniqOk);
112201          }
112202          sqlite3VdbeJumpHere(v, jmp4);
112203          sqlite3ResolvePartIdxLabel(pParse, jmp3);
112204        }
112205        sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
112206        sqlite3VdbeJumpHere(v, loopTop-1);
112207#ifndef SQLITE_OMIT_BTREECOUNT
112208        sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
112209        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
112210          if( pPk==pIdx ) continue;
112211          addr = sqlite3VdbeCurrentAddr(v);
112212          sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
112213          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
112214          sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
112215          sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
112216          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
112217          sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
112218          sqlite3VdbeLoadString(v, 3, pIdx->zName);
112219          sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
112220          sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
112221        }
112222#endif /* SQLITE_OMIT_BTREECOUNT */
112223      }
112224    }
112225    {
112226      static const int iLn = VDBE_OFFSET_LINENO(2);
112227      static const VdbeOpList endCode[] = {
112228        { OP_AddImm,      1, 0,        0},    /* 0 */
112229        { OP_If,          1, 4,        0},    /* 1 */
112230        { OP_String8,     0, 3,        0},    /* 2 */
112231        { OP_ResultRow,   3, 1,        0},    /* 3 */
112232      };
112233      VdbeOp *aOp;
112234
112235      aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
112236      if( aOp ){
112237        aOp[0].p2 = -mxErr;
112238        aOp[2].p4type = P4_STATIC;
112239        aOp[2].p4.z = "ok";
112240      }
112241    }
112242  }
112243  break;
112244#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
112245
112246#ifndef SQLITE_OMIT_UTF16
112247  /*
112248  **   PRAGMA encoding
112249  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
112250  **
112251  ** In its first form, this pragma returns the encoding of the main
112252  ** database. If the database is not initialized, it is initialized now.
112253  **
112254  ** The second form of this pragma is a no-op if the main database file
112255  ** has not already been initialized. In this case it sets the default
112256  ** encoding that will be used for the main database file if a new file
112257  ** is created. If an existing main database file is opened, then the
112258  ** default text encoding for the existing database is used.
112259  **
112260  ** In all cases new databases created using the ATTACH command are
112261  ** created to use the same default text encoding as the main database. If
112262  ** the main database has not been initialized and/or created when ATTACH
112263  ** is executed, this is done before the ATTACH operation.
112264  **
112265  ** In the second form this pragma sets the text encoding to be used in
112266  ** new database files created using this database handle. It is only
112267  ** useful if invoked immediately after the main database i
112268  */
112269  case PragTyp_ENCODING: {
112270    static const struct EncName {
112271      char *zName;
112272      u8 enc;
112273    } encnames[] = {
112274      { "UTF8",     SQLITE_UTF8        },
112275      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
112276      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
112277      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
112278      { "UTF16le",  SQLITE_UTF16LE     },
112279      { "UTF16be",  SQLITE_UTF16BE     },
112280      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
112281      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
112282      { 0, 0 }
112283    };
112284    const struct EncName *pEnc;
112285    if( !zRight ){    /* "PRAGMA encoding" */
112286      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
112287      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
112288      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
112289      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
112290      returnSingleText(v, "encoding", encnames[ENC(pParse->db)].zName);
112291    }else{                        /* "PRAGMA encoding = XXX" */
112292      /* Only change the value of sqlite.enc if the database handle is not
112293      ** initialized. If the main database exists, the new sqlite.enc value
112294      ** will be overwritten when the schema is next loaded. If it does not
112295      ** already exists, it will be created to use the new encoding value.
112296      */
112297      if(
112298        !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
112299        DbHasProperty(db, 0, DB_Empty)
112300      ){
112301        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
112302          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
112303            SCHEMA_ENC(db) = ENC(db) =
112304                pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
112305            break;
112306          }
112307        }
112308        if( !pEnc->zName ){
112309          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
112310        }
112311      }
112312    }
112313  }
112314  break;
112315#endif /* SQLITE_OMIT_UTF16 */
112316
112317#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
112318  /*
112319  **   PRAGMA [schema.]schema_version
112320  **   PRAGMA [schema.]schema_version = <integer>
112321  **
112322  **   PRAGMA [schema.]user_version
112323  **   PRAGMA [schema.]user_version = <integer>
112324  **
112325  **   PRAGMA [schema.]freelist_count
112326  **
112327  **   PRAGMA [schema.]data_version
112328  **
112329  **   PRAGMA [schema.]application_id
112330  **   PRAGMA [schema.]application_id = <integer>
112331  **
112332  ** The pragma's schema_version and user_version are used to set or get
112333  ** the value of the schema-version and user-version, respectively. Both
112334  ** the schema-version and the user-version are 32-bit signed integers
112335  ** stored in the database header.
112336  **
112337  ** The schema-cookie is usually only manipulated internally by SQLite. It
112338  ** is incremented by SQLite whenever the database schema is modified (by
112339  ** creating or dropping a table or index). The schema version is used by
112340  ** SQLite each time a query is executed to ensure that the internal cache
112341  ** of the schema used when compiling the SQL query matches the schema of
112342  ** the database against which the compiled query is actually executed.
112343  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
112344  ** the schema-version is potentially dangerous and may lead to program
112345  ** crashes or database corruption. Use with caution!
112346  **
112347  ** The user-version is not used internally by SQLite. It may be used by
112348  ** applications for any purpose.
112349  */
112350  case PragTyp_HEADER_VALUE: {
112351    int iCookie = pPragma->iArg;  /* Which cookie to read or write */
112352    sqlite3VdbeUsesBtree(v, iDb);
112353    if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){
112354      /* Write the specified cookie value */
112355      static const VdbeOpList setCookie[] = {
112356        { OP_Transaction,    0,  1,  0},    /* 0 */
112357        { OP_SetCookie,      0,  0,  0},    /* 1 */
112358      };
112359      VdbeOp *aOp;
112360      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
112361      aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
112362      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
112363      aOp[0].p1 = iDb;
112364      aOp[1].p1 = iDb;
112365      aOp[1].p2 = iCookie;
112366      aOp[1].p3 = sqlite3Atoi(zRight);
112367    }else{
112368      /* Read the specified cookie value */
112369      static const VdbeOpList readCookie[] = {
112370        { OP_Transaction,     0,  0,  0},    /* 0 */
112371        { OP_ReadCookie,      0,  1,  0},    /* 1 */
112372        { OP_ResultRow,       1,  1,  0}
112373      };
112374      VdbeOp *aOp;
112375      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
112376      aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
112377      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
112378      aOp[0].p1 = iDb;
112379      aOp[1].p1 = iDb;
112380      aOp[1].p3 = iCookie;
112381      sqlite3VdbeSetNumCols(v, 1);
112382      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
112383      sqlite3VdbeReusable(v);
112384    }
112385  }
112386  break;
112387#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
112388
112389#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
112390  /*
112391  **   PRAGMA compile_options
112392  **
112393  ** Return the names of all compile-time options used in this build,
112394  ** one option per row.
112395  */
112396  case PragTyp_COMPILE_OPTIONS: {
112397    int i = 0;
112398    const char *zOpt;
112399    pParse->nMem = 1;
112400    setOneColumnName(v, "compile_option");
112401    while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
112402      sqlite3VdbeLoadString(v, 1, zOpt);
112403      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
112404    }
112405    sqlite3VdbeReusable(v);
112406  }
112407  break;
112408#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
112409
112410#ifndef SQLITE_OMIT_WAL
112411  /*
112412  **   PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
112413  **
112414  ** Checkpoint the database.
112415  */
112416  case PragTyp_WAL_CHECKPOINT: {
112417    static const char *azCol[] = { "busy", "log", "checkpointed" };
112418    int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
112419    int eMode = SQLITE_CHECKPOINT_PASSIVE;
112420    if( zRight ){
112421      if( sqlite3StrICmp(zRight, "full")==0 ){
112422        eMode = SQLITE_CHECKPOINT_FULL;
112423      }else if( sqlite3StrICmp(zRight, "restart")==0 ){
112424        eMode = SQLITE_CHECKPOINT_RESTART;
112425      }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
112426        eMode = SQLITE_CHECKPOINT_TRUNCATE;
112427      }
112428    }
112429    setAllColumnNames(v, 3, azCol);  assert( 3==ArraySize(azCol) );
112430    pParse->nMem = 3;
112431    sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
112432    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
112433  }
112434  break;
112435
112436  /*
112437  **   PRAGMA wal_autocheckpoint
112438  **   PRAGMA wal_autocheckpoint = N
112439  **
112440  ** Configure a database connection to automatically checkpoint a database
112441  ** after accumulating N frames in the log. Or query for the current value
112442  ** of N.
112443  */
112444  case PragTyp_WAL_AUTOCHECKPOINT: {
112445    if( zRight ){
112446      sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
112447    }
112448    returnSingleInt(v, "wal_autocheckpoint",
112449       db->xWalCallback==sqlite3WalDefaultHook ?
112450           SQLITE_PTR_TO_INT(db->pWalArg) : 0);
112451  }
112452  break;
112453#endif
112454
112455  /*
112456  **  PRAGMA shrink_memory
112457  **
112458  ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
112459  ** connection on which it is invoked to free up as much memory as it
112460  ** can, by calling sqlite3_db_release_memory().
112461  */
112462  case PragTyp_SHRINK_MEMORY: {
112463    sqlite3_db_release_memory(db);
112464    break;
112465  }
112466
112467  /*
112468  **   PRAGMA busy_timeout
112469  **   PRAGMA busy_timeout = N
112470  **
112471  ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
112472  ** if one is set.  If no busy handler or a different busy handler is set
112473  ** then 0 is returned.  Setting the busy_timeout to 0 or negative
112474  ** disables the timeout.
112475  */
112476  /*case PragTyp_BUSY_TIMEOUT*/ default: {
112477    assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
112478    if( zRight ){
112479      sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
112480    }
112481    returnSingleInt(v, "timeout",  db->busyTimeout);
112482    break;
112483  }
112484
112485  /*
112486  **   PRAGMA soft_heap_limit
112487  **   PRAGMA soft_heap_limit = N
112488  **
112489  ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
112490  ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
112491  ** specified and is a non-negative integer.
112492  ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
112493  ** returns the same integer that would be returned by the
112494  ** sqlite3_soft_heap_limit64(-1) C-language function.
112495  */
112496  case PragTyp_SOFT_HEAP_LIMIT: {
112497    sqlite3_int64 N;
112498    if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
112499      sqlite3_soft_heap_limit64(N);
112500    }
112501    returnSingleInt(v, "soft_heap_limit",  sqlite3_soft_heap_limit64(-1));
112502    break;
112503  }
112504
112505  /*
112506  **   PRAGMA threads
112507  **   PRAGMA threads = N
112508  **
112509  ** Configure the maximum number of worker threads.  Return the new
112510  ** maximum, which might be less than requested.
112511  */
112512  case PragTyp_THREADS: {
112513    sqlite3_int64 N;
112514    if( zRight
112515     && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
112516     && N>=0
112517    ){
112518      sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
112519    }
112520    returnSingleInt(v, "threads",
112521                    sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
112522    break;
112523  }
112524
112525#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
112526  /*
112527  ** Report the current state of file logs for all databases
112528  */
112529  case PragTyp_LOCK_STATUS: {
112530    static const char *const azLockName[] = {
112531      "unlocked", "shared", "reserved", "pending", "exclusive"
112532    };
112533    static const char *azCol[] = { "database", "status" };
112534    int i;
112535    setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
112536    pParse->nMem = 2;
112537    for(i=0; i<db->nDb; i++){
112538      Btree *pBt;
112539      const char *zState = "unknown";
112540      int j;
112541      if( db->aDb[i].zName==0 ) continue;
112542      pBt = db->aDb[i].pBt;
112543      if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
112544        zState = "closed";
112545      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
112546                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
112547         zState = azLockName[j];
112548      }
112549      sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zName, zState);
112550      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
112551    }
112552    break;
112553  }
112554#endif
112555
112556#ifdef SQLITE_HAS_CODEC
112557  case PragTyp_KEY: {
112558    if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
112559    break;
112560  }
112561  case PragTyp_REKEY: {
112562    if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
112563    break;
112564  }
112565  case PragTyp_HEXKEY: {
112566    if( zRight ){
112567      u8 iByte;
112568      int i;
112569      char zKey[40];
112570      for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
112571        iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
112572        if( (i&1)!=0 ) zKey[i/2] = iByte;
112573      }
112574      if( (zLeft[3] & 0xf)==0xb ){
112575        sqlite3_key_v2(db, zDb, zKey, i/2);
112576      }else{
112577        sqlite3_rekey_v2(db, zDb, zKey, i/2);
112578      }
112579    }
112580    break;
112581  }
112582#endif
112583#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
112584  case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
112585#ifdef SQLITE_HAS_CODEC
112586    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
112587      sqlite3_activate_see(&zRight[4]);
112588    }
112589#endif
112590#ifdef SQLITE_ENABLE_CEROD
112591    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
112592      sqlite3_activate_cerod(&zRight[6]);
112593    }
112594#endif
112595  }
112596  break;
112597#endif
112598
112599  } /* End of the PRAGMA switch */
112600
112601pragma_out:
112602  sqlite3DbFree(db, zLeft);
112603  sqlite3DbFree(db, zRight);
112604}
112605
112606#endif /* SQLITE_OMIT_PRAGMA */
112607
112608/************** End of pragma.c **********************************************/
112609/************** Begin file prepare.c *****************************************/
112610/*
112611** 2005 May 25
112612**
112613** The author disclaims copyright to this source code.  In place of
112614** a legal notice, here is a blessing:
112615**
112616**    May you do good and not evil.
112617**    May you find forgiveness for yourself and forgive others.
112618**    May you share freely, never taking more than you give.
112619**
112620*************************************************************************
112621** This file contains the implementation of the sqlite3_prepare()
112622** interface, and routines that contribute to loading the database schema
112623** from disk.
112624*/
112625/* #include "sqliteInt.h" */
112626
112627/*
112628** Fill the InitData structure with an error message that indicates
112629** that the database is corrupt.
112630*/
112631static void corruptSchema(
112632  InitData *pData,     /* Initialization context */
112633  const char *zObj,    /* Object being parsed at the point of error */
112634  const char *zExtra   /* Error information */
112635){
112636  sqlite3 *db = pData->db;
112637  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
112638    char *z;
112639    if( zObj==0 ) zObj = "?";
112640    z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
112641    if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
112642    sqlite3DbFree(db, *pData->pzErrMsg);
112643    *pData->pzErrMsg = z;
112644  }
112645  pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT;
112646}
112647
112648/*
112649** This is the callback routine for the code that initializes the
112650** database.  See sqlite3Init() below for additional information.
112651** This routine is also called from the OP_ParseSchema opcode of the VDBE.
112652**
112653** Each callback contains the following information:
112654**
112655**     argv[0] = name of thing being created
112656**     argv[1] = root page number for table or index. 0 for trigger or view.
112657**     argv[2] = SQL text for the CREATE statement.
112658**
112659*/
112660SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
112661  InitData *pData = (InitData*)pInit;
112662  sqlite3 *db = pData->db;
112663  int iDb = pData->iDb;
112664
112665  assert( argc==3 );
112666  UNUSED_PARAMETER2(NotUsed, argc);
112667  assert( sqlite3_mutex_held(db->mutex) );
112668  DbClearProperty(db, iDb, DB_Empty);
112669  if( db->mallocFailed ){
112670    corruptSchema(pData, argv[0], 0);
112671    return 1;
112672  }
112673
112674  assert( iDb>=0 && iDb<db->nDb );
112675  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
112676  if( argv[1]==0 ){
112677    corruptSchema(pData, argv[0], 0);
112678  }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
112679    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
112680    ** But because db->init.busy is set to 1, no VDBE code is generated
112681    ** or executed.  All the parser does is build the internal data
112682    ** structures that describe the table, index, or view.
112683    */
112684    int rc;
112685    sqlite3_stmt *pStmt;
112686    TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
112687
112688    assert( db->init.busy );
112689    db->init.iDb = iDb;
112690    db->init.newTnum = sqlite3Atoi(argv[1]);
112691    db->init.orphanTrigger = 0;
112692    TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
112693    rc = db->errCode;
112694    assert( (rc&0xFF)==(rcp&0xFF) );
112695    db->init.iDb = 0;
112696    if( SQLITE_OK!=rc ){
112697      if( db->init.orphanTrigger ){
112698        assert( iDb==1 );
112699      }else{
112700        pData->rc = rc;
112701        if( rc==SQLITE_NOMEM ){
112702          sqlite3OomFault(db);
112703        }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
112704          corruptSchema(pData, argv[0], sqlite3_errmsg(db));
112705        }
112706      }
112707    }
112708    sqlite3_finalize(pStmt);
112709  }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
112710    corruptSchema(pData, argv[0], 0);
112711  }else{
112712    /* If the SQL column is blank it means this is an index that
112713    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
112714    ** constraint for a CREATE TABLE.  The index should have already
112715    ** been created when we processed the CREATE TABLE.  All we have
112716    ** to do here is record the root page number for that index.
112717    */
112718    Index *pIndex;
112719    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
112720    if( pIndex==0 ){
112721      /* This can occur if there exists an index on a TEMP table which
112722      ** has the same name as another index on a permanent index.  Since
112723      ** the permanent table is hidden by the TEMP table, we can also
112724      ** safely ignore the index on the permanent table.
112725      */
112726      /* Do Nothing */;
112727    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
112728      corruptSchema(pData, argv[0], "invalid rootpage");
112729    }
112730  }
112731  return 0;
112732}
112733
112734/*
112735** Attempt to read the database schema and initialize internal
112736** data structures for a single database file.  The index of the
112737** database file is given by iDb.  iDb==0 is used for the main
112738** database.  iDb==1 should never be used.  iDb>=2 is used for
112739** auxiliary databases.  Return one of the SQLITE_ error codes to
112740** indicate success or failure.
112741*/
112742static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
112743  int rc;
112744  int i;
112745#ifndef SQLITE_OMIT_DEPRECATED
112746  int size;
112747#endif
112748  Db *pDb;
112749  char const *azArg[4];
112750  int meta[5];
112751  InitData initData;
112752  const char *zMasterName;
112753  int openedTransaction = 0;
112754
112755  assert( iDb>=0 && iDb<db->nDb );
112756  assert( db->aDb[iDb].pSchema );
112757  assert( sqlite3_mutex_held(db->mutex) );
112758  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
112759
112760  /* Construct the in-memory representation schema tables (sqlite_master or
112761  ** sqlite_temp_master) by invoking the parser directly.  The appropriate
112762  ** table name will be inserted automatically by the parser so we can just
112763  ** use the abbreviation "x" here.  The parser will also automatically tag
112764  ** the schema table as read-only. */
112765  azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
112766  azArg[1] = "1";
112767  azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
112768                            "rootpage integer,sql text)";
112769  azArg[3] = 0;
112770  initData.db = db;
112771  initData.iDb = iDb;
112772  initData.rc = SQLITE_OK;
112773  initData.pzErrMsg = pzErrMsg;
112774  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
112775  if( initData.rc ){
112776    rc = initData.rc;
112777    goto error_out;
112778  }
112779
112780  /* Create a cursor to hold the database open
112781  */
112782  pDb = &db->aDb[iDb];
112783  if( pDb->pBt==0 ){
112784    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
112785      DbSetProperty(db, 1, DB_SchemaLoaded);
112786    }
112787    return SQLITE_OK;
112788  }
112789
112790  /* If there is not already a read-only (or read-write) transaction opened
112791  ** on the b-tree database, open one now. If a transaction is opened, it
112792  ** will be closed before this function returns.  */
112793  sqlite3BtreeEnter(pDb->pBt);
112794  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
112795    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
112796    if( rc!=SQLITE_OK ){
112797      sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
112798      goto initone_error_out;
112799    }
112800    openedTransaction = 1;
112801  }
112802
112803  /* Get the database meta information.
112804  **
112805  ** Meta values are as follows:
112806  **    meta[0]   Schema cookie.  Changes with each schema change.
112807  **    meta[1]   File format of schema layer.
112808  **    meta[2]   Size of the page cache.
112809  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
112810  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
112811  **    meta[5]   User version
112812  **    meta[6]   Incremental vacuum mode
112813  **    meta[7]   unused
112814  **    meta[8]   unused
112815  **    meta[9]   unused
112816  **
112817  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
112818  ** the possible values of meta[4].
112819  */
112820  for(i=0; i<ArraySize(meta); i++){
112821    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
112822  }
112823  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
112824
112825  /* If opening a non-empty database, check the text encoding. For the
112826  ** main database, set sqlite3.enc to the encoding of the main database.
112827  ** For an attached db, it is an error if the encoding is not the same
112828  ** as sqlite3.enc.
112829  */
112830  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
112831    if( iDb==0 ){
112832#ifndef SQLITE_OMIT_UTF16
112833      u8 encoding;
112834      /* If opening the main database, set ENC(db). */
112835      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
112836      if( encoding==0 ) encoding = SQLITE_UTF8;
112837      ENC(db) = encoding;
112838#else
112839      ENC(db) = SQLITE_UTF8;
112840#endif
112841    }else{
112842      /* If opening an attached database, the encoding much match ENC(db) */
112843      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
112844        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
112845            " text encoding as main database");
112846        rc = SQLITE_ERROR;
112847        goto initone_error_out;
112848      }
112849    }
112850  }else{
112851    DbSetProperty(db, iDb, DB_Empty);
112852  }
112853  pDb->pSchema->enc = ENC(db);
112854
112855  if( pDb->pSchema->cache_size==0 ){
112856#ifndef SQLITE_OMIT_DEPRECATED
112857    size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
112858    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
112859    pDb->pSchema->cache_size = size;
112860#else
112861    pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
112862#endif
112863    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
112864  }
112865
112866  /*
112867  ** file_format==1    Version 3.0.0.
112868  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
112869  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
112870  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
112871  */
112872  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
112873  if( pDb->pSchema->file_format==0 ){
112874    pDb->pSchema->file_format = 1;
112875  }
112876  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
112877    sqlite3SetString(pzErrMsg, db, "unsupported file format");
112878    rc = SQLITE_ERROR;
112879    goto initone_error_out;
112880  }
112881
112882  /* Ticket #2804:  When we open a database in the newer file format,
112883  ** clear the legacy_file_format pragma flag so that a VACUUM will
112884  ** not downgrade the database and thus invalidate any descending
112885  ** indices that the user might have created.
112886  */
112887  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
112888    db->flags &= ~SQLITE_LegacyFileFmt;
112889  }
112890
112891  /* Read the schema information out of the schema tables
112892  */
112893  assert( db->init.busy );
112894  {
112895    char *zSql;
112896    zSql = sqlite3MPrintf(db,
112897        "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
112898        db->aDb[iDb].zName, zMasterName);
112899#ifndef SQLITE_OMIT_AUTHORIZATION
112900    {
112901      sqlite3_xauth xAuth;
112902      xAuth = db->xAuth;
112903      db->xAuth = 0;
112904#endif
112905      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
112906#ifndef SQLITE_OMIT_AUTHORIZATION
112907      db->xAuth = xAuth;
112908    }
112909#endif
112910    if( rc==SQLITE_OK ) rc = initData.rc;
112911    sqlite3DbFree(db, zSql);
112912#ifndef SQLITE_OMIT_ANALYZE
112913    if( rc==SQLITE_OK ){
112914      sqlite3AnalysisLoad(db, iDb);
112915    }
112916#endif
112917  }
112918  if( db->mallocFailed ){
112919    rc = SQLITE_NOMEM_BKPT;
112920    sqlite3ResetAllSchemasOfConnection(db);
112921  }
112922  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
112923    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
112924    ** the schema loaded, even if errors occurred. In this situation the
112925    ** current sqlite3_prepare() operation will fail, but the following one
112926    ** will attempt to compile the supplied statement against whatever subset
112927    ** of the schema was loaded before the error occurred. The primary
112928    ** purpose of this is to allow access to the sqlite_master table
112929    ** even when its contents have been corrupted.
112930    */
112931    DbSetProperty(db, iDb, DB_SchemaLoaded);
112932    rc = SQLITE_OK;
112933  }
112934
112935  /* Jump here for an error that occurs after successfully allocating
112936  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
112937  ** before that point, jump to error_out.
112938  */
112939initone_error_out:
112940  if( openedTransaction ){
112941    sqlite3BtreeCommit(pDb->pBt);
112942  }
112943  sqlite3BtreeLeave(pDb->pBt);
112944
112945error_out:
112946  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
112947    sqlite3OomFault(db);
112948  }
112949  return rc;
112950}
112951
112952/*
112953** Initialize all database files - the main database file, the file
112954** used to store temporary tables, and any additional database files
112955** created using ATTACH statements.  Return a success code.  If an
112956** error occurs, write an error message into *pzErrMsg.
112957**
112958** After a database is initialized, the DB_SchemaLoaded bit is set
112959** bit is set in the flags field of the Db structure. If the database
112960** file was of zero-length, then the DB_Empty flag is also set.
112961*/
112962SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
112963  int i, rc;
112964  int commit_internal = !(db->flags&SQLITE_InternChanges);
112965
112966  assert( sqlite3_mutex_held(db->mutex) );
112967  assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
112968  assert( db->init.busy==0 );
112969  rc = SQLITE_OK;
112970  db->init.busy = 1;
112971  ENC(db) = SCHEMA_ENC(db);
112972  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
112973    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
112974    rc = sqlite3InitOne(db, i, pzErrMsg);
112975    if( rc ){
112976      sqlite3ResetOneSchema(db, i);
112977    }
112978  }
112979
112980  /* Once all the other databases have been initialized, load the schema
112981  ** for the TEMP database. This is loaded last, as the TEMP database
112982  ** schema may contain references to objects in other databases.
112983  */
112984#ifndef SQLITE_OMIT_TEMPDB
112985  assert( db->nDb>1 );
112986  if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
112987    rc = sqlite3InitOne(db, 1, pzErrMsg);
112988    if( rc ){
112989      sqlite3ResetOneSchema(db, 1);
112990    }
112991  }
112992#endif
112993
112994  db->init.busy = 0;
112995  if( rc==SQLITE_OK && commit_internal ){
112996    sqlite3CommitInternalChanges(db);
112997  }
112998
112999  return rc;
113000}
113001
113002/*
113003** This routine is a no-op if the database schema is already initialized.
113004** Otherwise, the schema is loaded. An error code is returned.
113005*/
113006SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
113007  int rc = SQLITE_OK;
113008  sqlite3 *db = pParse->db;
113009  assert( sqlite3_mutex_held(db->mutex) );
113010  if( !db->init.busy ){
113011    rc = sqlite3Init(db, &pParse->zErrMsg);
113012  }
113013  if( rc!=SQLITE_OK ){
113014    pParse->rc = rc;
113015    pParse->nErr++;
113016  }
113017  return rc;
113018}
113019
113020
113021/*
113022** Check schema cookies in all databases.  If any cookie is out
113023** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
113024** make no changes to pParse->rc.
113025*/
113026static void schemaIsValid(Parse *pParse){
113027  sqlite3 *db = pParse->db;
113028  int iDb;
113029  int rc;
113030  int cookie;
113031
113032  assert( pParse->checkSchema );
113033  assert( sqlite3_mutex_held(db->mutex) );
113034  for(iDb=0; iDb<db->nDb; iDb++){
113035    int openedTransaction = 0;         /* True if a transaction is opened */
113036    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
113037    if( pBt==0 ) continue;
113038
113039    /* If there is not already a read-only (or read-write) transaction opened
113040    ** on the b-tree database, open one now. If a transaction is opened, it
113041    ** will be closed immediately after reading the meta-value. */
113042    if( !sqlite3BtreeIsInReadTrans(pBt) ){
113043      rc = sqlite3BtreeBeginTrans(pBt, 0);
113044      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
113045        sqlite3OomFault(db);
113046      }
113047      if( rc!=SQLITE_OK ) return;
113048      openedTransaction = 1;
113049    }
113050
113051    /* Read the schema cookie from the database. If it does not match the
113052    ** value stored as part of the in-memory schema representation,
113053    ** set Parse.rc to SQLITE_SCHEMA. */
113054    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
113055    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
113056    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
113057      sqlite3ResetOneSchema(db, iDb);
113058      pParse->rc = SQLITE_SCHEMA;
113059    }
113060
113061    /* Close the transaction, if one was opened. */
113062    if( openedTransaction ){
113063      sqlite3BtreeCommit(pBt);
113064    }
113065  }
113066}
113067
113068/*
113069** Convert a schema pointer into the iDb index that indicates
113070** which database file in db->aDb[] the schema refers to.
113071**
113072** If the same database is attached more than once, the first
113073** attached database is returned.
113074*/
113075SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
113076  int i = -1000000;
113077
113078  /* If pSchema is NULL, then return -1000000. This happens when code in
113079  ** expr.c is trying to resolve a reference to a transient table (i.e. one
113080  ** created by a sub-select). In this case the return value of this
113081  ** function should never be used.
113082  **
113083  ** We return -1000000 instead of the more usual -1 simply because using
113084  ** -1000000 as the incorrect index into db->aDb[] is much
113085  ** more likely to cause a segfault than -1 (of course there are assert()
113086  ** statements too, but it never hurts to play the odds).
113087  */
113088  assert( sqlite3_mutex_held(db->mutex) );
113089  if( pSchema ){
113090    for(i=0; ALWAYS(i<db->nDb); i++){
113091      if( db->aDb[i].pSchema==pSchema ){
113092        break;
113093      }
113094    }
113095    assert( i>=0 && i<db->nDb );
113096  }
113097  return i;
113098}
113099
113100/*
113101** Free all memory allocations in the pParse object
113102*/
113103SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
113104  if( pParse ){
113105    sqlite3 *db = pParse->db;
113106    sqlite3DbFree(db, pParse->aLabel);
113107    sqlite3ExprListDelete(db, pParse->pConstExpr);
113108    if( db ){
113109      assert( db->lookaside.bDisable >= pParse->disableLookaside );
113110      db->lookaside.bDisable -= pParse->disableLookaside;
113111    }
113112    pParse->disableLookaside = 0;
113113  }
113114}
113115
113116/*
113117** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
113118*/
113119static int sqlite3Prepare(
113120  sqlite3 *db,              /* Database handle. */
113121  const char *zSql,         /* UTF-8 encoded SQL statement. */
113122  int nBytes,               /* Length of zSql in bytes. */
113123  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
113124  Vdbe *pReprepare,         /* VM being reprepared */
113125  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113126  const char **pzTail       /* OUT: End of parsed string */
113127){
113128  Parse *pParse;            /* Parsing context */
113129  char *zErrMsg = 0;        /* Error message */
113130  int rc = SQLITE_OK;       /* Result code */
113131  int i;                    /* Loop counter */
113132
113133  /* Allocate the parsing context */
113134  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
113135  if( pParse==0 ){
113136    rc = SQLITE_NOMEM_BKPT;
113137    goto end_prepare;
113138  }
113139  pParse->pReprepare = pReprepare;
113140  assert( ppStmt && *ppStmt==0 );
113141  /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
113142  assert( sqlite3_mutex_held(db->mutex) );
113143
113144  /* Check to verify that it is possible to get a read lock on all
113145  ** database schemas.  The inability to get a read lock indicates that
113146  ** some other database connection is holding a write-lock, which in
113147  ** turn means that the other connection has made uncommitted changes
113148  ** to the schema.
113149  **
113150  ** Were we to proceed and prepare the statement against the uncommitted
113151  ** schema changes and if those schema changes are subsequently rolled
113152  ** back and different changes are made in their place, then when this
113153  ** prepared statement goes to run the schema cookie would fail to detect
113154  ** the schema change.  Disaster would follow.
113155  **
113156  ** This thread is currently holding mutexes on all Btrees (because
113157  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
113158  ** is not possible for another thread to start a new schema change
113159  ** while this routine is running.  Hence, we do not need to hold
113160  ** locks on the schema, we just need to make sure nobody else is
113161  ** holding them.
113162  **
113163  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
113164  ** but it does *not* override schema lock detection, so this all still
113165  ** works even if READ_UNCOMMITTED is set.
113166  */
113167  for(i=0; i<db->nDb; i++) {
113168    Btree *pBt = db->aDb[i].pBt;
113169    if( pBt ){
113170      assert( sqlite3BtreeHoldsMutex(pBt) );
113171      rc = sqlite3BtreeSchemaLocked(pBt);
113172      if( rc ){
113173        const char *zDb = db->aDb[i].zName;
113174        sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
113175        testcase( db->flags & SQLITE_ReadUncommitted );
113176        goto end_prepare;
113177      }
113178    }
113179  }
113180
113181  sqlite3VtabUnlockList(db);
113182
113183  pParse->db = db;
113184  pParse->nQueryLoop = 0;  /* Logarithmic, so 0 really means 1 */
113185  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
113186    char *zSqlCopy;
113187    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
113188    testcase( nBytes==mxLen );
113189    testcase( nBytes==mxLen+1 );
113190    if( nBytes>mxLen ){
113191      sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
113192      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
113193      goto end_prepare;
113194    }
113195    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
113196    if( zSqlCopy ){
113197      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
113198      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
113199      sqlite3DbFree(db, zSqlCopy);
113200    }else{
113201      pParse->zTail = &zSql[nBytes];
113202    }
113203  }else{
113204    sqlite3RunParser(pParse, zSql, &zErrMsg);
113205  }
113206  assert( 0==pParse->nQueryLoop );
113207
113208  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
113209  if( pParse->checkSchema ){
113210    schemaIsValid(pParse);
113211  }
113212  if( db->mallocFailed ){
113213    pParse->rc = SQLITE_NOMEM_BKPT;
113214  }
113215  if( pzTail ){
113216    *pzTail = pParse->zTail;
113217  }
113218  rc = pParse->rc;
113219
113220#ifndef SQLITE_OMIT_EXPLAIN
113221  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
113222    static const char * const azColName[] = {
113223       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
113224       "selectid", "order", "from", "detail"
113225    };
113226    int iFirst, mx;
113227    if( pParse->explain==2 ){
113228      sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
113229      iFirst = 8;
113230      mx = 12;
113231    }else{
113232      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
113233      iFirst = 0;
113234      mx = 8;
113235    }
113236    for(i=iFirst; i<mx; i++){
113237      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
113238                            azColName[i], SQLITE_STATIC);
113239    }
113240  }
113241#endif
113242
113243  if( db->init.busy==0 ){
113244    Vdbe *pVdbe = pParse->pVdbe;
113245    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
113246  }
113247  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
113248    sqlite3VdbeFinalize(pParse->pVdbe);
113249    assert(!(*ppStmt));
113250  }else{
113251    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
113252  }
113253
113254  if( zErrMsg ){
113255    sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
113256    sqlite3DbFree(db, zErrMsg);
113257  }else{
113258    sqlite3Error(db, rc);
113259  }
113260
113261  /* Delete any TriggerPrg structures allocated while parsing this statement. */
113262  while( pParse->pTriggerPrg ){
113263    TriggerPrg *pT = pParse->pTriggerPrg;
113264    pParse->pTriggerPrg = pT->pNext;
113265    sqlite3DbFree(db, pT);
113266  }
113267
113268end_prepare:
113269
113270  sqlite3ParserReset(pParse);
113271  sqlite3StackFree(db, pParse);
113272  rc = sqlite3ApiExit(db, rc);
113273  assert( (rc&db->errMask)==rc );
113274  return rc;
113275}
113276static int sqlite3LockAndPrepare(
113277  sqlite3 *db,              /* Database handle. */
113278  const char *zSql,         /* UTF-8 encoded SQL statement. */
113279  int nBytes,               /* Length of zSql in bytes. */
113280  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
113281  Vdbe *pOld,               /* VM being reprepared */
113282  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113283  const char **pzTail       /* OUT: End of parsed string */
113284){
113285  int rc;
113286
113287#ifdef SQLITE_ENABLE_API_ARMOR
113288  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
113289#endif
113290  *ppStmt = 0;
113291  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
113292    return SQLITE_MISUSE_BKPT;
113293  }
113294  sqlite3_mutex_enter(db->mutex);
113295  sqlite3BtreeEnterAll(db);
113296  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
113297  if( rc==SQLITE_SCHEMA ){
113298    sqlite3_finalize(*ppStmt);
113299    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
113300  }
113301  sqlite3BtreeLeaveAll(db);
113302  sqlite3_mutex_leave(db->mutex);
113303  assert( rc==SQLITE_OK || *ppStmt==0 );
113304  return rc;
113305}
113306
113307/*
113308** Rerun the compilation of a statement after a schema change.
113309**
113310** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
113311** if the statement cannot be recompiled because another connection has
113312** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
113313** occurs, return SQLITE_SCHEMA.
113314*/
113315SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
113316  int rc;
113317  sqlite3_stmt *pNew;
113318  const char *zSql;
113319  sqlite3 *db;
113320
113321  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
113322  zSql = sqlite3_sql((sqlite3_stmt *)p);
113323  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
113324  db = sqlite3VdbeDb(p);
113325  assert( sqlite3_mutex_held(db->mutex) );
113326  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
113327  if( rc ){
113328    if( rc==SQLITE_NOMEM ){
113329      sqlite3OomFault(db);
113330    }
113331    assert( pNew==0 );
113332    return rc;
113333  }else{
113334    assert( pNew!=0 );
113335  }
113336  sqlite3VdbeSwap((Vdbe*)pNew, p);
113337  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
113338  sqlite3VdbeResetStepResult((Vdbe*)pNew);
113339  sqlite3VdbeFinalize((Vdbe*)pNew);
113340  return SQLITE_OK;
113341}
113342
113343
113344/*
113345** Two versions of the official API.  Legacy and new use.  In the legacy
113346** version, the original SQL text is not saved in the prepared statement
113347** and so if a schema change occurs, SQLITE_SCHEMA is returned by
113348** sqlite3_step().  In the new version, the original SQL text is retained
113349** and the statement is automatically recompiled if an schema change
113350** occurs.
113351*/
113352SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
113353  sqlite3 *db,              /* Database handle. */
113354  const char *zSql,         /* UTF-8 encoded SQL statement. */
113355  int nBytes,               /* Length of zSql in bytes. */
113356  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113357  const char **pzTail       /* OUT: End of parsed string */
113358){
113359  int rc;
113360  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
113361  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
113362  return rc;
113363}
113364SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
113365  sqlite3 *db,              /* Database handle. */
113366  const char *zSql,         /* UTF-8 encoded SQL statement. */
113367  int nBytes,               /* Length of zSql in bytes. */
113368  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113369  const char **pzTail       /* OUT: End of parsed string */
113370){
113371  int rc;
113372  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
113373  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
113374  return rc;
113375}
113376
113377
113378#ifndef SQLITE_OMIT_UTF16
113379/*
113380** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
113381*/
113382static int sqlite3Prepare16(
113383  sqlite3 *db,              /* Database handle. */
113384  const void *zSql,         /* UTF-16 encoded SQL statement. */
113385  int nBytes,               /* Length of zSql in bytes. */
113386  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
113387  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113388  const void **pzTail       /* OUT: End of parsed string */
113389){
113390  /* This function currently works by first transforming the UTF-16
113391  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
113392  ** tricky bit is figuring out the pointer to return in *pzTail.
113393  */
113394  char *zSql8;
113395  const char *zTail8 = 0;
113396  int rc = SQLITE_OK;
113397
113398#ifdef SQLITE_ENABLE_API_ARMOR
113399  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
113400#endif
113401  *ppStmt = 0;
113402  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
113403    return SQLITE_MISUSE_BKPT;
113404  }
113405  if( nBytes>=0 ){
113406    int sz;
113407    const char *z = (const char*)zSql;
113408    for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
113409    nBytes = sz;
113410  }
113411  sqlite3_mutex_enter(db->mutex);
113412  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
113413  if( zSql8 ){
113414    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
113415  }
113416
113417  if( zTail8 && pzTail ){
113418    /* If sqlite3_prepare returns a tail pointer, we calculate the
113419    ** equivalent pointer into the UTF-16 string by counting the unicode
113420    ** characters between zSql8 and zTail8, and then returning a pointer
113421    ** the same number of characters into the UTF-16 string.
113422    */
113423    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
113424    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
113425  }
113426  sqlite3DbFree(db, zSql8);
113427  rc = sqlite3ApiExit(db, rc);
113428  sqlite3_mutex_leave(db->mutex);
113429  return rc;
113430}
113431
113432/*
113433** Two versions of the official API.  Legacy and new use.  In the legacy
113434** version, the original SQL text is not saved in the prepared statement
113435** and so if a schema change occurs, SQLITE_SCHEMA is returned by
113436** sqlite3_step().  In the new version, the original SQL text is retained
113437** and the statement is automatically recompiled if an schema change
113438** occurs.
113439*/
113440SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
113441  sqlite3 *db,              /* Database handle. */
113442  const void *zSql,         /* UTF-16 encoded SQL statement. */
113443  int nBytes,               /* Length of zSql in bytes. */
113444  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113445  const void **pzTail       /* OUT: End of parsed string */
113446){
113447  int rc;
113448  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
113449  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
113450  return rc;
113451}
113452SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
113453  sqlite3 *db,              /* Database handle. */
113454  const void *zSql,         /* UTF-16 encoded SQL statement. */
113455  int nBytes,               /* Length of zSql in bytes. */
113456  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113457  const void **pzTail       /* OUT: End of parsed string */
113458){
113459  int rc;
113460  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
113461  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
113462  return rc;
113463}
113464
113465#endif /* SQLITE_OMIT_UTF16 */
113466
113467/************** End of prepare.c *********************************************/
113468/************** Begin file select.c ******************************************/
113469/*
113470** 2001 September 15
113471**
113472** The author disclaims copyright to this source code.  In place of
113473** a legal notice, here is a blessing:
113474**
113475**    May you do good and not evil.
113476**    May you find forgiveness for yourself and forgive others.
113477**    May you share freely, never taking more than you give.
113478**
113479*************************************************************************
113480** This file contains C code routines that are called by the parser
113481** to handle SELECT statements in SQLite.
113482*/
113483/* #include "sqliteInt.h" */
113484
113485/*
113486** Trace output macros
113487*/
113488#if SELECTTRACE_ENABLED
113489/***/ int sqlite3SelectTrace = 0;
113490# define SELECTTRACE(K,P,S,X)  \
113491  if(sqlite3SelectTrace&(K))   \
113492    sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
113493        (S)->zSelName,(S)),\
113494    sqlite3DebugPrintf X
113495#else
113496# define SELECTTRACE(K,P,S,X)
113497#endif
113498
113499
113500/*
113501** An instance of the following object is used to record information about
113502** how to process the DISTINCT keyword, to simplify passing that information
113503** into the selectInnerLoop() routine.
113504*/
113505typedef struct DistinctCtx DistinctCtx;
113506struct DistinctCtx {
113507  u8 isTnct;      /* True if the DISTINCT keyword is present */
113508  u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
113509  int tabTnct;    /* Ephemeral table used for DISTINCT processing */
113510  int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
113511};
113512
113513/*
113514** An instance of the following object is used to record information about
113515** the ORDER BY (or GROUP BY) clause of query is being coded.
113516*/
113517typedef struct SortCtx SortCtx;
113518struct SortCtx {
113519  ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
113520  int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
113521  int iECursor;         /* Cursor number for the sorter */
113522  int regReturn;        /* Register holding block-output return address */
113523  int labelBkOut;       /* Start label for the block-output subroutine */
113524  int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
113525  int labelDone;        /* Jump here when done, ex: LIMIT reached */
113526  u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
113527  u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */
113528};
113529#define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
113530
113531/*
113532** Delete all the content of a Select structure.  Deallocate the structure
113533** itself only if bFree is true.
113534*/
113535static void clearSelect(sqlite3 *db, Select *p, int bFree){
113536  while( p ){
113537    Select *pPrior = p->pPrior;
113538    sqlite3ExprListDelete(db, p->pEList);
113539    sqlite3SrcListDelete(db, p->pSrc);
113540    sqlite3ExprDelete(db, p->pWhere);
113541    sqlite3ExprListDelete(db, p->pGroupBy);
113542    sqlite3ExprDelete(db, p->pHaving);
113543    sqlite3ExprListDelete(db, p->pOrderBy);
113544    sqlite3ExprDelete(db, p->pLimit);
113545    sqlite3ExprDelete(db, p->pOffset);
113546    if( p->pWith ) sqlite3WithDelete(db, p->pWith);
113547    if( bFree ) sqlite3DbFree(db, p);
113548    p = pPrior;
113549    bFree = 1;
113550  }
113551}
113552
113553/*
113554** Initialize a SelectDest structure.
113555*/
113556SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
113557  pDest->eDest = (u8)eDest;
113558  pDest->iSDParm = iParm;
113559  pDest->affSdst = 0;
113560  pDest->iSdst = 0;
113561  pDest->nSdst = 0;
113562}
113563
113564
113565/*
113566** Allocate a new Select structure and return a pointer to that
113567** structure.
113568*/
113569SQLITE_PRIVATE Select *sqlite3SelectNew(
113570  Parse *pParse,        /* Parsing context */
113571  ExprList *pEList,     /* which columns to include in the result */
113572  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
113573  Expr *pWhere,         /* the WHERE clause */
113574  ExprList *pGroupBy,   /* the GROUP BY clause */
113575  Expr *pHaving,        /* the HAVING clause */
113576  ExprList *pOrderBy,   /* the ORDER BY clause */
113577  u32 selFlags,         /* Flag parameters, such as SF_Distinct */
113578  Expr *pLimit,         /* LIMIT value.  NULL means not used */
113579  Expr *pOffset         /* OFFSET value.  NULL means no offset */
113580){
113581  Select *pNew;
113582  Select standin;
113583  sqlite3 *db = pParse->db;
113584  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
113585  if( pNew==0 ){
113586    assert( db->mallocFailed );
113587    pNew = &standin;
113588  }
113589  if( pEList==0 ){
113590    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ASTERISK,0));
113591  }
113592  pNew->pEList = pEList;
113593  pNew->op = TK_SELECT;
113594  pNew->selFlags = selFlags;
113595  pNew->iLimit = 0;
113596  pNew->iOffset = 0;
113597#if SELECTTRACE_ENABLED
113598  pNew->zSelName[0] = 0;
113599#endif
113600  pNew->addrOpenEphm[0] = -1;
113601  pNew->addrOpenEphm[1] = -1;
113602  pNew->nSelectRow = 0;
113603  if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
113604  pNew->pSrc = pSrc;
113605  pNew->pWhere = pWhere;
113606  pNew->pGroupBy = pGroupBy;
113607  pNew->pHaving = pHaving;
113608  pNew->pOrderBy = pOrderBy;
113609  pNew->pPrior = 0;
113610  pNew->pNext = 0;
113611  pNew->pLimit = pLimit;
113612  pNew->pOffset = pOffset;
113613  pNew->pWith = 0;
113614  assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
113615  if( db->mallocFailed ) {
113616    clearSelect(db, pNew, pNew!=&standin);
113617    pNew = 0;
113618  }else{
113619    assert( pNew->pSrc!=0 || pParse->nErr>0 );
113620  }
113621  assert( pNew!=&standin );
113622  return pNew;
113623}
113624
113625#if SELECTTRACE_ENABLED
113626/*
113627** Set the name of a Select object
113628*/
113629SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
113630  if( p && zName ){
113631    sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
113632  }
113633}
113634#endif
113635
113636
113637/*
113638** Delete the given Select structure and all of its substructures.
113639*/
113640SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
113641  if( p ) clearSelect(db, p, 1);
113642}
113643
113644/*
113645** Return a pointer to the right-most SELECT statement in a compound.
113646*/
113647static Select *findRightmost(Select *p){
113648  while( p->pNext ) p = p->pNext;
113649  return p;
113650}
113651
113652/*
113653** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
113654** type of join.  Return an integer constant that expresses that type
113655** in terms of the following bit values:
113656**
113657**     JT_INNER
113658**     JT_CROSS
113659**     JT_OUTER
113660**     JT_NATURAL
113661**     JT_LEFT
113662**     JT_RIGHT
113663**
113664** A full outer join is the combination of JT_LEFT and JT_RIGHT.
113665**
113666** If an illegal or unsupported join type is seen, then still return
113667** a join type, but put an error in the pParse structure.
113668*/
113669SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
113670  int jointype = 0;
113671  Token *apAll[3];
113672  Token *p;
113673                             /*   0123456789 123456789 123456789 123 */
113674  static const char zKeyText[] = "naturaleftouterightfullinnercross";
113675  static const struct {
113676    u8 i;        /* Beginning of keyword text in zKeyText[] */
113677    u8 nChar;    /* Length of the keyword in characters */
113678    u8 code;     /* Join type mask */
113679  } aKeyword[] = {
113680    /* natural */ { 0,  7, JT_NATURAL                },
113681    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
113682    /* outer   */ { 10, 5, JT_OUTER                  },
113683    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
113684    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
113685    /* inner   */ { 23, 5, JT_INNER                  },
113686    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
113687  };
113688  int i, j;
113689  apAll[0] = pA;
113690  apAll[1] = pB;
113691  apAll[2] = pC;
113692  for(i=0; i<3 && apAll[i]; i++){
113693    p = apAll[i];
113694    for(j=0; j<ArraySize(aKeyword); j++){
113695      if( p->n==aKeyword[j].nChar
113696          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
113697        jointype |= aKeyword[j].code;
113698        break;
113699      }
113700    }
113701    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
113702    if( j>=ArraySize(aKeyword) ){
113703      jointype |= JT_ERROR;
113704      break;
113705    }
113706  }
113707  if(
113708     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
113709     (jointype & JT_ERROR)!=0
113710  ){
113711    const char *zSp = " ";
113712    assert( pB!=0 );
113713    if( pC==0 ){ zSp++; }
113714    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
113715       "%T %T%s%T", pA, pB, zSp, pC);
113716    jointype = JT_INNER;
113717  }else if( (jointype & JT_OUTER)!=0
113718         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
113719    sqlite3ErrorMsg(pParse,
113720      "RIGHT and FULL OUTER JOINs are not currently supported");
113721    jointype = JT_INNER;
113722  }
113723  return jointype;
113724}
113725
113726/*
113727** Return the index of a column in a table.  Return -1 if the column
113728** is not contained in the table.
113729*/
113730static int columnIndex(Table *pTab, const char *zCol){
113731  int i;
113732  for(i=0; i<pTab->nCol; i++){
113733    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
113734  }
113735  return -1;
113736}
113737
113738/*
113739** Search the first N tables in pSrc, from left to right, looking for a
113740** table that has a column named zCol.
113741**
113742** When found, set *piTab and *piCol to the table index and column index
113743** of the matching column and return TRUE.
113744**
113745** If not found, return FALSE.
113746*/
113747static int tableAndColumnIndex(
113748  SrcList *pSrc,       /* Array of tables to search */
113749  int N,               /* Number of tables in pSrc->a[] to search */
113750  const char *zCol,    /* Name of the column we are looking for */
113751  int *piTab,          /* Write index of pSrc->a[] here */
113752  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
113753){
113754  int i;               /* For looping over tables in pSrc */
113755  int iCol;            /* Index of column matching zCol */
113756
113757  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
113758  for(i=0; i<N; i++){
113759    iCol = columnIndex(pSrc->a[i].pTab, zCol);
113760    if( iCol>=0 ){
113761      if( piTab ){
113762        *piTab = i;
113763        *piCol = iCol;
113764      }
113765      return 1;
113766    }
113767  }
113768  return 0;
113769}
113770
113771/*
113772** This function is used to add terms implied by JOIN syntax to the
113773** WHERE clause expression of a SELECT statement. The new term, which
113774** is ANDed with the existing WHERE clause, is of the form:
113775**
113776**    (tab1.col1 = tab2.col2)
113777**
113778** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
113779** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
113780** column iColRight of tab2.
113781*/
113782static void addWhereTerm(
113783  Parse *pParse,                  /* Parsing context */
113784  SrcList *pSrc,                  /* List of tables in FROM clause */
113785  int iLeft,                      /* Index of first table to join in pSrc */
113786  int iColLeft,                   /* Index of column in first table */
113787  int iRight,                     /* Index of second table in pSrc */
113788  int iColRight,                  /* Index of column in second table */
113789  int isOuterJoin,                /* True if this is an OUTER join */
113790  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
113791){
113792  sqlite3 *db = pParse->db;
113793  Expr *pE1;
113794  Expr *pE2;
113795  Expr *pEq;
113796
113797  assert( iLeft<iRight );
113798  assert( pSrc->nSrc>iRight );
113799  assert( pSrc->a[iLeft].pTab );
113800  assert( pSrc->a[iRight].pTab );
113801
113802  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
113803  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
113804
113805  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
113806  if( pEq && isOuterJoin ){
113807    ExprSetProperty(pEq, EP_FromJoin);
113808    assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
113809    ExprSetVVAProperty(pEq, EP_NoReduce);
113810    pEq->iRightJoinTable = (i16)pE2->iTable;
113811  }
113812  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
113813}
113814
113815/*
113816** Set the EP_FromJoin property on all terms of the given expression.
113817** And set the Expr.iRightJoinTable to iTable for every term in the
113818** expression.
113819**
113820** The EP_FromJoin property is used on terms of an expression to tell
113821** the LEFT OUTER JOIN processing logic that this term is part of the
113822** join restriction specified in the ON or USING clause and not a part
113823** of the more general WHERE clause.  These terms are moved over to the
113824** WHERE clause during join processing but we need to remember that they
113825** originated in the ON or USING clause.
113826**
113827** The Expr.iRightJoinTable tells the WHERE clause processing that the
113828** expression depends on table iRightJoinTable even if that table is not
113829** explicitly mentioned in the expression.  That information is needed
113830** for cases like this:
113831**
113832**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
113833**
113834** The where clause needs to defer the handling of the t1.x=5
113835** term until after the t2 loop of the join.  In that way, a
113836** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
113837** defer the handling of t1.x=5, it will be processed immediately
113838** after the t1 loop and rows with t1.x!=5 will never appear in
113839** the output, which is incorrect.
113840*/
113841static void setJoinExpr(Expr *p, int iTable){
113842  while( p ){
113843    ExprSetProperty(p, EP_FromJoin);
113844    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
113845    ExprSetVVAProperty(p, EP_NoReduce);
113846    p->iRightJoinTable = (i16)iTable;
113847    if( p->op==TK_FUNCTION && p->x.pList ){
113848      int i;
113849      for(i=0; i<p->x.pList->nExpr; i++){
113850        setJoinExpr(p->x.pList->a[i].pExpr, iTable);
113851      }
113852    }
113853    setJoinExpr(p->pLeft, iTable);
113854    p = p->pRight;
113855  }
113856}
113857
113858/*
113859** This routine processes the join information for a SELECT statement.
113860** ON and USING clauses are converted into extra terms of the WHERE clause.
113861** NATURAL joins also create extra WHERE clause terms.
113862**
113863** The terms of a FROM clause are contained in the Select.pSrc structure.
113864** The left most table is the first entry in Select.pSrc.  The right-most
113865** table is the last entry.  The join operator is held in the entry to
113866** the left.  Thus entry 0 contains the join operator for the join between
113867** entries 0 and 1.  Any ON or USING clauses associated with the join are
113868** also attached to the left entry.
113869**
113870** This routine returns the number of errors encountered.
113871*/
113872static int sqliteProcessJoin(Parse *pParse, Select *p){
113873  SrcList *pSrc;                  /* All tables in the FROM clause */
113874  int i, j;                       /* Loop counters */
113875  struct SrcList_item *pLeft;     /* Left table being joined */
113876  struct SrcList_item *pRight;    /* Right table being joined */
113877
113878  pSrc = p->pSrc;
113879  pLeft = &pSrc->a[0];
113880  pRight = &pLeft[1];
113881  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
113882    Table *pLeftTab = pLeft->pTab;
113883    Table *pRightTab = pRight->pTab;
113884    int isOuter;
113885
113886    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
113887    isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
113888
113889    /* When the NATURAL keyword is present, add WHERE clause terms for
113890    ** every column that the two tables have in common.
113891    */
113892    if( pRight->fg.jointype & JT_NATURAL ){
113893      if( pRight->pOn || pRight->pUsing ){
113894        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
113895           "an ON or USING clause", 0);
113896        return 1;
113897      }
113898      for(j=0; j<pRightTab->nCol; j++){
113899        char *zName;   /* Name of column in the right table */
113900        int iLeft;     /* Matching left table */
113901        int iLeftCol;  /* Matching column in the left table */
113902
113903        zName = pRightTab->aCol[j].zName;
113904        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
113905          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
113906                       isOuter, &p->pWhere);
113907        }
113908      }
113909    }
113910
113911    /* Disallow both ON and USING clauses in the same join
113912    */
113913    if( pRight->pOn && pRight->pUsing ){
113914      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
113915        "clauses in the same join");
113916      return 1;
113917    }
113918
113919    /* Add the ON clause to the end of the WHERE clause, connected by
113920    ** an AND operator.
113921    */
113922    if( pRight->pOn ){
113923      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
113924      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
113925      pRight->pOn = 0;
113926    }
113927
113928    /* Create extra terms on the WHERE clause for each column named
113929    ** in the USING clause.  Example: If the two tables to be joined are
113930    ** A and B and the USING clause names X, Y, and Z, then add this
113931    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
113932    ** Report an error if any column mentioned in the USING clause is
113933    ** not contained in both tables to be joined.
113934    */
113935    if( pRight->pUsing ){
113936      IdList *pList = pRight->pUsing;
113937      for(j=0; j<pList->nId; j++){
113938        char *zName;     /* Name of the term in the USING clause */
113939        int iLeft;       /* Table on the left with matching column name */
113940        int iLeftCol;    /* Column number of matching column on the left */
113941        int iRightCol;   /* Column number of matching column on the right */
113942
113943        zName = pList->a[j].zName;
113944        iRightCol = columnIndex(pRightTab, zName);
113945        if( iRightCol<0
113946         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
113947        ){
113948          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
113949            "not present in both tables", zName);
113950          return 1;
113951        }
113952        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
113953                     isOuter, &p->pWhere);
113954      }
113955    }
113956  }
113957  return 0;
113958}
113959
113960/* Forward reference */
113961static KeyInfo *keyInfoFromExprList(
113962  Parse *pParse,       /* Parsing context */
113963  ExprList *pList,     /* Form the KeyInfo object from this ExprList */
113964  int iStart,          /* Begin with this column of pList */
113965  int nExtra           /* Add this many extra columns to the end */
113966);
113967
113968/*
113969** Generate code that will push the record in registers regData
113970** through regData+nData-1 onto the sorter.
113971*/
113972static void pushOntoSorter(
113973  Parse *pParse,         /* Parser context */
113974  SortCtx *pSort,        /* Information about the ORDER BY clause */
113975  Select *pSelect,       /* The whole SELECT statement */
113976  int regData,           /* First register holding data to be sorted */
113977  int regOrigData,       /* First register holding data before packing */
113978  int nData,             /* Number of elements in the data array */
113979  int nPrefixReg         /* No. of reg prior to regData available for use */
113980){
113981  Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
113982  int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
113983  int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
113984  int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
113985  int regBase;                                     /* Regs for sorter record */
113986  int regRecord = ++pParse->nMem;                  /* Assembled sorter record */
113987  int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
113988  int op;                            /* Opcode to add sorter record to sorter */
113989  int iLimit;                        /* LIMIT counter */
113990
113991  assert( bSeq==0 || bSeq==1 );
113992  assert( nData==1 || regData==regOrigData );
113993  if( nPrefixReg ){
113994    assert( nPrefixReg==nExpr+bSeq );
113995    regBase = regData - nExpr - bSeq;
113996  }else{
113997    regBase = pParse->nMem + 1;
113998    pParse->nMem += nBase;
113999  }
114000  assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
114001  iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
114002  pSort->labelDone = sqlite3VdbeMakeLabel(v);
114003  sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
114004                          SQLITE_ECEL_DUP|SQLITE_ECEL_REF);
114005  if( bSeq ){
114006    sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
114007  }
114008  if( nPrefixReg==0 ){
114009    sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
114010  }
114011  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
114012  if( nOBSat>0 ){
114013    int regPrevKey;   /* The first nOBSat columns of the previous row */
114014    int addrFirst;    /* Address of the OP_IfNot opcode */
114015    int addrJmp;      /* Address of the OP_Jump opcode */
114016    VdbeOp *pOp;      /* Opcode that opens the sorter */
114017    int nKey;         /* Number of sorting key columns, including OP_Sequence */
114018    KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
114019
114020    regPrevKey = pParse->nMem+1;
114021    pParse->nMem += pSort->nOBSat;
114022    nKey = nExpr - pSort->nOBSat + bSeq;
114023    if( bSeq ){
114024      addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
114025    }else{
114026      addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
114027    }
114028    VdbeCoverage(v);
114029    sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
114030    pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
114031    if( pParse->db->mallocFailed ) return;
114032    pOp->p2 = nKey + nData;
114033    pKI = pOp->p4.pKeyInfo;
114034    memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
114035    sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
114036    testcase( pKI->nXField>2 );
114037    pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
114038                                           pKI->nXField-1);
114039    addrJmp = sqlite3VdbeCurrentAddr(v);
114040    sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
114041    pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
114042    pSort->regReturn = ++pParse->nMem;
114043    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
114044    sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
114045    if( iLimit ){
114046      sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
114047      VdbeCoverage(v);
114048    }
114049    sqlite3VdbeJumpHere(v, addrFirst);
114050    sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
114051    sqlite3VdbeJumpHere(v, addrJmp);
114052  }
114053  if( pSort->sortFlags & SORTFLAG_UseSorter ){
114054    op = OP_SorterInsert;
114055  }else{
114056    op = OP_IdxInsert;
114057  }
114058  sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
114059  if( iLimit ){
114060    int addr;
114061    int r1 = 0;
114062    /* Fill the sorter until it contains LIMIT+OFFSET entries.  (The iLimit
114063    ** register is initialized with value of LIMIT+OFFSET.)  After the sorter
114064    ** fills up, delete the least entry in the sorter after each insert.
114065    ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */
114066    addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v);
114067    sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
114068    if( pSort->bOrderedInnerLoop ){
114069      r1 = ++pParse->nMem;
114070      sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1);
114071      VdbeComment((v, "seq"));
114072    }
114073    sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
114074    if( pSort->bOrderedInnerLoop ){
114075      /* If the inner loop is driven by an index such that values from
114076      ** the same iteration of the inner loop are in sorted order, then
114077      ** immediately jump to the next iteration of an inner loop if the
114078      ** entry from the current iteration does not fit into the top
114079      ** LIMIT+OFFSET entries of the sorter. */
114080      int iBrk = sqlite3VdbeCurrentAddr(v) + 2;
114081      sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1);
114082      sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
114083      VdbeCoverage(v);
114084    }
114085    sqlite3VdbeJumpHere(v, addr);
114086  }
114087}
114088
114089/*
114090** Add code to implement the OFFSET
114091*/
114092static void codeOffset(
114093  Vdbe *v,          /* Generate code into this VM */
114094  int iOffset,      /* Register holding the offset counter */
114095  int iContinue     /* Jump here to skip the current record */
114096){
114097  if( iOffset>0 ){
114098    sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
114099    VdbeComment((v, "OFFSET"));
114100  }
114101}
114102
114103/*
114104** Add code that will check to make sure the N registers starting at iMem
114105** form a distinct entry.  iTab is a sorting index that holds previously
114106** seen combinations of the N values.  A new entry is made in iTab
114107** if the current N values are new.
114108**
114109** A jump to addrRepeat is made and the N+1 values are popped from the
114110** stack if the top N elements are not distinct.
114111*/
114112static void codeDistinct(
114113  Parse *pParse,     /* Parsing and code generating context */
114114  int iTab,          /* A sorting index used to test for distinctness */
114115  int addrRepeat,    /* Jump to here if not distinct */
114116  int N,             /* Number of elements */
114117  int iMem           /* First element */
114118){
114119  Vdbe *v;
114120  int r1;
114121
114122  v = pParse->pVdbe;
114123  r1 = sqlite3GetTempReg(pParse);
114124  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
114125  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
114126  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
114127  sqlite3ReleaseTempReg(pParse, r1);
114128}
114129
114130#ifndef SQLITE_OMIT_SUBQUERY
114131/*
114132** Generate an error message when a SELECT is used within a subexpression
114133** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
114134** column.  We do this in a subroutine because the error used to occur
114135** in multiple places.  (The error only occurs in one place now, but we
114136** retain the subroutine to minimize code disruption.)
114137*/
114138static int checkForMultiColumnSelectError(
114139  Parse *pParse,       /* Parse context. */
114140  SelectDest *pDest,   /* Destination of SELECT results */
114141  int nExpr            /* Number of result columns returned by SELECT */
114142){
114143  int eDest = pDest->eDest;
114144  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
114145    sqlite3ErrorMsg(pParse, "only a single result allowed for "
114146       "a SELECT that is part of an expression");
114147    return 1;
114148  }else{
114149    return 0;
114150  }
114151}
114152#endif
114153
114154/*
114155** This routine generates the code for the inside of the inner loop
114156** of a SELECT.
114157**
114158** If srcTab is negative, then the pEList expressions
114159** are evaluated in order to get the data for this row.  If srcTab is
114160** zero or more, then data is pulled from srcTab and pEList is used only
114161** to get number columns and the datatype for each column.
114162*/
114163static void selectInnerLoop(
114164  Parse *pParse,          /* The parser context */
114165  Select *p,              /* The complete select statement being coded */
114166  ExprList *pEList,       /* List of values being extracted */
114167  int srcTab,             /* Pull data from this table */
114168  SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
114169  DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
114170  SelectDest *pDest,      /* How to dispose of the results */
114171  int iContinue,          /* Jump here to continue with next row */
114172  int iBreak              /* Jump here to break out of the inner loop */
114173){
114174  Vdbe *v = pParse->pVdbe;
114175  int i;
114176  int hasDistinct;        /* True if the DISTINCT keyword is present */
114177  int regResult;              /* Start of memory holding result set */
114178  int eDest = pDest->eDest;   /* How to dispose of results */
114179  int iParm = pDest->iSDParm; /* First argument to disposal method */
114180  int nResultCol;             /* Number of result columns */
114181  int nPrefixReg = 0;         /* Number of extra registers before regResult */
114182
114183  assert( v );
114184  assert( pEList!=0 );
114185  hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
114186  if( pSort && pSort->pOrderBy==0 ) pSort = 0;
114187  if( pSort==0 && !hasDistinct ){
114188    assert( iContinue!=0 );
114189    codeOffset(v, p->iOffset, iContinue);
114190  }
114191
114192  /* Pull the requested columns.
114193  */
114194  nResultCol = pEList->nExpr;
114195
114196  if( pDest->iSdst==0 ){
114197    if( pSort ){
114198      nPrefixReg = pSort->pOrderBy->nExpr;
114199      if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
114200      pParse->nMem += nPrefixReg;
114201    }
114202    pDest->iSdst = pParse->nMem+1;
114203    pParse->nMem += nResultCol;
114204  }else if( pDest->iSdst+nResultCol > pParse->nMem ){
114205    /* This is an error condition that can result, for example, when a SELECT
114206    ** on the right-hand side of an INSERT contains more result columns than
114207    ** there are columns in the table on the left.  The error will be caught
114208    ** and reported later.  But we need to make sure enough memory is allocated
114209    ** to avoid other spurious errors in the meantime. */
114210    pParse->nMem += nResultCol;
114211  }
114212  pDest->nSdst = nResultCol;
114213  regResult = pDest->iSdst;
114214  if( srcTab>=0 ){
114215    for(i=0; i<nResultCol; i++){
114216      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
114217      VdbeComment((v, "%s", pEList->a[i].zName));
114218    }
114219  }else if( eDest!=SRT_Exists ){
114220    /* If the destination is an EXISTS(...) expression, the actual
114221    ** values returned by the SELECT are not required.
114222    */
114223    u8 ecelFlags;
114224    if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
114225      ecelFlags = SQLITE_ECEL_DUP;
114226    }else{
114227      ecelFlags = 0;
114228    }
114229    sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags);
114230  }
114231
114232  /* If the DISTINCT keyword was present on the SELECT statement
114233  ** and this row has been seen before, then do not make this row
114234  ** part of the result.
114235  */
114236  if( hasDistinct ){
114237    switch( pDistinct->eTnctType ){
114238      case WHERE_DISTINCT_ORDERED: {
114239        VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
114240        int iJump;              /* Jump destination */
114241        int regPrev;            /* Previous row content */
114242
114243        /* Allocate space for the previous row */
114244        regPrev = pParse->nMem+1;
114245        pParse->nMem += nResultCol;
114246
114247        /* Change the OP_OpenEphemeral coded earlier to an OP_Null
114248        ** sets the MEM_Cleared bit on the first register of the
114249        ** previous value.  This will cause the OP_Ne below to always
114250        ** fail on the first iteration of the loop even if the first
114251        ** row is all NULLs.
114252        */
114253        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
114254        pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
114255        pOp->opcode = OP_Null;
114256        pOp->p1 = 1;
114257        pOp->p2 = regPrev;
114258
114259        iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
114260        for(i=0; i<nResultCol; i++){
114261          CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
114262          if( i<nResultCol-1 ){
114263            sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
114264            VdbeCoverage(v);
114265          }else{
114266            sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
114267            VdbeCoverage(v);
114268           }
114269          sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
114270          sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
114271        }
114272        assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
114273        sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
114274        break;
114275      }
114276
114277      case WHERE_DISTINCT_UNIQUE: {
114278        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
114279        break;
114280      }
114281
114282      default: {
114283        assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
114284        codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
114285                     regResult);
114286        break;
114287      }
114288    }
114289    if( pSort==0 ){
114290      codeOffset(v, p->iOffset, iContinue);
114291    }
114292  }
114293
114294  switch( eDest ){
114295    /* In this mode, write each query result to the key of the temporary
114296    ** table iParm.
114297    */
114298#ifndef SQLITE_OMIT_COMPOUND_SELECT
114299    case SRT_Union: {
114300      int r1;
114301      r1 = sqlite3GetTempReg(pParse);
114302      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
114303      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
114304      sqlite3ReleaseTempReg(pParse, r1);
114305      break;
114306    }
114307
114308    /* Construct a record from the query result, but instead of
114309    ** saving that record, use it as a key to delete elements from
114310    ** the temporary table iParm.
114311    */
114312    case SRT_Except: {
114313      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
114314      break;
114315    }
114316#endif /* SQLITE_OMIT_COMPOUND_SELECT */
114317
114318    /* Store the result as data using a unique key.
114319    */
114320    case SRT_Fifo:
114321    case SRT_DistFifo:
114322    case SRT_Table:
114323    case SRT_EphemTab: {
114324      int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
114325      testcase( eDest==SRT_Table );
114326      testcase( eDest==SRT_EphemTab );
114327      testcase( eDest==SRT_Fifo );
114328      testcase( eDest==SRT_DistFifo );
114329      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
114330#ifndef SQLITE_OMIT_CTE
114331      if( eDest==SRT_DistFifo ){
114332        /* If the destination is DistFifo, then cursor (iParm+1) is open
114333        ** on an ephemeral index. If the current row is already present
114334        ** in the index, do not write it to the output. If not, add the
114335        ** current row to the index and proceed with writing it to the
114336        ** output table as well.  */
114337        int addr = sqlite3VdbeCurrentAddr(v) + 4;
114338        sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
114339        VdbeCoverage(v);
114340        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
114341        assert( pSort==0 );
114342      }
114343#endif
114344      if( pSort ){
114345        pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
114346      }else{
114347        int r2 = sqlite3GetTempReg(pParse);
114348        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
114349        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
114350        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
114351        sqlite3ReleaseTempReg(pParse, r2);
114352      }
114353      sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
114354      break;
114355    }
114356
114357#ifndef SQLITE_OMIT_SUBQUERY
114358    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
114359    ** then there should be a single item on the stack.  Write this
114360    ** item into the set table with bogus data.
114361    */
114362    case SRT_Set: {
114363      assert( nResultCol==1 );
114364      pDest->affSdst =
114365                  sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
114366      if( pSort ){
114367        /* At first glance you would think we could optimize out the
114368        ** ORDER BY in this case since the order of entries in the set
114369        ** does not matter.  But there might be a LIMIT clause, in which
114370        ** case the order does matter */
114371        pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
114372      }else{
114373        int r1 = sqlite3GetTempReg(pParse);
114374        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
114375        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
114376        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
114377        sqlite3ReleaseTempReg(pParse, r1);
114378      }
114379      break;
114380    }
114381
114382    /* If any row exist in the result set, record that fact and abort.
114383    */
114384    case SRT_Exists: {
114385      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
114386      /* The LIMIT clause will terminate the loop for us */
114387      break;
114388    }
114389
114390    /* If this is a scalar select that is part of an expression, then
114391    ** store the results in the appropriate memory cell and break out
114392    ** of the scan loop.
114393    */
114394    case SRT_Mem: {
114395      assert( nResultCol==1 );
114396      if( pSort ){
114397        pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
114398      }else{
114399        assert( regResult==iParm );
114400        /* The LIMIT clause will jump out of the loop for us */
114401      }
114402      break;
114403    }
114404#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
114405
114406    case SRT_Coroutine:       /* Send data to a co-routine */
114407    case SRT_Output: {        /* Return the results */
114408      testcase( eDest==SRT_Coroutine );
114409      testcase( eDest==SRT_Output );
114410      if( pSort ){
114411        pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol,
114412                       nPrefixReg);
114413      }else if( eDest==SRT_Coroutine ){
114414        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
114415      }else{
114416        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
114417        sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
114418      }
114419      break;
114420    }
114421
114422#ifndef SQLITE_OMIT_CTE
114423    /* Write the results into a priority queue that is order according to
114424    ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
114425    ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
114426    ** pSO->nExpr columns, then make sure all keys are unique by adding a
114427    ** final OP_Sequence column.  The last column is the record as a blob.
114428    */
114429    case SRT_DistQueue:
114430    case SRT_Queue: {
114431      int nKey;
114432      int r1, r2, r3;
114433      int addrTest = 0;
114434      ExprList *pSO;
114435      pSO = pDest->pOrderBy;
114436      assert( pSO );
114437      nKey = pSO->nExpr;
114438      r1 = sqlite3GetTempReg(pParse);
114439      r2 = sqlite3GetTempRange(pParse, nKey+2);
114440      r3 = r2+nKey+1;
114441      if( eDest==SRT_DistQueue ){
114442        /* If the destination is DistQueue, then cursor (iParm+1) is open
114443        ** on a second ephemeral index that holds all values every previously
114444        ** added to the queue. */
114445        addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
114446                                        regResult, nResultCol);
114447        VdbeCoverage(v);
114448      }
114449      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
114450      if( eDest==SRT_DistQueue ){
114451        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
114452        sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
114453      }
114454      for(i=0; i<nKey; i++){
114455        sqlite3VdbeAddOp2(v, OP_SCopy,
114456                          regResult + pSO->a[i].u.x.iOrderByCol - 1,
114457                          r2+i);
114458      }
114459      sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
114460      sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
114461      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
114462      if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
114463      sqlite3ReleaseTempReg(pParse, r1);
114464      sqlite3ReleaseTempRange(pParse, r2, nKey+2);
114465      break;
114466    }
114467#endif /* SQLITE_OMIT_CTE */
114468
114469
114470
114471#if !defined(SQLITE_OMIT_TRIGGER)
114472    /* Discard the results.  This is used for SELECT statements inside
114473    ** the body of a TRIGGER.  The purpose of such selects is to call
114474    ** user-defined functions that have side effects.  We do not care
114475    ** about the actual results of the select.
114476    */
114477    default: {
114478      assert( eDest==SRT_Discard );
114479      break;
114480    }
114481#endif
114482  }
114483
114484  /* Jump to the end of the loop if the LIMIT is reached.  Except, if
114485  ** there is a sorter, in which case the sorter has already limited
114486  ** the output for us.
114487  */
114488  if( pSort==0 && p->iLimit ){
114489    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
114490  }
114491}
114492
114493/*
114494** Allocate a KeyInfo object sufficient for an index of N key columns and
114495** X extra columns.
114496*/
114497SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
114498  int nExtra = (N+X)*(sizeof(CollSeq*)+1);
114499  KeyInfo *p = sqlite3DbMallocRaw(db, sizeof(KeyInfo) + nExtra);
114500  if( p ){
114501    p->aSortOrder = (u8*)&p->aColl[N+X];
114502    p->nField = (u16)N;
114503    p->nXField = (u16)X;
114504    p->enc = ENC(db);
114505    p->db = db;
114506    p->nRef = 1;
114507    memset(&p[1], 0, nExtra);
114508  }else{
114509    sqlite3OomFault(db);
114510  }
114511  return p;
114512}
114513
114514/*
114515** Deallocate a KeyInfo object
114516*/
114517SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
114518  if( p ){
114519    assert( p->nRef>0 );
114520    p->nRef--;
114521    if( p->nRef==0 ) sqlite3DbFree(p->db, p);
114522  }
114523}
114524
114525/*
114526** Make a new pointer to a KeyInfo object
114527*/
114528SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
114529  if( p ){
114530    assert( p->nRef>0 );
114531    p->nRef++;
114532  }
114533  return p;
114534}
114535
114536#ifdef SQLITE_DEBUG
114537/*
114538** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
114539** can only be changed if this is just a single reference to the object.
114540**
114541** This routine is used only inside of assert() statements.
114542*/
114543SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
114544#endif /* SQLITE_DEBUG */
114545
114546/*
114547** Given an expression list, generate a KeyInfo structure that records
114548** the collating sequence for each expression in that expression list.
114549**
114550** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
114551** KeyInfo structure is appropriate for initializing a virtual index to
114552** implement that clause.  If the ExprList is the result set of a SELECT
114553** then the KeyInfo structure is appropriate for initializing a virtual
114554** index to implement a DISTINCT test.
114555**
114556** Space to hold the KeyInfo structure is obtained from malloc.  The calling
114557** function is responsible for seeing that this structure is eventually
114558** freed.
114559*/
114560static KeyInfo *keyInfoFromExprList(
114561  Parse *pParse,       /* Parsing context */
114562  ExprList *pList,     /* Form the KeyInfo object from this ExprList */
114563  int iStart,          /* Begin with this column of pList */
114564  int nExtra           /* Add this many extra columns to the end */
114565){
114566  int nExpr;
114567  KeyInfo *pInfo;
114568  struct ExprList_item *pItem;
114569  sqlite3 *db = pParse->db;
114570  int i;
114571
114572  nExpr = pList->nExpr;
114573  pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
114574  if( pInfo ){
114575    assert( sqlite3KeyInfoIsWriteable(pInfo) );
114576    for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
114577      CollSeq *pColl;
114578      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
114579      if( !pColl ) pColl = db->pDfltColl;
114580      pInfo->aColl[i-iStart] = pColl;
114581      pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
114582    }
114583  }
114584  return pInfo;
114585}
114586
114587/*
114588** Name of the connection operator, used for error messages.
114589*/
114590static const char *selectOpName(int id){
114591  char *z;
114592  switch( id ){
114593    case TK_ALL:       z = "UNION ALL";   break;
114594    case TK_INTERSECT: z = "INTERSECT";   break;
114595    case TK_EXCEPT:    z = "EXCEPT";      break;
114596    default:           z = "UNION";       break;
114597  }
114598  return z;
114599}
114600
114601#ifndef SQLITE_OMIT_EXPLAIN
114602/*
114603** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
114604** is a no-op. Otherwise, it adds a single row of output to the EQP result,
114605** where the caption is of the form:
114606**
114607**   "USE TEMP B-TREE FOR xxx"
114608**
114609** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
114610** is determined by the zUsage argument.
114611*/
114612static void explainTempTable(Parse *pParse, const char *zUsage){
114613  if( pParse->explain==2 ){
114614    Vdbe *v = pParse->pVdbe;
114615    char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
114616    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
114617  }
114618}
114619
114620/*
114621** Assign expression b to lvalue a. A second, no-op, version of this macro
114622** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
114623** in sqlite3Select() to assign values to structure member variables that
114624** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
114625** code with #ifndef directives.
114626*/
114627# define explainSetInteger(a, b) a = b
114628
114629#else
114630/* No-op versions of the explainXXX() functions and macros. */
114631# define explainTempTable(y,z)
114632# define explainSetInteger(y,z)
114633#endif
114634
114635#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
114636/*
114637** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
114638** is a no-op. Otherwise, it adds a single row of output to the EQP result,
114639** where the caption is of one of the two forms:
114640**
114641**   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
114642**   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
114643**
114644** where iSub1 and iSub2 are the integers passed as the corresponding
114645** function parameters, and op is the text representation of the parameter
114646** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
114647** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
114648** false, or the second form if it is true.
114649*/
114650static void explainComposite(
114651  Parse *pParse,                  /* Parse context */
114652  int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
114653  int iSub1,                      /* Subquery id 1 */
114654  int iSub2,                      /* Subquery id 2 */
114655  int bUseTmp                     /* True if a temp table was used */
114656){
114657  assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
114658  if( pParse->explain==2 ){
114659    Vdbe *v = pParse->pVdbe;
114660    char *zMsg = sqlite3MPrintf(
114661        pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
114662        bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
114663    );
114664    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
114665  }
114666}
114667#else
114668/* No-op versions of the explainXXX() functions and macros. */
114669# define explainComposite(v,w,x,y,z)
114670#endif
114671
114672/*
114673** If the inner loop was generated using a non-null pOrderBy argument,
114674** then the results were placed in a sorter.  After the loop is terminated
114675** we need to run the sorter and output the results.  The following
114676** routine generates the code needed to do that.
114677*/
114678static void generateSortTail(
114679  Parse *pParse,    /* Parsing context */
114680  Select *p,        /* The SELECT statement */
114681  SortCtx *pSort,   /* Information on the ORDER BY clause */
114682  int nColumn,      /* Number of columns of data */
114683  SelectDest *pDest /* Write the sorted results here */
114684){
114685  Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
114686  int addrBreak = pSort->labelDone;            /* Jump here to exit loop */
114687  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
114688  int addr;
114689  int addrOnce = 0;
114690  int iTab;
114691  ExprList *pOrderBy = pSort->pOrderBy;
114692  int eDest = pDest->eDest;
114693  int iParm = pDest->iSDParm;
114694  int regRow;
114695  int regRowid;
114696  int nKey;
114697  int iSortTab;                   /* Sorter cursor to read from */
114698  int nSortData;                  /* Trailing values to read from sorter */
114699  int i;
114700  int bSeq;                       /* True if sorter record includes seq. no. */
114701#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
114702  struct ExprList_item *aOutEx = p->pEList->a;
114703#endif
114704
114705  assert( addrBreak<0 );
114706  if( pSort->labelBkOut ){
114707    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
114708    sqlite3VdbeGoto(v, addrBreak);
114709    sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
114710  }
114711  iTab = pSort->iECursor;
114712  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
114713    regRowid = 0;
114714    regRow = pDest->iSdst;
114715    nSortData = nColumn;
114716  }else{
114717    regRowid = sqlite3GetTempReg(pParse);
114718    regRow = sqlite3GetTempReg(pParse);
114719    nSortData = 1;
114720  }
114721  nKey = pOrderBy->nExpr - pSort->nOBSat;
114722  if( pSort->sortFlags & SORTFLAG_UseSorter ){
114723    int regSortOut = ++pParse->nMem;
114724    iSortTab = pParse->nTab++;
114725    if( pSort->labelBkOut ){
114726      addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
114727    }
114728    sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
114729    if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
114730    addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
114731    VdbeCoverage(v);
114732    codeOffset(v, p->iOffset, addrContinue);
114733    sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
114734    bSeq = 0;
114735  }else{
114736    addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
114737    codeOffset(v, p->iOffset, addrContinue);
114738    iSortTab = iTab;
114739    bSeq = 1;
114740  }
114741  for(i=0; i<nSortData; i++){
114742    sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
114743    VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
114744  }
114745  switch( eDest ){
114746    case SRT_EphemTab: {
114747      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
114748      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
114749      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
114750      break;
114751    }
114752#ifndef SQLITE_OMIT_SUBQUERY
114753    case SRT_Set: {
114754      assert( nColumn==1 );
114755      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
114756                        &pDest->affSdst, 1);
114757      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
114758      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
114759      break;
114760    }
114761    case SRT_Mem: {
114762      assert( nColumn==1 );
114763      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
114764      /* The LIMIT clause will terminate the loop for us */
114765      break;
114766    }
114767#endif
114768    default: {
114769      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
114770      testcase( eDest==SRT_Output );
114771      testcase( eDest==SRT_Coroutine );
114772      if( eDest==SRT_Output ){
114773        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
114774        sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
114775      }else{
114776        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
114777      }
114778      break;
114779    }
114780  }
114781  if( regRowid ){
114782    sqlite3ReleaseTempReg(pParse, regRow);
114783    sqlite3ReleaseTempReg(pParse, regRowid);
114784  }
114785  /* The bottom of the loop
114786  */
114787  sqlite3VdbeResolveLabel(v, addrContinue);
114788  if( pSort->sortFlags & SORTFLAG_UseSorter ){
114789    sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
114790  }else{
114791    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
114792  }
114793  if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
114794  sqlite3VdbeResolveLabel(v, addrBreak);
114795}
114796
114797/*
114798** Return a pointer to a string containing the 'declaration type' of the
114799** expression pExpr. The string may be treated as static by the caller.
114800**
114801** Also try to estimate the size of the returned value and return that
114802** result in *pEstWidth.
114803**
114804** The declaration type is the exact datatype definition extracted from the
114805** original CREATE TABLE statement if the expression is a column. The
114806** declaration type for a ROWID field is INTEGER. Exactly when an expression
114807** is considered a column can be complex in the presence of subqueries. The
114808** result-set expression in all of the following SELECT statements is
114809** considered a column by this function.
114810**
114811**   SELECT col FROM tbl;
114812**   SELECT (SELECT col FROM tbl;
114813**   SELECT (SELECT col FROM tbl);
114814**   SELECT abc FROM (SELECT col AS abc FROM tbl);
114815**
114816** The declaration type for any expression other than a column is NULL.
114817**
114818** This routine has either 3 or 6 parameters depending on whether or not
114819** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
114820*/
114821#ifdef SQLITE_ENABLE_COLUMN_METADATA
114822# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
114823#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
114824# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
114825#endif
114826static const char *columnTypeImpl(
114827  NameContext *pNC,
114828  Expr *pExpr,
114829#ifdef SQLITE_ENABLE_COLUMN_METADATA
114830  const char **pzOrigDb,
114831  const char **pzOrigTab,
114832  const char **pzOrigCol,
114833#endif
114834  u8 *pEstWidth
114835){
114836  char const *zType = 0;
114837  int j;
114838  u8 estWidth = 1;
114839#ifdef SQLITE_ENABLE_COLUMN_METADATA
114840  char const *zOrigDb = 0;
114841  char const *zOrigTab = 0;
114842  char const *zOrigCol = 0;
114843#endif
114844
114845  assert( pExpr!=0 );
114846  assert( pNC->pSrcList!=0 );
114847  switch( pExpr->op ){
114848    case TK_AGG_COLUMN:
114849    case TK_COLUMN: {
114850      /* The expression is a column. Locate the table the column is being
114851      ** extracted from in NameContext.pSrcList. This table may be real
114852      ** database table or a subquery.
114853      */
114854      Table *pTab = 0;            /* Table structure column is extracted from */
114855      Select *pS = 0;             /* Select the column is extracted from */
114856      int iCol = pExpr->iColumn;  /* Index of column in pTab */
114857      testcase( pExpr->op==TK_AGG_COLUMN );
114858      testcase( pExpr->op==TK_COLUMN );
114859      while( pNC && !pTab ){
114860        SrcList *pTabList = pNC->pSrcList;
114861        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
114862        if( j<pTabList->nSrc ){
114863          pTab = pTabList->a[j].pTab;
114864          pS = pTabList->a[j].pSelect;
114865        }else{
114866          pNC = pNC->pNext;
114867        }
114868      }
114869
114870      if( pTab==0 ){
114871        /* At one time, code such as "SELECT new.x" within a trigger would
114872        ** cause this condition to run.  Since then, we have restructured how
114873        ** trigger code is generated and so this condition is no longer
114874        ** possible. However, it can still be true for statements like
114875        ** the following:
114876        **
114877        **   CREATE TABLE t1(col INTEGER);
114878        **   SELECT (SELECT t1.col) FROM FROM t1;
114879        **
114880        ** when columnType() is called on the expression "t1.col" in the
114881        ** sub-select. In this case, set the column type to NULL, even
114882        ** though it should really be "INTEGER".
114883        **
114884        ** This is not a problem, as the column type of "t1.col" is never
114885        ** used. When columnType() is called on the expression
114886        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
114887        ** branch below.  */
114888        break;
114889      }
114890
114891      assert( pTab && pExpr->pTab==pTab );
114892      if( pS ){
114893        /* The "table" is actually a sub-select or a view in the FROM clause
114894        ** of the SELECT statement. Return the declaration type and origin
114895        ** data for the result-set column of the sub-select.
114896        */
114897        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
114898          /* If iCol is less than zero, then the expression requests the
114899          ** rowid of the sub-select or view. This expression is legal (see
114900          ** test case misc2.2.2) - it always evaluates to NULL.
114901          **
114902          ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
114903          ** caught already by name resolution.
114904          */
114905          NameContext sNC;
114906          Expr *p = pS->pEList->a[iCol].pExpr;
114907          sNC.pSrcList = pS->pSrc;
114908          sNC.pNext = pNC;
114909          sNC.pParse = pNC->pParse;
114910          zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
114911        }
114912      }else if( pTab->pSchema ){
114913        /* A real table */
114914        assert( !pS );
114915        if( iCol<0 ) iCol = pTab->iPKey;
114916        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
114917#ifdef SQLITE_ENABLE_COLUMN_METADATA
114918        if( iCol<0 ){
114919          zType = "INTEGER";
114920          zOrigCol = "rowid";
114921        }else{
114922          zOrigCol = pTab->aCol[iCol].zName;
114923          zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
114924          estWidth = pTab->aCol[iCol].szEst;
114925        }
114926        zOrigTab = pTab->zName;
114927        if( pNC->pParse ){
114928          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
114929          zOrigDb = pNC->pParse->db->aDb[iDb].zName;
114930        }
114931#else
114932        if( iCol<0 ){
114933          zType = "INTEGER";
114934        }else{
114935          zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
114936          estWidth = pTab->aCol[iCol].szEst;
114937        }
114938#endif
114939      }
114940      break;
114941    }
114942#ifndef SQLITE_OMIT_SUBQUERY
114943    case TK_SELECT: {
114944      /* The expression is a sub-select. Return the declaration type and
114945      ** origin info for the single column in the result set of the SELECT
114946      ** statement.
114947      */
114948      NameContext sNC;
114949      Select *pS = pExpr->x.pSelect;
114950      Expr *p = pS->pEList->a[0].pExpr;
114951      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
114952      sNC.pSrcList = pS->pSrc;
114953      sNC.pNext = pNC;
114954      sNC.pParse = pNC->pParse;
114955      zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
114956      break;
114957    }
114958#endif
114959  }
114960
114961#ifdef SQLITE_ENABLE_COLUMN_METADATA
114962  if( pzOrigDb ){
114963    assert( pzOrigTab && pzOrigCol );
114964    *pzOrigDb = zOrigDb;
114965    *pzOrigTab = zOrigTab;
114966    *pzOrigCol = zOrigCol;
114967  }
114968#endif
114969  if( pEstWidth ) *pEstWidth = estWidth;
114970  return zType;
114971}
114972
114973/*
114974** Generate code that will tell the VDBE the declaration types of columns
114975** in the result set.
114976*/
114977static void generateColumnTypes(
114978  Parse *pParse,      /* Parser context */
114979  SrcList *pTabList,  /* List of tables */
114980  ExprList *pEList    /* Expressions defining the result set */
114981){
114982#ifndef SQLITE_OMIT_DECLTYPE
114983  Vdbe *v = pParse->pVdbe;
114984  int i;
114985  NameContext sNC;
114986  sNC.pSrcList = pTabList;
114987  sNC.pParse = pParse;
114988  for(i=0; i<pEList->nExpr; i++){
114989    Expr *p = pEList->a[i].pExpr;
114990    const char *zType;
114991#ifdef SQLITE_ENABLE_COLUMN_METADATA
114992    const char *zOrigDb = 0;
114993    const char *zOrigTab = 0;
114994    const char *zOrigCol = 0;
114995    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
114996
114997    /* The vdbe must make its own copy of the column-type and other
114998    ** column specific strings, in case the schema is reset before this
114999    ** virtual machine is deleted.
115000    */
115001    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
115002    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
115003    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
115004#else
115005    zType = columnType(&sNC, p, 0, 0, 0, 0);
115006#endif
115007    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
115008  }
115009#endif /* !defined(SQLITE_OMIT_DECLTYPE) */
115010}
115011
115012/*
115013** Generate code that will tell the VDBE the names of columns
115014** in the result set.  This information is used to provide the
115015** azCol[] values in the callback.
115016*/
115017static void generateColumnNames(
115018  Parse *pParse,      /* Parser context */
115019  SrcList *pTabList,  /* List of tables */
115020  ExprList *pEList    /* Expressions defining the result set */
115021){
115022  Vdbe *v = pParse->pVdbe;
115023  int i, j;
115024  sqlite3 *db = pParse->db;
115025  int fullNames, shortNames;
115026
115027#ifndef SQLITE_OMIT_EXPLAIN
115028  /* If this is an EXPLAIN, skip this step */
115029  if( pParse->explain ){
115030    return;
115031  }
115032#endif
115033
115034  if( pParse->colNamesSet || db->mallocFailed ) return;
115035  assert( v!=0 );
115036  assert( pTabList!=0 );
115037  pParse->colNamesSet = 1;
115038  fullNames = (db->flags & SQLITE_FullColNames)!=0;
115039  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
115040  sqlite3VdbeSetNumCols(v, pEList->nExpr);
115041  for(i=0; i<pEList->nExpr; i++){
115042    Expr *p;
115043    p = pEList->a[i].pExpr;
115044    if( NEVER(p==0) ) continue;
115045    if( pEList->a[i].zName ){
115046      char *zName = pEList->a[i].zName;
115047      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
115048    }else if( p->op==TK_COLUMN || p->op==TK_AGG_COLUMN ){
115049      Table *pTab;
115050      char *zCol;
115051      int iCol = p->iColumn;
115052      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
115053        if( pTabList->a[j].iCursor==p->iTable ) break;
115054      }
115055      assert( j<pTabList->nSrc );
115056      pTab = pTabList->a[j].pTab;
115057      if( iCol<0 ) iCol = pTab->iPKey;
115058      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
115059      if( iCol<0 ){
115060        zCol = "rowid";
115061      }else{
115062        zCol = pTab->aCol[iCol].zName;
115063      }
115064      if( !shortNames && !fullNames ){
115065        sqlite3VdbeSetColName(v, i, COLNAME_NAME,
115066            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
115067      }else if( fullNames ){
115068        char *zName = 0;
115069        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
115070        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
115071      }else{
115072        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
115073      }
115074    }else{
115075      const char *z = pEList->a[i].zSpan;
115076      z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
115077      sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
115078    }
115079  }
115080  generateColumnTypes(pParse, pTabList, pEList);
115081}
115082
115083/*
115084** Given an expression list (which is really the list of expressions
115085** that form the result set of a SELECT statement) compute appropriate
115086** column names for a table that would hold the expression list.
115087**
115088** All column names will be unique.
115089**
115090** Only the column names are computed.  Column.zType, Column.zColl,
115091** and other fields of Column are zeroed.
115092**
115093** Return SQLITE_OK on success.  If a memory allocation error occurs,
115094** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
115095*/
115096SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
115097  Parse *pParse,          /* Parsing context */
115098  ExprList *pEList,       /* Expr list from which to derive column names */
115099  i16 *pnCol,             /* Write the number of columns here */
115100  Column **paCol          /* Write the new column list here */
115101){
115102  sqlite3 *db = pParse->db;   /* Database connection */
115103  int i, j;                   /* Loop counters */
115104  u32 cnt;                    /* Index added to make the name unique */
115105  Column *aCol, *pCol;        /* For looping over result columns */
115106  int nCol;                   /* Number of columns in the result set */
115107  Expr *p;                    /* Expression for a single result column */
115108  char *zName;                /* Column name */
115109  int nName;                  /* Size of name in zName[] */
115110  Hash ht;                    /* Hash table of column names */
115111
115112  sqlite3HashInit(&ht);
115113  if( pEList ){
115114    nCol = pEList->nExpr;
115115    aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
115116    testcase( aCol==0 );
115117  }else{
115118    nCol = 0;
115119    aCol = 0;
115120  }
115121  assert( nCol==(i16)nCol );
115122  *pnCol = nCol;
115123  *paCol = aCol;
115124
115125  for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
115126    /* Get an appropriate name for the column
115127    */
115128    p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
115129    if( (zName = pEList->a[i].zName)!=0 ){
115130      /* If the column contains an "AS <name>" phrase, use <name> as the name */
115131    }else{
115132      Expr *pColExpr = p;  /* The expression that is the result column name */
115133      Table *pTab;         /* Table associated with this expression */
115134      while( pColExpr->op==TK_DOT ){
115135        pColExpr = pColExpr->pRight;
115136        assert( pColExpr!=0 );
115137      }
115138      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
115139        /* For columns use the column name name */
115140        int iCol = pColExpr->iColumn;
115141        pTab = pColExpr->pTab;
115142        if( iCol<0 ) iCol = pTab->iPKey;
115143        zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
115144      }else if( pColExpr->op==TK_ID ){
115145        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
115146        zName = pColExpr->u.zToken;
115147      }else{
115148        /* Use the original text of the column expression as its name */
115149        zName = pEList->a[i].zSpan;
115150      }
115151    }
115152    zName = sqlite3MPrintf(db, "%s", zName);
115153
115154    /* Make sure the column name is unique.  If the name is not unique,
115155    ** append an integer to the name so that it becomes unique.
115156    */
115157    cnt = 0;
115158    while( zName && sqlite3HashFind(&ht, zName)!=0 ){
115159      nName = sqlite3Strlen30(zName);
115160      if( nName>0 ){
115161        for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
115162        if( zName[j]==':' ) nName = j;
115163      }
115164      zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
115165      if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
115166    }
115167    pCol->zName = zName;
115168    sqlite3ColumnPropertiesFromName(0, pCol);
115169    if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
115170      sqlite3OomFault(db);
115171    }
115172  }
115173  sqlite3HashClear(&ht);
115174  if( db->mallocFailed ){
115175    for(j=0; j<i; j++){
115176      sqlite3DbFree(db, aCol[j].zName);
115177    }
115178    sqlite3DbFree(db, aCol);
115179    *paCol = 0;
115180    *pnCol = 0;
115181    return SQLITE_NOMEM_BKPT;
115182  }
115183  return SQLITE_OK;
115184}
115185
115186/*
115187** Add type and collation information to a column list based on
115188** a SELECT statement.
115189**
115190** The column list presumably came from selectColumnNamesFromExprList().
115191** The column list has only names, not types or collations.  This
115192** routine goes through and adds the types and collations.
115193**
115194** This routine requires that all identifiers in the SELECT
115195** statement be resolved.
115196*/
115197SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
115198  Parse *pParse,        /* Parsing contexts */
115199  Table *pTab,          /* Add column type information to this table */
115200  Select *pSelect       /* SELECT used to determine types and collations */
115201){
115202  sqlite3 *db = pParse->db;
115203  NameContext sNC;
115204  Column *pCol;
115205  CollSeq *pColl;
115206  int i;
115207  Expr *p;
115208  struct ExprList_item *a;
115209  u64 szAll = 0;
115210
115211  assert( pSelect!=0 );
115212  assert( (pSelect->selFlags & SF_Resolved)!=0 );
115213  assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
115214  if( db->mallocFailed ) return;
115215  memset(&sNC, 0, sizeof(sNC));
115216  sNC.pSrcList = pSelect->pSrc;
115217  a = pSelect->pEList->a;
115218  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
115219    const char *zType;
115220    int n, m;
115221    p = a[i].pExpr;
115222    zType = columnType(&sNC, p, 0, 0, 0, &pCol->szEst);
115223    szAll += pCol->szEst;
115224    pCol->affinity = sqlite3ExprAffinity(p);
115225    if( zType && (m = sqlite3Strlen30(zType))>0 ){
115226      n = sqlite3Strlen30(pCol->zName);
115227      pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
115228      if( pCol->zName ){
115229        memcpy(&pCol->zName[n+1], zType, m+1);
115230        pCol->colFlags |= COLFLAG_HASTYPE;
115231      }
115232    }
115233    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
115234    pColl = sqlite3ExprCollSeq(pParse, p);
115235    if( pColl && pCol->zColl==0 ){
115236      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
115237    }
115238  }
115239  pTab->szTabRow = sqlite3LogEst(szAll*4);
115240}
115241
115242/*
115243** Given a SELECT statement, generate a Table structure that describes
115244** the result set of that SELECT.
115245*/
115246SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
115247  Table *pTab;
115248  sqlite3 *db = pParse->db;
115249  int savedFlags;
115250
115251  savedFlags = db->flags;
115252  db->flags &= ~SQLITE_FullColNames;
115253  db->flags |= SQLITE_ShortColNames;
115254  sqlite3SelectPrep(pParse, pSelect, 0);
115255  if( pParse->nErr ) return 0;
115256  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
115257  db->flags = savedFlags;
115258  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
115259  if( pTab==0 ){
115260    return 0;
115261  }
115262  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
115263  ** is disabled */
115264  assert( db->lookaside.bDisable );
115265  pTab->nRef = 1;
115266  pTab->zName = 0;
115267  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
115268  sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
115269  sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
115270  pTab->iPKey = -1;
115271  if( db->mallocFailed ){
115272    sqlite3DeleteTable(db, pTab);
115273    return 0;
115274  }
115275  return pTab;
115276}
115277
115278/*
115279** Get a VDBE for the given parser context.  Create a new one if necessary.
115280** If an error occurs, return NULL and leave a message in pParse.
115281*/
115282static SQLITE_NOINLINE Vdbe *allocVdbe(Parse *pParse){
115283  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
115284  if( v ) sqlite3VdbeAddOp0(v, OP_Init);
115285  if( pParse->pToplevel==0
115286   && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
115287  ){
115288    pParse->okConstFactor = 1;
115289  }
115290  return v;
115291}
115292SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
115293  Vdbe *v = pParse->pVdbe;
115294  return v ? v : allocVdbe(pParse);
115295}
115296
115297
115298/*
115299** Compute the iLimit and iOffset fields of the SELECT based on the
115300** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
115301** that appear in the original SQL statement after the LIMIT and OFFSET
115302** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
115303** are the integer memory register numbers for counters used to compute
115304** the limit and offset.  If there is no limit and/or offset, then
115305** iLimit and iOffset are negative.
115306**
115307** This routine changes the values of iLimit and iOffset only if
115308** a limit or offset is defined by pLimit and pOffset.  iLimit and
115309** iOffset should have been preset to appropriate default values (zero)
115310** prior to calling this routine.
115311**
115312** The iOffset register (if it exists) is initialized to the value
115313** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
115314** iOffset+1 is initialized to LIMIT+OFFSET.
115315**
115316** Only if pLimit!=0 or pOffset!=0 do the limit registers get
115317** redefined.  The UNION ALL operator uses this property to force
115318** the reuse of the same limit and offset registers across multiple
115319** SELECT statements.
115320*/
115321static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
115322  Vdbe *v = 0;
115323  int iLimit = 0;
115324  int iOffset;
115325  int n;
115326  if( p->iLimit ) return;
115327
115328  /*
115329  ** "LIMIT -1" always shows all rows.  There is some
115330  ** controversy about what the correct behavior should be.
115331  ** The current implementation interprets "LIMIT 0" to mean
115332  ** no rows.
115333  */
115334  sqlite3ExprCacheClear(pParse);
115335  assert( p->pOffset==0 || p->pLimit!=0 );
115336  if( p->pLimit ){
115337    p->iLimit = iLimit = ++pParse->nMem;
115338    v = sqlite3GetVdbe(pParse);
115339    assert( v!=0 );
115340    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
115341      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
115342      VdbeComment((v, "LIMIT counter"));
115343      if( n==0 ){
115344        sqlite3VdbeGoto(v, iBreak);
115345      }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
115346        p->nSelectRow = sqlite3LogEst((u64)n);
115347        p->selFlags |= SF_FixedLimit;
115348      }
115349    }else{
115350      sqlite3ExprCode(pParse, p->pLimit, iLimit);
115351      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
115352      VdbeComment((v, "LIMIT counter"));
115353      sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
115354    }
115355    if( p->pOffset ){
115356      p->iOffset = iOffset = ++pParse->nMem;
115357      pParse->nMem++;   /* Allocate an extra register for limit+offset */
115358      sqlite3ExprCode(pParse, p->pOffset, iOffset);
115359      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
115360      VdbeComment((v, "OFFSET counter"));
115361      sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
115362      VdbeComment((v, "LIMIT+OFFSET"));
115363    }
115364  }
115365}
115366
115367#ifndef SQLITE_OMIT_COMPOUND_SELECT
115368/*
115369** Return the appropriate collating sequence for the iCol-th column of
115370** the result set for the compound-select statement "p".  Return NULL if
115371** the column has no default collating sequence.
115372**
115373** The collating sequence for the compound select is taken from the
115374** left-most term of the select that has a collating sequence.
115375*/
115376static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
115377  CollSeq *pRet;
115378  if( p->pPrior ){
115379    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
115380  }else{
115381    pRet = 0;
115382  }
115383  assert( iCol>=0 );
115384  /* iCol must be less than p->pEList->nExpr.  Otherwise an error would
115385  ** have been thrown during name resolution and we would not have gotten
115386  ** this far */
115387  if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
115388    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
115389  }
115390  return pRet;
115391}
115392
115393/*
115394** The select statement passed as the second parameter is a compound SELECT
115395** with an ORDER BY clause. This function allocates and returns a KeyInfo
115396** structure suitable for implementing the ORDER BY.
115397**
115398** Space to hold the KeyInfo structure is obtained from malloc. The calling
115399** function is responsible for ensuring that this structure is eventually
115400** freed.
115401*/
115402static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
115403  ExprList *pOrderBy = p->pOrderBy;
115404  int nOrderBy = p->pOrderBy->nExpr;
115405  sqlite3 *db = pParse->db;
115406  KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
115407  if( pRet ){
115408    int i;
115409    for(i=0; i<nOrderBy; i++){
115410      struct ExprList_item *pItem = &pOrderBy->a[i];
115411      Expr *pTerm = pItem->pExpr;
115412      CollSeq *pColl;
115413
115414      if( pTerm->flags & EP_Collate ){
115415        pColl = sqlite3ExprCollSeq(pParse, pTerm);
115416      }else{
115417        pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
115418        if( pColl==0 ) pColl = db->pDfltColl;
115419        pOrderBy->a[i].pExpr =
115420          sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
115421      }
115422      assert( sqlite3KeyInfoIsWriteable(pRet) );
115423      pRet->aColl[i] = pColl;
115424      pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
115425    }
115426  }
115427
115428  return pRet;
115429}
115430
115431#ifndef SQLITE_OMIT_CTE
115432/*
115433** This routine generates VDBE code to compute the content of a WITH RECURSIVE
115434** query of the form:
115435**
115436**   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
115437**                         \___________/             \_______________/
115438**                           p->pPrior                      p
115439**
115440**
115441** There is exactly one reference to the recursive-table in the FROM clause
115442** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
115443**
115444** The setup-query runs once to generate an initial set of rows that go
115445** into a Queue table.  Rows are extracted from the Queue table one by
115446** one.  Each row extracted from Queue is output to pDest.  Then the single
115447** extracted row (now in the iCurrent table) becomes the content of the
115448** recursive-table for a recursive-query run.  The output of the recursive-query
115449** is added back into the Queue table.  Then another row is extracted from Queue
115450** and the iteration continues until the Queue table is empty.
115451**
115452** If the compound query operator is UNION then no duplicate rows are ever
115453** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
115454** that have ever been inserted into Queue and causes duplicates to be
115455** discarded.  If the operator is UNION ALL, then duplicates are allowed.
115456**
115457** If the query has an ORDER BY, then entries in the Queue table are kept in
115458** ORDER BY order and the first entry is extracted for each cycle.  Without
115459** an ORDER BY, the Queue table is just a FIFO.
115460**
115461** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
115462** have been output to pDest.  A LIMIT of zero means to output no rows and a
115463** negative LIMIT means to output all rows.  If there is also an OFFSET clause
115464** with a positive value, then the first OFFSET outputs are discarded rather
115465** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
115466** rows have been skipped.
115467*/
115468static void generateWithRecursiveQuery(
115469  Parse *pParse,        /* Parsing context */
115470  Select *p,            /* The recursive SELECT to be coded */
115471  SelectDest *pDest     /* What to do with query results */
115472){
115473  SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
115474  int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
115475  Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
115476  Select *pSetup = p->pPrior;   /* The setup query */
115477  int addrTop;                  /* Top of the loop */
115478  int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
115479  int iCurrent = 0;             /* The Current table */
115480  int regCurrent;               /* Register holding Current table */
115481  int iQueue;                   /* The Queue table */
115482  int iDistinct = 0;            /* To ensure unique results if UNION */
115483  int eDest = SRT_Fifo;         /* How to write to Queue */
115484  SelectDest destQueue;         /* SelectDest targetting the Queue table */
115485  int i;                        /* Loop counter */
115486  int rc;                       /* Result code */
115487  ExprList *pOrderBy;           /* The ORDER BY clause */
115488  Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
115489  int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
115490
115491  /* Obtain authorization to do a recursive query */
115492  if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
115493
115494  /* Process the LIMIT and OFFSET clauses, if they exist */
115495  addrBreak = sqlite3VdbeMakeLabel(v);
115496  computeLimitRegisters(pParse, p, addrBreak);
115497  pLimit = p->pLimit;
115498  pOffset = p->pOffset;
115499  regLimit = p->iLimit;
115500  regOffset = p->iOffset;
115501  p->pLimit = p->pOffset = 0;
115502  p->iLimit = p->iOffset = 0;
115503  pOrderBy = p->pOrderBy;
115504
115505  /* Locate the cursor number of the Current table */
115506  for(i=0; ALWAYS(i<pSrc->nSrc); i++){
115507    if( pSrc->a[i].fg.isRecursive ){
115508      iCurrent = pSrc->a[i].iCursor;
115509      break;
115510    }
115511  }
115512
115513  /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
115514  ** the Distinct table must be exactly one greater than Queue in order
115515  ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
115516  iQueue = pParse->nTab++;
115517  if( p->op==TK_UNION ){
115518    eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
115519    iDistinct = pParse->nTab++;
115520  }else{
115521    eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
115522  }
115523  sqlite3SelectDestInit(&destQueue, eDest, iQueue);
115524
115525  /* Allocate cursors for Current, Queue, and Distinct. */
115526  regCurrent = ++pParse->nMem;
115527  sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
115528  if( pOrderBy ){
115529    KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
115530    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
115531                      (char*)pKeyInfo, P4_KEYINFO);
115532    destQueue.pOrderBy = pOrderBy;
115533  }else{
115534    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
115535  }
115536  VdbeComment((v, "Queue table"));
115537  if( iDistinct ){
115538    p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
115539    p->selFlags |= SF_UsesEphemeral;
115540  }
115541
115542  /* Detach the ORDER BY clause from the compound SELECT */
115543  p->pOrderBy = 0;
115544
115545  /* Store the results of the setup-query in Queue. */
115546  pSetup->pNext = 0;
115547  rc = sqlite3Select(pParse, pSetup, &destQueue);
115548  pSetup->pNext = p;
115549  if( rc ) goto end_of_recursive_query;
115550
115551  /* Find the next row in the Queue and output that row */
115552  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
115553
115554  /* Transfer the next row in Queue over to Current */
115555  sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
115556  if( pOrderBy ){
115557    sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
115558  }else{
115559    sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
115560  }
115561  sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
115562
115563  /* Output the single row in Current */
115564  addrCont = sqlite3VdbeMakeLabel(v);
115565  codeOffset(v, regOffset, addrCont);
115566  selectInnerLoop(pParse, p, p->pEList, iCurrent,
115567      0, 0, pDest, addrCont, addrBreak);
115568  if( regLimit ){
115569    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
115570    VdbeCoverage(v);
115571  }
115572  sqlite3VdbeResolveLabel(v, addrCont);
115573
115574  /* Execute the recursive SELECT taking the single row in Current as
115575  ** the value for the recursive-table. Store the results in the Queue.
115576  */
115577  if( p->selFlags & SF_Aggregate ){
115578    sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
115579  }else{
115580    p->pPrior = 0;
115581    sqlite3Select(pParse, p, &destQueue);
115582    assert( p->pPrior==0 );
115583    p->pPrior = pSetup;
115584  }
115585
115586  /* Keep running the loop until the Queue is empty */
115587  sqlite3VdbeGoto(v, addrTop);
115588  sqlite3VdbeResolveLabel(v, addrBreak);
115589
115590end_of_recursive_query:
115591  sqlite3ExprListDelete(pParse->db, p->pOrderBy);
115592  p->pOrderBy = pOrderBy;
115593  p->pLimit = pLimit;
115594  p->pOffset = pOffset;
115595  return;
115596}
115597#endif /* SQLITE_OMIT_CTE */
115598
115599/* Forward references */
115600static int multiSelectOrderBy(
115601  Parse *pParse,        /* Parsing context */
115602  Select *p,            /* The right-most of SELECTs to be coded */
115603  SelectDest *pDest     /* What to do with query results */
115604);
115605
115606/*
115607** Handle the special case of a compound-select that originates from a
115608** VALUES clause.  By handling this as a special case, we avoid deep
115609** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
115610** on a VALUES clause.
115611**
115612** Because the Select object originates from a VALUES clause:
115613**   (1) It has no LIMIT or OFFSET
115614**   (2) All terms are UNION ALL
115615**   (3) There is no ORDER BY clause
115616*/
115617static int multiSelectValues(
115618  Parse *pParse,        /* Parsing context */
115619  Select *p,            /* The right-most of SELECTs to be coded */
115620  SelectDest *pDest     /* What to do with query results */
115621){
115622  Select *pPrior;
115623  int nRow = 1;
115624  int rc = 0;
115625  assert( p->selFlags & SF_MultiValue );
115626  do{
115627    assert( p->selFlags & SF_Values );
115628    assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
115629    assert( p->pLimit==0 );
115630    assert( p->pOffset==0 );
115631    assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
115632    if( p->pPrior==0 ) break;
115633    assert( p->pPrior->pNext==p );
115634    p = p->pPrior;
115635    nRow++;
115636  }while(1);
115637  while( p ){
115638    pPrior = p->pPrior;
115639    p->pPrior = 0;
115640    rc = sqlite3Select(pParse, p, pDest);
115641    p->pPrior = pPrior;
115642    if( rc ) break;
115643    p->nSelectRow = nRow;
115644    p = p->pNext;
115645  }
115646  return rc;
115647}
115648
115649/*
115650** This routine is called to process a compound query form from
115651** two or more separate queries using UNION, UNION ALL, EXCEPT, or
115652** INTERSECT
115653**
115654** "p" points to the right-most of the two queries.  the query on the
115655** left is p->pPrior.  The left query could also be a compound query
115656** in which case this routine will be called recursively.
115657**
115658** The results of the total query are to be written into a destination
115659** of type eDest with parameter iParm.
115660**
115661** Example 1:  Consider a three-way compound SQL statement.
115662**
115663**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
115664**
115665** This statement is parsed up as follows:
115666**
115667**     SELECT c FROM t3
115668**      |
115669**      `----->  SELECT b FROM t2
115670**                |
115671**                `------>  SELECT a FROM t1
115672**
115673** The arrows in the diagram above represent the Select.pPrior pointer.
115674** So if this routine is called with p equal to the t3 query, then
115675** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
115676**
115677** Notice that because of the way SQLite parses compound SELECTs, the
115678** individual selects always group from left to right.
115679*/
115680static int multiSelect(
115681  Parse *pParse,        /* Parsing context */
115682  Select *p,            /* The right-most of SELECTs to be coded */
115683  SelectDest *pDest     /* What to do with query results */
115684){
115685  int rc = SQLITE_OK;   /* Success code from a subroutine */
115686  Select *pPrior;       /* Another SELECT immediately to our left */
115687  Vdbe *v;              /* Generate code to this VDBE */
115688  SelectDest dest;      /* Alternative data destination */
115689  Select *pDelete = 0;  /* Chain of simple selects to delete */
115690  sqlite3 *db;          /* Database connection */
115691#ifndef SQLITE_OMIT_EXPLAIN
115692  int iSub1 = 0;        /* EQP id of left-hand query */
115693  int iSub2 = 0;        /* EQP id of right-hand query */
115694#endif
115695
115696  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
115697  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
115698  */
115699  assert( p && p->pPrior );  /* Calling function guarantees this much */
115700  assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
115701  db = pParse->db;
115702  pPrior = p->pPrior;
115703  dest = *pDest;
115704  if( pPrior->pOrderBy ){
115705    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
115706      selectOpName(p->op));
115707    rc = 1;
115708    goto multi_select_end;
115709  }
115710  if( pPrior->pLimit ){
115711    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
115712      selectOpName(p->op));
115713    rc = 1;
115714    goto multi_select_end;
115715  }
115716
115717  v = sqlite3GetVdbe(pParse);
115718  assert( v!=0 );  /* The VDBE already created by calling function */
115719
115720  /* Create the destination temporary table if necessary
115721  */
115722  if( dest.eDest==SRT_EphemTab ){
115723    assert( p->pEList );
115724    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
115725    dest.eDest = SRT_Table;
115726  }
115727
115728  /* Special handling for a compound-select that originates as a VALUES clause.
115729  */
115730  if( p->selFlags & SF_MultiValue ){
115731    rc = multiSelectValues(pParse, p, &dest);
115732    goto multi_select_end;
115733  }
115734
115735  /* Make sure all SELECTs in the statement have the same number of elements
115736  ** in their result sets.
115737  */
115738  assert( p->pEList && pPrior->pEList );
115739  assert( p->pEList->nExpr==pPrior->pEList->nExpr );
115740
115741#ifndef SQLITE_OMIT_CTE
115742  if( p->selFlags & SF_Recursive ){
115743    generateWithRecursiveQuery(pParse, p, &dest);
115744  }else
115745#endif
115746
115747  /* Compound SELECTs that have an ORDER BY clause are handled separately.
115748  */
115749  if( p->pOrderBy ){
115750    return multiSelectOrderBy(pParse, p, pDest);
115751  }else
115752
115753  /* Generate code for the left and right SELECT statements.
115754  */
115755  switch( p->op ){
115756    case TK_ALL: {
115757      int addr = 0;
115758      int nLimit;
115759      assert( !pPrior->pLimit );
115760      pPrior->iLimit = p->iLimit;
115761      pPrior->iOffset = p->iOffset;
115762      pPrior->pLimit = p->pLimit;
115763      pPrior->pOffset = p->pOffset;
115764      explainSetInteger(iSub1, pParse->iNextSelectId);
115765      rc = sqlite3Select(pParse, pPrior, &dest);
115766      p->pLimit = 0;
115767      p->pOffset = 0;
115768      if( rc ){
115769        goto multi_select_end;
115770      }
115771      p->pPrior = 0;
115772      p->iLimit = pPrior->iLimit;
115773      p->iOffset = pPrior->iOffset;
115774      if( p->iLimit ){
115775        addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
115776        VdbeComment((v, "Jump ahead if LIMIT reached"));
115777        if( p->iOffset ){
115778          sqlite3VdbeAddOp3(v, OP_OffsetLimit,
115779                            p->iLimit, p->iOffset+1, p->iOffset);
115780        }
115781      }
115782      explainSetInteger(iSub2, pParse->iNextSelectId);
115783      rc = sqlite3Select(pParse, p, &dest);
115784      testcase( rc!=SQLITE_OK );
115785      pDelete = p->pPrior;
115786      p->pPrior = pPrior;
115787      p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
115788      if( pPrior->pLimit
115789       && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
115790       && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
115791      ){
115792        p->nSelectRow = sqlite3LogEst((u64)nLimit);
115793      }
115794      if( addr ){
115795        sqlite3VdbeJumpHere(v, addr);
115796      }
115797      break;
115798    }
115799    case TK_EXCEPT:
115800    case TK_UNION: {
115801      int unionTab;    /* Cursor number of the temporary table holding result */
115802      u8 op = 0;       /* One of the SRT_ operations to apply to self */
115803      int priorOp;     /* The SRT_ operation to apply to prior selects */
115804      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
115805      int addr;
115806      SelectDest uniondest;
115807
115808      testcase( p->op==TK_EXCEPT );
115809      testcase( p->op==TK_UNION );
115810      priorOp = SRT_Union;
115811      if( dest.eDest==priorOp ){
115812        /* We can reuse a temporary table generated by a SELECT to our
115813        ** right.
115814        */
115815        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
115816        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
115817        unionTab = dest.iSDParm;
115818      }else{
115819        /* We will need to create our own temporary table to hold the
115820        ** intermediate results.
115821        */
115822        unionTab = pParse->nTab++;
115823        assert( p->pOrderBy==0 );
115824        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
115825        assert( p->addrOpenEphm[0] == -1 );
115826        p->addrOpenEphm[0] = addr;
115827        findRightmost(p)->selFlags |= SF_UsesEphemeral;
115828        assert( p->pEList );
115829      }
115830
115831      /* Code the SELECT statements to our left
115832      */
115833      assert( !pPrior->pOrderBy );
115834      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
115835      explainSetInteger(iSub1, pParse->iNextSelectId);
115836      rc = sqlite3Select(pParse, pPrior, &uniondest);
115837      if( rc ){
115838        goto multi_select_end;
115839      }
115840
115841      /* Code the current SELECT statement
115842      */
115843      if( p->op==TK_EXCEPT ){
115844        op = SRT_Except;
115845      }else{
115846        assert( p->op==TK_UNION );
115847        op = SRT_Union;
115848      }
115849      p->pPrior = 0;
115850      pLimit = p->pLimit;
115851      p->pLimit = 0;
115852      pOffset = p->pOffset;
115853      p->pOffset = 0;
115854      uniondest.eDest = op;
115855      explainSetInteger(iSub2, pParse->iNextSelectId);
115856      rc = sqlite3Select(pParse, p, &uniondest);
115857      testcase( rc!=SQLITE_OK );
115858      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
115859      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
115860      sqlite3ExprListDelete(db, p->pOrderBy);
115861      pDelete = p->pPrior;
115862      p->pPrior = pPrior;
115863      p->pOrderBy = 0;
115864      if( p->op==TK_UNION ){
115865        p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
115866      }
115867      sqlite3ExprDelete(db, p->pLimit);
115868      p->pLimit = pLimit;
115869      p->pOffset = pOffset;
115870      p->iLimit = 0;
115871      p->iOffset = 0;
115872
115873      /* Convert the data in the temporary table into whatever form
115874      ** it is that we currently need.
115875      */
115876      assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
115877      if( dest.eDest!=priorOp ){
115878        int iCont, iBreak, iStart;
115879        assert( p->pEList );
115880        if( dest.eDest==SRT_Output ){
115881          Select *pFirst = p;
115882          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
115883          generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
115884        }
115885        iBreak = sqlite3VdbeMakeLabel(v);
115886        iCont = sqlite3VdbeMakeLabel(v);
115887        computeLimitRegisters(pParse, p, iBreak);
115888        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
115889        iStart = sqlite3VdbeCurrentAddr(v);
115890        selectInnerLoop(pParse, p, p->pEList, unionTab,
115891                        0, 0, &dest, iCont, iBreak);
115892        sqlite3VdbeResolveLabel(v, iCont);
115893        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
115894        sqlite3VdbeResolveLabel(v, iBreak);
115895        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
115896      }
115897      break;
115898    }
115899    default: assert( p->op==TK_INTERSECT ); {
115900      int tab1, tab2;
115901      int iCont, iBreak, iStart;
115902      Expr *pLimit, *pOffset;
115903      int addr;
115904      SelectDest intersectdest;
115905      int r1;
115906
115907      /* INTERSECT is different from the others since it requires
115908      ** two temporary tables.  Hence it has its own case.  Begin
115909      ** by allocating the tables we will need.
115910      */
115911      tab1 = pParse->nTab++;
115912      tab2 = pParse->nTab++;
115913      assert( p->pOrderBy==0 );
115914
115915      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
115916      assert( p->addrOpenEphm[0] == -1 );
115917      p->addrOpenEphm[0] = addr;
115918      findRightmost(p)->selFlags |= SF_UsesEphemeral;
115919      assert( p->pEList );
115920
115921      /* Code the SELECTs to our left into temporary table "tab1".
115922      */
115923      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
115924      explainSetInteger(iSub1, pParse->iNextSelectId);
115925      rc = sqlite3Select(pParse, pPrior, &intersectdest);
115926      if( rc ){
115927        goto multi_select_end;
115928      }
115929
115930      /* Code the current SELECT into temporary table "tab2"
115931      */
115932      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
115933      assert( p->addrOpenEphm[1] == -1 );
115934      p->addrOpenEphm[1] = addr;
115935      p->pPrior = 0;
115936      pLimit = p->pLimit;
115937      p->pLimit = 0;
115938      pOffset = p->pOffset;
115939      p->pOffset = 0;
115940      intersectdest.iSDParm = tab2;
115941      explainSetInteger(iSub2, pParse->iNextSelectId);
115942      rc = sqlite3Select(pParse, p, &intersectdest);
115943      testcase( rc!=SQLITE_OK );
115944      pDelete = p->pPrior;
115945      p->pPrior = pPrior;
115946      if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
115947      sqlite3ExprDelete(db, p->pLimit);
115948      p->pLimit = pLimit;
115949      p->pOffset = pOffset;
115950
115951      /* Generate code to take the intersection of the two temporary
115952      ** tables.
115953      */
115954      assert( p->pEList );
115955      if( dest.eDest==SRT_Output ){
115956        Select *pFirst = p;
115957        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
115958        generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
115959      }
115960      iBreak = sqlite3VdbeMakeLabel(v);
115961      iCont = sqlite3VdbeMakeLabel(v);
115962      computeLimitRegisters(pParse, p, iBreak);
115963      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
115964      r1 = sqlite3GetTempReg(pParse);
115965      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
115966      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
115967      sqlite3ReleaseTempReg(pParse, r1);
115968      selectInnerLoop(pParse, p, p->pEList, tab1,
115969                      0, 0, &dest, iCont, iBreak);
115970      sqlite3VdbeResolveLabel(v, iCont);
115971      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
115972      sqlite3VdbeResolveLabel(v, iBreak);
115973      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
115974      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
115975      break;
115976    }
115977  }
115978
115979  explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
115980
115981  /* Compute collating sequences used by
115982  ** temporary tables needed to implement the compound select.
115983  ** Attach the KeyInfo structure to all temporary tables.
115984  **
115985  ** This section is run by the right-most SELECT statement only.
115986  ** SELECT statements to the left always skip this part.  The right-most
115987  ** SELECT might also skip this part if it has no ORDER BY clause and
115988  ** no temp tables are required.
115989  */
115990  if( p->selFlags & SF_UsesEphemeral ){
115991    int i;                        /* Loop counter */
115992    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
115993    Select *pLoop;                /* For looping through SELECT statements */
115994    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
115995    int nCol;                     /* Number of columns in result set */
115996
115997    assert( p->pNext==0 );
115998    nCol = p->pEList->nExpr;
115999    pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
116000    if( !pKeyInfo ){
116001      rc = SQLITE_NOMEM_BKPT;
116002      goto multi_select_end;
116003    }
116004    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
116005      *apColl = multiSelectCollSeq(pParse, p, i);
116006      if( 0==*apColl ){
116007        *apColl = db->pDfltColl;
116008      }
116009    }
116010
116011    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
116012      for(i=0; i<2; i++){
116013        int addr = pLoop->addrOpenEphm[i];
116014        if( addr<0 ){
116015          /* If [0] is unused then [1] is also unused.  So we can
116016          ** always safely abort as soon as the first unused slot is found */
116017          assert( pLoop->addrOpenEphm[1]<0 );
116018          break;
116019        }
116020        sqlite3VdbeChangeP2(v, addr, nCol);
116021        sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
116022                            P4_KEYINFO);
116023        pLoop->addrOpenEphm[i] = -1;
116024      }
116025    }
116026    sqlite3KeyInfoUnref(pKeyInfo);
116027  }
116028
116029multi_select_end:
116030  pDest->iSdst = dest.iSdst;
116031  pDest->nSdst = dest.nSdst;
116032  sqlite3SelectDelete(db, pDelete);
116033  return rc;
116034}
116035#endif /* SQLITE_OMIT_COMPOUND_SELECT */
116036
116037/*
116038** Error message for when two or more terms of a compound select have different
116039** size result sets.
116040*/
116041SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
116042  if( p->selFlags & SF_Values ){
116043    sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
116044  }else{
116045    sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
116046      " do not have the same number of result columns", selectOpName(p->op));
116047  }
116048}
116049
116050/*
116051** Code an output subroutine for a coroutine implementation of a
116052** SELECT statment.
116053**
116054** The data to be output is contained in pIn->iSdst.  There are
116055** pIn->nSdst columns to be output.  pDest is where the output should
116056** be sent.
116057**
116058** regReturn is the number of the register holding the subroutine
116059** return address.
116060**
116061** If regPrev>0 then it is the first register in a vector that
116062** records the previous output.  mem[regPrev] is a flag that is false
116063** if there has been no previous output.  If regPrev>0 then code is
116064** generated to suppress duplicates.  pKeyInfo is used for comparing
116065** keys.
116066**
116067** If the LIMIT found in p->iLimit is reached, jump immediately to
116068** iBreak.
116069*/
116070static int generateOutputSubroutine(
116071  Parse *pParse,          /* Parsing context */
116072  Select *p,              /* The SELECT statement */
116073  SelectDest *pIn,        /* Coroutine supplying data */
116074  SelectDest *pDest,      /* Where to send the data */
116075  int regReturn,          /* The return address register */
116076  int regPrev,            /* Previous result register.  No uniqueness if 0 */
116077  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
116078  int iBreak              /* Jump here if we hit the LIMIT */
116079){
116080  Vdbe *v = pParse->pVdbe;
116081  int iContinue;
116082  int addr;
116083
116084  addr = sqlite3VdbeCurrentAddr(v);
116085  iContinue = sqlite3VdbeMakeLabel(v);
116086
116087  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
116088  */
116089  if( regPrev ){
116090    int addr1, addr2;
116091    addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
116092    addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
116093                              (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
116094    sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
116095    sqlite3VdbeJumpHere(v, addr1);
116096    sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
116097    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
116098  }
116099  if( pParse->db->mallocFailed ) return 0;
116100
116101  /* Suppress the first OFFSET entries if there is an OFFSET clause
116102  */
116103  codeOffset(v, p->iOffset, iContinue);
116104
116105  assert( pDest->eDest!=SRT_Exists );
116106  assert( pDest->eDest!=SRT_Table );
116107  switch( pDest->eDest ){
116108    /* Store the result as data using a unique key.
116109    */
116110    case SRT_EphemTab: {
116111      int r1 = sqlite3GetTempReg(pParse);
116112      int r2 = sqlite3GetTempReg(pParse);
116113      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
116114      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
116115      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
116116      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
116117      sqlite3ReleaseTempReg(pParse, r2);
116118      sqlite3ReleaseTempReg(pParse, r1);
116119      break;
116120    }
116121
116122#ifndef SQLITE_OMIT_SUBQUERY
116123    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
116124    ** then there should be a single item on the stack.  Write this
116125    ** item into the set table with bogus data.
116126    */
116127    case SRT_Set: {
116128      int r1;
116129      assert( pIn->nSdst==1 || pParse->nErr>0 );
116130      pDest->affSdst =
116131         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
116132      r1 = sqlite3GetTempReg(pParse);
116133      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
116134      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
116135      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
116136      sqlite3ReleaseTempReg(pParse, r1);
116137      break;
116138    }
116139
116140    /* If this is a scalar select that is part of an expression, then
116141    ** store the results in the appropriate memory cell and break out
116142    ** of the scan loop.
116143    */
116144    case SRT_Mem: {
116145      assert( pIn->nSdst==1 || pParse->nErr>0 );  testcase( pIn->nSdst!=1 );
116146      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
116147      /* The LIMIT clause will jump out of the loop for us */
116148      break;
116149    }
116150#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
116151
116152    /* The results are stored in a sequence of registers
116153    ** starting at pDest->iSdst.  Then the co-routine yields.
116154    */
116155    case SRT_Coroutine: {
116156      if( pDest->iSdst==0 ){
116157        pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
116158        pDest->nSdst = pIn->nSdst;
116159      }
116160      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
116161      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
116162      break;
116163    }
116164
116165    /* If none of the above, then the result destination must be
116166    ** SRT_Output.  This routine is never called with any other
116167    ** destination other than the ones handled above or SRT_Output.
116168    **
116169    ** For SRT_Output, results are stored in a sequence of registers.
116170    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
116171    ** return the next row of result.
116172    */
116173    default: {
116174      assert( pDest->eDest==SRT_Output );
116175      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
116176      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
116177      break;
116178    }
116179  }
116180
116181  /* Jump to the end of the loop if the LIMIT is reached.
116182  */
116183  if( p->iLimit ){
116184    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
116185  }
116186
116187  /* Generate the subroutine return
116188  */
116189  sqlite3VdbeResolveLabel(v, iContinue);
116190  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
116191
116192  return addr;
116193}
116194
116195/*
116196** Alternative compound select code generator for cases when there
116197** is an ORDER BY clause.
116198**
116199** We assume a query of the following form:
116200**
116201**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
116202**
116203** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
116204** is to code both <selectA> and <selectB> with the ORDER BY clause as
116205** co-routines.  Then run the co-routines in parallel and merge the results
116206** into the output.  In addition to the two coroutines (called selectA and
116207** selectB) there are 7 subroutines:
116208**
116209**    outA:    Move the output of the selectA coroutine into the output
116210**             of the compound query.
116211**
116212**    outB:    Move the output of the selectB coroutine into the output
116213**             of the compound query.  (Only generated for UNION and
116214**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
116215**             appears only in B.)
116216**
116217**    AltB:    Called when there is data from both coroutines and A<B.
116218**
116219**    AeqB:    Called when there is data from both coroutines and A==B.
116220**
116221**    AgtB:    Called when there is data from both coroutines and A>B.
116222**
116223**    EofA:    Called when data is exhausted from selectA.
116224**
116225**    EofB:    Called when data is exhausted from selectB.
116226**
116227** The implementation of the latter five subroutines depend on which
116228** <operator> is used:
116229**
116230**
116231**             UNION ALL         UNION            EXCEPT          INTERSECT
116232**          -------------  -----------------  --------------  -----------------
116233**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
116234**
116235**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
116236**
116237**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
116238**
116239**   EofA:   outB, nextB      outB, nextB          halt             halt
116240**
116241**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
116242**
116243** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
116244** causes an immediate jump to EofA and an EOF on B following nextB causes
116245** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
116246** following nextX causes a jump to the end of the select processing.
116247**
116248** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
116249** within the output subroutine.  The regPrev register set holds the previously
116250** output value.  A comparison is made against this value and the output
116251** is skipped if the next results would be the same as the previous.
116252**
116253** The implementation plan is to implement the two coroutines and seven
116254** subroutines first, then put the control logic at the bottom.  Like this:
116255**
116256**          goto Init
116257**     coA: coroutine for left query (A)
116258**     coB: coroutine for right query (B)
116259**    outA: output one row of A
116260**    outB: output one row of B (UNION and UNION ALL only)
116261**    EofA: ...
116262**    EofB: ...
116263**    AltB: ...
116264**    AeqB: ...
116265**    AgtB: ...
116266**    Init: initialize coroutine registers
116267**          yield coA
116268**          if eof(A) goto EofA
116269**          yield coB
116270**          if eof(B) goto EofB
116271**    Cmpr: Compare A, B
116272**          Jump AltB, AeqB, AgtB
116273**     End: ...
116274**
116275** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
116276** actually called using Gosub and they do not Return.  EofA and EofB loop
116277** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
116278** and AgtB jump to either L2 or to one of EofA or EofB.
116279*/
116280#ifndef SQLITE_OMIT_COMPOUND_SELECT
116281static int multiSelectOrderBy(
116282  Parse *pParse,        /* Parsing context */
116283  Select *p,            /* The right-most of SELECTs to be coded */
116284  SelectDest *pDest     /* What to do with query results */
116285){
116286  int i, j;             /* Loop counters */
116287  Select *pPrior;       /* Another SELECT immediately to our left */
116288  Vdbe *v;              /* Generate code to this VDBE */
116289  SelectDest destA;     /* Destination for coroutine A */
116290  SelectDest destB;     /* Destination for coroutine B */
116291  int regAddrA;         /* Address register for select-A coroutine */
116292  int regAddrB;         /* Address register for select-B coroutine */
116293  int addrSelectA;      /* Address of the select-A coroutine */
116294  int addrSelectB;      /* Address of the select-B coroutine */
116295  int regOutA;          /* Address register for the output-A subroutine */
116296  int regOutB;          /* Address register for the output-B subroutine */
116297  int addrOutA;         /* Address of the output-A subroutine */
116298  int addrOutB = 0;     /* Address of the output-B subroutine */
116299  int addrEofA;         /* Address of the select-A-exhausted subroutine */
116300  int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
116301  int addrEofB;         /* Address of the select-B-exhausted subroutine */
116302  int addrAltB;         /* Address of the A<B subroutine */
116303  int addrAeqB;         /* Address of the A==B subroutine */
116304  int addrAgtB;         /* Address of the A>B subroutine */
116305  int regLimitA;        /* Limit register for select-A */
116306  int regLimitB;        /* Limit register for select-A */
116307  int regPrev;          /* A range of registers to hold previous output */
116308  int savedLimit;       /* Saved value of p->iLimit */
116309  int savedOffset;      /* Saved value of p->iOffset */
116310  int labelCmpr;        /* Label for the start of the merge algorithm */
116311  int labelEnd;         /* Label for the end of the overall SELECT stmt */
116312  int addr1;            /* Jump instructions that get retargetted */
116313  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
116314  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
116315  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
116316  sqlite3 *db;          /* Database connection */
116317  ExprList *pOrderBy;   /* The ORDER BY clause */
116318  int nOrderBy;         /* Number of terms in the ORDER BY clause */
116319  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
116320#ifndef SQLITE_OMIT_EXPLAIN
116321  int iSub1;            /* EQP id of left-hand query */
116322  int iSub2;            /* EQP id of right-hand query */
116323#endif
116324
116325  assert( p->pOrderBy!=0 );
116326  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
116327  db = pParse->db;
116328  v = pParse->pVdbe;
116329  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
116330  labelEnd = sqlite3VdbeMakeLabel(v);
116331  labelCmpr = sqlite3VdbeMakeLabel(v);
116332
116333
116334  /* Patch up the ORDER BY clause
116335  */
116336  op = p->op;
116337  pPrior = p->pPrior;
116338  assert( pPrior->pOrderBy==0 );
116339  pOrderBy = p->pOrderBy;
116340  assert( pOrderBy );
116341  nOrderBy = pOrderBy->nExpr;
116342
116343  /* For operators other than UNION ALL we have to make sure that
116344  ** the ORDER BY clause covers every term of the result set.  Add
116345  ** terms to the ORDER BY clause as necessary.
116346  */
116347  if( op!=TK_ALL ){
116348    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
116349      struct ExprList_item *pItem;
116350      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
116351        assert( pItem->u.x.iOrderByCol>0 );
116352        if( pItem->u.x.iOrderByCol==i ) break;
116353      }
116354      if( j==nOrderBy ){
116355        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
116356        if( pNew==0 ) return SQLITE_NOMEM_BKPT;
116357        pNew->flags |= EP_IntValue;
116358        pNew->u.iValue = i;
116359        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
116360        if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
116361      }
116362    }
116363  }
116364
116365  /* Compute the comparison permutation and keyinfo that is used with
116366  ** the permutation used to determine if the next
116367  ** row of results comes from selectA or selectB.  Also add explicit
116368  ** collations to the ORDER BY clause terms so that when the subqueries
116369  ** to the right and the left are evaluated, they use the correct
116370  ** collation.
116371  */
116372  aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
116373  if( aPermute ){
116374    struct ExprList_item *pItem;
116375    aPermute[0] = nOrderBy;
116376    for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
116377      assert( pItem->u.x.iOrderByCol>0 );
116378      assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
116379      aPermute[i] = pItem->u.x.iOrderByCol - 1;
116380    }
116381    pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
116382  }else{
116383    pKeyMerge = 0;
116384  }
116385
116386  /* Reattach the ORDER BY clause to the query.
116387  */
116388  p->pOrderBy = pOrderBy;
116389  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
116390
116391  /* Allocate a range of temporary registers and the KeyInfo needed
116392  ** for the logic that removes duplicate result rows when the
116393  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
116394  */
116395  if( op==TK_ALL ){
116396    regPrev = 0;
116397  }else{
116398    int nExpr = p->pEList->nExpr;
116399    assert( nOrderBy>=nExpr || db->mallocFailed );
116400    regPrev = pParse->nMem+1;
116401    pParse->nMem += nExpr+1;
116402    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
116403    pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
116404    if( pKeyDup ){
116405      assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
116406      for(i=0; i<nExpr; i++){
116407        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
116408        pKeyDup->aSortOrder[i] = 0;
116409      }
116410    }
116411  }
116412
116413  /* Separate the left and the right query from one another
116414  */
116415  p->pPrior = 0;
116416  pPrior->pNext = 0;
116417  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
116418  if( pPrior->pPrior==0 ){
116419    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
116420  }
116421
116422  /* Compute the limit registers */
116423  computeLimitRegisters(pParse, p, labelEnd);
116424  if( p->iLimit && op==TK_ALL ){
116425    regLimitA = ++pParse->nMem;
116426    regLimitB = ++pParse->nMem;
116427    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
116428                                  regLimitA);
116429    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
116430  }else{
116431    regLimitA = regLimitB = 0;
116432  }
116433  sqlite3ExprDelete(db, p->pLimit);
116434  p->pLimit = 0;
116435  sqlite3ExprDelete(db, p->pOffset);
116436  p->pOffset = 0;
116437
116438  regAddrA = ++pParse->nMem;
116439  regAddrB = ++pParse->nMem;
116440  regOutA = ++pParse->nMem;
116441  regOutB = ++pParse->nMem;
116442  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
116443  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
116444
116445  /* Generate a coroutine to evaluate the SELECT statement to the
116446  ** left of the compound operator - the "A" select.
116447  */
116448  addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
116449  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
116450  VdbeComment((v, "left SELECT"));
116451  pPrior->iLimit = regLimitA;
116452  explainSetInteger(iSub1, pParse->iNextSelectId);
116453  sqlite3Select(pParse, pPrior, &destA);
116454  sqlite3VdbeEndCoroutine(v, regAddrA);
116455  sqlite3VdbeJumpHere(v, addr1);
116456
116457  /* Generate a coroutine to evaluate the SELECT statement on
116458  ** the right - the "B" select
116459  */
116460  addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
116461  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
116462  VdbeComment((v, "right SELECT"));
116463  savedLimit = p->iLimit;
116464  savedOffset = p->iOffset;
116465  p->iLimit = regLimitB;
116466  p->iOffset = 0;
116467  explainSetInteger(iSub2, pParse->iNextSelectId);
116468  sqlite3Select(pParse, p, &destB);
116469  p->iLimit = savedLimit;
116470  p->iOffset = savedOffset;
116471  sqlite3VdbeEndCoroutine(v, regAddrB);
116472
116473  /* Generate a subroutine that outputs the current row of the A
116474  ** select as the next output row of the compound select.
116475  */
116476  VdbeNoopComment((v, "Output routine for A"));
116477  addrOutA = generateOutputSubroutine(pParse,
116478                 p, &destA, pDest, regOutA,
116479                 regPrev, pKeyDup, labelEnd);
116480
116481  /* Generate a subroutine that outputs the current row of the B
116482  ** select as the next output row of the compound select.
116483  */
116484  if( op==TK_ALL || op==TK_UNION ){
116485    VdbeNoopComment((v, "Output routine for B"));
116486    addrOutB = generateOutputSubroutine(pParse,
116487                 p, &destB, pDest, regOutB,
116488                 regPrev, pKeyDup, labelEnd);
116489  }
116490  sqlite3KeyInfoUnref(pKeyDup);
116491
116492  /* Generate a subroutine to run when the results from select A
116493  ** are exhausted and only data in select B remains.
116494  */
116495  if( op==TK_EXCEPT || op==TK_INTERSECT ){
116496    addrEofA_noB = addrEofA = labelEnd;
116497  }else{
116498    VdbeNoopComment((v, "eof-A subroutine"));
116499    addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
116500    addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
116501                                     VdbeCoverage(v);
116502    sqlite3VdbeGoto(v, addrEofA);
116503    p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
116504  }
116505
116506  /* Generate a subroutine to run when the results from select B
116507  ** are exhausted and only data in select A remains.
116508  */
116509  if( op==TK_INTERSECT ){
116510    addrEofB = addrEofA;
116511    if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
116512  }else{
116513    VdbeNoopComment((v, "eof-B subroutine"));
116514    addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
116515    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
116516    sqlite3VdbeGoto(v, addrEofB);
116517  }
116518
116519  /* Generate code to handle the case of A<B
116520  */
116521  VdbeNoopComment((v, "A-lt-B subroutine"));
116522  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
116523  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
116524  sqlite3VdbeGoto(v, labelCmpr);
116525
116526  /* Generate code to handle the case of A==B
116527  */
116528  if( op==TK_ALL ){
116529    addrAeqB = addrAltB;
116530  }else if( op==TK_INTERSECT ){
116531    addrAeqB = addrAltB;
116532    addrAltB++;
116533  }else{
116534    VdbeNoopComment((v, "A-eq-B subroutine"));
116535    addrAeqB =
116536    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
116537    sqlite3VdbeGoto(v, labelCmpr);
116538  }
116539
116540  /* Generate code to handle the case of A>B
116541  */
116542  VdbeNoopComment((v, "A-gt-B subroutine"));
116543  addrAgtB = sqlite3VdbeCurrentAddr(v);
116544  if( op==TK_ALL || op==TK_UNION ){
116545    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
116546  }
116547  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
116548  sqlite3VdbeGoto(v, labelCmpr);
116549
116550  /* This code runs once to initialize everything.
116551  */
116552  sqlite3VdbeJumpHere(v, addr1);
116553  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
116554  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
116555
116556  /* Implement the main merge loop
116557  */
116558  sqlite3VdbeResolveLabel(v, labelCmpr);
116559  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
116560  sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
116561                         (char*)pKeyMerge, P4_KEYINFO);
116562  sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
116563  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
116564
116565  /* Jump to the this point in order to terminate the query.
116566  */
116567  sqlite3VdbeResolveLabel(v, labelEnd);
116568
116569  /* Set the number of output columns
116570  */
116571  if( pDest->eDest==SRT_Output ){
116572    Select *pFirst = pPrior;
116573    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
116574    generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
116575  }
116576
116577  /* Reassembly the compound query so that it will be freed correctly
116578  ** by the calling function */
116579  if( p->pPrior ){
116580    sqlite3SelectDelete(db, p->pPrior);
116581  }
116582  p->pPrior = pPrior;
116583  pPrior->pNext = p;
116584
116585  /*** TBD:  Insert subroutine calls to close cursors on incomplete
116586  **** subqueries ****/
116587  explainComposite(pParse, p->op, iSub1, iSub2, 0);
116588  return pParse->nErr!=0;
116589}
116590#endif
116591
116592#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
116593/* Forward Declarations */
116594static void substExprList(sqlite3*, ExprList*, int, ExprList*);
116595static void substSelect(sqlite3*, Select *, int, ExprList*, int);
116596
116597/*
116598** Scan through the expression pExpr.  Replace every reference to
116599** a column in table number iTable with a copy of the iColumn-th
116600** entry in pEList.  (But leave references to the ROWID column
116601** unchanged.)
116602**
116603** This routine is part of the flattening procedure.  A subquery
116604** whose result set is defined by pEList appears as entry in the
116605** FROM clause of a SELECT such that the VDBE cursor assigned to that
116606** FORM clause entry is iTable.  This routine make the necessary
116607** changes to pExpr so that it refers directly to the source table
116608** of the subquery rather the result set of the subquery.
116609*/
116610static Expr *substExpr(
116611  sqlite3 *db,        /* Report malloc errors to this connection */
116612  Expr *pExpr,        /* Expr in which substitution occurs */
116613  int iTable,         /* Table to be substituted */
116614  ExprList *pEList    /* Substitute expressions */
116615){
116616  if( pExpr==0 ) return 0;
116617  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
116618    if( pExpr->iColumn<0 ){
116619      pExpr->op = TK_NULL;
116620    }else{
116621      Expr *pNew;
116622      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
116623      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
116624      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
116625      sqlite3ExprDelete(db, pExpr);
116626      pExpr = pNew;
116627    }
116628  }else{
116629    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
116630    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
116631    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
116632      substSelect(db, pExpr->x.pSelect, iTable, pEList, 1);
116633    }else{
116634      substExprList(db, pExpr->x.pList, iTable, pEList);
116635    }
116636  }
116637  return pExpr;
116638}
116639static void substExprList(
116640  sqlite3 *db,         /* Report malloc errors here */
116641  ExprList *pList,     /* List to scan and in which to make substitutes */
116642  int iTable,          /* Table to be substituted */
116643  ExprList *pEList     /* Substitute values */
116644){
116645  int i;
116646  if( pList==0 ) return;
116647  for(i=0; i<pList->nExpr; i++){
116648    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
116649  }
116650}
116651static void substSelect(
116652  sqlite3 *db,         /* Report malloc errors here */
116653  Select *p,           /* SELECT statement in which to make substitutions */
116654  int iTable,          /* Table to be replaced */
116655  ExprList *pEList,    /* Substitute values */
116656  int doPrior          /* Do substitutes on p->pPrior too */
116657){
116658  SrcList *pSrc;
116659  struct SrcList_item *pItem;
116660  int i;
116661  if( !p ) return;
116662  do{
116663    substExprList(db, p->pEList, iTable, pEList);
116664    substExprList(db, p->pGroupBy, iTable, pEList);
116665    substExprList(db, p->pOrderBy, iTable, pEList);
116666    p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
116667    p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
116668    pSrc = p->pSrc;
116669    assert( pSrc!=0 );
116670    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
116671      substSelect(db, pItem->pSelect, iTable, pEList, 1);
116672      if( pItem->fg.isTabFunc ){
116673        substExprList(db, pItem->u1.pFuncArg, iTable, pEList);
116674      }
116675    }
116676  }while( doPrior && (p = p->pPrior)!=0 );
116677}
116678#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
116679
116680#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
116681/*
116682** This routine attempts to flatten subqueries as a performance optimization.
116683** This routine returns 1 if it makes changes and 0 if no flattening occurs.
116684**
116685** To understand the concept of flattening, consider the following
116686** query:
116687**
116688**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
116689**
116690** The default way of implementing this query is to execute the
116691** subquery first and store the results in a temporary table, then
116692** run the outer query on that temporary table.  This requires two
116693** passes over the data.  Furthermore, because the temporary table
116694** has no indices, the WHERE clause on the outer query cannot be
116695** optimized.
116696**
116697** This routine attempts to rewrite queries such as the above into
116698** a single flat select, like this:
116699**
116700**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
116701**
116702** The code generated for this simplification gives the same result
116703** but only has to scan the data once.  And because indices might
116704** exist on the table t1, a complete scan of the data might be
116705** avoided.
116706**
116707** Flattening is only attempted if all of the following are true:
116708**
116709**   (1)  The subquery and the outer query do not both use aggregates.
116710**
116711**   (2)  The subquery is not an aggregate or (2a) the outer query is not a join
116712**        and (2b) the outer query does not use subqueries other than the one
116713**        FROM-clause subquery that is a candidate for flattening.  (2b is
116714**        due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
116715**
116716**   (3)  The subquery is not the right operand of a left outer join
116717**        (Originally ticket #306.  Strengthened by ticket #3300)
116718**
116719**   (4)  The subquery is not DISTINCT.
116720**
116721**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
116722**        sub-queries that were excluded from this optimization. Restriction
116723**        (4) has since been expanded to exclude all DISTINCT subqueries.
116724**
116725**   (6)  The subquery does not use aggregates or the outer query is not
116726**        DISTINCT.
116727**
116728**   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
116729**        A FROM clause, consider adding a FROM close with the special
116730**        table sqlite_once that consists of a single row containing a
116731**        single NULL.
116732**
116733**   (8)  The subquery does not use LIMIT or the outer query is not a join.
116734**
116735**   (9)  The subquery does not use LIMIT or the outer query does not use
116736**        aggregates.
116737**
116738**  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
116739**        accidently carried the comment forward until 2014-09-15.  Original
116740**        text: "The subquery does not use aggregates or the outer query
116741**        does not use LIMIT."
116742**
116743**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
116744**
116745**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
116746**        a separate restriction deriving from ticket #350.
116747**
116748**  (13)  The subquery and outer query do not both use LIMIT.
116749**
116750**  (14)  The subquery does not use OFFSET.
116751**
116752**  (15)  The outer query is not part of a compound select or the
116753**        subquery does not have a LIMIT clause.
116754**        (See ticket #2339 and ticket [02a8e81d44]).
116755**
116756**  (16)  The outer query is not an aggregate or the subquery does
116757**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
116758**        until we introduced the group_concat() function.
116759**
116760**  (17)  The sub-query is not a compound select, or it is a UNION ALL
116761**        compound clause made up entirely of non-aggregate queries, and
116762**        the parent query:
116763**
116764**          * is not itself part of a compound select,
116765**          * is not an aggregate or DISTINCT query, and
116766**          * is not a join
116767**
116768**        The parent and sub-query may contain WHERE clauses. Subject to
116769**        rules (11), (13) and (14), they may also contain ORDER BY,
116770**        LIMIT and OFFSET clauses.  The subquery cannot use any compound
116771**        operator other than UNION ALL because all the other compound
116772**        operators have an implied DISTINCT which is disallowed by
116773**        restriction (4).
116774**
116775**        Also, each component of the sub-query must return the same number
116776**        of result columns. This is actually a requirement for any compound
116777**        SELECT statement, but all the code here does is make sure that no
116778**        such (illegal) sub-query is flattened. The caller will detect the
116779**        syntax error and return a detailed message.
116780**
116781**  (18)  If the sub-query is a compound select, then all terms of the
116782**        ORDER by clause of the parent must be simple references to
116783**        columns of the sub-query.
116784**
116785**  (19)  The subquery does not use LIMIT or the outer query does not
116786**        have a WHERE clause.
116787**
116788**  (20)  If the sub-query is a compound select, then it must not use
116789**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
116790**        somewhat by saying that the terms of the ORDER BY clause must
116791**        appear as unmodified result columns in the outer query.  But we
116792**        have other optimizations in mind to deal with that case.
116793**
116794**  (21)  The subquery does not use LIMIT or the outer query is not
116795**        DISTINCT.  (See ticket [752e1646fc]).
116796**
116797**  (22)  The subquery is not a recursive CTE.
116798**
116799**  (23)  The parent is not a recursive CTE, or the sub-query is not a
116800**        compound query. This restriction is because transforming the
116801**        parent to a compound query confuses the code that handles
116802**        recursive queries in multiSelect().
116803**
116804**  (24)  The subquery is not an aggregate that uses the built-in min() or
116805**        or max() functions.  (Without this restriction, a query like:
116806**        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
116807**        return the value X for which Y was maximal.)
116808**
116809**
116810** In this routine, the "p" parameter is a pointer to the outer query.
116811** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
116812** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
116813**
116814** If flattening is not attempted, this routine is a no-op and returns 0.
116815** If flattening is attempted this routine returns 1.
116816**
116817** All of the expression analysis must occur on both the outer query and
116818** the subquery before this routine runs.
116819*/
116820static int flattenSubquery(
116821  Parse *pParse,       /* Parsing context */
116822  Select *p,           /* The parent or outer SELECT statement */
116823  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
116824  int isAgg,           /* True if outer SELECT uses aggregate functions */
116825  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
116826){
116827  const char *zSavedAuthContext = pParse->zAuthContext;
116828  Select *pParent;    /* Current UNION ALL term of the other query */
116829  Select *pSub;       /* The inner query or "subquery" */
116830  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
116831  SrcList *pSrc;      /* The FROM clause of the outer query */
116832  SrcList *pSubSrc;   /* The FROM clause of the subquery */
116833  ExprList *pList;    /* The result set of the outer query */
116834  int iParent;        /* VDBE cursor number of the pSub result set temp table */
116835  int i;              /* Loop counter */
116836  Expr *pWhere;                    /* The WHERE clause */
116837  struct SrcList_item *pSubitem;   /* The subquery */
116838  sqlite3 *db = pParse->db;
116839
116840  /* Check to see if flattening is permitted.  Return 0 if not.
116841  */
116842  assert( p!=0 );
116843  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
116844  if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
116845  pSrc = p->pSrc;
116846  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
116847  pSubitem = &pSrc->a[iFrom];
116848  iParent = pSubitem->iCursor;
116849  pSub = pSubitem->pSelect;
116850  assert( pSub!=0 );
116851  if( subqueryIsAgg ){
116852    if( isAgg ) return 0;                                /* Restriction (1)   */
116853    if( pSrc->nSrc>1 ) return 0;                         /* Restriction (2a)  */
116854    if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
116855     || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
116856     || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
116857    ){
116858      return 0;                                          /* Restriction (2b)  */
116859    }
116860  }
116861
116862  pSubSrc = pSub->pSrc;
116863  assert( pSubSrc );
116864  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
116865  ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
116866  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
116867  ** became arbitrary expressions, we were forced to add restrictions (13)
116868  ** and (14). */
116869  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
116870  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
116871  if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
116872    return 0;                                            /* Restriction (15) */
116873  }
116874  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
116875  if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
116876  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
116877     return 0;         /* Restrictions (8)(9) */
116878  }
116879  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
116880     return 0;         /* Restriction (6)  */
116881  }
116882  if( p->pOrderBy && pSub->pOrderBy ){
116883     return 0;                                           /* Restriction (11) */
116884  }
116885  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
116886  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
116887  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
116888     return 0;         /* Restriction (21) */
116889  }
116890  testcase( pSub->selFlags & SF_Recursive );
116891  testcase( pSub->selFlags & SF_MinMaxAgg );
116892  if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
116893    return 0; /* Restrictions (22) and (24) */
116894  }
116895  if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
116896    return 0; /* Restriction (23) */
116897  }
116898
116899  /* OBSOLETE COMMENT 1:
116900  ** Restriction 3:  If the subquery is a join, make sure the subquery is
116901  ** not used as the right operand of an outer join.  Examples of why this
116902  ** is not allowed:
116903  **
116904  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
116905  **
116906  ** If we flatten the above, we would get
116907  **
116908  **         (t1 LEFT OUTER JOIN t2) JOIN t3
116909  **
116910  ** which is not at all the same thing.
116911  **
116912  ** OBSOLETE COMMENT 2:
116913  ** Restriction 12:  If the subquery is the right operand of a left outer
116914  ** join, make sure the subquery has no WHERE clause.
116915  ** An examples of why this is not allowed:
116916  **
116917  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
116918  **
116919  ** If we flatten the above, we would get
116920  **
116921  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
116922  **
116923  ** But the t2.x>0 test will always fail on a NULL row of t2, which
116924  ** effectively converts the OUTER JOIN into an INNER JOIN.
116925  **
116926  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
116927  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
116928  ** is fraught with danger.  Best to avoid the whole thing.  If the
116929  ** subquery is the right term of a LEFT JOIN, then do not flatten.
116930  */
116931  if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
116932    return 0;
116933  }
116934
116935  /* Restriction 17: If the sub-query is a compound SELECT, then it must
116936  ** use only the UNION ALL operator. And none of the simple select queries
116937  ** that make up the compound SELECT are allowed to be aggregate or distinct
116938  ** queries.
116939  */
116940  if( pSub->pPrior ){
116941    if( pSub->pOrderBy ){
116942      return 0;  /* Restriction 20 */
116943    }
116944    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
116945      return 0;
116946    }
116947    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
116948      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
116949      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
116950      assert( pSub->pSrc!=0 );
116951      assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
116952      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
116953       || (pSub1->pPrior && pSub1->op!=TK_ALL)
116954       || pSub1->pSrc->nSrc<1
116955      ){
116956        return 0;
116957      }
116958      testcase( pSub1->pSrc->nSrc>1 );
116959    }
116960
116961    /* Restriction 18. */
116962    if( p->pOrderBy ){
116963      int ii;
116964      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
116965        if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
116966      }
116967    }
116968  }
116969
116970  /***** If we reach this point, flattening is permitted. *****/
116971  SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
116972                   pSub->zSelName, pSub, iFrom));
116973
116974  /* Authorize the subquery */
116975  pParse->zAuthContext = pSubitem->zName;
116976  TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
116977  testcase( i==SQLITE_DENY );
116978  pParse->zAuthContext = zSavedAuthContext;
116979
116980  /* If the sub-query is a compound SELECT statement, then (by restrictions
116981  ** 17 and 18 above) it must be a UNION ALL and the parent query must
116982  ** be of the form:
116983  **
116984  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
116985  **
116986  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
116987  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
116988  ** OFFSET clauses and joins them to the left-hand-side of the original
116989  ** using UNION ALL operators. In this case N is the number of simple
116990  ** select statements in the compound sub-query.
116991  **
116992  ** Example:
116993  **
116994  **     SELECT a+1 FROM (
116995  **        SELECT x FROM tab
116996  **        UNION ALL
116997  **        SELECT y FROM tab
116998  **        UNION ALL
116999  **        SELECT abs(z*2) FROM tab2
117000  **     ) WHERE a!=5 ORDER BY 1
117001  **
117002  ** Transformed into:
117003  **
117004  **     SELECT x+1 FROM tab WHERE x+1!=5
117005  **     UNION ALL
117006  **     SELECT y+1 FROM tab WHERE y+1!=5
117007  **     UNION ALL
117008  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
117009  **     ORDER BY 1
117010  **
117011  ** We call this the "compound-subquery flattening".
117012  */
117013  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
117014    Select *pNew;
117015    ExprList *pOrderBy = p->pOrderBy;
117016    Expr *pLimit = p->pLimit;
117017    Expr *pOffset = p->pOffset;
117018    Select *pPrior = p->pPrior;
117019    p->pOrderBy = 0;
117020    p->pSrc = 0;
117021    p->pPrior = 0;
117022    p->pLimit = 0;
117023    p->pOffset = 0;
117024    pNew = sqlite3SelectDup(db, p, 0);
117025    sqlite3SelectSetName(pNew, pSub->zSelName);
117026    p->pOffset = pOffset;
117027    p->pLimit = pLimit;
117028    p->pOrderBy = pOrderBy;
117029    p->pSrc = pSrc;
117030    p->op = TK_ALL;
117031    if( pNew==0 ){
117032      p->pPrior = pPrior;
117033    }else{
117034      pNew->pPrior = pPrior;
117035      if( pPrior ) pPrior->pNext = pNew;
117036      pNew->pNext = p;
117037      p->pPrior = pNew;
117038      SELECTTRACE(2,pParse,p,
117039         ("compound-subquery flattener creates %s.%p as peer\n",
117040         pNew->zSelName, pNew));
117041    }
117042    if( db->mallocFailed ) return 1;
117043  }
117044
117045  /* Begin flattening the iFrom-th entry of the FROM clause
117046  ** in the outer query.
117047  */
117048  pSub = pSub1 = pSubitem->pSelect;
117049
117050  /* Delete the transient table structure associated with the
117051  ** subquery
117052  */
117053  sqlite3DbFree(db, pSubitem->zDatabase);
117054  sqlite3DbFree(db, pSubitem->zName);
117055  sqlite3DbFree(db, pSubitem->zAlias);
117056  pSubitem->zDatabase = 0;
117057  pSubitem->zName = 0;
117058  pSubitem->zAlias = 0;
117059  pSubitem->pSelect = 0;
117060
117061  /* Defer deleting the Table object associated with the
117062  ** subquery until code generation is
117063  ** complete, since there may still exist Expr.pTab entries that
117064  ** refer to the subquery even after flattening.  Ticket #3346.
117065  **
117066  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
117067  */
117068  if( ALWAYS(pSubitem->pTab!=0) ){
117069    Table *pTabToDel = pSubitem->pTab;
117070    if( pTabToDel->nRef==1 ){
117071      Parse *pToplevel = sqlite3ParseToplevel(pParse);
117072      pTabToDel->pNextZombie = pToplevel->pZombieTab;
117073      pToplevel->pZombieTab = pTabToDel;
117074    }else{
117075      pTabToDel->nRef--;
117076    }
117077    pSubitem->pTab = 0;
117078  }
117079
117080  /* The following loop runs once for each term in a compound-subquery
117081  ** flattening (as described above).  If we are doing a different kind
117082  ** of flattening - a flattening other than a compound-subquery flattening -
117083  ** then this loop only runs once.
117084  **
117085  ** This loop moves all of the FROM elements of the subquery into the
117086  ** the FROM clause of the outer query.  Before doing this, remember
117087  ** the cursor number for the original outer query FROM element in
117088  ** iParent.  The iParent cursor will never be used.  Subsequent code
117089  ** will scan expressions looking for iParent references and replace
117090  ** those references with expressions that resolve to the subquery FROM
117091  ** elements we are now copying in.
117092  */
117093  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
117094    int nSubSrc;
117095    u8 jointype = 0;
117096    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
117097    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
117098    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
117099
117100    if( pSrc ){
117101      assert( pParent==p );  /* First time through the loop */
117102      jointype = pSubitem->fg.jointype;
117103    }else{
117104      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
117105      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
117106      if( pSrc==0 ){
117107        assert( db->mallocFailed );
117108        break;
117109      }
117110    }
117111
117112    /* The subquery uses a single slot of the FROM clause of the outer
117113    ** query.  If the subquery has more than one element in its FROM clause,
117114    ** then expand the outer query to make space for it to hold all elements
117115    ** of the subquery.
117116    **
117117    ** Example:
117118    **
117119    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
117120    **
117121    ** The outer query has 3 slots in its FROM clause.  One slot of the
117122    ** outer query (the middle slot) is used by the subquery.  The next
117123    ** block of code will expand the outer query FROM clause to 4 slots.
117124    ** The middle slot is expanded to two slots in order to make space
117125    ** for the two elements in the FROM clause of the subquery.
117126    */
117127    if( nSubSrc>1 ){
117128      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
117129      if( db->mallocFailed ){
117130        break;
117131      }
117132    }
117133
117134    /* Transfer the FROM clause terms from the subquery into the
117135    ** outer query.
117136    */
117137    for(i=0; i<nSubSrc; i++){
117138      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
117139      assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
117140      pSrc->a[i+iFrom] = pSubSrc->a[i];
117141      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
117142    }
117143    pSrc->a[iFrom].fg.jointype = jointype;
117144
117145    /* Now begin substituting subquery result set expressions for
117146    ** references to the iParent in the outer query.
117147    **
117148    ** Example:
117149    **
117150    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
117151    **   \                     \_____________ subquery __________/          /
117152    **    \_____________________ outer query ______________________________/
117153    **
117154    ** We look at every expression in the outer query and every place we see
117155    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
117156    */
117157    pList = pParent->pEList;
117158    for(i=0; i<pList->nExpr; i++){
117159      if( pList->a[i].zName==0 ){
117160        char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
117161        sqlite3Dequote(zName);
117162        pList->a[i].zName = zName;
117163      }
117164    }
117165    if( pSub->pOrderBy ){
117166      /* At this point, any non-zero iOrderByCol values indicate that the
117167      ** ORDER BY column expression is identical to the iOrderByCol'th
117168      ** expression returned by SELECT statement pSub. Since these values
117169      ** do not necessarily correspond to columns in SELECT statement pParent,
117170      ** zero them before transfering the ORDER BY clause.
117171      **
117172      ** Not doing this may cause an error if a subsequent call to this
117173      ** function attempts to flatten a compound sub-query into pParent
117174      ** (the only way this can happen is if the compound sub-query is
117175      ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
117176      ExprList *pOrderBy = pSub->pOrderBy;
117177      for(i=0; i<pOrderBy->nExpr; i++){
117178        pOrderBy->a[i].u.x.iOrderByCol = 0;
117179      }
117180      assert( pParent->pOrderBy==0 );
117181      assert( pSub->pPrior==0 );
117182      pParent->pOrderBy = pOrderBy;
117183      pSub->pOrderBy = 0;
117184    }
117185    pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
117186    if( subqueryIsAgg ){
117187      assert( pParent->pHaving==0 );
117188      pParent->pHaving = pParent->pWhere;
117189      pParent->pWhere = pWhere;
117190      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
117191                                  sqlite3ExprDup(db, pSub->pHaving, 0));
117192      assert( pParent->pGroupBy==0 );
117193      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
117194    }else{
117195      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
117196    }
117197    substSelect(db, pParent, iParent, pSub->pEList, 0);
117198
117199    /* The flattened query is distinct if either the inner or the
117200    ** outer query is distinct.
117201    */
117202    pParent->selFlags |= pSub->selFlags & SF_Distinct;
117203
117204    /*
117205    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
117206    **
117207    ** One is tempted to try to add a and b to combine the limits.  But this
117208    ** does not work if either limit is negative.
117209    */
117210    if( pSub->pLimit ){
117211      pParent->pLimit = pSub->pLimit;
117212      pSub->pLimit = 0;
117213    }
117214  }
117215
117216  /* Finially, delete what is left of the subquery and return
117217  ** success.
117218  */
117219  sqlite3SelectDelete(db, pSub1);
117220
117221#if SELECTTRACE_ENABLED
117222  if( sqlite3SelectTrace & 0x100 ){
117223    SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
117224    sqlite3TreeViewSelect(0, p, 0);
117225  }
117226#endif
117227
117228  return 1;
117229}
117230#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
117231
117232
117233
117234#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
117235/*
117236** Make copies of relevant WHERE clause terms of the outer query into
117237** the WHERE clause of subquery.  Example:
117238**
117239**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
117240**
117241** Transformed into:
117242**
117243**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
117244**     WHERE x=5 AND y=10;
117245**
117246** The hope is that the terms added to the inner query will make it more
117247** efficient.
117248**
117249** Do not attempt this optimization if:
117250**
117251**   (1) The inner query is an aggregate.  (In that case, we'd really want
117252**       to copy the outer WHERE-clause terms onto the HAVING clause of the
117253**       inner query.  But they probably won't help there so do not bother.)
117254**
117255**   (2) The inner query is the recursive part of a common table expression.
117256**
117257**   (3) The inner query has a LIMIT clause (since the changes to the WHERE
117258**       close would change the meaning of the LIMIT).
117259**
117260**   (4) The inner query is the right operand of a LEFT JOIN.  (The caller
117261**       enforces this restriction since this routine does not have enough
117262**       information to know.)
117263**
117264**   (5) The WHERE clause expression originates in the ON or USING clause
117265**       of a LEFT JOIN.
117266**
117267** Return 0 if no changes are made and non-zero if one or more WHERE clause
117268** terms are duplicated into the subquery.
117269*/
117270static int pushDownWhereTerms(
117271  sqlite3 *db,          /* The database connection (for malloc()) */
117272  Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
117273  Expr *pWhere,         /* The WHERE clause of the outer query */
117274  int iCursor           /* Cursor number of the subquery */
117275){
117276  Expr *pNew;
117277  int nChng = 0;
117278  Select *pX;           /* For looping over compound SELECTs in pSubq */
117279  if( pWhere==0 ) return 0;
117280  for(pX=pSubq; pX; pX=pX->pPrior){
117281    if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
117282      testcase( pX->selFlags & SF_Aggregate );
117283      testcase( pX->selFlags & SF_Recursive );
117284      testcase( pX!=pSubq );
117285      return 0; /* restrictions (1) and (2) */
117286    }
117287  }
117288  if( pSubq->pLimit!=0 ){
117289    return 0; /* restriction (3) */
117290  }
117291  while( pWhere->op==TK_AND ){
117292    nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
117293    pWhere = pWhere->pLeft;
117294  }
117295  if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
117296  if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
117297    nChng++;
117298    while( pSubq ){
117299      pNew = sqlite3ExprDup(db, pWhere, 0);
117300      pNew = substExpr(db, pNew, iCursor, pSubq->pEList);
117301      pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew);
117302      pSubq = pSubq->pPrior;
117303    }
117304  }
117305  return nChng;
117306}
117307#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
117308
117309/*
117310** Based on the contents of the AggInfo structure indicated by the first
117311** argument, this function checks if the following are true:
117312**
117313**    * the query contains just a single aggregate function,
117314**    * the aggregate function is either min() or max(), and
117315**    * the argument to the aggregate function is a column value.
117316**
117317** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
117318** is returned as appropriate. Also, *ppMinMax is set to point to the
117319** list of arguments passed to the aggregate before returning.
117320**
117321** Or, if the conditions above are not met, *ppMinMax is set to 0 and
117322** WHERE_ORDERBY_NORMAL is returned.
117323*/
117324static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
117325  int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
117326
117327  *ppMinMax = 0;
117328  if( pAggInfo->nFunc==1 ){
117329    Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
117330    ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
117331
117332    assert( pExpr->op==TK_AGG_FUNCTION );
117333    if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
117334      const char *zFunc = pExpr->u.zToken;
117335      if( sqlite3StrICmp(zFunc, "min")==0 ){
117336        eRet = WHERE_ORDERBY_MIN;
117337        *ppMinMax = pEList;
117338      }else if( sqlite3StrICmp(zFunc, "max")==0 ){
117339        eRet = WHERE_ORDERBY_MAX;
117340        *ppMinMax = pEList;
117341      }
117342    }
117343  }
117344
117345  assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
117346  return eRet;
117347}
117348
117349/*
117350** The select statement passed as the first argument is an aggregate query.
117351** The second argument is the associated aggregate-info object. This
117352** function tests if the SELECT is of the form:
117353**
117354**   SELECT count(*) FROM <tbl>
117355**
117356** where table is a database table, not a sub-select or view. If the query
117357** does match this pattern, then a pointer to the Table object representing
117358** <tbl> is returned. Otherwise, 0 is returned.
117359*/
117360static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
117361  Table *pTab;
117362  Expr *pExpr;
117363
117364  assert( !p->pGroupBy );
117365
117366  if( p->pWhere || p->pEList->nExpr!=1
117367   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
117368  ){
117369    return 0;
117370  }
117371  pTab = p->pSrc->a[0].pTab;
117372  pExpr = p->pEList->a[0].pExpr;
117373  assert( pTab && !pTab->pSelect && pExpr );
117374
117375  if( IsVirtual(pTab) ) return 0;
117376  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
117377  if( NEVER(pAggInfo->nFunc==0) ) return 0;
117378  if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
117379  if( pExpr->flags&EP_Distinct ) return 0;
117380
117381  return pTab;
117382}
117383
117384/*
117385** If the source-list item passed as an argument was augmented with an
117386** INDEXED BY clause, then try to locate the specified index. If there
117387** was such a clause and the named index cannot be found, return
117388** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
117389** pFrom->pIndex and return SQLITE_OK.
117390*/
117391SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
117392  if( pFrom->pTab && pFrom->fg.isIndexedBy ){
117393    Table *pTab = pFrom->pTab;
117394    char *zIndexedBy = pFrom->u1.zIndexedBy;
117395    Index *pIdx;
117396    for(pIdx=pTab->pIndex;
117397        pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
117398        pIdx=pIdx->pNext
117399    );
117400    if( !pIdx ){
117401      sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
117402      pParse->checkSchema = 1;
117403      return SQLITE_ERROR;
117404    }
117405    pFrom->pIBIndex = pIdx;
117406  }
117407  return SQLITE_OK;
117408}
117409/*
117410** Detect compound SELECT statements that use an ORDER BY clause with
117411** an alternative collating sequence.
117412**
117413**    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
117414**
117415** These are rewritten as a subquery:
117416**
117417**    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
117418**     ORDER BY ... COLLATE ...
117419**
117420** This transformation is necessary because the multiSelectOrderBy() routine
117421** above that generates the code for a compound SELECT with an ORDER BY clause
117422** uses a merge algorithm that requires the same collating sequence on the
117423** result columns as on the ORDER BY clause.  See ticket
117424** http://www.sqlite.org/src/info/6709574d2a
117425**
117426** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
117427** The UNION ALL operator works fine with multiSelectOrderBy() even when
117428** there are COLLATE terms in the ORDER BY.
117429*/
117430static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
117431  int i;
117432  Select *pNew;
117433  Select *pX;
117434  sqlite3 *db;
117435  struct ExprList_item *a;
117436  SrcList *pNewSrc;
117437  Parse *pParse;
117438  Token dummy;
117439
117440  if( p->pPrior==0 ) return WRC_Continue;
117441  if( p->pOrderBy==0 ) return WRC_Continue;
117442  for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
117443  if( pX==0 ) return WRC_Continue;
117444  a = p->pOrderBy->a;
117445  for(i=p->pOrderBy->nExpr-1; i>=0; i--){
117446    if( a[i].pExpr->flags & EP_Collate ) break;
117447  }
117448  if( i<0 ) return WRC_Continue;
117449
117450  /* If we reach this point, that means the transformation is required. */
117451
117452  pParse = pWalker->pParse;
117453  db = pParse->db;
117454  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
117455  if( pNew==0 ) return WRC_Abort;
117456  memset(&dummy, 0, sizeof(dummy));
117457  pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
117458  if( pNewSrc==0 ) return WRC_Abort;
117459  *pNew = *p;
117460  p->pSrc = pNewSrc;
117461  p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
117462  p->op = TK_SELECT;
117463  p->pWhere = 0;
117464  pNew->pGroupBy = 0;
117465  pNew->pHaving = 0;
117466  pNew->pOrderBy = 0;
117467  p->pPrior = 0;
117468  p->pNext = 0;
117469  p->pWith = 0;
117470  p->selFlags &= ~SF_Compound;
117471  assert( (p->selFlags & SF_Converted)==0 );
117472  p->selFlags |= SF_Converted;
117473  assert( pNew->pPrior!=0 );
117474  pNew->pPrior->pNext = pNew;
117475  pNew->pLimit = 0;
117476  pNew->pOffset = 0;
117477  return WRC_Continue;
117478}
117479
117480/*
117481** Check to see if the FROM clause term pFrom has table-valued function
117482** arguments.  If it does, leave an error message in pParse and return
117483** non-zero, since pFrom is not allowed to be a table-valued function.
117484*/
117485static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
117486  if( pFrom->fg.isTabFunc ){
117487    sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
117488    return 1;
117489  }
117490  return 0;
117491}
117492
117493#ifndef SQLITE_OMIT_CTE
117494/*
117495** Argument pWith (which may be NULL) points to a linked list of nested
117496** WITH contexts, from inner to outermost. If the table identified by
117497** FROM clause element pItem is really a common-table-expression (CTE)
117498** then return a pointer to the CTE definition for that table. Otherwise
117499** return NULL.
117500**
117501** If a non-NULL value is returned, set *ppContext to point to the With
117502** object that the returned CTE belongs to.
117503*/
117504static struct Cte *searchWith(
117505  With *pWith,                    /* Current innermost WITH clause */
117506  struct SrcList_item *pItem,     /* FROM clause element to resolve */
117507  With **ppContext                /* OUT: WITH clause return value belongs to */
117508){
117509  const char *zName;
117510  if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
117511    With *p;
117512    for(p=pWith; p; p=p->pOuter){
117513      int i;
117514      for(i=0; i<p->nCte; i++){
117515        if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
117516          *ppContext = p;
117517          return &p->a[i];
117518        }
117519      }
117520    }
117521  }
117522  return 0;
117523}
117524
117525/* The code generator maintains a stack of active WITH clauses
117526** with the inner-most WITH clause being at the top of the stack.
117527**
117528** This routine pushes the WITH clause passed as the second argument
117529** onto the top of the stack. If argument bFree is true, then this
117530** WITH clause will never be popped from the stack. In this case it
117531** should be freed along with the Parse object. In other cases, when
117532** bFree==0, the With object will be freed along with the SELECT
117533** statement with which it is associated.
117534*/
117535SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
117536  assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
117537  if( pWith ){
117538    assert( pParse->pWith!=pWith );
117539    pWith->pOuter = pParse->pWith;
117540    pParse->pWith = pWith;
117541    if( bFree ) pParse->pWithToFree = pWith;
117542  }
117543}
117544
117545/*
117546** This function checks if argument pFrom refers to a CTE declared by
117547** a WITH clause on the stack currently maintained by the parser. And,
117548** if currently processing a CTE expression, if it is a recursive
117549** reference to the current CTE.
117550**
117551** If pFrom falls into either of the two categories above, pFrom->pTab
117552** and other fields are populated accordingly. The caller should check
117553** (pFrom->pTab!=0) to determine whether or not a successful match
117554** was found.
117555**
117556** Whether or not a match is found, SQLITE_OK is returned if no error
117557** occurs. If an error does occur, an error message is stored in the
117558** parser and some error code other than SQLITE_OK returned.
117559*/
117560static int withExpand(
117561  Walker *pWalker,
117562  struct SrcList_item *pFrom
117563){
117564  Parse *pParse = pWalker->pParse;
117565  sqlite3 *db = pParse->db;
117566  struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
117567  With *pWith;                    /* WITH clause that pCte belongs to */
117568
117569  assert( pFrom->pTab==0 );
117570
117571  pCte = searchWith(pParse->pWith, pFrom, &pWith);
117572  if( pCte ){
117573    Table *pTab;
117574    ExprList *pEList;
117575    Select *pSel;
117576    Select *pLeft;                /* Left-most SELECT statement */
117577    int bMayRecursive;            /* True if compound joined by UNION [ALL] */
117578    With *pSavedWith;             /* Initial value of pParse->pWith */
117579
117580    /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
117581    ** recursive reference to CTE pCte. Leave an error in pParse and return
117582    ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
117583    ** In this case, proceed.  */
117584    if( pCte->zCteErr ){
117585      sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
117586      return SQLITE_ERROR;
117587    }
117588    if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
117589
117590    assert( pFrom->pTab==0 );
117591    pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
117592    if( pTab==0 ) return WRC_Abort;
117593    pTab->nRef = 1;
117594    pTab->zName = sqlite3DbStrDup(db, pCte->zName);
117595    pTab->iPKey = -1;
117596    pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
117597    pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
117598    pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
117599    if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
117600    assert( pFrom->pSelect );
117601
117602    /* Check if this is a recursive CTE. */
117603    pSel = pFrom->pSelect;
117604    bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
117605    if( bMayRecursive ){
117606      int i;
117607      SrcList *pSrc = pFrom->pSelect->pSrc;
117608      for(i=0; i<pSrc->nSrc; i++){
117609        struct SrcList_item *pItem = &pSrc->a[i];
117610        if( pItem->zDatabase==0
117611         && pItem->zName!=0
117612         && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
117613          ){
117614          pItem->pTab = pTab;
117615          pItem->fg.isRecursive = 1;
117616          pTab->nRef++;
117617          pSel->selFlags |= SF_Recursive;
117618        }
117619      }
117620    }
117621
117622    /* Only one recursive reference is permitted. */
117623    if( pTab->nRef>2 ){
117624      sqlite3ErrorMsg(
117625          pParse, "multiple references to recursive table: %s", pCte->zName
117626      );
117627      return SQLITE_ERROR;
117628    }
117629    assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
117630
117631    pCte->zCteErr = "circular reference: %s";
117632    pSavedWith = pParse->pWith;
117633    pParse->pWith = pWith;
117634    sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
117635    pParse->pWith = pWith;
117636
117637    for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
117638    pEList = pLeft->pEList;
117639    if( pCte->pCols ){
117640      if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
117641        sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
117642            pCte->zName, pEList->nExpr, pCte->pCols->nExpr
117643        );
117644        pParse->pWith = pSavedWith;
117645        return SQLITE_ERROR;
117646      }
117647      pEList = pCte->pCols;
117648    }
117649
117650    sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
117651    if( bMayRecursive ){
117652      if( pSel->selFlags & SF_Recursive ){
117653        pCte->zCteErr = "multiple recursive references: %s";
117654      }else{
117655        pCte->zCteErr = "recursive reference in a subquery: %s";
117656      }
117657      sqlite3WalkSelect(pWalker, pSel);
117658    }
117659    pCte->zCteErr = 0;
117660    pParse->pWith = pSavedWith;
117661  }
117662
117663  return SQLITE_OK;
117664}
117665#endif
117666
117667#ifndef SQLITE_OMIT_CTE
117668/*
117669** If the SELECT passed as the second argument has an associated WITH
117670** clause, pop it from the stack stored as part of the Parse object.
117671**
117672** This function is used as the xSelectCallback2() callback by
117673** sqlite3SelectExpand() when walking a SELECT tree to resolve table
117674** names and other FROM clause elements.
117675*/
117676static void selectPopWith(Walker *pWalker, Select *p){
117677  Parse *pParse = pWalker->pParse;
117678  With *pWith = findRightmost(p)->pWith;
117679  if( pWith!=0 ){
117680    assert( pParse->pWith==pWith );
117681    pParse->pWith = pWith->pOuter;
117682  }
117683}
117684#else
117685#define selectPopWith 0
117686#endif
117687
117688/*
117689** This routine is a Walker callback for "expanding" a SELECT statement.
117690** "Expanding" means to do the following:
117691**
117692**    (1)  Make sure VDBE cursor numbers have been assigned to every
117693**         element of the FROM clause.
117694**
117695**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
117696**         defines FROM clause.  When views appear in the FROM clause,
117697**         fill pTabList->a[].pSelect with a copy of the SELECT statement
117698**         that implements the view.  A copy is made of the view's SELECT
117699**         statement so that we can freely modify or delete that statement
117700**         without worrying about messing up the persistent representation
117701**         of the view.
117702**
117703**    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
117704**         on joins and the ON and USING clause of joins.
117705**
117706**    (4)  Scan the list of columns in the result set (pEList) looking
117707**         for instances of the "*" operator or the TABLE.* operator.
117708**         If found, expand each "*" to be every column in every table
117709**         and TABLE.* to be every column in TABLE.
117710**
117711*/
117712static int selectExpander(Walker *pWalker, Select *p){
117713  Parse *pParse = pWalker->pParse;
117714  int i, j, k;
117715  SrcList *pTabList;
117716  ExprList *pEList;
117717  struct SrcList_item *pFrom;
117718  sqlite3 *db = pParse->db;
117719  Expr *pE, *pRight, *pExpr;
117720  u16 selFlags = p->selFlags;
117721
117722  p->selFlags |= SF_Expanded;
117723  if( db->mallocFailed  ){
117724    return WRC_Abort;
117725  }
117726  if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
117727    return WRC_Prune;
117728  }
117729  pTabList = p->pSrc;
117730  pEList = p->pEList;
117731  if( pWalker->xSelectCallback2==selectPopWith ){
117732    sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
117733  }
117734
117735  /* Make sure cursor numbers have been assigned to all entries in
117736  ** the FROM clause of the SELECT statement.
117737  */
117738  sqlite3SrcListAssignCursors(pParse, pTabList);
117739
117740  /* Look up every table named in the FROM clause of the select.  If
117741  ** an entry of the FROM clause is a subquery instead of a table or view,
117742  ** then create a transient table structure to describe the subquery.
117743  */
117744  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
117745    Table *pTab;
117746    assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
117747    if( pFrom->fg.isRecursive ) continue;
117748    assert( pFrom->pTab==0 );
117749#ifndef SQLITE_OMIT_CTE
117750    if( withExpand(pWalker, pFrom) ) return WRC_Abort;
117751    if( pFrom->pTab ) {} else
117752#endif
117753    if( pFrom->zName==0 ){
117754#ifndef SQLITE_OMIT_SUBQUERY
117755      Select *pSel = pFrom->pSelect;
117756      /* A sub-query in the FROM clause of a SELECT */
117757      assert( pSel!=0 );
117758      assert( pFrom->pTab==0 );
117759      if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
117760      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
117761      if( pTab==0 ) return WRC_Abort;
117762      pTab->nRef = 1;
117763      pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
117764      while( pSel->pPrior ){ pSel = pSel->pPrior; }
117765      sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
117766      pTab->iPKey = -1;
117767      pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
117768      pTab->tabFlags |= TF_Ephemeral;
117769#endif
117770    }else{
117771      /* An ordinary table or view name in the FROM clause */
117772      assert( pFrom->pTab==0 );
117773      pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
117774      if( pTab==0 ) return WRC_Abort;
117775      if( pTab->nRef==0xffff ){
117776        sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
117777           pTab->zName);
117778        pFrom->pTab = 0;
117779        return WRC_Abort;
117780      }
117781      pTab->nRef++;
117782      if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
117783        return WRC_Abort;
117784      }
117785#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
117786      if( IsVirtual(pTab) || pTab->pSelect ){
117787        i16 nCol;
117788        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
117789        assert( pFrom->pSelect==0 );
117790        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
117791        sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
117792        nCol = pTab->nCol;
117793        pTab->nCol = -1;
117794        sqlite3WalkSelect(pWalker, pFrom->pSelect);
117795        pTab->nCol = nCol;
117796      }
117797#endif
117798    }
117799
117800    /* Locate the index named by the INDEXED BY clause, if any. */
117801    if( sqlite3IndexedByLookup(pParse, pFrom) ){
117802      return WRC_Abort;
117803    }
117804  }
117805
117806  /* Process NATURAL keywords, and ON and USING clauses of joins.
117807  */
117808  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
117809    return WRC_Abort;
117810  }
117811
117812  /* For every "*" that occurs in the column list, insert the names of
117813  ** all columns in all tables.  And for every TABLE.* insert the names
117814  ** of all columns in TABLE.  The parser inserted a special expression
117815  ** with the TK_ASTERISK operator for each "*" that it found in the column
117816  ** list.  The following code just has to locate the TK_ASTERISK
117817  ** expressions and expand each one to the list of all columns in
117818  ** all tables.
117819  **
117820  ** The first loop just checks to see if there are any "*" operators
117821  ** that need expanding.
117822  */
117823  for(k=0; k<pEList->nExpr; k++){
117824    pE = pEList->a[k].pExpr;
117825    if( pE->op==TK_ASTERISK ) break;
117826    assert( pE->op!=TK_DOT || pE->pRight!=0 );
117827    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
117828    if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
117829  }
117830  if( k<pEList->nExpr ){
117831    /*
117832    ** If we get here it means the result set contains one or more "*"
117833    ** operators that need to be expanded.  Loop through each expression
117834    ** in the result set and expand them one by one.
117835    */
117836    struct ExprList_item *a = pEList->a;
117837    ExprList *pNew = 0;
117838    int flags = pParse->db->flags;
117839    int longNames = (flags & SQLITE_FullColNames)!=0
117840                      && (flags & SQLITE_ShortColNames)==0;
117841
117842    for(k=0; k<pEList->nExpr; k++){
117843      pE = a[k].pExpr;
117844      pRight = pE->pRight;
117845      assert( pE->op!=TK_DOT || pRight!=0 );
117846      if( pE->op!=TK_ASTERISK
117847       && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
117848      ){
117849        /* This particular expression does not need to be expanded.
117850        */
117851        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
117852        if( pNew ){
117853          pNew->a[pNew->nExpr-1].zName = a[k].zName;
117854          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
117855          a[k].zName = 0;
117856          a[k].zSpan = 0;
117857        }
117858        a[k].pExpr = 0;
117859      }else{
117860        /* This expression is a "*" or a "TABLE.*" and needs to be
117861        ** expanded. */
117862        int tableSeen = 0;      /* Set to 1 when TABLE matches */
117863        char *zTName = 0;       /* text of name of TABLE */
117864        if( pE->op==TK_DOT ){
117865          assert( pE->pLeft!=0 );
117866          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
117867          zTName = pE->pLeft->u.zToken;
117868        }
117869        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
117870          Table *pTab = pFrom->pTab;
117871          Select *pSub = pFrom->pSelect;
117872          char *zTabName = pFrom->zAlias;
117873          const char *zSchemaName = 0;
117874          int iDb;
117875          if( zTabName==0 ){
117876            zTabName = pTab->zName;
117877          }
117878          if( db->mallocFailed ) break;
117879          if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
117880            pSub = 0;
117881            if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
117882              continue;
117883            }
117884            iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
117885            zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
117886          }
117887          for(j=0; j<pTab->nCol; j++){
117888            char *zName = pTab->aCol[j].zName;
117889            char *zColname;  /* The computed column name */
117890            char *zToFree;   /* Malloced string that needs to be freed */
117891            Token sColname;  /* Computed column name as a token */
117892
117893            assert( zName );
117894            if( zTName && pSub
117895             && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
117896            ){
117897              continue;
117898            }
117899
117900            /* If a column is marked as 'hidden', omit it from the expanded
117901            ** result-set list unless the SELECT has the SF_IncludeHidden
117902            ** bit set.
117903            */
117904            if( (p->selFlags & SF_IncludeHidden)==0
117905             && IsHiddenColumn(&pTab->aCol[j])
117906            ){
117907              continue;
117908            }
117909            tableSeen = 1;
117910
117911            if( i>0 && zTName==0 ){
117912              if( (pFrom->fg.jointype & JT_NATURAL)!=0
117913                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
117914              ){
117915                /* In a NATURAL join, omit the join columns from the
117916                ** table to the right of the join */
117917                continue;
117918              }
117919              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
117920                /* In a join with a USING clause, omit columns in the
117921                ** using clause from the table on the right. */
117922                continue;
117923              }
117924            }
117925            pRight = sqlite3Expr(db, TK_ID, zName);
117926            zColname = zName;
117927            zToFree = 0;
117928            if( longNames || pTabList->nSrc>1 ){
117929              Expr *pLeft;
117930              pLeft = sqlite3Expr(db, TK_ID, zTabName);
117931              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
117932              if( zSchemaName ){
117933                pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
117934                pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
117935              }
117936              if( longNames ){
117937                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
117938                zToFree = zColname;
117939              }
117940            }else{
117941              pExpr = pRight;
117942            }
117943            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
117944            sqlite3TokenInit(&sColname, zColname);
117945            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
117946            if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
117947              struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
117948              if( pSub ){
117949                pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
117950                testcase( pX->zSpan==0 );
117951              }else{
117952                pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
117953                                           zSchemaName, zTabName, zColname);
117954                testcase( pX->zSpan==0 );
117955              }
117956              pX->bSpanIsTab = 1;
117957            }
117958            sqlite3DbFree(db, zToFree);
117959          }
117960        }
117961        if( !tableSeen ){
117962          if( zTName ){
117963            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
117964          }else{
117965            sqlite3ErrorMsg(pParse, "no tables specified");
117966          }
117967        }
117968      }
117969    }
117970    sqlite3ExprListDelete(db, pEList);
117971    p->pEList = pNew;
117972  }
117973#if SQLITE_MAX_COLUMN
117974  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
117975    sqlite3ErrorMsg(pParse, "too many columns in result set");
117976    return WRC_Abort;
117977  }
117978#endif
117979  return WRC_Continue;
117980}
117981
117982/*
117983** No-op routine for the parse-tree walker.
117984**
117985** When this routine is the Walker.xExprCallback then expression trees
117986** are walked without any actions being taken at each node.  Presumably,
117987** when this routine is used for Walker.xExprCallback then
117988** Walker.xSelectCallback is set to do something useful for every
117989** subquery in the parser tree.
117990*/
117991SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
117992  UNUSED_PARAMETER2(NotUsed, NotUsed2);
117993  return WRC_Continue;
117994}
117995
117996/*
117997** This routine "expands" a SELECT statement and all of its subqueries.
117998** For additional information on what it means to "expand" a SELECT
117999** statement, see the comment on the selectExpand worker callback above.
118000**
118001** Expanding a SELECT statement is the first step in processing a
118002** SELECT statement.  The SELECT statement must be expanded before
118003** name resolution is performed.
118004**
118005** If anything goes wrong, an error message is written into pParse.
118006** The calling function can detect the problem by looking at pParse->nErr
118007** and/or pParse->db->mallocFailed.
118008*/
118009static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
118010  Walker w;
118011  memset(&w, 0, sizeof(w));
118012  w.xExprCallback = sqlite3ExprWalkNoop;
118013  w.pParse = pParse;
118014  if( pParse->hasCompound ){
118015    w.xSelectCallback = convertCompoundSelectToSubquery;
118016    sqlite3WalkSelect(&w, pSelect);
118017  }
118018  w.xSelectCallback = selectExpander;
118019  if( (pSelect->selFlags & SF_MultiValue)==0 ){
118020    w.xSelectCallback2 = selectPopWith;
118021  }
118022  sqlite3WalkSelect(&w, pSelect);
118023}
118024
118025
118026#ifndef SQLITE_OMIT_SUBQUERY
118027/*
118028** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
118029** interface.
118030**
118031** For each FROM-clause subquery, add Column.zType and Column.zColl
118032** information to the Table structure that represents the result set
118033** of that subquery.
118034**
118035** The Table structure that represents the result set was constructed
118036** by selectExpander() but the type and collation information was omitted
118037** at that point because identifiers had not yet been resolved.  This
118038** routine is called after identifier resolution.
118039*/
118040static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
118041  Parse *pParse;
118042  int i;
118043  SrcList *pTabList;
118044  struct SrcList_item *pFrom;
118045
118046  assert( p->selFlags & SF_Resolved );
118047  assert( (p->selFlags & SF_HasTypeInfo)==0 );
118048  p->selFlags |= SF_HasTypeInfo;
118049  pParse = pWalker->pParse;
118050  pTabList = p->pSrc;
118051  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
118052    Table *pTab = pFrom->pTab;
118053    assert( pTab!=0 );
118054    if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
118055      /* A sub-query in the FROM clause of a SELECT */
118056      Select *pSel = pFrom->pSelect;
118057      if( pSel ){
118058        while( pSel->pPrior ) pSel = pSel->pPrior;
118059        sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
118060      }
118061    }
118062  }
118063}
118064#endif
118065
118066
118067/*
118068** This routine adds datatype and collating sequence information to
118069** the Table structures of all FROM-clause subqueries in a
118070** SELECT statement.
118071**
118072** Use this routine after name resolution.
118073*/
118074static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
118075#ifndef SQLITE_OMIT_SUBQUERY
118076  Walker w;
118077  memset(&w, 0, sizeof(w));
118078  w.xSelectCallback2 = selectAddSubqueryTypeInfo;
118079  w.xExprCallback = sqlite3ExprWalkNoop;
118080  w.pParse = pParse;
118081  sqlite3WalkSelect(&w, pSelect);
118082#endif
118083}
118084
118085
118086/*
118087** This routine sets up a SELECT statement for processing.  The
118088** following is accomplished:
118089**
118090**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
118091**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
118092**     *  ON and USING clauses are shifted into WHERE statements
118093**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
118094**     *  Identifiers in expression are matched to tables.
118095**
118096** This routine acts recursively on all subqueries within the SELECT.
118097*/
118098SQLITE_PRIVATE void sqlite3SelectPrep(
118099  Parse *pParse,         /* The parser context */
118100  Select *p,             /* The SELECT statement being coded. */
118101  NameContext *pOuterNC  /* Name context for container */
118102){
118103  sqlite3 *db;
118104  if( NEVER(p==0) ) return;
118105  db = pParse->db;
118106  if( db->mallocFailed ) return;
118107  if( p->selFlags & SF_HasTypeInfo ) return;
118108  sqlite3SelectExpand(pParse, p);
118109  if( pParse->nErr || db->mallocFailed ) return;
118110  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
118111  if( pParse->nErr || db->mallocFailed ) return;
118112  sqlite3SelectAddTypeInfo(pParse, p);
118113}
118114
118115/*
118116** Reset the aggregate accumulator.
118117**
118118** The aggregate accumulator is a set of memory cells that hold
118119** intermediate results while calculating an aggregate.  This
118120** routine generates code that stores NULLs in all of those memory
118121** cells.
118122*/
118123static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
118124  Vdbe *v = pParse->pVdbe;
118125  int i;
118126  struct AggInfo_func *pFunc;
118127  int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
118128  if( nReg==0 ) return;
118129#ifdef SQLITE_DEBUG
118130  /* Verify that all AggInfo registers are within the range specified by
118131  ** AggInfo.mnReg..AggInfo.mxReg */
118132  assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
118133  for(i=0; i<pAggInfo->nColumn; i++){
118134    assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
118135         && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
118136  }
118137  for(i=0; i<pAggInfo->nFunc; i++){
118138    assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
118139         && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
118140  }
118141#endif
118142  sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
118143  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
118144    if( pFunc->iDistinct>=0 ){
118145      Expr *pE = pFunc->pExpr;
118146      assert( !ExprHasProperty(pE, EP_xIsSelect) );
118147      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
118148        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
118149           "argument");
118150        pFunc->iDistinct = -1;
118151      }else{
118152        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
118153        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
118154                          (char*)pKeyInfo, P4_KEYINFO);
118155      }
118156    }
118157  }
118158}
118159
118160/*
118161** Invoke the OP_AggFinalize opcode for every aggregate function
118162** in the AggInfo structure.
118163*/
118164static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
118165  Vdbe *v = pParse->pVdbe;
118166  int i;
118167  struct AggInfo_func *pF;
118168  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
118169    ExprList *pList = pF->pExpr->x.pList;
118170    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
118171    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
118172                      (void*)pF->pFunc, P4_FUNCDEF);
118173  }
118174}
118175
118176/*
118177** Update the accumulator memory cells for an aggregate based on
118178** the current cursor position.
118179*/
118180static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
118181  Vdbe *v = pParse->pVdbe;
118182  int i;
118183  int regHit = 0;
118184  int addrHitTest = 0;
118185  struct AggInfo_func *pF;
118186  struct AggInfo_col *pC;
118187
118188  pAggInfo->directMode = 1;
118189  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
118190    int nArg;
118191    int addrNext = 0;
118192    int regAgg;
118193    ExprList *pList = pF->pExpr->x.pList;
118194    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
118195    if( pList ){
118196      nArg = pList->nExpr;
118197      regAgg = sqlite3GetTempRange(pParse, nArg);
118198      sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
118199    }else{
118200      nArg = 0;
118201      regAgg = 0;
118202    }
118203    if( pF->iDistinct>=0 ){
118204      addrNext = sqlite3VdbeMakeLabel(v);
118205      testcase( nArg==0 );  /* Error condition */
118206      testcase( nArg>1 );   /* Also an error */
118207      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
118208    }
118209    if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
118210      CollSeq *pColl = 0;
118211      struct ExprList_item *pItem;
118212      int j;
118213      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
118214      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
118215        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
118216      }
118217      if( !pColl ){
118218        pColl = pParse->db->pDfltColl;
118219      }
118220      if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
118221      sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
118222    }
118223    sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem,
118224                      (void*)pF->pFunc, P4_FUNCDEF);
118225    sqlite3VdbeChangeP5(v, (u8)nArg);
118226    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
118227    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
118228    if( addrNext ){
118229      sqlite3VdbeResolveLabel(v, addrNext);
118230      sqlite3ExprCacheClear(pParse);
118231    }
118232  }
118233
118234  /* Before populating the accumulator registers, clear the column cache.
118235  ** Otherwise, if any of the required column values are already present
118236  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
118237  ** to pC->iMem. But by the time the value is used, the original register
118238  ** may have been used, invalidating the underlying buffer holding the
118239  ** text or blob value. See ticket [883034dcb5].
118240  **
118241  ** Another solution would be to change the OP_SCopy used to copy cached
118242  ** values to an OP_Copy.
118243  */
118244  if( regHit ){
118245    addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
118246  }
118247  sqlite3ExprCacheClear(pParse);
118248  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
118249    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
118250  }
118251  pAggInfo->directMode = 0;
118252  sqlite3ExprCacheClear(pParse);
118253  if( addrHitTest ){
118254    sqlite3VdbeJumpHere(v, addrHitTest);
118255  }
118256}
118257
118258/*
118259** Add a single OP_Explain instruction to the VDBE to explain a simple
118260** count(*) query ("SELECT count(*) FROM pTab").
118261*/
118262#ifndef SQLITE_OMIT_EXPLAIN
118263static void explainSimpleCount(
118264  Parse *pParse,                  /* Parse context */
118265  Table *pTab,                    /* Table being queried */
118266  Index *pIdx                     /* Index used to optimize scan, or NULL */
118267){
118268  if( pParse->explain==2 ){
118269    int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
118270    char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
118271        pTab->zName,
118272        bCover ? " USING COVERING INDEX " : "",
118273        bCover ? pIdx->zName : ""
118274    );
118275    sqlite3VdbeAddOp4(
118276        pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
118277    );
118278  }
118279}
118280#else
118281# define explainSimpleCount(a,b,c)
118282#endif
118283
118284/*
118285** Generate code for the SELECT statement given in the p argument.
118286**
118287** The results are returned according to the SelectDest structure.
118288** See comments in sqliteInt.h for further information.
118289**
118290** This routine returns the number of errors.  If any errors are
118291** encountered, then an appropriate error message is left in
118292** pParse->zErrMsg.
118293**
118294** This routine does NOT free the Select structure passed in.  The
118295** calling function needs to do that.
118296*/
118297SQLITE_PRIVATE int sqlite3Select(
118298  Parse *pParse,         /* The parser context */
118299  Select *p,             /* The SELECT statement being coded. */
118300  SelectDest *pDest      /* What to do with the query results */
118301){
118302  int i, j;              /* Loop counters */
118303  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
118304  Vdbe *v;               /* The virtual machine under construction */
118305  int isAgg;             /* True for select lists like "count(*)" */
118306  ExprList *pEList = 0;  /* List of columns to extract. */
118307  SrcList *pTabList;     /* List of tables to select from */
118308  Expr *pWhere;          /* The WHERE clause.  May be NULL */
118309  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
118310  Expr *pHaving;         /* The HAVING clause.  May be NULL */
118311  int rc = 1;            /* Value to return from this function */
118312  DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
118313  SortCtx sSort;         /* Info on how to code the ORDER BY clause */
118314  AggInfo sAggInfo;      /* Information used by aggregate queries */
118315  int iEnd;              /* Address of the end of the query */
118316  sqlite3 *db;           /* The database connection */
118317
118318#ifndef SQLITE_OMIT_EXPLAIN
118319  int iRestoreSelectId = pParse->iSelectId;
118320  pParse->iSelectId = pParse->iNextSelectId++;
118321#endif
118322
118323  db = pParse->db;
118324  if( p==0 || db->mallocFailed || pParse->nErr ){
118325    return 1;
118326  }
118327  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
118328  memset(&sAggInfo, 0, sizeof(sAggInfo));
118329#if SELECTTRACE_ENABLED
118330  pParse->nSelectIndent++;
118331  SELECTTRACE(1,pParse,p, ("begin processing:\n"));
118332  if( sqlite3SelectTrace & 0x100 ){
118333    sqlite3TreeViewSelect(0, p, 0);
118334  }
118335#endif
118336
118337  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
118338  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
118339  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
118340  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
118341  if( IgnorableOrderby(pDest) ){
118342    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
118343           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
118344           pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
118345           pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
118346    /* If ORDER BY makes no difference in the output then neither does
118347    ** DISTINCT so it can be removed too. */
118348    sqlite3ExprListDelete(db, p->pOrderBy);
118349    p->pOrderBy = 0;
118350    p->selFlags &= ~SF_Distinct;
118351  }
118352  sqlite3SelectPrep(pParse, p, 0);
118353  memset(&sSort, 0, sizeof(sSort));
118354  sSort.pOrderBy = p->pOrderBy;
118355  pTabList = p->pSrc;
118356  if( pParse->nErr || db->mallocFailed ){
118357    goto select_end;
118358  }
118359  assert( p->pEList!=0 );
118360  isAgg = (p->selFlags & SF_Aggregate)!=0;
118361#if SELECTTRACE_ENABLED
118362  if( sqlite3SelectTrace & 0x100 ){
118363    SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
118364    sqlite3TreeViewSelect(0, p, 0);
118365  }
118366#endif
118367
118368
118369  /* If writing to memory or generating a set
118370  ** only a single column may be output.
118371  */
118372#ifndef SQLITE_OMIT_SUBQUERY
118373  if( checkForMultiColumnSelectError(pParse, pDest, p->pEList->nExpr) ){
118374    goto select_end;
118375  }
118376#endif
118377
118378  /* Try to flatten subqueries in the FROM clause up into the main query
118379  */
118380#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
118381  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
118382    struct SrcList_item *pItem = &pTabList->a[i];
118383    Select *pSub = pItem->pSelect;
118384    int isAggSub;
118385    Table *pTab = pItem->pTab;
118386    if( pSub==0 ) continue;
118387
118388    /* Catch mismatch in the declared columns of a view and the number of
118389    ** columns in the SELECT on the RHS */
118390    if( pTab->nCol!=pSub->pEList->nExpr ){
118391      sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
118392                      pTab->nCol, pTab->zName, pSub->pEList->nExpr);
118393      goto select_end;
118394    }
118395
118396    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
118397    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
118398      /* This subquery can be absorbed into its parent. */
118399      if( isAggSub ){
118400        isAgg = 1;
118401        p->selFlags |= SF_Aggregate;
118402      }
118403      i = -1;
118404    }
118405    pTabList = p->pSrc;
118406    if( db->mallocFailed ) goto select_end;
118407    if( !IgnorableOrderby(pDest) ){
118408      sSort.pOrderBy = p->pOrderBy;
118409    }
118410  }
118411#endif
118412
118413  /* Get a pointer the VDBE under construction, allocating a new VDBE if one
118414  ** does not already exist */
118415  v = sqlite3GetVdbe(pParse);
118416  if( v==0 ) goto select_end;
118417
118418#ifndef SQLITE_OMIT_COMPOUND_SELECT
118419  /* Handle compound SELECT statements using the separate multiSelect()
118420  ** procedure.
118421  */
118422  if( p->pPrior ){
118423    rc = multiSelect(pParse, p, pDest);
118424    explainSetInteger(pParse->iSelectId, iRestoreSelectId);
118425#if SELECTTRACE_ENABLED
118426    SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
118427    pParse->nSelectIndent--;
118428#endif
118429    return rc;
118430  }
118431#endif
118432
118433  /* Generate code for all sub-queries in the FROM clause
118434  */
118435#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
118436  for(i=0; i<pTabList->nSrc; i++){
118437    struct SrcList_item *pItem = &pTabList->a[i];
118438    SelectDest dest;
118439    Select *pSub = pItem->pSelect;
118440    if( pSub==0 ) continue;
118441
118442    /* Sometimes the code for a subquery will be generated more than
118443    ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
118444    ** for example.  In that case, do not regenerate the code to manifest
118445    ** a view or the co-routine to implement a view.  The first instance
118446    ** is sufficient, though the subroutine to manifest the view does need
118447    ** to be invoked again. */
118448    if( pItem->addrFillSub ){
118449      if( pItem->fg.viaCoroutine==0 ){
118450        sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
118451      }
118452      continue;
118453    }
118454
118455    /* Increment Parse.nHeight by the height of the largest expression
118456    ** tree referred to by this, the parent select. The child select
118457    ** may contain expression trees of at most
118458    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
118459    ** more conservative than necessary, but much easier than enforcing
118460    ** an exact limit.
118461    */
118462    pParse->nHeight += sqlite3SelectExprHeight(p);
118463
118464    /* Make copies of constant WHERE-clause terms in the outer query down
118465    ** inside the subquery.  This can help the subquery to run more efficiently.
118466    */
118467    if( (pItem->fg.jointype & JT_OUTER)==0
118468     && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor)
118469    ){
118470#if SELECTTRACE_ENABLED
118471      if( sqlite3SelectTrace & 0x100 ){
118472        SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
118473        sqlite3TreeViewSelect(0, p, 0);
118474      }
118475#endif
118476    }
118477
118478    /* Generate code to implement the subquery
118479    **
118480    ** The subquery is implemented as a co-routine if all of these are true:
118481    **   (1)  The subquery is guaranteed to be the outer loop (so that it
118482    **        does not need to be computed more than once)
118483    **   (2)  The ALL keyword after SELECT is omitted.  (Applications are
118484    **        allowed to say "SELECT ALL" instead of just "SELECT" to disable
118485    **        the use of co-routines.)
118486    **   (3)  Co-routines are not disabled using sqlite3_test_control()
118487    **        with SQLITE_TESTCTRL_OPTIMIZATIONS.
118488    **
118489    ** TODO: Are there other reasons beside (1) to use a co-routine
118490    ** implementation?
118491    */
118492    if( i==0
118493     && (pTabList->nSrc==1
118494            || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)  /* (1) */
118495     && (p->selFlags & SF_All)==0                                   /* (2) */
118496     && OptimizationEnabled(db, SQLITE_SubqCoroutine)               /* (3) */
118497    ){
118498      /* Implement a co-routine that will return a single row of the result
118499      ** set on each invocation.
118500      */
118501      int addrTop = sqlite3VdbeCurrentAddr(v)+1;
118502      pItem->regReturn = ++pParse->nMem;
118503      sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
118504      VdbeComment((v, "%s", pItem->pTab->zName));
118505      pItem->addrFillSub = addrTop;
118506      sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
118507      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
118508      sqlite3Select(pParse, pSub, &dest);
118509      pItem->pTab->nRowLogEst = pSub->nSelectRow;
118510      pItem->fg.viaCoroutine = 1;
118511      pItem->regResult = dest.iSdst;
118512      sqlite3VdbeEndCoroutine(v, pItem->regReturn);
118513      sqlite3VdbeJumpHere(v, addrTop-1);
118514      sqlite3ClearTempRegCache(pParse);
118515    }else{
118516      /* Generate a subroutine that will fill an ephemeral table with
118517      ** the content of this subquery.  pItem->addrFillSub will point
118518      ** to the address of the generated subroutine.  pItem->regReturn
118519      ** is a register allocated to hold the subroutine return address
118520      */
118521      int topAddr;
118522      int onceAddr = 0;
118523      int retAddr;
118524      assert( pItem->addrFillSub==0 );
118525      pItem->regReturn = ++pParse->nMem;
118526      topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
118527      pItem->addrFillSub = topAddr+1;
118528      if( pItem->fg.isCorrelated==0 ){
118529        /* If the subquery is not correlated and if we are not inside of
118530        ** a trigger, then we only need to compute the value of the subquery
118531        ** once. */
118532        onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
118533        VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
118534      }else{
118535        VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
118536      }
118537      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
118538      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
118539      sqlite3Select(pParse, pSub, &dest);
118540      pItem->pTab->nRowLogEst = pSub->nSelectRow;
118541      if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
118542      retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
118543      VdbeComment((v, "end %s", pItem->pTab->zName));
118544      sqlite3VdbeChangeP1(v, topAddr, retAddr);
118545      sqlite3ClearTempRegCache(pParse);
118546    }
118547    if( db->mallocFailed ) goto select_end;
118548    pParse->nHeight -= sqlite3SelectExprHeight(p);
118549  }
118550#endif
118551
118552  /* Various elements of the SELECT copied into local variables for
118553  ** convenience */
118554  pEList = p->pEList;
118555  pWhere = p->pWhere;
118556  pGroupBy = p->pGroupBy;
118557  pHaving = p->pHaving;
118558  sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
118559
118560#if SELECTTRACE_ENABLED
118561  if( sqlite3SelectTrace & 0x400 ){
118562    SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
118563    sqlite3TreeViewSelect(0, p, 0);
118564  }
118565#endif
118566
118567  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
118568  ** if the select-list is the same as the ORDER BY list, then this query
118569  ** can be rewritten as a GROUP BY. In other words, this:
118570  **
118571  **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
118572  **
118573  ** is transformed to:
118574  **
118575  **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
118576  **
118577  ** The second form is preferred as a single index (or temp-table) may be
118578  ** used for both the ORDER BY and DISTINCT processing. As originally
118579  ** written the query must use a temp-table for at least one of the ORDER
118580  ** BY and DISTINCT, and an index or separate temp-table for the other.
118581  */
118582  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
118583   && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
118584  ){
118585    p->selFlags &= ~SF_Distinct;
118586    pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
118587    /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
118588    ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
118589    ** original setting of the SF_Distinct flag, not the current setting */
118590    assert( sDistinct.isTnct );
118591
118592#if SELECTTRACE_ENABLED
118593    if( sqlite3SelectTrace & 0x400 ){
118594      SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
118595      sqlite3TreeViewSelect(0, p, 0);
118596    }
118597#endif
118598  }
118599
118600  /* If there is an ORDER BY clause, then create an ephemeral index to
118601  ** do the sorting.  But this sorting ephemeral index might end up
118602  ** being unused if the data can be extracted in pre-sorted order.
118603  ** If that is the case, then the OP_OpenEphemeral instruction will be
118604  ** changed to an OP_Noop once we figure out that the sorting index is
118605  ** not needed.  The sSort.addrSortIndex variable is used to facilitate
118606  ** that change.
118607  */
118608  if( sSort.pOrderBy ){
118609    KeyInfo *pKeyInfo;
118610    pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
118611    sSort.iECursor = pParse->nTab++;
118612    sSort.addrSortIndex =
118613      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
118614          sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
118615          (char*)pKeyInfo, P4_KEYINFO
118616      );
118617  }else{
118618    sSort.addrSortIndex = -1;
118619  }
118620
118621  /* If the output is destined for a temporary table, open that table.
118622  */
118623  if( pDest->eDest==SRT_EphemTab ){
118624    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
118625  }
118626
118627  /* Set the limiter.
118628  */
118629  iEnd = sqlite3VdbeMakeLabel(v);
118630  p->nSelectRow = 320;  /* 4 billion rows */
118631  computeLimitRegisters(pParse, p, iEnd);
118632  if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
118633    sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
118634    sSort.sortFlags |= SORTFLAG_UseSorter;
118635  }
118636
118637  /* Open an ephemeral index to use for the distinct set.
118638  */
118639  if( p->selFlags & SF_Distinct ){
118640    sDistinct.tabTnct = pParse->nTab++;
118641    sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
118642                             sDistinct.tabTnct, 0, 0,
118643                             (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
118644                             P4_KEYINFO);
118645    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
118646    sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
118647  }else{
118648    sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
118649  }
118650
118651  if( !isAgg && pGroupBy==0 ){
118652    /* No aggregate functions and no GROUP BY clause */
118653    u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
118654    assert( WHERE_USE_LIMIT==SF_FixedLimit );
118655    wctrlFlags |= p->selFlags & SF_FixedLimit;
118656
118657    /* Begin the database scan. */
118658    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
118659                               p->pEList, wctrlFlags, p->nSelectRow);
118660    if( pWInfo==0 ) goto select_end;
118661    if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
118662      p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
118663    }
118664    if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
118665      sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
118666    }
118667    if( sSort.pOrderBy ){
118668      sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
118669      sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo);
118670      if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
118671        sSort.pOrderBy = 0;
118672      }
118673    }
118674
118675    /* If sorting index that was created by a prior OP_OpenEphemeral
118676    ** instruction ended up not being needed, then change the OP_OpenEphemeral
118677    ** into an OP_Noop.
118678    */
118679    if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
118680      sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
118681    }
118682
118683    /* Use the standard inner loop. */
118684    selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
118685                    sqlite3WhereContinueLabel(pWInfo),
118686                    sqlite3WhereBreakLabel(pWInfo));
118687
118688    /* End the database scan loop.
118689    */
118690    sqlite3WhereEnd(pWInfo);
118691  }else{
118692    /* This case when there exist aggregate functions or a GROUP BY clause
118693    ** or both */
118694    NameContext sNC;    /* Name context for processing aggregate information */
118695    int iAMem;          /* First Mem address for storing current GROUP BY */
118696    int iBMem;          /* First Mem address for previous GROUP BY */
118697    int iUseFlag;       /* Mem address holding flag indicating that at least
118698                        ** one row of the input to the aggregator has been
118699                        ** processed */
118700    int iAbortFlag;     /* Mem address which causes query abort if positive */
118701    int groupBySort;    /* Rows come from source in GROUP BY order */
118702    int addrEnd;        /* End of processing for this SELECT */
118703    int sortPTab = 0;   /* Pseudotable used to decode sorting results */
118704    int sortOut = 0;    /* Output register from the sorter */
118705    int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
118706
118707    /* Remove any and all aliases between the result set and the
118708    ** GROUP BY clause.
118709    */
118710    if( pGroupBy ){
118711      int k;                        /* Loop counter */
118712      struct ExprList_item *pItem;  /* For looping over expression in a list */
118713
118714      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
118715        pItem->u.x.iAlias = 0;
118716      }
118717      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
118718        pItem->u.x.iAlias = 0;
118719      }
118720      assert( 66==sqlite3LogEst(100) );
118721      if( p->nSelectRow>66 ) p->nSelectRow = 66;
118722    }else{
118723      assert( 0==sqlite3LogEst(1) );
118724      p->nSelectRow = 0;
118725    }
118726
118727    /* If there is both a GROUP BY and an ORDER BY clause and they are
118728    ** identical, then it may be possible to disable the ORDER BY clause
118729    ** on the grounds that the GROUP BY will cause elements to come out
118730    ** in the correct order. It also may not - the GROUP BY might use a
118731    ** database index that causes rows to be grouped together as required
118732    ** but not actually sorted. Either way, record the fact that the
118733    ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
118734    ** variable.  */
118735    if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
118736      orderByGrp = 1;
118737    }
118738
118739    /* Create a label to jump to when we want to abort the query */
118740    addrEnd = sqlite3VdbeMakeLabel(v);
118741
118742    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
118743    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
118744    ** SELECT statement.
118745    */
118746    memset(&sNC, 0, sizeof(sNC));
118747    sNC.pParse = pParse;
118748    sNC.pSrcList = pTabList;
118749    sNC.pAggInfo = &sAggInfo;
118750    sAggInfo.mnReg = pParse->nMem+1;
118751    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
118752    sAggInfo.pGroupBy = pGroupBy;
118753    sqlite3ExprAnalyzeAggList(&sNC, pEList);
118754    sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
118755    if( pHaving ){
118756      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
118757    }
118758    sAggInfo.nAccumulator = sAggInfo.nColumn;
118759    for(i=0; i<sAggInfo.nFunc; i++){
118760      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
118761      sNC.ncFlags |= NC_InAggFunc;
118762      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
118763      sNC.ncFlags &= ~NC_InAggFunc;
118764    }
118765    sAggInfo.mxReg = pParse->nMem;
118766    if( db->mallocFailed ) goto select_end;
118767
118768    /* Processing for aggregates with GROUP BY is very different and
118769    ** much more complex than aggregates without a GROUP BY.
118770    */
118771    if( pGroupBy ){
118772      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
118773      int addr1;          /* A-vs-B comparision jump */
118774      int addrOutputRow;  /* Start of subroutine that outputs a result row */
118775      int regOutputRow;   /* Return address register for output subroutine */
118776      int addrSetAbort;   /* Set the abort flag and return */
118777      int addrTopOfLoop;  /* Top of the input loop */
118778      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
118779      int addrReset;      /* Subroutine for resetting the accumulator */
118780      int regReset;       /* Return address register for reset subroutine */
118781
118782      /* If there is a GROUP BY clause we might need a sorting index to
118783      ** implement it.  Allocate that sorting index now.  If it turns out
118784      ** that we do not need it after all, the OP_SorterOpen instruction
118785      ** will be converted into a Noop.
118786      */
118787      sAggInfo.sortingIdx = pParse->nTab++;
118788      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
118789      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
118790          sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
118791          0, (char*)pKeyInfo, P4_KEYINFO);
118792
118793      /* Initialize memory locations used by GROUP BY aggregate processing
118794      */
118795      iUseFlag = ++pParse->nMem;
118796      iAbortFlag = ++pParse->nMem;
118797      regOutputRow = ++pParse->nMem;
118798      addrOutputRow = sqlite3VdbeMakeLabel(v);
118799      regReset = ++pParse->nMem;
118800      addrReset = sqlite3VdbeMakeLabel(v);
118801      iAMem = pParse->nMem + 1;
118802      pParse->nMem += pGroupBy->nExpr;
118803      iBMem = pParse->nMem + 1;
118804      pParse->nMem += pGroupBy->nExpr;
118805      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
118806      VdbeComment((v, "clear abort flag"));
118807      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
118808      VdbeComment((v, "indicate accumulator empty"));
118809      sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
118810
118811      /* Begin a loop that will extract all source rows in GROUP BY order.
118812      ** This might involve two separate loops with an OP_Sort in between, or
118813      ** it might be a single loop that uses an index to extract information
118814      ** in the right order to begin with.
118815      */
118816      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
118817      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
118818          WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
118819      );
118820      if( pWInfo==0 ) goto select_end;
118821      if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
118822        /* The optimizer is able to deliver rows in group by order so
118823        ** we do not have to sort.  The OP_OpenEphemeral table will be
118824        ** cancelled later because we still need to use the pKeyInfo
118825        */
118826        groupBySort = 0;
118827      }else{
118828        /* Rows are coming out in undetermined order.  We have to push
118829        ** each row into a sorting index, terminate the first loop,
118830        ** then loop over the sorting index in order to get the output
118831        ** in sorted order
118832        */
118833        int regBase;
118834        int regRecord;
118835        int nCol;
118836        int nGroupBy;
118837
118838        explainTempTable(pParse,
118839            (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
118840                    "DISTINCT" : "GROUP BY");
118841
118842        groupBySort = 1;
118843        nGroupBy = pGroupBy->nExpr;
118844        nCol = nGroupBy;
118845        j = nGroupBy;
118846        for(i=0; i<sAggInfo.nColumn; i++){
118847          if( sAggInfo.aCol[i].iSorterColumn>=j ){
118848            nCol++;
118849            j++;
118850          }
118851        }
118852        regBase = sqlite3GetTempRange(pParse, nCol);
118853        sqlite3ExprCacheClear(pParse);
118854        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
118855        j = nGroupBy;
118856        for(i=0; i<sAggInfo.nColumn; i++){
118857          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
118858          if( pCol->iSorterColumn>=j ){
118859            int r1 = j + regBase;
118860            sqlite3ExprCodeGetColumnToReg(pParse,
118861                               pCol->pTab, pCol->iColumn, pCol->iTable, r1);
118862            j++;
118863          }
118864        }
118865        regRecord = sqlite3GetTempReg(pParse);
118866        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
118867        sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
118868        sqlite3ReleaseTempReg(pParse, regRecord);
118869        sqlite3ReleaseTempRange(pParse, regBase, nCol);
118870        sqlite3WhereEnd(pWInfo);
118871        sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
118872        sortOut = sqlite3GetTempReg(pParse);
118873        sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
118874        sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
118875        VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
118876        sAggInfo.useSortingIdx = 1;
118877        sqlite3ExprCacheClear(pParse);
118878
118879      }
118880
118881      /* If the index or temporary table used by the GROUP BY sort
118882      ** will naturally deliver rows in the order required by the ORDER BY
118883      ** clause, cancel the ephemeral table open coded earlier.
118884      **
118885      ** This is an optimization - the correct answer should result regardless.
118886      ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
118887      ** disable this optimization for testing purposes.  */
118888      if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
118889       && (groupBySort || sqlite3WhereIsSorted(pWInfo))
118890      ){
118891        sSort.pOrderBy = 0;
118892        sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
118893      }
118894
118895      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
118896      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
118897      ** Then compare the current GROUP BY terms against the GROUP BY terms
118898      ** from the previous row currently stored in a0, a1, a2...
118899      */
118900      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
118901      sqlite3ExprCacheClear(pParse);
118902      if( groupBySort ){
118903        sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
118904                          sortOut, sortPTab);
118905      }
118906      for(j=0; j<pGroupBy->nExpr; j++){
118907        if( groupBySort ){
118908          sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
118909        }else{
118910          sAggInfo.directMode = 1;
118911          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
118912        }
118913      }
118914      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
118915                          (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
118916      addr1 = sqlite3VdbeCurrentAddr(v);
118917      sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
118918
118919      /* Generate code that runs whenever the GROUP BY changes.
118920      ** Changes in the GROUP BY are detected by the previous code
118921      ** block.  If there were no changes, this block is skipped.
118922      **
118923      ** This code copies current group by terms in b0,b1,b2,...
118924      ** over to a0,a1,a2.  It then calls the output subroutine
118925      ** and resets the aggregate accumulator registers in preparation
118926      ** for the next GROUP BY batch.
118927      */
118928      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
118929      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
118930      VdbeComment((v, "output one row"));
118931      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
118932      VdbeComment((v, "check abort flag"));
118933      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
118934      VdbeComment((v, "reset accumulator"));
118935
118936      /* Update the aggregate accumulators based on the content of
118937      ** the current row
118938      */
118939      sqlite3VdbeJumpHere(v, addr1);
118940      updateAccumulator(pParse, &sAggInfo);
118941      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
118942      VdbeComment((v, "indicate data in accumulator"));
118943
118944      /* End of the loop
118945      */
118946      if( groupBySort ){
118947        sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
118948        VdbeCoverage(v);
118949      }else{
118950        sqlite3WhereEnd(pWInfo);
118951        sqlite3VdbeChangeToNoop(v, addrSortingIdx);
118952      }
118953
118954      /* Output the final row of result
118955      */
118956      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
118957      VdbeComment((v, "output final row"));
118958
118959      /* Jump over the subroutines
118960      */
118961      sqlite3VdbeGoto(v, addrEnd);
118962
118963      /* Generate a subroutine that outputs a single row of the result
118964      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
118965      ** is less than or equal to zero, the subroutine is a no-op.  If
118966      ** the processing calls for the query to abort, this subroutine
118967      ** increments the iAbortFlag memory location before returning in
118968      ** order to signal the caller to abort.
118969      */
118970      addrSetAbort = sqlite3VdbeCurrentAddr(v);
118971      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
118972      VdbeComment((v, "set abort flag"));
118973      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
118974      sqlite3VdbeResolveLabel(v, addrOutputRow);
118975      addrOutputRow = sqlite3VdbeCurrentAddr(v);
118976      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
118977      VdbeCoverage(v);
118978      VdbeComment((v, "Groupby result generator entry point"));
118979      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
118980      finalizeAggFunctions(pParse, &sAggInfo);
118981      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
118982      selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
118983                      &sDistinct, pDest,
118984                      addrOutputRow+1, addrSetAbort);
118985      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
118986      VdbeComment((v, "end groupby result generator"));
118987
118988      /* Generate a subroutine that will reset the group-by accumulator
118989      */
118990      sqlite3VdbeResolveLabel(v, addrReset);
118991      resetAccumulator(pParse, &sAggInfo);
118992      sqlite3VdbeAddOp1(v, OP_Return, regReset);
118993
118994    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
118995    else {
118996      ExprList *pDel = 0;
118997#ifndef SQLITE_OMIT_BTREECOUNT
118998      Table *pTab;
118999      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
119000        /* If isSimpleCount() returns a pointer to a Table structure, then
119001        ** the SQL statement is of the form:
119002        **
119003        **   SELECT count(*) FROM <tbl>
119004        **
119005        ** where the Table structure returned represents table <tbl>.
119006        **
119007        ** This statement is so common that it is optimized specially. The
119008        ** OP_Count instruction is executed either on the intkey table that
119009        ** contains the data for table <tbl> or on one of its indexes. It
119010        ** is better to execute the op on an index, as indexes are almost
119011        ** always spread across less pages than their corresponding tables.
119012        */
119013        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
119014        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
119015        Index *pIdx;                         /* Iterator variable */
119016        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
119017        Index *pBest = 0;                    /* Best index found so far */
119018        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
119019
119020        sqlite3CodeVerifySchema(pParse, iDb);
119021        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
119022
119023        /* Search for the index that has the lowest scan cost.
119024        **
119025        ** (2011-04-15) Do not do a full scan of an unordered index.
119026        **
119027        ** (2013-10-03) Do not count the entries in a partial index.
119028        **
119029        ** In practice the KeyInfo structure will not be used. It is only
119030        ** passed to keep OP_OpenRead happy.
119031        */
119032        if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
119033        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
119034          if( pIdx->bUnordered==0
119035           && pIdx->szIdxRow<pTab->szTabRow
119036           && pIdx->pPartIdxWhere==0
119037           && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
119038          ){
119039            pBest = pIdx;
119040          }
119041        }
119042        if( pBest ){
119043          iRoot = pBest->tnum;
119044          pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
119045        }
119046
119047        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
119048        sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
119049        if( pKeyInfo ){
119050          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
119051        }
119052        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
119053        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
119054        explainSimpleCount(pParse, pTab, pBest);
119055      }else
119056#endif /* SQLITE_OMIT_BTREECOUNT */
119057      {
119058        /* Check if the query is of one of the following forms:
119059        **
119060        **   SELECT min(x) FROM ...
119061        **   SELECT max(x) FROM ...
119062        **
119063        ** If it is, then ask the code in where.c to attempt to sort results
119064        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
119065        ** If where.c is able to produce results sorted in this order, then
119066        ** add vdbe code to break out of the processing loop after the
119067        ** first iteration (since the first iteration of the loop is
119068        ** guaranteed to operate on the row with the minimum or maximum
119069        ** value of x, the only row required).
119070        **
119071        ** A special flag must be passed to sqlite3WhereBegin() to slightly
119072        ** modify behavior as follows:
119073        **
119074        **   + If the query is a "SELECT min(x)", then the loop coded by
119075        **     where.c should not iterate over any values with a NULL value
119076        **     for x.
119077        **
119078        **   + The optimizer code in where.c (the thing that decides which
119079        **     index or indices to use) should place a different priority on
119080        **     satisfying the 'ORDER BY' clause than it does in other cases.
119081        **     Refer to code and comments in where.c for details.
119082        */
119083        ExprList *pMinMax = 0;
119084        u8 flag = WHERE_ORDERBY_NORMAL;
119085
119086        assert( p->pGroupBy==0 );
119087        assert( flag==0 );
119088        if( p->pHaving==0 ){
119089          flag = minMaxQuery(&sAggInfo, &pMinMax);
119090        }
119091        assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
119092
119093        if( flag ){
119094          pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
119095          pDel = pMinMax;
119096          assert( db->mallocFailed || pMinMax!=0 );
119097          if( !db->mallocFailed ){
119098            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
119099            pMinMax->a[0].pExpr->op = TK_COLUMN;
119100          }
119101        }
119102
119103        /* This case runs if the aggregate has no GROUP BY clause.  The
119104        ** processing is much simpler since there is only a single row
119105        ** of output.
119106        */
119107        resetAccumulator(pParse, &sAggInfo);
119108        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
119109        if( pWInfo==0 ){
119110          sqlite3ExprListDelete(db, pDel);
119111          goto select_end;
119112        }
119113        updateAccumulator(pParse, &sAggInfo);
119114        assert( pMinMax==0 || pMinMax->nExpr==1 );
119115        if( sqlite3WhereIsOrdered(pWInfo)>0 ){
119116          sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
119117          VdbeComment((v, "%s() by index",
119118                (flag==WHERE_ORDERBY_MIN?"min":"max")));
119119        }
119120        sqlite3WhereEnd(pWInfo);
119121        finalizeAggFunctions(pParse, &sAggInfo);
119122      }
119123
119124      sSort.pOrderBy = 0;
119125      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
119126      selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
119127                      pDest, addrEnd, addrEnd);
119128      sqlite3ExprListDelete(db, pDel);
119129    }
119130    sqlite3VdbeResolveLabel(v, addrEnd);
119131
119132  } /* endif aggregate query */
119133
119134  if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
119135    explainTempTable(pParse, "DISTINCT");
119136  }
119137
119138  /* If there is an ORDER BY clause, then we need to sort the results
119139  ** and send them to the callback one by one.
119140  */
119141  if( sSort.pOrderBy ){
119142    explainTempTable(pParse,
119143                     sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
119144    generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
119145  }
119146
119147  /* Jump here to skip this query
119148  */
119149  sqlite3VdbeResolveLabel(v, iEnd);
119150
119151  /* The SELECT has been coded. If there is an error in the Parse structure,
119152  ** set the return code to 1. Otherwise 0. */
119153  rc = (pParse->nErr>0);
119154
119155  /* Control jumps to here if an error is encountered above, or upon
119156  ** successful coding of the SELECT.
119157  */
119158select_end:
119159  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
119160
119161  /* Identify column names if results of the SELECT are to be output.
119162  */
119163  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
119164    generateColumnNames(pParse, pTabList, pEList);
119165  }
119166
119167  sqlite3DbFree(db, sAggInfo.aCol);
119168  sqlite3DbFree(db, sAggInfo.aFunc);
119169#if SELECTTRACE_ENABLED
119170  SELECTTRACE(1,pParse,p,("end processing\n"));
119171  pParse->nSelectIndent--;
119172#endif
119173  return rc;
119174}
119175
119176/************** End of select.c **********************************************/
119177/************** Begin file table.c *******************************************/
119178/*
119179** 2001 September 15
119180**
119181** The author disclaims copyright to this source code.  In place of
119182** a legal notice, here is a blessing:
119183**
119184**    May you do good and not evil.
119185**    May you find forgiveness for yourself and forgive others.
119186**    May you share freely, never taking more than you give.
119187**
119188*************************************************************************
119189** This file contains the sqlite3_get_table() and sqlite3_free_table()
119190** interface routines.  These are just wrappers around the main
119191** interface routine of sqlite3_exec().
119192**
119193** These routines are in a separate files so that they will not be linked
119194** if they are not used.
119195*/
119196/* #include "sqliteInt.h" */
119197/* #include <stdlib.h> */
119198/* #include <string.h> */
119199
119200#ifndef SQLITE_OMIT_GET_TABLE
119201
119202/*
119203** This structure is used to pass data from sqlite3_get_table() through
119204** to the callback function is uses to build the result.
119205*/
119206typedef struct TabResult {
119207  char **azResult;   /* Accumulated output */
119208  char *zErrMsg;     /* Error message text, if an error occurs */
119209  u32 nAlloc;        /* Slots allocated for azResult[] */
119210  u32 nRow;          /* Number of rows in the result */
119211  u32 nColumn;       /* Number of columns in the result */
119212  u32 nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
119213  int rc;            /* Return code from sqlite3_exec() */
119214} TabResult;
119215
119216/*
119217** This routine is called once for each row in the result table.  Its job
119218** is to fill in the TabResult structure appropriately, allocating new
119219** memory as necessary.
119220*/
119221static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
119222  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
119223  int need;                         /* Slots needed in p->azResult[] */
119224  int i;                            /* Loop counter */
119225  char *z;                          /* A single column of result */
119226
119227  /* Make sure there is enough space in p->azResult to hold everything
119228  ** we need to remember from this invocation of the callback.
119229  */
119230  if( p->nRow==0 && argv!=0 ){
119231    need = nCol*2;
119232  }else{
119233    need = nCol;
119234  }
119235  if( p->nData + need > p->nAlloc ){
119236    char **azNew;
119237    p->nAlloc = p->nAlloc*2 + need;
119238    azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
119239    if( azNew==0 ) goto malloc_failed;
119240    p->azResult = azNew;
119241  }
119242
119243  /* If this is the first row, then generate an extra row containing
119244  ** the names of all columns.
119245  */
119246  if( p->nRow==0 ){
119247    p->nColumn = nCol;
119248    for(i=0; i<nCol; i++){
119249      z = sqlite3_mprintf("%s", colv[i]);
119250      if( z==0 ) goto malloc_failed;
119251      p->azResult[p->nData++] = z;
119252    }
119253  }else if( (int)p->nColumn!=nCol ){
119254    sqlite3_free(p->zErrMsg);
119255    p->zErrMsg = sqlite3_mprintf(
119256       "sqlite3_get_table() called with two or more incompatible queries"
119257    );
119258    p->rc = SQLITE_ERROR;
119259    return 1;
119260  }
119261
119262  /* Copy over the row data
119263  */
119264  if( argv!=0 ){
119265    for(i=0; i<nCol; i++){
119266      if( argv[i]==0 ){
119267        z = 0;
119268      }else{
119269        int n = sqlite3Strlen30(argv[i])+1;
119270        z = sqlite3_malloc64( n );
119271        if( z==0 ) goto malloc_failed;
119272        memcpy(z, argv[i], n);
119273      }
119274      p->azResult[p->nData++] = z;
119275    }
119276    p->nRow++;
119277  }
119278  return 0;
119279
119280malloc_failed:
119281  p->rc = SQLITE_NOMEM_BKPT;
119282  return 1;
119283}
119284
119285/*
119286** Query the database.  But instead of invoking a callback for each row,
119287** malloc() for space to hold the result and return the entire results
119288** at the conclusion of the call.
119289**
119290** The result that is written to ***pazResult is held in memory obtained
119291** from malloc().  But the caller cannot free this memory directly.
119292** Instead, the entire table should be passed to sqlite3_free_table() when
119293** the calling procedure is finished using it.
119294*/
119295SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
119296  sqlite3 *db,                /* The database on which the SQL executes */
119297  const char *zSql,           /* The SQL to be executed */
119298  char ***pazResult,          /* Write the result table here */
119299  int *pnRow,                 /* Write the number of rows in the result here */
119300  int *pnColumn,              /* Write the number of columns of result here */
119301  char **pzErrMsg             /* Write error messages here */
119302){
119303  int rc;
119304  TabResult res;
119305
119306#ifdef SQLITE_ENABLE_API_ARMOR
119307  if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
119308#endif
119309  *pazResult = 0;
119310  if( pnColumn ) *pnColumn = 0;
119311  if( pnRow ) *pnRow = 0;
119312  if( pzErrMsg ) *pzErrMsg = 0;
119313  res.zErrMsg = 0;
119314  res.nRow = 0;
119315  res.nColumn = 0;
119316  res.nData = 1;
119317  res.nAlloc = 20;
119318  res.rc = SQLITE_OK;
119319  res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
119320  if( res.azResult==0 ){
119321     db->errCode = SQLITE_NOMEM;
119322     return SQLITE_NOMEM_BKPT;
119323  }
119324  res.azResult[0] = 0;
119325  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
119326  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
119327  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
119328  if( (rc&0xff)==SQLITE_ABORT ){
119329    sqlite3_free_table(&res.azResult[1]);
119330    if( res.zErrMsg ){
119331      if( pzErrMsg ){
119332        sqlite3_free(*pzErrMsg);
119333        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
119334      }
119335      sqlite3_free(res.zErrMsg);
119336    }
119337    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
119338    return res.rc;
119339  }
119340  sqlite3_free(res.zErrMsg);
119341  if( rc!=SQLITE_OK ){
119342    sqlite3_free_table(&res.azResult[1]);
119343    return rc;
119344  }
119345  if( res.nAlloc>res.nData ){
119346    char **azNew;
119347    azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
119348    if( azNew==0 ){
119349      sqlite3_free_table(&res.azResult[1]);
119350      db->errCode = SQLITE_NOMEM;
119351      return SQLITE_NOMEM_BKPT;
119352    }
119353    res.azResult = azNew;
119354  }
119355  *pazResult = &res.azResult[1];
119356  if( pnColumn ) *pnColumn = res.nColumn;
119357  if( pnRow ) *pnRow = res.nRow;
119358  return rc;
119359}
119360
119361/*
119362** This routine frees the space the sqlite3_get_table() malloced.
119363*/
119364SQLITE_API void SQLITE_STDCALL sqlite3_free_table(
119365  char **azResult            /* Result returned from sqlite3_get_table() */
119366){
119367  if( azResult ){
119368    int i, n;
119369    azResult--;
119370    assert( azResult!=0 );
119371    n = SQLITE_PTR_TO_INT(azResult[0]);
119372    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
119373    sqlite3_free(azResult);
119374  }
119375}
119376
119377#endif /* SQLITE_OMIT_GET_TABLE */
119378
119379/************** End of table.c ***********************************************/
119380/************** Begin file trigger.c *****************************************/
119381/*
119382**
119383** The author disclaims copyright to this source code.  In place of
119384** a legal notice, here is a blessing:
119385**
119386**    May you do good and not evil.
119387**    May you find forgiveness for yourself and forgive others.
119388**    May you share freely, never taking more than you give.
119389**
119390*************************************************************************
119391** This file contains the implementation for TRIGGERs
119392*/
119393/* #include "sqliteInt.h" */
119394
119395#ifndef SQLITE_OMIT_TRIGGER
119396/*
119397** Delete a linked list of TriggerStep structures.
119398*/
119399SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
119400  while( pTriggerStep ){
119401    TriggerStep * pTmp = pTriggerStep;
119402    pTriggerStep = pTriggerStep->pNext;
119403
119404    sqlite3ExprDelete(db, pTmp->pWhere);
119405    sqlite3ExprListDelete(db, pTmp->pExprList);
119406    sqlite3SelectDelete(db, pTmp->pSelect);
119407    sqlite3IdListDelete(db, pTmp->pIdList);
119408
119409    sqlite3DbFree(db, pTmp);
119410  }
119411}
119412
119413/*
119414** Given table pTab, return a list of all the triggers attached to
119415** the table. The list is connected by Trigger.pNext pointers.
119416**
119417** All of the triggers on pTab that are in the same database as pTab
119418** are already attached to pTab->pTrigger.  But there might be additional
119419** triggers on pTab in the TEMP schema.  This routine prepends all
119420** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
119421** and returns the combined list.
119422**
119423** To state it another way:  This routine returns a list of all triggers
119424** that fire off of pTab.  The list will include any TEMP triggers on
119425** pTab as well as the triggers lised in pTab->pTrigger.
119426*/
119427SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
119428  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
119429  Trigger *pList = 0;                  /* List of triggers to return */
119430
119431  if( pParse->disableTriggers ){
119432    return 0;
119433  }
119434
119435  if( pTmpSchema!=pTab->pSchema ){
119436    HashElem *p;
119437    assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
119438    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
119439      Trigger *pTrig = (Trigger *)sqliteHashData(p);
119440      if( pTrig->pTabSchema==pTab->pSchema
119441       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
119442      ){
119443        pTrig->pNext = (pList ? pList : pTab->pTrigger);
119444        pList = pTrig;
119445      }
119446    }
119447  }
119448
119449  return (pList ? pList : pTab->pTrigger);
119450}
119451
119452/*
119453** This is called by the parser when it sees a CREATE TRIGGER statement
119454** up to the point of the BEGIN before the trigger actions.  A Trigger
119455** structure is generated based on the information available and stored
119456** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
119457** sqlite3FinishTrigger() function is called to complete the trigger
119458** construction process.
119459*/
119460SQLITE_PRIVATE void sqlite3BeginTrigger(
119461  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
119462  Token *pName1,      /* The name of the trigger */
119463  Token *pName2,      /* The name of the trigger */
119464  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
119465  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
119466  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
119467  SrcList *pTableName,/* The name of the table/view the trigger applies to */
119468  Expr *pWhen,        /* WHEN clause */
119469  int isTemp,         /* True if the TEMPORARY keyword is present */
119470  int noErr           /* Suppress errors if the trigger already exists */
119471){
119472  Trigger *pTrigger = 0;  /* The new trigger */
119473  Table *pTab;            /* Table that the trigger fires off of */
119474  char *zName = 0;        /* Name of the trigger */
119475  sqlite3 *db = pParse->db;  /* The database connection */
119476  int iDb;                /* The database to store the trigger in */
119477  Token *pName;           /* The unqualified db name */
119478  DbFixer sFix;           /* State vector for the DB fixer */
119479  int iTabDb;             /* Index of the database holding pTab */
119480
119481  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
119482  assert( pName2!=0 );
119483  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
119484  assert( op>0 && op<0xff );
119485  if( isTemp ){
119486    /* If TEMP was specified, then the trigger name may not be qualified. */
119487    if( pName2->n>0 ){
119488      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
119489      goto trigger_cleanup;
119490    }
119491    iDb = 1;
119492    pName = pName1;
119493  }else{
119494    /* Figure out the db that the trigger will be created in */
119495    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
119496    if( iDb<0 ){
119497      goto trigger_cleanup;
119498    }
119499  }
119500  if( !pTableName || db->mallocFailed ){
119501    goto trigger_cleanup;
119502  }
119503
119504  /* A long-standing parser bug is that this syntax was allowed:
119505  **
119506  **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
119507  **                                                 ^^^^^^^^
119508  **
119509  ** To maintain backwards compatibility, ignore the database
119510  ** name on pTableName if we are reparsing out of SQLITE_MASTER.
119511  */
119512  if( db->init.busy && iDb!=1 ){
119513    sqlite3DbFree(db, pTableName->a[0].zDatabase);
119514    pTableName->a[0].zDatabase = 0;
119515  }
119516
119517  /* If the trigger name was unqualified, and the table is a temp table,
119518  ** then set iDb to 1 to create the trigger in the temporary database.
119519  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
119520  ** exist, the error is caught by the block below.
119521  */
119522  pTab = sqlite3SrcListLookup(pParse, pTableName);
119523  if( db->init.busy==0 && pName2->n==0 && pTab
119524        && pTab->pSchema==db->aDb[1].pSchema ){
119525    iDb = 1;
119526  }
119527
119528  /* Ensure the table name matches database name and that the table exists */
119529  if( db->mallocFailed ) goto trigger_cleanup;
119530  assert( pTableName->nSrc==1 );
119531  sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
119532  if( sqlite3FixSrcList(&sFix, pTableName) ){
119533    goto trigger_cleanup;
119534  }
119535  pTab = sqlite3SrcListLookup(pParse, pTableName);
119536  if( !pTab ){
119537    /* The table does not exist. */
119538    if( db->init.iDb==1 ){
119539      /* Ticket #3810.
119540      ** Normally, whenever a table is dropped, all associated triggers are
119541      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
119542      ** and the table is dropped by a different database connection, the
119543      ** trigger is not visible to the database connection that does the
119544      ** drop so the trigger cannot be dropped.  This results in an
119545      ** "orphaned trigger" - a trigger whose associated table is missing.
119546      */
119547      db->init.orphanTrigger = 1;
119548    }
119549    goto trigger_cleanup;
119550  }
119551  if( IsVirtual(pTab) ){
119552    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
119553    goto trigger_cleanup;
119554  }
119555
119556  /* Check that the trigger name is not reserved and that no trigger of the
119557  ** specified name exists */
119558  zName = sqlite3NameFromToken(db, pName);
119559  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
119560    goto trigger_cleanup;
119561  }
119562  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
119563  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
119564    if( !noErr ){
119565      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
119566    }else{
119567      assert( !db->init.busy );
119568      sqlite3CodeVerifySchema(pParse, iDb);
119569    }
119570    goto trigger_cleanup;
119571  }
119572
119573  /* Do not create a trigger on a system table */
119574  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
119575    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
119576    goto trigger_cleanup;
119577  }
119578
119579  /* INSTEAD of triggers are only for views and views only support INSTEAD
119580  ** of triggers.
119581  */
119582  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
119583    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
119584        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
119585    goto trigger_cleanup;
119586  }
119587  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
119588    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
119589        " trigger on table: %S", pTableName, 0);
119590    goto trigger_cleanup;
119591  }
119592  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
119593
119594#ifndef SQLITE_OMIT_AUTHORIZATION
119595  {
119596    int code = SQLITE_CREATE_TRIGGER;
119597    const char *zDb = db->aDb[iTabDb].zName;
119598    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
119599    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
119600    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
119601      goto trigger_cleanup;
119602    }
119603    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
119604      goto trigger_cleanup;
119605    }
119606  }
119607#endif
119608
119609  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
119610  ** cannot appear on views.  So we might as well translate every
119611  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
119612  ** elsewhere.
119613  */
119614  if (tr_tm == TK_INSTEAD){
119615    tr_tm = TK_BEFORE;
119616  }
119617
119618  /* Build the Trigger object */
119619  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
119620  if( pTrigger==0 ) goto trigger_cleanup;
119621  pTrigger->zName = zName;
119622  zName = 0;
119623  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
119624  pTrigger->pSchema = db->aDb[iDb].pSchema;
119625  pTrigger->pTabSchema = pTab->pSchema;
119626  pTrigger->op = (u8)op;
119627  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
119628  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
119629  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
119630  assert( pParse->pNewTrigger==0 );
119631  pParse->pNewTrigger = pTrigger;
119632
119633trigger_cleanup:
119634  sqlite3DbFree(db, zName);
119635  sqlite3SrcListDelete(db, pTableName);
119636  sqlite3IdListDelete(db, pColumns);
119637  sqlite3ExprDelete(db, pWhen);
119638  if( !pParse->pNewTrigger ){
119639    sqlite3DeleteTrigger(db, pTrigger);
119640  }else{
119641    assert( pParse->pNewTrigger==pTrigger );
119642  }
119643}
119644
119645/*
119646** This routine is called after all of the trigger actions have been parsed
119647** in order to complete the process of building the trigger.
119648*/
119649SQLITE_PRIVATE void sqlite3FinishTrigger(
119650  Parse *pParse,          /* Parser context */
119651  TriggerStep *pStepList, /* The triggered program */
119652  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
119653){
119654  Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
119655  char *zName;                            /* Name of trigger */
119656  sqlite3 *db = pParse->db;               /* The database */
119657  DbFixer sFix;                           /* Fixer object */
119658  int iDb;                                /* Database containing the trigger */
119659  Token nameToken;                        /* Trigger name for error reporting */
119660
119661  pParse->pNewTrigger = 0;
119662  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
119663  zName = pTrig->zName;
119664  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
119665  pTrig->step_list = pStepList;
119666  while( pStepList ){
119667    pStepList->pTrig = pTrig;
119668    pStepList = pStepList->pNext;
119669  }
119670  sqlite3TokenInit(&nameToken, pTrig->zName);
119671  sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
119672  if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
119673   || sqlite3FixExpr(&sFix, pTrig->pWhen)
119674  ){
119675    goto triggerfinish_cleanup;
119676  }
119677
119678  /* if we are not initializing,
119679  ** build the sqlite_master entry
119680  */
119681  if( !db->init.busy ){
119682    Vdbe *v;
119683    char *z;
119684
119685    /* Make an entry in the sqlite_master table */
119686    v = sqlite3GetVdbe(pParse);
119687    if( v==0 ) goto triggerfinish_cleanup;
119688    sqlite3BeginWriteOperation(pParse, 0, iDb);
119689    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
119690    sqlite3NestedParse(pParse,
119691       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
119692       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
119693       pTrig->table, z);
119694    sqlite3DbFree(db, z);
119695    sqlite3ChangeCookie(pParse, iDb);
119696    sqlite3VdbeAddParseSchemaOp(v, iDb,
119697        sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
119698  }
119699
119700  if( db->init.busy ){
119701    Trigger *pLink = pTrig;
119702    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
119703    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
119704    pTrig = sqlite3HashInsert(pHash, zName, pTrig);
119705    if( pTrig ){
119706      sqlite3OomFault(db);
119707    }else if( pLink->pSchema==pLink->pTabSchema ){
119708      Table *pTab;
119709      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
119710      assert( pTab!=0 );
119711      pLink->pNext = pTab->pTrigger;
119712      pTab->pTrigger = pLink;
119713    }
119714  }
119715
119716triggerfinish_cleanup:
119717  sqlite3DeleteTrigger(db, pTrig);
119718  assert( !pParse->pNewTrigger );
119719  sqlite3DeleteTriggerStep(db, pStepList);
119720}
119721
119722/*
119723** Turn a SELECT statement (that the pSelect parameter points to) into
119724** a trigger step.  Return a pointer to a TriggerStep structure.
119725**
119726** The parser calls this routine when it finds a SELECT statement in
119727** body of a TRIGGER.
119728*/
119729SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
119730  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
119731  if( pTriggerStep==0 ) {
119732    sqlite3SelectDelete(db, pSelect);
119733    return 0;
119734  }
119735  pTriggerStep->op = TK_SELECT;
119736  pTriggerStep->pSelect = pSelect;
119737  pTriggerStep->orconf = OE_Default;
119738  return pTriggerStep;
119739}
119740
119741/*
119742** Allocate space to hold a new trigger step.  The allocated space
119743** holds both the TriggerStep object and the TriggerStep.target.z string.
119744**
119745** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
119746*/
119747static TriggerStep *triggerStepAllocate(
119748  sqlite3 *db,                /* Database connection */
119749  u8 op,                      /* Trigger opcode */
119750  Token *pName                /* The target name */
119751){
119752  TriggerStep *pTriggerStep;
119753
119754  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
119755  if( pTriggerStep ){
119756    char *z = (char*)&pTriggerStep[1];
119757    memcpy(z, pName->z, pName->n);
119758    sqlite3Dequote(z);
119759    pTriggerStep->zTarget = z;
119760    pTriggerStep->op = op;
119761  }
119762  return pTriggerStep;
119763}
119764
119765/*
119766** Build a trigger step out of an INSERT statement.  Return a pointer
119767** to the new trigger step.
119768**
119769** The parser calls this routine when it sees an INSERT inside the
119770** body of a trigger.
119771*/
119772SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
119773  sqlite3 *db,        /* The database connection */
119774  Token *pTableName,  /* Name of the table into which we insert */
119775  IdList *pColumn,    /* List of columns in pTableName to insert into */
119776  Select *pSelect,    /* A SELECT statement that supplies values */
119777  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
119778){
119779  TriggerStep *pTriggerStep;
119780
119781  assert(pSelect != 0 || db->mallocFailed);
119782
119783  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
119784  if( pTriggerStep ){
119785    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
119786    pTriggerStep->pIdList = pColumn;
119787    pTriggerStep->orconf = orconf;
119788  }else{
119789    sqlite3IdListDelete(db, pColumn);
119790  }
119791  sqlite3SelectDelete(db, pSelect);
119792
119793  return pTriggerStep;
119794}
119795
119796/*
119797** Construct a trigger step that implements an UPDATE statement and return
119798** a pointer to that trigger step.  The parser calls this routine when it
119799** sees an UPDATE statement inside the body of a CREATE TRIGGER.
119800*/
119801SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
119802  sqlite3 *db,         /* The database connection */
119803  Token *pTableName,   /* Name of the table to be updated */
119804  ExprList *pEList,    /* The SET clause: list of column and new values */
119805  Expr *pWhere,        /* The WHERE clause */
119806  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
119807){
119808  TriggerStep *pTriggerStep;
119809
119810  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
119811  if( pTriggerStep ){
119812    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
119813    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
119814    pTriggerStep->orconf = orconf;
119815  }
119816  sqlite3ExprListDelete(db, pEList);
119817  sqlite3ExprDelete(db, pWhere);
119818  return pTriggerStep;
119819}
119820
119821/*
119822** Construct a trigger step that implements a DELETE statement and return
119823** a pointer to that trigger step.  The parser calls this routine when it
119824** sees a DELETE statement inside the body of a CREATE TRIGGER.
119825*/
119826SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
119827  sqlite3 *db,            /* Database connection */
119828  Token *pTableName,      /* The table from which rows are deleted */
119829  Expr *pWhere            /* The WHERE clause */
119830){
119831  TriggerStep *pTriggerStep;
119832
119833  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
119834  if( pTriggerStep ){
119835    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
119836    pTriggerStep->orconf = OE_Default;
119837  }
119838  sqlite3ExprDelete(db, pWhere);
119839  return pTriggerStep;
119840}
119841
119842/*
119843** Recursively delete a Trigger structure
119844*/
119845SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
119846  if( pTrigger==0 ) return;
119847  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
119848  sqlite3DbFree(db, pTrigger->zName);
119849  sqlite3DbFree(db, pTrigger->table);
119850  sqlite3ExprDelete(db, pTrigger->pWhen);
119851  sqlite3IdListDelete(db, pTrigger->pColumns);
119852  sqlite3DbFree(db, pTrigger);
119853}
119854
119855/*
119856** This function is called to drop a trigger from the database schema.
119857**
119858** This may be called directly from the parser and therefore identifies
119859** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
119860** same job as this routine except it takes a pointer to the trigger
119861** instead of the trigger name.
119862**/
119863SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
119864  Trigger *pTrigger = 0;
119865  int i;
119866  const char *zDb;
119867  const char *zName;
119868  sqlite3 *db = pParse->db;
119869
119870  if( db->mallocFailed ) goto drop_trigger_cleanup;
119871  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
119872    goto drop_trigger_cleanup;
119873  }
119874
119875  assert( pName->nSrc==1 );
119876  zDb = pName->a[0].zDatabase;
119877  zName = pName->a[0].zName;
119878  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
119879  for(i=OMIT_TEMPDB; i<db->nDb; i++){
119880    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
119881    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
119882    assert( sqlite3SchemaMutexHeld(db, j, 0) );
119883    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
119884    if( pTrigger ) break;
119885  }
119886  if( !pTrigger ){
119887    if( !noErr ){
119888      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
119889    }else{
119890      sqlite3CodeVerifyNamedSchema(pParse, zDb);
119891    }
119892    pParse->checkSchema = 1;
119893    goto drop_trigger_cleanup;
119894  }
119895  sqlite3DropTriggerPtr(pParse, pTrigger);
119896
119897drop_trigger_cleanup:
119898  sqlite3SrcListDelete(db, pName);
119899}
119900
119901/*
119902** Return a pointer to the Table structure for the table that a trigger
119903** is set on.
119904*/
119905static Table *tableOfTrigger(Trigger *pTrigger){
119906  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
119907}
119908
119909
119910/*
119911** Drop a trigger given a pointer to that trigger.
119912*/
119913SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
119914  Table   *pTable;
119915  Vdbe *v;
119916  sqlite3 *db = pParse->db;
119917  int iDb;
119918
119919  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
119920  assert( iDb>=0 && iDb<db->nDb );
119921  pTable = tableOfTrigger(pTrigger);
119922  assert( pTable );
119923  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
119924#ifndef SQLITE_OMIT_AUTHORIZATION
119925  {
119926    int code = SQLITE_DROP_TRIGGER;
119927    const char *zDb = db->aDb[iDb].zName;
119928    const char *zTab = SCHEMA_TABLE(iDb);
119929    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
119930    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
119931      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
119932      return;
119933    }
119934  }
119935#endif
119936
119937  /* Generate code to destroy the database record of the trigger.
119938  */
119939  assert( pTable!=0 );
119940  if( (v = sqlite3GetVdbe(pParse))!=0 ){
119941    sqlite3NestedParse(pParse,
119942       "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
119943       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrigger->zName
119944    );
119945    sqlite3ChangeCookie(pParse, iDb);
119946    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
119947  }
119948}
119949
119950/*
119951** Remove a trigger from the hash tables of the sqlite* pointer.
119952*/
119953SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
119954  Trigger *pTrigger;
119955  Hash *pHash;
119956
119957  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
119958  pHash = &(db->aDb[iDb].pSchema->trigHash);
119959  pTrigger = sqlite3HashInsert(pHash, zName, 0);
119960  if( ALWAYS(pTrigger) ){
119961    if( pTrigger->pSchema==pTrigger->pTabSchema ){
119962      Table *pTab = tableOfTrigger(pTrigger);
119963      Trigger **pp;
119964      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
119965      *pp = (*pp)->pNext;
119966    }
119967    sqlite3DeleteTrigger(db, pTrigger);
119968    db->flags |= SQLITE_InternChanges;
119969  }
119970}
119971
119972/*
119973** pEList is the SET clause of an UPDATE statement.  Each entry
119974** in pEList is of the format <id>=<expr>.  If any of the entries
119975** in pEList have an <id> which matches an identifier in pIdList,
119976** then return TRUE.  If pIdList==NULL, then it is considered a
119977** wildcard that matches anything.  Likewise if pEList==NULL then
119978** it matches anything so always return true.  Return false only
119979** if there is no match.
119980*/
119981static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
119982  int e;
119983  if( pIdList==0 || NEVER(pEList==0) ) return 1;
119984  for(e=0; e<pEList->nExpr; e++){
119985    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
119986  }
119987  return 0;
119988}
119989
119990/*
119991** Return a list of all triggers on table pTab if there exists at least
119992** one trigger that must be fired when an operation of type 'op' is
119993** performed on the table, and, if that operation is an UPDATE, if at
119994** least one of the columns in pChanges is being modified.
119995*/
119996SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
119997  Parse *pParse,          /* Parse context */
119998  Table *pTab,            /* The table the contains the triggers */
119999  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
120000  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
120001  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
120002){
120003  int mask = 0;
120004  Trigger *pList = 0;
120005  Trigger *p;
120006
120007  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
120008    pList = sqlite3TriggerList(pParse, pTab);
120009  }
120010  assert( pList==0 || IsVirtual(pTab)==0 );
120011  for(p=pList; p; p=p->pNext){
120012    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
120013      mask |= p->tr_tm;
120014    }
120015  }
120016  if( pMask ){
120017    *pMask = mask;
120018  }
120019  return (mask ? pList : 0);
120020}
120021
120022/*
120023** Convert the pStep->zTarget string into a SrcList and return a pointer
120024** to that SrcList.
120025**
120026** This routine adds a specific database name, if needed, to the target when
120027** forming the SrcList.  This prevents a trigger in one database from
120028** referring to a target in another database.  An exception is when the
120029** trigger is in TEMP in which case it can refer to any other database it
120030** wants.
120031*/
120032static SrcList *targetSrcList(
120033  Parse *pParse,       /* The parsing context */
120034  TriggerStep *pStep   /* The trigger containing the target token */
120035){
120036  sqlite3 *db = pParse->db;
120037  int iDb;             /* Index of the database to use */
120038  SrcList *pSrc;       /* SrcList to be returned */
120039
120040  pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
120041  if( pSrc ){
120042    assert( pSrc->nSrc>0 );
120043    pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
120044    iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
120045    if( iDb==0 || iDb>=2 ){
120046      assert( iDb<db->nDb );
120047      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
120048    }
120049  }
120050  return pSrc;
120051}
120052
120053/*
120054** Generate VDBE code for the statements inside the body of a single
120055** trigger.
120056*/
120057static int codeTriggerProgram(
120058  Parse *pParse,            /* The parser context */
120059  TriggerStep *pStepList,   /* List of statements inside the trigger body */
120060  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
120061){
120062  TriggerStep *pStep;
120063  Vdbe *v = pParse->pVdbe;
120064  sqlite3 *db = pParse->db;
120065
120066  assert( pParse->pTriggerTab && pParse->pToplevel );
120067  assert( pStepList );
120068  assert( v!=0 );
120069  for(pStep=pStepList; pStep; pStep=pStep->pNext){
120070    /* Figure out the ON CONFLICT policy that will be used for this step
120071    ** of the trigger program. If the statement that caused this trigger
120072    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
120073    ** the ON CONFLICT policy that was specified as part of the trigger
120074    ** step statement. Example:
120075    **
120076    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
120077    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
120078    **   END;
120079    **
120080    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
120081    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
120082    */
120083    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
120084    assert( pParse->okConstFactor==0 );
120085
120086    switch( pStep->op ){
120087      case TK_UPDATE: {
120088        sqlite3Update(pParse,
120089          targetSrcList(pParse, pStep),
120090          sqlite3ExprListDup(db, pStep->pExprList, 0),
120091          sqlite3ExprDup(db, pStep->pWhere, 0),
120092          pParse->eOrconf
120093        );
120094        break;
120095      }
120096      case TK_INSERT: {
120097        sqlite3Insert(pParse,
120098          targetSrcList(pParse, pStep),
120099          sqlite3SelectDup(db, pStep->pSelect, 0),
120100          sqlite3IdListDup(db, pStep->pIdList),
120101          pParse->eOrconf
120102        );
120103        break;
120104      }
120105      case TK_DELETE: {
120106        sqlite3DeleteFrom(pParse,
120107          targetSrcList(pParse, pStep),
120108          sqlite3ExprDup(db, pStep->pWhere, 0)
120109        );
120110        break;
120111      }
120112      default: assert( pStep->op==TK_SELECT ); {
120113        SelectDest sDest;
120114        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
120115        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
120116        sqlite3Select(pParse, pSelect, &sDest);
120117        sqlite3SelectDelete(db, pSelect);
120118        break;
120119      }
120120    }
120121    if( pStep->op!=TK_SELECT ){
120122      sqlite3VdbeAddOp0(v, OP_ResetCount);
120123    }
120124  }
120125
120126  return 0;
120127}
120128
120129#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
120130/*
120131** This function is used to add VdbeComment() annotations to a VDBE
120132** program. It is not used in production code, only for debugging.
120133*/
120134static const char *onErrorText(int onError){
120135  switch( onError ){
120136    case OE_Abort:    return "abort";
120137    case OE_Rollback: return "rollback";
120138    case OE_Fail:     return "fail";
120139    case OE_Replace:  return "replace";
120140    case OE_Ignore:   return "ignore";
120141    case OE_Default:  return "default";
120142  }
120143  return "n/a";
120144}
120145#endif
120146
120147/*
120148** Parse context structure pFrom has just been used to create a sub-vdbe
120149** (trigger program). If an error has occurred, transfer error information
120150** from pFrom to pTo.
120151*/
120152static void transferParseError(Parse *pTo, Parse *pFrom){
120153  assert( pFrom->zErrMsg==0 || pFrom->nErr );
120154  assert( pTo->zErrMsg==0 || pTo->nErr );
120155  if( pTo->nErr==0 ){
120156    pTo->zErrMsg = pFrom->zErrMsg;
120157    pTo->nErr = pFrom->nErr;
120158    pTo->rc = pFrom->rc;
120159  }else{
120160    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
120161  }
120162}
120163
120164/*
120165** Create and populate a new TriggerPrg object with a sub-program
120166** implementing trigger pTrigger with ON CONFLICT policy orconf.
120167*/
120168static TriggerPrg *codeRowTrigger(
120169  Parse *pParse,       /* Current parse context */
120170  Trigger *pTrigger,   /* Trigger to code */
120171  Table *pTab,         /* The table pTrigger is attached to */
120172  int orconf           /* ON CONFLICT policy to code trigger program with */
120173){
120174  Parse *pTop = sqlite3ParseToplevel(pParse);
120175  sqlite3 *db = pParse->db;   /* Database handle */
120176  TriggerPrg *pPrg;           /* Value to return */
120177  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
120178  Vdbe *v;                    /* Temporary VM */
120179  NameContext sNC;            /* Name context for sub-vdbe */
120180  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
120181  Parse *pSubParse;           /* Parse context for sub-vdbe */
120182  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
120183
120184  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
120185  assert( pTop->pVdbe );
120186
120187  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
120188  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
120189  ** list of the top-level Parse object sooner rather than later.  */
120190  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
120191  if( !pPrg ) return 0;
120192  pPrg->pNext = pTop->pTriggerPrg;
120193  pTop->pTriggerPrg = pPrg;
120194  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
120195  if( !pProgram ) return 0;
120196  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
120197  pPrg->pTrigger = pTrigger;
120198  pPrg->orconf = orconf;
120199  pPrg->aColmask[0] = 0xffffffff;
120200  pPrg->aColmask[1] = 0xffffffff;
120201
120202  /* Allocate and populate a new Parse context to use for coding the
120203  ** trigger sub-program.  */
120204  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
120205  if( !pSubParse ) return 0;
120206  memset(&sNC, 0, sizeof(sNC));
120207  sNC.pParse = pSubParse;
120208  pSubParse->db = db;
120209  pSubParse->pTriggerTab = pTab;
120210  pSubParse->pToplevel = pTop;
120211  pSubParse->zAuthContext = pTrigger->zName;
120212  pSubParse->eTriggerOp = pTrigger->op;
120213  pSubParse->nQueryLoop = pParse->nQueryLoop;
120214
120215  v = sqlite3GetVdbe(pSubParse);
120216  if( v ){
120217    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
120218      pTrigger->zName, onErrorText(orconf),
120219      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
120220        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
120221        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
120222        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
120223      pTab->zName
120224    ));
120225#ifndef SQLITE_OMIT_TRACE
120226    sqlite3VdbeChangeP4(v, -1,
120227      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
120228    );
120229#endif
120230
120231    /* If one was specified, code the WHEN clause. If it evaluates to false
120232    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
120233    ** OP_Halt inserted at the end of the program.  */
120234    if( pTrigger->pWhen ){
120235      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
120236      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
120237       && db->mallocFailed==0
120238      ){
120239        iEndTrigger = sqlite3VdbeMakeLabel(v);
120240        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
120241      }
120242      sqlite3ExprDelete(db, pWhen);
120243    }
120244
120245    /* Code the trigger program into the sub-vdbe. */
120246    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
120247
120248    /* Insert an OP_Halt at the end of the sub-program. */
120249    if( iEndTrigger ){
120250      sqlite3VdbeResolveLabel(v, iEndTrigger);
120251    }
120252    sqlite3VdbeAddOp0(v, OP_Halt);
120253    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
120254
120255    transferParseError(pParse, pSubParse);
120256    if( db->mallocFailed==0 ){
120257      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
120258    }
120259    pProgram->nMem = pSubParse->nMem;
120260    pProgram->nCsr = pSubParse->nTab;
120261    pProgram->nOnce = pSubParse->nOnce;
120262    pProgram->token = (void *)pTrigger;
120263    pPrg->aColmask[0] = pSubParse->oldmask;
120264    pPrg->aColmask[1] = pSubParse->newmask;
120265    sqlite3VdbeDelete(v);
120266  }
120267
120268  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
120269  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
120270  sqlite3ParserReset(pSubParse);
120271  sqlite3StackFree(db, pSubParse);
120272
120273  return pPrg;
120274}
120275
120276/*
120277** Return a pointer to a TriggerPrg object containing the sub-program for
120278** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
120279** TriggerPrg object exists, a new object is allocated and populated before
120280** being returned.
120281*/
120282static TriggerPrg *getRowTrigger(
120283  Parse *pParse,       /* Current parse context */
120284  Trigger *pTrigger,   /* Trigger to code */
120285  Table *pTab,         /* The table trigger pTrigger is attached to */
120286  int orconf           /* ON CONFLICT algorithm. */
120287){
120288  Parse *pRoot = sqlite3ParseToplevel(pParse);
120289  TriggerPrg *pPrg;
120290
120291  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
120292
120293  /* It may be that this trigger has already been coded (or is in the
120294  ** process of being coded). If this is the case, then an entry with
120295  ** a matching TriggerPrg.pTrigger field will be present somewhere
120296  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
120297  for(pPrg=pRoot->pTriggerPrg;
120298      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
120299      pPrg=pPrg->pNext
120300  );
120301
120302  /* If an existing TriggerPrg could not be located, create a new one. */
120303  if( !pPrg ){
120304    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
120305  }
120306
120307  return pPrg;
120308}
120309
120310/*
120311** Generate code for the trigger program associated with trigger p on
120312** table pTab. The reg, orconf and ignoreJump parameters passed to this
120313** function are the same as those described in the header function for
120314** sqlite3CodeRowTrigger()
120315*/
120316SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
120317  Parse *pParse,       /* Parse context */
120318  Trigger *p,          /* Trigger to code */
120319  Table *pTab,         /* The table to code triggers from */
120320  int reg,             /* Reg array containing OLD.* and NEW.* values */
120321  int orconf,          /* ON CONFLICT policy */
120322  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
120323){
120324  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
120325  TriggerPrg *pPrg;
120326  pPrg = getRowTrigger(pParse, p, pTab, orconf);
120327  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
120328
120329  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
120330  ** is a pointer to the sub-vdbe containing the trigger program.  */
120331  if( pPrg ){
120332    int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
120333
120334    sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
120335                      (const char *)pPrg->pProgram, P4_SUBPROGRAM);
120336    VdbeComment(
120337        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
120338
120339    /* Set the P5 operand of the OP_Program instruction to non-zero if
120340    ** recursive invocation of this trigger program is disallowed. Recursive
120341    ** invocation is disallowed if (a) the sub-program is really a trigger,
120342    ** not a foreign key action, and (b) the flag to enable recursive triggers
120343    ** is clear.  */
120344    sqlite3VdbeChangeP5(v, (u8)bRecursive);
120345  }
120346}
120347
120348/*
120349** This is called to code the required FOR EACH ROW triggers for an operation
120350** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
120351** is given by the op parameter. The tr_tm parameter determines whether the
120352** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
120353** parameter pChanges is passed the list of columns being modified.
120354**
120355** If there are no triggers that fire at the specified time for the specified
120356** operation on pTab, this function is a no-op.
120357**
120358** The reg argument is the address of the first in an array of registers
120359** that contain the values substituted for the new.* and old.* references
120360** in the trigger program. If N is the number of columns in table pTab
120361** (a copy of pTab->nCol), then registers are populated as follows:
120362**
120363**   Register       Contains
120364**   ------------------------------------------------------
120365**   reg+0          OLD.rowid
120366**   reg+1          OLD.* value of left-most column of pTab
120367**   ...            ...
120368**   reg+N          OLD.* value of right-most column of pTab
120369**   reg+N+1        NEW.rowid
120370**   reg+N+2        OLD.* value of left-most column of pTab
120371**   ...            ...
120372**   reg+N+N+1      NEW.* value of right-most column of pTab
120373**
120374** For ON DELETE triggers, the registers containing the NEW.* values will
120375** never be accessed by the trigger program, so they are not allocated or
120376** populated by the caller (there is no data to populate them with anyway).
120377** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
120378** are never accessed, and so are not allocated by the caller. So, for an
120379** ON INSERT trigger, the value passed to this function as parameter reg
120380** is not a readable register, although registers (reg+N) through
120381** (reg+N+N+1) are.
120382**
120383** Parameter orconf is the default conflict resolution algorithm for the
120384** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
120385** is the instruction that control should jump to if a trigger program
120386** raises an IGNORE exception.
120387*/
120388SQLITE_PRIVATE void sqlite3CodeRowTrigger(
120389  Parse *pParse,       /* Parse context */
120390  Trigger *pTrigger,   /* List of triggers on table pTab */
120391  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
120392  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
120393  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
120394  Table *pTab,         /* The table to code triggers from */
120395  int reg,             /* The first in an array of registers (see above) */
120396  int orconf,          /* ON CONFLICT policy */
120397  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
120398){
120399  Trigger *p;          /* Used to iterate through pTrigger list */
120400
120401  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
120402  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
120403  assert( (op==TK_UPDATE)==(pChanges!=0) );
120404
120405  for(p=pTrigger; p; p=p->pNext){
120406
120407    /* Sanity checking:  The schema for the trigger and for the table are
120408    ** always defined.  The trigger must be in the same schema as the table
120409    ** or else it must be a TEMP trigger. */
120410    assert( p->pSchema!=0 );
120411    assert( p->pTabSchema!=0 );
120412    assert( p->pSchema==p->pTabSchema
120413         || p->pSchema==pParse->db->aDb[1].pSchema );
120414
120415    /* Determine whether we should code this trigger */
120416    if( p->op==op
120417     && p->tr_tm==tr_tm
120418     && checkColumnOverlap(p->pColumns, pChanges)
120419    ){
120420      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
120421    }
120422  }
120423}
120424
120425/*
120426** Triggers may access values stored in the old.* or new.* pseudo-table.
120427** This function returns a 32-bit bitmask indicating which columns of the
120428** old.* or new.* tables actually are used by triggers. This information
120429** may be used by the caller, for example, to avoid having to load the entire
120430** old.* record into memory when executing an UPDATE or DELETE command.
120431**
120432** Bit 0 of the returned mask is set if the left-most column of the
120433** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
120434** the second leftmost column value is required, and so on. If there
120435** are more than 32 columns in the table, and at least one of the columns
120436** with an index greater than 32 may be accessed, 0xffffffff is returned.
120437**
120438** It is not possible to determine if the old.rowid or new.rowid column is
120439** accessed by triggers. The caller must always assume that it is.
120440**
120441** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
120442** applies to the old.* table. If 1, the new.* table.
120443**
120444** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
120445** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
120446** included in the returned mask if the TRIGGER_BEFORE bit is set in the
120447** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
120448** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
120449*/
120450SQLITE_PRIVATE u32 sqlite3TriggerColmask(
120451  Parse *pParse,       /* Parse context */
120452  Trigger *pTrigger,   /* List of triggers on table pTab */
120453  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
120454  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
120455  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
120456  Table *pTab,         /* The table to code triggers from */
120457  int orconf           /* Default ON CONFLICT policy for trigger steps */
120458){
120459  const int op = pChanges ? TK_UPDATE : TK_DELETE;
120460  u32 mask = 0;
120461  Trigger *p;
120462
120463  assert( isNew==1 || isNew==0 );
120464  for(p=pTrigger; p; p=p->pNext){
120465    if( p->op==op && (tr_tm&p->tr_tm)
120466     && checkColumnOverlap(p->pColumns,pChanges)
120467    ){
120468      TriggerPrg *pPrg;
120469      pPrg = getRowTrigger(pParse, p, pTab, orconf);
120470      if( pPrg ){
120471        mask |= pPrg->aColmask[isNew];
120472      }
120473    }
120474  }
120475
120476  return mask;
120477}
120478
120479#endif /* !defined(SQLITE_OMIT_TRIGGER) */
120480
120481/************** End of trigger.c *********************************************/
120482/************** Begin file update.c ******************************************/
120483/*
120484** 2001 September 15
120485**
120486** The author disclaims copyright to this source code.  In place of
120487** a legal notice, here is a blessing:
120488**
120489**    May you do good and not evil.
120490**    May you find forgiveness for yourself and forgive others.
120491**    May you share freely, never taking more than you give.
120492**
120493*************************************************************************
120494** This file contains C code routines that are called by the parser
120495** to handle UPDATE statements.
120496*/
120497/* #include "sqliteInt.h" */
120498
120499#ifndef SQLITE_OMIT_VIRTUALTABLE
120500/* Forward declaration */
120501static void updateVirtualTable(
120502  Parse *pParse,       /* The parsing context */
120503  SrcList *pSrc,       /* The virtual table to be modified */
120504  Table *pTab,         /* The virtual table */
120505  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
120506  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
120507  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
120508  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
120509  int onError          /* ON CONFLICT strategy */
120510);
120511#endif /* SQLITE_OMIT_VIRTUALTABLE */
120512
120513/*
120514** The most recently coded instruction was an OP_Column to retrieve the
120515** i-th column of table pTab. This routine sets the P4 parameter of the
120516** OP_Column to the default value, if any.
120517**
120518** The default value of a column is specified by a DEFAULT clause in the
120519** column definition. This was either supplied by the user when the table
120520** was created, or added later to the table definition by an ALTER TABLE
120521** command. If the latter, then the row-records in the table btree on disk
120522** may not contain a value for the column and the default value, taken
120523** from the P4 parameter of the OP_Column instruction, is returned instead.
120524** If the former, then all row-records are guaranteed to include a value
120525** for the column and the P4 value is not required.
120526**
120527** Column definitions created by an ALTER TABLE command may only have
120528** literal default values specified: a number, null or a string. (If a more
120529** complicated default expression value was provided, it is evaluated
120530** when the ALTER TABLE is executed and one of the literal values written
120531** into the sqlite_master table.)
120532**
120533** Therefore, the P4 parameter is only required if the default value for
120534** the column is a literal number, string or null. The sqlite3ValueFromExpr()
120535** function is capable of transforming these types of expressions into
120536** sqlite3_value objects.
120537**
120538** If parameter iReg is not negative, code an OP_RealAffinity instruction
120539** on register iReg. This is used when an equivalent integer value is
120540** stored in place of an 8-byte floating point value in order to save
120541** space.
120542*/
120543SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
120544  assert( pTab!=0 );
120545  if( !pTab->pSelect ){
120546    sqlite3_value *pValue = 0;
120547    u8 enc = ENC(sqlite3VdbeDb(v));
120548    Column *pCol = &pTab->aCol[i];
120549    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
120550    assert( i<pTab->nCol );
120551    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
120552                         pCol->affinity, &pValue);
120553    if( pValue ){
120554      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
120555    }
120556#ifndef SQLITE_OMIT_FLOATING_POINT
120557    if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
120558      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
120559    }
120560#endif
120561  }
120562}
120563
120564/*
120565** Process an UPDATE statement.
120566**
120567**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
120568**          \_______/ \________/     \______/       \________________/
120569*            onError   pTabList      pChanges             pWhere
120570*/
120571SQLITE_PRIVATE void sqlite3Update(
120572  Parse *pParse,         /* The parser context */
120573  SrcList *pTabList,     /* The table in which we should change things */
120574  ExprList *pChanges,    /* Things to be changed */
120575  Expr *pWhere,          /* The WHERE clause.  May be null */
120576  int onError            /* How to handle constraint errors */
120577){
120578  int i, j;              /* Loop counters */
120579  Table *pTab;           /* The table to be updated */
120580  int addrTop = 0;       /* VDBE instruction address of the start of the loop */
120581  WhereInfo *pWInfo;     /* Information about the WHERE clause */
120582  Vdbe *v;               /* The virtual database engine */
120583  Index *pIdx;           /* For looping over indices */
120584  Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
120585  int nIdx;              /* Number of indices that need updating */
120586  int iBaseCur;          /* Base cursor number */
120587  int iDataCur;          /* Cursor for the canonical data btree */
120588  int iIdxCur;           /* Cursor for the first index */
120589  sqlite3 *db;           /* The database structure */
120590  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
120591  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
120592                         ** an expression for the i-th column of the table.
120593                         ** aXRef[i]==-1 if the i-th column is not changed. */
120594  u8 *aToOpen;           /* 1 for tables and indices to be opened */
120595  u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
120596  u8 chngRowid;          /* Rowid changed in a normal table */
120597  u8 chngKey;            /* Either chngPk or chngRowid */
120598  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
120599  AuthContext sContext;  /* The authorization context */
120600  NameContext sNC;       /* The name-context to resolve expressions in */
120601  int iDb;               /* Database containing the table being updated */
120602  int okOnePass;         /* True for one-pass algorithm without the FIFO */
120603  int hasFK;             /* True if foreign key processing is required */
120604  int labelBreak;        /* Jump here to break out of UPDATE loop */
120605  int labelContinue;     /* Jump here to continue next step of UPDATE loop */
120606
120607#ifndef SQLITE_OMIT_TRIGGER
120608  int isView;            /* True when updating a view (INSTEAD OF trigger) */
120609  Trigger *pTrigger;     /* List of triggers on pTab, if required */
120610  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
120611#endif
120612  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
120613  int iEph = 0;          /* Ephemeral table holding all primary key values */
120614  int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
120615  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
120616
120617  /* Register Allocations */
120618  int regRowCount = 0;   /* A count of rows changed */
120619  int regOldRowid = 0;   /* The old rowid */
120620  int regNewRowid = 0;   /* The new rowid */
120621  int regNew = 0;        /* Content of the NEW.* table in triggers */
120622  int regOld = 0;        /* Content of OLD.* table in triggers */
120623  int regRowSet = 0;     /* Rowset of rows to be updated */
120624  int regKey = 0;        /* composite PRIMARY KEY value */
120625
120626  memset(&sContext, 0, sizeof(sContext));
120627  db = pParse->db;
120628  if( pParse->nErr || db->mallocFailed ){
120629    goto update_cleanup;
120630  }
120631  assert( pTabList->nSrc==1 );
120632
120633  /* Locate the table which we want to update.
120634  */
120635  pTab = sqlite3SrcListLookup(pParse, pTabList);
120636  if( pTab==0 ) goto update_cleanup;
120637  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
120638
120639  /* Figure out if we have any triggers and if the table being
120640  ** updated is a view.
120641  */
120642#ifndef SQLITE_OMIT_TRIGGER
120643  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
120644  isView = pTab->pSelect!=0;
120645  assert( pTrigger || tmask==0 );
120646#else
120647# define pTrigger 0
120648# define isView 0
120649# define tmask 0
120650#endif
120651#ifdef SQLITE_OMIT_VIEW
120652# undef isView
120653# define isView 0
120654#endif
120655
120656  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
120657    goto update_cleanup;
120658  }
120659  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
120660    goto update_cleanup;
120661  }
120662
120663  /* Allocate a cursors for the main database table and for all indices.
120664  ** The index cursors might not be used, but if they are used they
120665  ** need to occur right after the database cursor.  So go ahead and
120666  ** allocate enough space, just in case.
120667  */
120668  pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
120669  iIdxCur = iDataCur+1;
120670  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
120671  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
120672    if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
120673      iDataCur = pParse->nTab;
120674      pTabList->a[0].iCursor = iDataCur;
120675    }
120676    pParse->nTab++;
120677  }
120678
120679  /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
120680  ** Initialize aXRef[] and aToOpen[] to their default values.
120681  */
120682  aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
120683  if( aXRef==0 ) goto update_cleanup;
120684  aRegIdx = aXRef+pTab->nCol;
120685  aToOpen = (u8*)(aRegIdx+nIdx);
120686  memset(aToOpen, 1, nIdx+1);
120687  aToOpen[nIdx+1] = 0;
120688  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
120689
120690  /* Initialize the name-context */
120691  memset(&sNC, 0, sizeof(sNC));
120692  sNC.pParse = pParse;
120693  sNC.pSrcList = pTabList;
120694
120695  /* Resolve the column names in all the expressions of the
120696  ** of the UPDATE statement.  Also find the column index
120697  ** for each column to be updated in the pChanges array.  For each
120698  ** column to be updated, make sure we have authorization to change
120699  ** that column.
120700  */
120701  chngRowid = chngPk = 0;
120702  for(i=0; i<pChanges->nExpr; i++){
120703    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
120704      goto update_cleanup;
120705    }
120706    for(j=0; j<pTab->nCol; j++){
120707      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
120708        if( j==pTab->iPKey ){
120709          chngRowid = 1;
120710          pRowidExpr = pChanges->a[i].pExpr;
120711        }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
120712          chngPk = 1;
120713        }
120714        aXRef[j] = i;
120715        break;
120716      }
120717    }
120718    if( j>=pTab->nCol ){
120719      if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
120720        j = -1;
120721        chngRowid = 1;
120722        pRowidExpr = pChanges->a[i].pExpr;
120723      }else{
120724        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
120725        pParse->checkSchema = 1;
120726        goto update_cleanup;
120727      }
120728    }
120729#ifndef SQLITE_OMIT_AUTHORIZATION
120730    {
120731      int rc;
120732      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
120733                            j<0 ? "ROWID" : pTab->aCol[j].zName,
120734                            db->aDb[iDb].zName);
120735      if( rc==SQLITE_DENY ){
120736        goto update_cleanup;
120737      }else if( rc==SQLITE_IGNORE ){
120738        aXRef[j] = -1;
120739      }
120740    }
120741#endif
120742  }
120743  assert( (chngRowid & chngPk)==0 );
120744  assert( chngRowid==0 || chngRowid==1 );
120745  assert( chngPk==0 || chngPk==1 );
120746  chngKey = chngRowid + chngPk;
120747
120748  /* The SET expressions are not actually used inside the WHERE loop.
120749  ** So reset the colUsed mask. Unless this is a virtual table. In that
120750  ** case, set all bits of the colUsed mask (to ensure that the virtual
120751  ** table implementation makes all columns available).
120752  */
120753  pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
120754
120755  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
120756
120757  /* There is one entry in the aRegIdx[] array for each index on the table
120758  ** being updated.  Fill in aRegIdx[] with a register number that will hold
120759  ** the key for accessing each index.
120760  **
120761  ** FIXME:  Be smarter about omitting indexes that use expressions.
120762  */
120763  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
120764    int reg;
120765    if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
120766      reg = ++pParse->nMem;
120767    }else{
120768      reg = 0;
120769      for(i=0; i<pIdx->nKeyCol; i++){
120770        i16 iIdxCol = pIdx->aiColumn[i];
120771        if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
120772          reg = ++pParse->nMem;
120773          break;
120774        }
120775      }
120776    }
120777    if( reg==0 ) aToOpen[j+1] = 0;
120778    aRegIdx[j] = reg;
120779  }
120780
120781  /* Begin generating code. */
120782  v = sqlite3GetVdbe(pParse);
120783  if( v==0 ) goto update_cleanup;
120784  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
120785  sqlite3BeginWriteOperation(pParse, 1, iDb);
120786
120787  /* Allocate required registers. */
120788  if( !IsVirtual(pTab) ){
120789    regRowSet = ++pParse->nMem;
120790    regOldRowid = regNewRowid = ++pParse->nMem;
120791    if( chngPk || pTrigger || hasFK ){
120792      regOld = pParse->nMem + 1;
120793      pParse->nMem += pTab->nCol;
120794    }
120795    if( chngKey || pTrigger || hasFK ){
120796      regNewRowid = ++pParse->nMem;
120797    }
120798    regNew = pParse->nMem + 1;
120799    pParse->nMem += pTab->nCol;
120800  }
120801
120802  /* Start the view context. */
120803  if( isView ){
120804    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
120805  }
120806
120807  /* If we are trying to update a view, realize that view into
120808  ** an ephemeral table.
120809  */
120810#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
120811  if( isView ){
120812    sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
120813  }
120814#endif
120815
120816  /* Resolve the column names in all the expressions in the
120817  ** WHERE clause.
120818  */
120819  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
120820    goto update_cleanup;
120821  }
120822
120823#ifndef SQLITE_OMIT_VIRTUALTABLE
120824  /* Virtual tables must be handled separately */
120825  if( IsVirtual(pTab) ){
120826    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
120827                       pWhere, onError);
120828    goto update_cleanup;
120829  }
120830#endif
120831
120832  /* Begin the database scan
120833  */
120834  if( HasRowid(pTab) ){
120835    sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
120836    pWInfo = sqlite3WhereBegin(
120837        pParse, pTabList, pWhere, 0, 0,
120838            WHERE_ONEPASS_DESIRED | WHERE_SEEK_TABLE, iIdxCur
120839    );
120840    if( pWInfo==0 ) goto update_cleanup;
120841    okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
120842
120843    /* Remember the rowid of every item to be updated.
120844    */
120845    sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
120846    if( !okOnePass ){
120847      sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
120848    }
120849
120850    /* End the database scan loop.
120851    */
120852    sqlite3WhereEnd(pWInfo);
120853  }else{
120854    int iPk;         /* First of nPk memory cells holding PRIMARY KEY value */
120855    i16 nPk;         /* Number of components of the PRIMARY KEY */
120856    int addrOpen;    /* Address of the OpenEphemeral instruction */
120857
120858    assert( pPk!=0 );
120859    nPk = pPk->nKeyCol;
120860    iPk = pParse->nMem+1;
120861    pParse->nMem += nPk;
120862    regKey = ++pParse->nMem;
120863    iEph = pParse->nTab++;
120864    sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
120865    addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
120866    sqlite3VdbeSetP4KeyInfo(pParse, pPk);
120867    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
120868                               WHERE_ONEPASS_DESIRED, iIdxCur);
120869    if( pWInfo==0 ) goto update_cleanup;
120870    okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
120871    for(i=0; i<nPk; i++){
120872      assert( pPk->aiColumn[i]>=0 );
120873      sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
120874                                      iPk+i);
120875    }
120876    if( okOnePass ){
120877      sqlite3VdbeChangeToNoop(v, addrOpen);
120878      nKey = nPk;
120879      regKey = iPk;
120880    }else{
120881      sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
120882                        sqlite3IndexAffinityStr(db, pPk), nPk);
120883      sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
120884    }
120885    sqlite3WhereEnd(pWInfo);
120886  }
120887
120888  /* Initialize the count of updated rows
120889  */
120890  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
120891    regRowCount = ++pParse->nMem;
120892    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
120893  }
120894
120895  labelBreak = sqlite3VdbeMakeLabel(v);
120896  if( !isView ){
120897    /*
120898    ** Open every index that needs updating.  Note that if any
120899    ** index could potentially invoke a REPLACE conflict resolution
120900    ** action, then we need to open all indices because we might need
120901    ** to be deleting some records.
120902    */
120903    if( onError==OE_Replace ){
120904      memset(aToOpen, 1, nIdx+1);
120905    }else{
120906      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
120907        if( pIdx->onError==OE_Replace ){
120908          memset(aToOpen, 1, nIdx+1);
120909          break;
120910        }
120911      }
120912    }
120913    if( okOnePass ){
120914      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
120915      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
120916    }
120917    sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
120918                               0, 0);
120919  }
120920
120921  /* Top of the update loop */
120922  if( okOnePass ){
120923    if( aToOpen[iDataCur-iBaseCur] && !isView ){
120924      assert( pPk );
120925      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
120926      VdbeCoverageNeverTaken(v);
120927    }
120928    labelContinue = labelBreak;
120929    sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
120930    VdbeCoverageIf(v, pPk==0);
120931    VdbeCoverageIf(v, pPk!=0);
120932  }else if( pPk ){
120933    labelContinue = sqlite3VdbeMakeLabel(v);
120934    sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
120935    addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
120936    sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
120937    VdbeCoverage(v);
120938  }else{
120939    labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
120940                             regOldRowid);
120941    VdbeCoverage(v);
120942    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
120943    VdbeCoverage(v);
120944  }
120945
120946  /* If the record number will change, set register regNewRowid to
120947  ** contain the new value. If the record number is not being modified,
120948  ** then regNewRowid is the same register as regOldRowid, which is
120949  ** already populated.  */
120950  assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
120951  if( chngRowid ){
120952    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
120953    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
120954  }
120955
120956  /* Compute the old pre-UPDATE content of the row being changed, if that
120957  ** information is needed */
120958  if( chngPk || hasFK || pTrigger ){
120959    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
120960    oldmask |= sqlite3TriggerColmask(pParse,
120961        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
120962    );
120963    for(i=0; i<pTab->nCol; i++){
120964      if( oldmask==0xffffffff
120965       || (i<32 && (oldmask & MASKBIT32(i))!=0)
120966       || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
120967      ){
120968        testcase(  oldmask!=0xffffffff && i==31 );
120969        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
120970      }else{
120971        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
120972      }
120973    }
120974    if( chngRowid==0 && pPk==0 ){
120975      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
120976    }
120977  }
120978
120979  /* Populate the array of registers beginning at regNew with the new
120980  ** row data. This array is used to check constants, create the new
120981  ** table and index records, and as the values for any new.* references
120982  ** made by triggers.
120983  **
120984  ** If there are one or more BEFORE triggers, then do not populate the
120985  ** registers associated with columns that are (a) not modified by
120986  ** this UPDATE statement and (b) not accessed by new.* references. The
120987  ** values for registers not modified by the UPDATE must be reloaded from
120988  ** the database after the BEFORE triggers are fired anyway (as the trigger
120989  ** may have modified them). So not loading those that are not going to
120990  ** be used eliminates some redundant opcodes.
120991  */
120992  newmask = sqlite3TriggerColmask(
120993      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
120994  );
120995  for(i=0; i<pTab->nCol; i++){
120996    if( i==pTab->iPKey ){
120997      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
120998    }else{
120999      j = aXRef[i];
121000      if( j>=0 ){
121001        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
121002      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
121003        /* This branch loads the value of a column that will not be changed
121004        ** into a register. This is done if there are no BEFORE triggers, or
121005        ** if there are one or more BEFORE triggers that use this value via
121006        ** a new.* reference in a trigger program.
121007        */
121008        testcase( i==31 );
121009        testcase( i==32 );
121010        sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
121011      }else{
121012        sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
121013      }
121014    }
121015  }
121016
121017  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
121018  ** verified. One could argue that this is wrong.
121019  */
121020  if( tmask&TRIGGER_BEFORE ){
121021    sqlite3TableAffinity(v, pTab, regNew);
121022    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
121023        TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
121024
121025    /* The row-trigger may have deleted the row being updated. In this
121026    ** case, jump to the next row. No updates or AFTER triggers are
121027    ** required. This behavior - what happens when the row being updated
121028    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
121029    ** documentation.
121030    */
121031    if( pPk ){
121032      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
121033      VdbeCoverage(v);
121034    }else{
121035      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
121036      VdbeCoverage(v);
121037    }
121038
121039    /* If it did not delete it, the row-trigger may still have modified
121040    ** some of the columns of the row being updated. Load the values for
121041    ** all columns not modified by the update statement into their
121042    ** registers in case this has happened.
121043    */
121044    for(i=0; i<pTab->nCol; i++){
121045      if( aXRef[i]<0 && i!=pTab->iPKey ){
121046        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
121047      }
121048    }
121049  }
121050
121051  if( !isView ){
121052    int addr1 = 0;        /* Address of jump instruction */
121053    int bReplace = 0;     /* True if REPLACE conflict resolution might happen */
121054
121055    /* Do constraint checks. */
121056    assert( regOldRowid>0 );
121057    sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
121058        regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
121059        aXRef);
121060
121061    /* Do FK constraint checks. */
121062    if( hasFK ){
121063      sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
121064    }
121065
121066    /* Delete the index entries associated with the current record.  */
121067    if( bReplace || chngKey ){
121068      if( pPk ){
121069        addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
121070      }else{
121071        addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
121072      }
121073      VdbeCoverageNeverTaken(v);
121074    }
121075    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
121076
121077    /* If changing the rowid value, or if there are foreign key constraints
121078    ** to process, delete the old record. Otherwise, add a noop OP_Delete
121079    ** to invoke the pre-update hook.
121080    **
121081    ** That (regNew==regnewRowid+1) is true is also important for the
121082    ** pre-update hook. If the caller invokes preupdate_new(), the returned
121083    ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
121084    ** is the column index supplied by the user.
121085    */
121086    assert( regNew==regNewRowid+1 );
121087#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
121088    sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
121089        OPFLAG_ISUPDATE | ((hasFK || chngKey || pPk!=0) ? 0 : OPFLAG_ISNOOP),
121090        regNewRowid
121091    );
121092    if( !pParse->nested ){
121093      sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE);
121094    }
121095#else
121096    if( hasFK || chngKey || pPk!=0 ){
121097      sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
121098    }
121099#endif
121100    if( bReplace || chngKey ){
121101      sqlite3VdbeJumpHere(v, addr1);
121102    }
121103
121104    if( hasFK ){
121105      sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
121106    }
121107
121108    /* Insert the new index entries and the new record. */
121109    sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
121110                             regNewRowid, aRegIdx, 1, 0, 0);
121111
121112    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
121113    ** handle rows (possibly in other tables) that refer via a foreign key
121114    ** to the row just updated. */
121115    if( hasFK ){
121116      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
121117    }
121118  }
121119
121120  /* Increment the row counter
121121  */
121122  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
121123    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
121124  }
121125
121126  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
121127      TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
121128
121129  /* Repeat the above with the next record to be updated, until
121130  ** all record selected by the WHERE clause have been updated.
121131  */
121132  if( okOnePass ){
121133    /* Nothing to do at end-of-loop for a single-pass */
121134  }else if( pPk ){
121135    sqlite3VdbeResolveLabel(v, labelContinue);
121136    sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
121137  }else{
121138    sqlite3VdbeGoto(v, labelContinue);
121139  }
121140  sqlite3VdbeResolveLabel(v, labelBreak);
121141
121142  /* Close all tables */
121143  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
121144    assert( aRegIdx );
121145    if( aToOpen[i+1] ){
121146      sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
121147    }
121148  }
121149  if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
121150
121151  /* Update the sqlite_sequence table by storing the content of the
121152  ** maximum rowid counter values recorded while inserting into
121153  ** autoincrement tables.
121154  */
121155  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
121156    sqlite3AutoincrementEnd(pParse);
121157  }
121158
121159  /*
121160  ** Return the number of rows that were changed. If this routine is
121161  ** generating code because of a call to sqlite3NestedParse(), do not
121162  ** invoke the callback function.
121163  */
121164  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
121165    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
121166    sqlite3VdbeSetNumCols(v, 1);
121167    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
121168  }
121169
121170update_cleanup:
121171  sqlite3AuthContextPop(&sContext);
121172  sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
121173  sqlite3SrcListDelete(db, pTabList);
121174  sqlite3ExprListDelete(db, pChanges);
121175  sqlite3ExprDelete(db, pWhere);
121176  return;
121177}
121178/* Make sure "isView" and other macros defined above are undefined. Otherwise
121179** they may interfere with compilation of other functions in this file
121180** (or in another file, if this file becomes part of the amalgamation).  */
121181#ifdef isView
121182 #undef isView
121183#endif
121184#ifdef pTrigger
121185 #undef pTrigger
121186#endif
121187
121188#ifndef SQLITE_OMIT_VIRTUALTABLE
121189/*
121190** Generate code for an UPDATE of a virtual table.
121191**
121192** There are two possible strategies - the default and the special
121193** "onepass" strategy. Onepass is only used if the virtual table
121194** implementation indicates that pWhere may match at most one row.
121195**
121196** The default strategy is to create an ephemeral table that contains
121197** for each row to be changed:
121198**
121199**   (A)  The original rowid of that row.
121200**   (B)  The revised rowid for the row.
121201**   (C)  The content of every column in the row.
121202**
121203** Then loop through the contents of this ephemeral table executing a
121204** VUpdate for each row. When finished, drop the ephemeral table.
121205**
121206** The "onepass" strategy does not use an ephemeral table. Instead, it
121207** stores the same values (A, B and C above) in a register array and
121208** makes a single invocation of VUpdate.
121209*/
121210static void updateVirtualTable(
121211  Parse *pParse,       /* The parsing context */
121212  SrcList *pSrc,       /* The virtual table to be modified */
121213  Table *pTab,         /* The virtual table */
121214  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
121215  Expr *pRowid,        /* Expression used to recompute the rowid */
121216  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
121217  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
121218  int onError          /* ON CONFLICT strategy */
121219){
121220  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
121221  int ephemTab;             /* Table holding the result of the SELECT */
121222  int i;                    /* Loop counter */
121223  sqlite3 *db = pParse->db; /* Database connection */
121224  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
121225  WhereInfo *pWInfo;
121226  int nArg = 2 + pTab->nCol;      /* Number of arguments to VUpdate */
121227  int regArg;                     /* First register in VUpdate arg array */
121228  int regRec;                     /* Register in which to assemble record */
121229  int regRowid;                   /* Register for ephem table rowid */
121230  int iCsr = pSrc->a[0].iCursor;  /* Cursor used for virtual table scan */
121231  int aDummy[2];                  /* Unused arg for sqlite3WhereOkOnePass() */
121232  int bOnePass;                   /* True to use onepass strategy */
121233  int addr;                       /* Address of OP_OpenEphemeral */
121234
121235  /* Allocate nArg registers to martial the arguments to VUpdate. Then
121236  ** create and open the ephemeral table in which the records created from
121237  ** these arguments will be temporarily stored. */
121238  assert( v );
121239  ephemTab = pParse->nTab++;
121240  addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
121241  regArg = pParse->nMem + 1;
121242  pParse->nMem += nArg;
121243  regRec = ++pParse->nMem;
121244  regRowid = ++pParse->nMem;
121245
121246  /* Start scanning the virtual table */
121247  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
121248  if( pWInfo==0 ) return;
121249
121250  /* Populate the argument registers. */
121251  sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
121252  if( pRowid ){
121253    sqlite3ExprCode(pParse, pRowid, regArg+1);
121254  }else{
121255    sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
121256  }
121257  for(i=0; i<pTab->nCol; i++){
121258    if( aXRef[i]>=0 ){
121259      sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
121260    }else{
121261      sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
121262    }
121263  }
121264
121265  bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
121266
121267  if( bOnePass ){
121268    /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
121269    ** above. Also, if this is a top-level parse (not a trigger), clear the
121270    ** multi-write flag so that the VM does not open a statement journal */
121271    sqlite3VdbeChangeToNoop(v, addr);
121272    if( sqlite3IsToplevel(pParse) ){
121273      pParse->isMultiWrite = 0;
121274    }
121275  }else{
121276    /* Create a record from the argument register contents and insert it into
121277    ** the ephemeral table. */
121278    sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
121279    sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
121280    sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
121281  }
121282
121283
121284  if( bOnePass==0 ){
121285    /* End the virtual table scan */
121286    sqlite3WhereEnd(pWInfo);
121287
121288    /* Begin scannning through the ephemeral table. */
121289    addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
121290
121291    /* Extract arguments from the current row of the ephemeral table and
121292    ** invoke the VUpdate method.  */
121293    for(i=0; i<nArg; i++){
121294      sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
121295    }
121296  }
121297  sqlite3VtabMakeWritable(pParse, pTab);
121298  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
121299  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
121300  sqlite3MayAbort(pParse);
121301
121302  /* End of the ephemeral table scan. Or, if using the onepass strategy,
121303  ** jump to here if the scan visited zero rows. */
121304  if( bOnePass==0 ){
121305    sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
121306    sqlite3VdbeJumpHere(v, addr);
121307    sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
121308  }else{
121309    sqlite3WhereEnd(pWInfo);
121310  }
121311}
121312#endif /* SQLITE_OMIT_VIRTUALTABLE */
121313
121314/************** End of update.c **********************************************/
121315/************** Begin file vacuum.c ******************************************/
121316/*
121317** 2003 April 6
121318**
121319** The author disclaims copyright to this source code.  In place of
121320** a legal notice, here is a blessing:
121321**
121322**    May you do good and not evil.
121323**    May you find forgiveness for yourself and forgive others.
121324**    May you share freely, never taking more than you give.
121325**
121326*************************************************************************
121327** This file contains code used to implement the VACUUM command.
121328**
121329** Most of the code in this file may be omitted by defining the
121330** SQLITE_OMIT_VACUUM macro.
121331*/
121332/* #include "sqliteInt.h" */
121333/* #include "vdbeInt.h" */
121334
121335#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
121336/*
121337** Finalize a prepared statement.  If there was an error, store the
121338** text of the error message in *pzErrMsg.  Return the result code.
121339*/
121340static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
121341  int rc;
121342  rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
121343  if( rc ){
121344    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
121345  }
121346  return rc;
121347}
121348
121349/*
121350** Execute zSql on database db. Return an error code.
121351*/
121352static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
121353  sqlite3_stmt *pStmt;
121354  VVA_ONLY( int rc; )
121355  if( !zSql ){
121356    return SQLITE_NOMEM_BKPT;
121357  }
121358  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
121359    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
121360    return sqlite3_errcode(db);
121361  }
121362  VVA_ONLY( rc = ) sqlite3_step(pStmt);
121363  assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
121364  return vacuumFinalize(db, pStmt, pzErrMsg);
121365}
121366
121367/*
121368** Execute zSql on database db. The statement returns exactly
121369** one column. Execute this as SQL on the same database.
121370*/
121371static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
121372  sqlite3_stmt *pStmt;
121373  int rc;
121374
121375  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
121376  if( rc!=SQLITE_OK ) return rc;
121377
121378  while( SQLITE_ROW==sqlite3_step(pStmt) ){
121379    rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
121380    if( rc!=SQLITE_OK ){
121381      vacuumFinalize(db, pStmt, pzErrMsg);
121382      return rc;
121383    }
121384  }
121385
121386  return vacuumFinalize(db, pStmt, pzErrMsg);
121387}
121388
121389/*
121390** The VACUUM command is used to clean up the database,
121391** collapse free space, etc.  It is modelled after the VACUUM command
121392** in PostgreSQL.  The VACUUM command works as follows:
121393**
121394**   (1)  Create a new transient database file
121395**   (2)  Copy all content from the database being vacuumed into
121396**        the new transient database file
121397**   (3)  Copy content from the transient database back into the
121398**        original database.
121399**
121400** The transient database requires temporary disk space approximately
121401** equal to the size of the original database.  The copy operation of
121402** step (3) requires additional temporary disk space approximately equal
121403** to the size of the original database for the rollback journal.
121404** Hence, temporary disk space that is approximately 2x the size of the
121405** original database is required.  Every page of the database is written
121406** approximately 3 times:  Once for step (2) and twice for step (3).
121407** Two writes per page are required in step (3) because the original
121408** database content must be written into the rollback journal prior to
121409** overwriting the database with the vacuumed content.
121410**
121411** Only 1x temporary space and only 1x writes would be required if
121412** the copy of step (3) were replaced by deleting the original database
121413** and renaming the transient database as the original.  But that will
121414** not work if other processes are attached to the original database.
121415** And a power loss in between deleting the original and renaming the
121416** transient would cause the database file to appear to be deleted
121417** following reboot.
121418*/
121419SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
121420  Vdbe *v = sqlite3GetVdbe(pParse);
121421  if( v ){
121422    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
121423    sqlite3VdbeUsesBtree(v, 0);
121424  }
121425  return;
121426}
121427
121428/*
121429** This routine implements the OP_Vacuum opcode of the VDBE.
121430*/
121431SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
121432  int rc = SQLITE_OK;     /* Return code from service routines */
121433  Btree *pMain;           /* The database being vacuumed */
121434  Btree *pTemp;           /* The temporary database we vacuum into */
121435  char *zSql = 0;         /* SQL statements */
121436  int saved_flags;        /* Saved value of the db->flags */
121437  int saved_nChange;      /* Saved value of db->nChange */
121438  int saved_nTotalChange; /* Saved value of db->nTotalChange */
121439  u8 saved_mTrace;        /* Saved trace settings */
121440  Db *pDb = 0;            /* Database to detach at end of vacuum */
121441  int isMemDb;            /* True if vacuuming a :memory: database */
121442  int nRes;               /* Bytes of reserved space at the end of each page */
121443  int nDb;                /* Number of attached databases */
121444
121445  if( !db->autoCommit ){
121446    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
121447    return SQLITE_ERROR;
121448  }
121449  if( db->nVdbeActive>1 ){
121450    sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
121451    return SQLITE_ERROR;
121452  }
121453
121454  /* Save the current value of the database flags so that it can be
121455  ** restored before returning. Then set the writable-schema flag, and
121456  ** disable CHECK and foreign key constraints.  */
121457  saved_flags = db->flags;
121458  saved_nChange = db->nChange;
121459  saved_nTotalChange = db->nTotalChange;
121460  saved_mTrace = db->mTrace;
121461  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
121462  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
121463  db->mTrace = 0;
121464
121465  pMain = db->aDb[0].pBt;
121466  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
121467
121468  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
121469  ** can be set to 'off' for this file, as it is not recovered if a crash
121470  ** occurs anyway. The integrity of the database is maintained by a
121471  ** (possibly synchronous) transaction opened on the main database before
121472  ** sqlite3BtreeCopyFile() is called.
121473  **
121474  ** An optimisation would be to use a non-journaled pager.
121475  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
121476  ** that actually made the VACUUM run slower.  Very little journalling
121477  ** actually occurs when doing a vacuum since the vacuum_db is initially
121478  ** empty.  Only the journal header is written.  Apparently it takes more
121479  ** time to parse and run the PRAGMA to turn journalling off than it does
121480  ** to write the journal header file.
121481  */
121482  nDb = db->nDb;
121483  if( sqlite3TempInMemory(db) ){
121484    zSql = "ATTACH ':memory:' AS vacuum_db;";
121485  }else{
121486    zSql = "ATTACH '' AS vacuum_db;";
121487  }
121488  rc = execSql(db, pzErrMsg, zSql);
121489  if( db->nDb>nDb ){
121490    pDb = &db->aDb[db->nDb-1];
121491    assert( strcmp(pDb->zName,"vacuum_db")==0 );
121492  }
121493  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121494  pTemp = db->aDb[db->nDb-1].pBt;
121495
121496  /* The call to execSql() to attach the temp database has left the file
121497  ** locked (as there was more than one active statement when the transaction
121498  ** to read the schema was concluded. Unlock it here so that this doesn't
121499  ** cause problems for the call to BtreeSetPageSize() below.  */
121500  sqlite3BtreeCommit(pTemp);
121501
121502  nRes = sqlite3BtreeGetOptimalReserve(pMain);
121503
121504  /* A VACUUM cannot change the pagesize of an encrypted database. */
121505#ifdef SQLITE_HAS_CODEC
121506  if( db->nextPagesize ){
121507    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
121508    int nKey;
121509    char *zKey;
121510    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
121511    if( nKey ) db->nextPagesize = 0;
121512  }
121513#endif
121514
121515  sqlite3BtreeSetCacheSize(pTemp, db->aDb[0].pSchema->cache_size);
121516  sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
121517  rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
121518  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121519
121520  /* Begin a transaction and take an exclusive lock on the main database
121521  ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
121522  ** to ensure that we do not try to change the page-size on a WAL database.
121523  */
121524  rc = execSql(db, pzErrMsg, "BEGIN;");
121525  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121526  rc = sqlite3BtreeBeginTrans(pMain, 2);
121527  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121528
121529  /* Do not attempt to change the page size for a WAL database */
121530  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
121531                                               ==PAGER_JOURNALMODE_WAL ){
121532    db->nextPagesize = 0;
121533  }
121534
121535  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
121536   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
121537   || NEVER(db->mallocFailed)
121538  ){
121539    rc = SQLITE_NOMEM_BKPT;
121540    goto end_of_vacuum;
121541  }
121542
121543#ifndef SQLITE_OMIT_AUTOVACUUM
121544  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
121545                                           sqlite3BtreeGetAutoVacuum(pMain));
121546#endif
121547
121548  /* Query the schema of the main database. Create a mirror schema
121549  ** in the temporary database.
121550  */
121551  rc = execExecSql(db, pzErrMsg,
121552      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
121553      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
121554      "   AND coalesce(rootpage,1)>0"
121555  );
121556  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121557  rc = execExecSql(db, pzErrMsg,
121558      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
121559      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
121560  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121561  rc = execExecSql(db, pzErrMsg,
121562      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
121563      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
121564  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121565
121566  /* Loop through the tables in the main database. For each, do
121567  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
121568  ** the contents to the temporary database.
121569  */
121570  assert( (db->flags & SQLITE_Vacuum)==0 );
121571  db->flags |= SQLITE_Vacuum;
121572  rc = execExecSql(db, pzErrMsg,
121573      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
121574      "|| ' SELECT * FROM main.' || quote(name) || ';'"
121575      "FROM main.sqlite_master "
121576      "WHERE type = 'table' AND name!='sqlite_sequence' "
121577      "  AND coalesce(rootpage,1)>0"
121578  );
121579  assert( (db->flags & SQLITE_Vacuum)!=0 );
121580  db->flags &= ~SQLITE_Vacuum;
121581  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121582
121583  /* Copy over the sequence table
121584  */
121585  rc = execExecSql(db, pzErrMsg,
121586      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
121587      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
121588  );
121589  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121590  rc = execExecSql(db, pzErrMsg,
121591      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
121592      "|| ' SELECT * FROM main.' || quote(name) || ';' "
121593      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
121594  );
121595  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121596
121597
121598  /* Copy the triggers, views, and virtual tables from the main database
121599  ** over to the temporary database.  None of these objects has any
121600  ** associated storage, so all we have to do is copy their entries
121601  ** from the SQLITE_MASTER table.
121602  */
121603  rc = execSql(db, pzErrMsg,
121604      "INSERT INTO vacuum_db.sqlite_master "
121605      "  SELECT type, name, tbl_name, rootpage, sql"
121606      "    FROM main.sqlite_master"
121607      "   WHERE type='view' OR type='trigger'"
121608      "      OR (type='table' AND rootpage=0)"
121609  );
121610  if( rc ) goto end_of_vacuum;
121611
121612  /* At this point, there is a write transaction open on both the
121613  ** vacuum database and the main database. Assuming no error occurs,
121614  ** both transactions are closed by this block - the main database
121615  ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
121616  ** call to sqlite3BtreeCommit().
121617  */
121618  {
121619    u32 meta;
121620    int i;
121621
121622    /* This array determines which meta meta values are preserved in the
121623    ** vacuum.  Even entries are the meta value number and odd entries
121624    ** are an increment to apply to the meta value after the vacuum.
121625    ** The increment is used to increase the schema cookie so that other
121626    ** connections to the same database will know to reread the schema.
121627    */
121628    static const unsigned char aCopy[] = {
121629       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
121630       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
121631       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
121632       BTREE_USER_VERSION,       0,  /* Preserve the user version */
121633       BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
121634    };
121635
121636    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
121637    assert( 1==sqlite3BtreeIsInTrans(pMain) );
121638
121639    /* Copy Btree meta values */
121640    for(i=0; i<ArraySize(aCopy); i+=2){
121641      /* GetMeta() and UpdateMeta() cannot fail in this context because
121642      ** we already have page 1 loaded into cache and marked dirty. */
121643      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
121644      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
121645      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
121646    }
121647
121648    rc = sqlite3BtreeCopyFile(pMain, pTemp);
121649    if( rc!=SQLITE_OK ) goto end_of_vacuum;
121650    rc = sqlite3BtreeCommit(pTemp);
121651    if( rc!=SQLITE_OK ) goto end_of_vacuum;
121652#ifndef SQLITE_OMIT_AUTOVACUUM
121653    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
121654#endif
121655  }
121656
121657  assert( rc==SQLITE_OK );
121658  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
121659
121660end_of_vacuum:
121661  /* Restore the original value of db->flags */
121662  db->flags = saved_flags;
121663  db->nChange = saved_nChange;
121664  db->nTotalChange = saved_nTotalChange;
121665  db->mTrace = saved_mTrace;
121666  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
121667
121668  /* Currently there is an SQL level transaction open on the vacuum
121669  ** database. No locks are held on any other files (since the main file
121670  ** was committed at the btree level). So it safe to end the transaction
121671  ** by manually setting the autoCommit flag to true and detaching the
121672  ** vacuum database. The vacuum_db journal file is deleted when the pager
121673  ** is closed by the DETACH.
121674  */
121675  db->autoCommit = 1;
121676
121677  if( pDb ){
121678    sqlite3BtreeClose(pDb->pBt);
121679    pDb->pBt = 0;
121680    pDb->pSchema = 0;
121681  }
121682
121683  /* This both clears the schemas and reduces the size of the db->aDb[]
121684  ** array. */
121685  sqlite3ResetAllSchemasOfConnection(db);
121686
121687  return rc;
121688}
121689
121690#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
121691
121692/************** End of vacuum.c **********************************************/
121693/************** Begin file vtab.c ********************************************/
121694/*
121695** 2006 June 10
121696**
121697** The author disclaims copyright to this source code.  In place of
121698** a legal notice, here is a blessing:
121699**
121700**    May you do good and not evil.
121701**    May you find forgiveness for yourself and forgive others.
121702**    May you share freely, never taking more than you give.
121703**
121704*************************************************************************
121705** This file contains code used to help implement virtual tables.
121706*/
121707#ifndef SQLITE_OMIT_VIRTUALTABLE
121708/* #include "sqliteInt.h" */
121709
121710/*
121711** Before a virtual table xCreate() or xConnect() method is invoked, the
121712** sqlite3.pVtabCtx member variable is set to point to an instance of
121713** this struct allocated on the stack. It is used by the implementation of
121714** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
121715** are invoked only from within xCreate and xConnect methods.
121716*/
121717struct VtabCtx {
121718  VTable *pVTable;    /* The virtual table being constructed */
121719  Table *pTab;        /* The Table object to which the virtual table belongs */
121720  VtabCtx *pPrior;    /* Parent context (if any) */
121721  int bDeclared;      /* True after sqlite3_declare_vtab() is called */
121722};
121723
121724/*
121725** The actual function that does the work of creating a new module.
121726** This function implements the sqlite3_create_module() and
121727** sqlite3_create_module_v2() interfaces.
121728*/
121729static int createModule(
121730  sqlite3 *db,                    /* Database in which module is registered */
121731  const char *zName,              /* Name assigned to this module */
121732  const sqlite3_module *pModule,  /* The definition of the module */
121733  void *pAux,                     /* Context pointer for xCreate/xConnect */
121734  void (*xDestroy)(void *)        /* Module destructor function */
121735){
121736  int rc = SQLITE_OK;
121737  int nName;
121738
121739  sqlite3_mutex_enter(db->mutex);
121740  nName = sqlite3Strlen30(zName);
121741  if( sqlite3HashFind(&db->aModule, zName) ){
121742    rc = SQLITE_MISUSE_BKPT;
121743  }else{
121744    Module *pMod;
121745    pMod = (Module *)sqlite3DbMallocRawNN(db, sizeof(Module) + nName + 1);
121746    if( pMod ){
121747      Module *pDel;
121748      char *zCopy = (char *)(&pMod[1]);
121749      memcpy(zCopy, zName, nName+1);
121750      pMod->zName = zCopy;
121751      pMod->pModule = pModule;
121752      pMod->pAux = pAux;
121753      pMod->xDestroy = xDestroy;
121754      pMod->pEpoTab = 0;
121755      pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
121756      assert( pDel==0 || pDel==pMod );
121757      if( pDel ){
121758        sqlite3OomFault(db);
121759        sqlite3DbFree(db, pDel);
121760      }
121761    }
121762  }
121763  rc = sqlite3ApiExit(db, rc);
121764  if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
121765
121766  sqlite3_mutex_leave(db->mutex);
121767  return rc;
121768}
121769
121770
121771/*
121772** External API function used to create a new virtual-table module.
121773*/
121774SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
121775  sqlite3 *db,                    /* Database in which module is registered */
121776  const char *zName,              /* Name assigned to this module */
121777  const sqlite3_module *pModule,  /* The definition of the module */
121778  void *pAux                      /* Context pointer for xCreate/xConnect */
121779){
121780#ifdef SQLITE_ENABLE_API_ARMOR
121781  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
121782#endif
121783  return createModule(db, zName, pModule, pAux, 0);
121784}
121785
121786/*
121787** External API function used to create a new virtual-table module.
121788*/
121789SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
121790  sqlite3 *db,                    /* Database in which module is registered */
121791  const char *zName,              /* Name assigned to this module */
121792  const sqlite3_module *pModule,  /* The definition of the module */
121793  void *pAux,                     /* Context pointer for xCreate/xConnect */
121794  void (*xDestroy)(void *)        /* Module destructor function */
121795){
121796#ifdef SQLITE_ENABLE_API_ARMOR
121797  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
121798#endif
121799  return createModule(db, zName, pModule, pAux, xDestroy);
121800}
121801
121802/*
121803** Lock the virtual table so that it cannot be disconnected.
121804** Locks nest.  Every lock should have a corresponding unlock.
121805** If an unlock is omitted, resources leaks will occur.
121806**
121807** If a disconnect is attempted while a virtual table is locked,
121808** the disconnect is deferred until all locks have been removed.
121809*/
121810SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
121811  pVTab->nRef++;
121812}
121813
121814
121815/*
121816** pTab is a pointer to a Table structure representing a virtual-table.
121817** Return a pointer to the VTable object used by connection db to access
121818** this virtual-table, if one has been created, or NULL otherwise.
121819*/
121820SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
121821  VTable *pVtab;
121822  assert( IsVirtual(pTab) );
121823  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
121824  return pVtab;
121825}
121826
121827/*
121828** Decrement the ref-count on a virtual table object. When the ref-count
121829** reaches zero, call the xDisconnect() method to delete the object.
121830*/
121831SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
121832  sqlite3 *db = pVTab->db;
121833
121834  assert( db );
121835  assert( pVTab->nRef>0 );
121836  assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
121837
121838  pVTab->nRef--;
121839  if( pVTab->nRef==0 ){
121840    sqlite3_vtab *p = pVTab->pVtab;
121841    if( p ){
121842      p->pModule->xDisconnect(p);
121843    }
121844    sqlite3DbFree(db, pVTab);
121845  }
121846}
121847
121848/*
121849** Table p is a virtual table. This function moves all elements in the
121850** p->pVTable list to the sqlite3.pDisconnect lists of their associated
121851** database connections to be disconnected at the next opportunity.
121852** Except, if argument db is not NULL, then the entry associated with
121853** connection db is left in the p->pVTable list.
121854*/
121855static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
121856  VTable *pRet = 0;
121857  VTable *pVTable = p->pVTable;
121858  p->pVTable = 0;
121859
121860  /* Assert that the mutex (if any) associated with the BtShared database
121861  ** that contains table p is held by the caller. See header comments
121862  ** above function sqlite3VtabUnlockList() for an explanation of why
121863  ** this makes it safe to access the sqlite3.pDisconnect list of any
121864  ** database connection that may have an entry in the p->pVTable list.
121865  */
121866  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
121867
121868  while( pVTable ){
121869    sqlite3 *db2 = pVTable->db;
121870    VTable *pNext = pVTable->pNext;
121871    assert( db2 );
121872    if( db2==db ){
121873      pRet = pVTable;
121874      p->pVTable = pRet;
121875      pRet->pNext = 0;
121876    }else{
121877      pVTable->pNext = db2->pDisconnect;
121878      db2->pDisconnect = pVTable;
121879    }
121880    pVTable = pNext;
121881  }
121882
121883  assert( !db || pRet );
121884  return pRet;
121885}
121886
121887/*
121888** Table *p is a virtual table. This function removes the VTable object
121889** for table *p associated with database connection db from the linked
121890** list in p->pVTab. It also decrements the VTable ref count. This is
121891** used when closing database connection db to free all of its VTable
121892** objects without disturbing the rest of the Schema object (which may
121893** be being used by other shared-cache connections).
121894*/
121895SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
121896  VTable **ppVTab;
121897
121898  assert( IsVirtual(p) );
121899  assert( sqlite3BtreeHoldsAllMutexes(db) );
121900  assert( sqlite3_mutex_held(db->mutex) );
121901
121902  for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
121903    if( (*ppVTab)->db==db  ){
121904      VTable *pVTab = *ppVTab;
121905      *ppVTab = pVTab->pNext;
121906      sqlite3VtabUnlock(pVTab);
121907      break;
121908    }
121909  }
121910}
121911
121912
121913/*
121914** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
121915**
121916** This function may only be called when the mutexes associated with all
121917** shared b-tree databases opened using connection db are held by the
121918** caller. This is done to protect the sqlite3.pDisconnect list. The
121919** sqlite3.pDisconnect list is accessed only as follows:
121920**
121921**   1) By this function. In this case, all BtShared mutexes and the mutex
121922**      associated with the database handle itself must be held.
121923**
121924**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
121925**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
121926**      associated with the database the virtual table is stored in is held
121927**      or, if the virtual table is stored in a non-sharable database, then
121928**      the database handle mutex is held.
121929**
121930** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
121931** by multiple threads. It is thread-safe.
121932*/
121933SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
121934  VTable *p = db->pDisconnect;
121935  db->pDisconnect = 0;
121936
121937  assert( sqlite3BtreeHoldsAllMutexes(db) );
121938  assert( sqlite3_mutex_held(db->mutex) );
121939
121940  if( p ){
121941    sqlite3ExpirePreparedStatements(db);
121942    do {
121943      VTable *pNext = p->pNext;
121944      sqlite3VtabUnlock(p);
121945      p = pNext;
121946    }while( p );
121947  }
121948}
121949
121950/*
121951** Clear any and all virtual-table information from the Table record.
121952** This routine is called, for example, just before deleting the Table
121953** record.
121954**
121955** Since it is a virtual-table, the Table structure contains a pointer
121956** to the head of a linked list of VTable structures. Each VTable
121957** structure is associated with a single sqlite3* user of the schema.
121958** The reference count of the VTable structure associated with database
121959** connection db is decremented immediately (which may lead to the
121960** structure being xDisconnected and free). Any other VTable structures
121961** in the list are moved to the sqlite3.pDisconnect list of the associated
121962** database connection.
121963*/
121964SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
121965  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
121966  if( p->azModuleArg ){
121967    int i;
121968    for(i=0; i<p->nModuleArg; i++){
121969      if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
121970    }
121971    sqlite3DbFree(db, p->azModuleArg);
121972  }
121973}
121974
121975/*
121976** Add a new module argument to pTable->azModuleArg[].
121977** The string is not copied - the pointer is stored.  The
121978** string will be freed automatically when the table is
121979** deleted.
121980*/
121981static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
121982  int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
121983  char **azModuleArg;
121984  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
121985  if( azModuleArg==0 ){
121986    sqlite3DbFree(db, zArg);
121987  }else{
121988    int i = pTable->nModuleArg++;
121989    azModuleArg[i] = zArg;
121990    azModuleArg[i+1] = 0;
121991    pTable->azModuleArg = azModuleArg;
121992  }
121993}
121994
121995/*
121996** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
121997** statement.  The module name has been parsed, but the optional list
121998** of parameters that follow the module name are still pending.
121999*/
122000SQLITE_PRIVATE void sqlite3VtabBeginParse(
122001  Parse *pParse,        /* Parsing context */
122002  Token *pName1,        /* Name of new table, or database name */
122003  Token *pName2,        /* Name of new table or NULL */
122004  Token *pModuleName,   /* Name of the module for the virtual table */
122005  int ifNotExists       /* No error if the table already exists */
122006){
122007  int iDb;              /* The database the table is being created in */
122008  Table *pTable;        /* The new virtual table */
122009  sqlite3 *db;          /* Database connection */
122010
122011  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
122012  pTable = pParse->pNewTable;
122013  if( pTable==0 ) return;
122014  assert( 0==pTable->pIndex );
122015
122016  db = pParse->db;
122017  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
122018  assert( iDb>=0 );
122019
122020  pTable->tabFlags |= TF_Virtual;
122021  pTable->nModuleArg = 0;
122022  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
122023  addModuleArgument(db, pTable, 0);
122024  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
122025  assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
122026       || (pParse->sNameToken.z==pName1->z && pName2->z==0)
122027  );
122028  pParse->sNameToken.n = (int)(
122029      &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
122030  );
122031
122032#ifndef SQLITE_OMIT_AUTHORIZATION
122033  /* Creating a virtual table invokes the authorization callback twice.
122034  ** The first invocation, to obtain permission to INSERT a row into the
122035  ** sqlite_master table, has already been made by sqlite3StartTable().
122036  ** The second call, to obtain permission to create the table, is made now.
122037  */
122038  if( pTable->azModuleArg ){
122039    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
122040            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
122041  }
122042#endif
122043}
122044
122045/*
122046** This routine takes the module argument that has been accumulating
122047** in pParse->zArg[] and appends it to the list of arguments on the
122048** virtual table currently under construction in pParse->pTable.
122049*/
122050static void addArgumentToVtab(Parse *pParse){
122051  if( pParse->sArg.z && pParse->pNewTable ){
122052    const char *z = (const char*)pParse->sArg.z;
122053    int n = pParse->sArg.n;
122054    sqlite3 *db = pParse->db;
122055    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
122056  }
122057}
122058
122059/*
122060** The parser calls this routine after the CREATE VIRTUAL TABLE statement
122061** has been completely parsed.
122062*/
122063SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
122064  Table *pTab = pParse->pNewTable;  /* The table being constructed */
122065  sqlite3 *db = pParse->db;         /* The database connection */
122066
122067  if( pTab==0 ) return;
122068  addArgumentToVtab(pParse);
122069  pParse->sArg.z = 0;
122070  if( pTab->nModuleArg<1 ) return;
122071
122072  /* If the CREATE VIRTUAL TABLE statement is being entered for the
122073  ** first time (in other words if the virtual table is actually being
122074  ** created now instead of just being read out of sqlite_master) then
122075  ** do additional initialization work and store the statement text
122076  ** in the sqlite_master table.
122077  */
122078  if( !db->init.busy ){
122079    char *zStmt;
122080    char *zWhere;
122081    int iDb;
122082    int iReg;
122083    Vdbe *v;
122084
122085    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
122086    if( pEnd ){
122087      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
122088    }
122089    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
122090
122091    /* A slot for the record has already been allocated in the
122092    ** SQLITE_MASTER table.  We just need to update that slot with all
122093    ** the information we've collected.
122094    **
122095    ** The VM register number pParse->regRowid holds the rowid of an
122096    ** entry in the sqlite_master table tht was created for this vtab
122097    ** by sqlite3StartTable().
122098    */
122099    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
122100    sqlite3NestedParse(pParse,
122101      "UPDATE %Q.%s "
122102         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
122103       "WHERE rowid=#%d",
122104      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
122105      pTab->zName,
122106      pTab->zName,
122107      zStmt,
122108      pParse->regRowid
122109    );
122110    sqlite3DbFree(db, zStmt);
122111    v = sqlite3GetVdbe(pParse);
122112    sqlite3ChangeCookie(pParse, iDb);
122113
122114    sqlite3VdbeAddOp0(v, OP_Expire);
122115    zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
122116    sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
122117
122118    iReg = ++pParse->nMem;
122119    sqlite3VdbeLoadString(v, iReg, pTab->zName);
122120    sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
122121  }
122122
122123  /* If we are rereading the sqlite_master table create the in-memory
122124  ** record of the table. The xConnect() method is not called until
122125  ** the first time the virtual table is used in an SQL statement. This
122126  ** allows a schema that contains virtual tables to be loaded before
122127  ** the required virtual table implementations are registered.  */
122128  else {
122129    Table *pOld;
122130    Schema *pSchema = pTab->pSchema;
122131    const char *zName = pTab->zName;
122132    assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
122133    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
122134    if( pOld ){
122135      sqlite3OomFault(db);
122136      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
122137      return;
122138    }
122139    pParse->pNewTable = 0;
122140  }
122141}
122142
122143/*
122144** The parser calls this routine when it sees the first token
122145** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
122146*/
122147SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
122148  addArgumentToVtab(pParse);
122149  pParse->sArg.z = 0;
122150  pParse->sArg.n = 0;
122151}
122152
122153/*
122154** The parser calls this routine for each token after the first token
122155** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
122156*/
122157SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
122158  Token *pArg = &pParse->sArg;
122159  if( pArg->z==0 ){
122160    pArg->z = p->z;
122161    pArg->n = p->n;
122162  }else{
122163    assert(pArg->z <= p->z);
122164    pArg->n = (int)(&p->z[p->n] - pArg->z);
122165  }
122166}
122167
122168/*
122169** Invoke a virtual table constructor (either xCreate or xConnect). The
122170** pointer to the function to invoke is passed as the fourth parameter
122171** to this procedure.
122172*/
122173static int vtabCallConstructor(
122174  sqlite3 *db,
122175  Table *pTab,
122176  Module *pMod,
122177  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
122178  char **pzErr
122179){
122180  VtabCtx sCtx;
122181  VTable *pVTable;
122182  int rc;
122183  const char *const*azArg = (const char *const*)pTab->azModuleArg;
122184  int nArg = pTab->nModuleArg;
122185  char *zErr = 0;
122186  char *zModuleName;
122187  int iDb;
122188  VtabCtx *pCtx;
122189
122190  /* Check that the virtual-table is not already being initialized */
122191  for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
122192    if( pCtx->pTab==pTab ){
122193      *pzErr = sqlite3MPrintf(db,
122194          "vtable constructor called recursively: %s", pTab->zName
122195      );
122196      return SQLITE_LOCKED;
122197    }
122198  }
122199
122200  zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
122201  if( !zModuleName ){
122202    return SQLITE_NOMEM_BKPT;
122203  }
122204
122205  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
122206  if( !pVTable ){
122207    sqlite3DbFree(db, zModuleName);
122208    return SQLITE_NOMEM_BKPT;
122209  }
122210  pVTable->db = db;
122211  pVTable->pMod = pMod;
122212
122213  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
122214  pTab->azModuleArg[1] = db->aDb[iDb].zName;
122215
122216  /* Invoke the virtual table constructor */
122217  assert( &db->pVtabCtx );
122218  assert( xConstruct );
122219  sCtx.pTab = pTab;
122220  sCtx.pVTable = pVTable;
122221  sCtx.pPrior = db->pVtabCtx;
122222  sCtx.bDeclared = 0;
122223  db->pVtabCtx = &sCtx;
122224  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
122225  db->pVtabCtx = sCtx.pPrior;
122226  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
122227  assert( sCtx.pTab==pTab );
122228
122229  if( SQLITE_OK!=rc ){
122230    if( zErr==0 ){
122231      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
122232    }else {
122233      *pzErr = sqlite3MPrintf(db, "%s", zErr);
122234      sqlite3_free(zErr);
122235    }
122236    sqlite3DbFree(db, pVTable);
122237  }else if( ALWAYS(pVTable->pVtab) ){
122238    /* Justification of ALWAYS():  A correct vtab constructor must allocate
122239    ** the sqlite3_vtab object if successful.  */
122240    memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
122241    pVTable->pVtab->pModule = pMod->pModule;
122242    pVTable->nRef = 1;
122243    if( sCtx.bDeclared==0 ){
122244      const char *zFormat = "vtable constructor did not declare schema: %s";
122245      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
122246      sqlite3VtabUnlock(pVTable);
122247      rc = SQLITE_ERROR;
122248    }else{
122249      int iCol;
122250      u8 oooHidden = 0;
122251      /* If everything went according to plan, link the new VTable structure
122252      ** into the linked list headed by pTab->pVTable. Then loop through the
122253      ** columns of the table to see if any of them contain the token "hidden".
122254      ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
122255      ** the type string.  */
122256      pVTable->pNext = pTab->pVTable;
122257      pTab->pVTable = pVTable;
122258
122259      for(iCol=0; iCol<pTab->nCol; iCol++){
122260        char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
122261        int nType;
122262        int i = 0;
122263        nType = sqlite3Strlen30(zType);
122264        for(i=0; i<nType; i++){
122265          if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
122266           && (i==0 || zType[i-1]==' ')
122267           && (zType[i+6]=='\0' || zType[i+6]==' ')
122268          ){
122269            break;
122270          }
122271        }
122272        if( i<nType ){
122273          int j;
122274          int nDel = 6 + (zType[i+6] ? 1 : 0);
122275          for(j=i; (j+nDel)<=nType; j++){
122276            zType[j] = zType[j+nDel];
122277          }
122278          if( zType[i]=='\0' && i>0 ){
122279            assert(zType[i-1]==' ');
122280            zType[i-1] = '\0';
122281          }
122282          pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
122283          oooHidden = TF_OOOHidden;
122284        }else{
122285          pTab->tabFlags |= oooHidden;
122286        }
122287      }
122288    }
122289  }
122290
122291  sqlite3DbFree(db, zModuleName);
122292  return rc;
122293}
122294
122295/*
122296** This function is invoked by the parser to call the xConnect() method
122297** of the virtual table pTab. If an error occurs, an error code is returned
122298** and an error left in pParse.
122299**
122300** This call is a no-op if table pTab is not a virtual table.
122301*/
122302SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
122303  sqlite3 *db = pParse->db;
122304  const char *zMod;
122305  Module *pMod;
122306  int rc;
122307
122308  assert( pTab );
122309  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
122310    return SQLITE_OK;
122311  }
122312
122313  /* Locate the required virtual table module */
122314  zMod = pTab->azModuleArg[0];
122315  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
122316
122317  if( !pMod ){
122318    const char *zModule = pTab->azModuleArg[0];
122319    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
122320    rc = SQLITE_ERROR;
122321  }else{
122322    char *zErr = 0;
122323    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
122324    if( rc!=SQLITE_OK ){
122325      sqlite3ErrorMsg(pParse, "%s", zErr);
122326    }
122327    sqlite3DbFree(db, zErr);
122328  }
122329
122330  return rc;
122331}
122332/*
122333** Grow the db->aVTrans[] array so that there is room for at least one
122334** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
122335*/
122336static int growVTrans(sqlite3 *db){
122337  const int ARRAY_INCR = 5;
122338
122339  /* Grow the sqlite3.aVTrans array if required */
122340  if( (db->nVTrans%ARRAY_INCR)==0 ){
122341    VTable **aVTrans;
122342    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
122343    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
122344    if( !aVTrans ){
122345      return SQLITE_NOMEM_BKPT;
122346    }
122347    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
122348    db->aVTrans = aVTrans;
122349  }
122350
122351  return SQLITE_OK;
122352}
122353
122354/*
122355** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
122356** have already been reserved using growVTrans().
122357*/
122358static void addToVTrans(sqlite3 *db, VTable *pVTab){
122359  /* Add pVtab to the end of sqlite3.aVTrans */
122360  db->aVTrans[db->nVTrans++] = pVTab;
122361  sqlite3VtabLock(pVTab);
122362}
122363
122364/*
122365** This function is invoked by the vdbe to call the xCreate method
122366** of the virtual table named zTab in database iDb.
122367**
122368** If an error occurs, *pzErr is set to point an an English language
122369** description of the error and an SQLITE_XXX error code is returned.
122370** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
122371*/
122372SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
122373  int rc = SQLITE_OK;
122374  Table *pTab;
122375  Module *pMod;
122376  const char *zMod;
122377
122378  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
122379  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
122380
122381  /* Locate the required virtual table module */
122382  zMod = pTab->azModuleArg[0];
122383  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
122384
122385  /* If the module has been registered and includes a Create method,
122386  ** invoke it now. If the module has not been registered, return an
122387  ** error. Otherwise, do nothing.
122388  */
122389  if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
122390    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
122391    rc = SQLITE_ERROR;
122392  }else{
122393    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
122394  }
122395
122396  /* Justification of ALWAYS():  The xConstructor method is required to
122397  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
122398  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
122399    rc = growVTrans(db);
122400    if( rc==SQLITE_OK ){
122401      addToVTrans(db, sqlite3GetVTable(db, pTab));
122402    }
122403  }
122404
122405  return rc;
122406}
122407
122408/*
122409** This function is used to set the schema of a virtual table.  It is only
122410** valid to call this function from within the xCreate() or xConnect() of a
122411** virtual table module.
122412*/
122413SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
122414  VtabCtx *pCtx;
122415  Parse *pParse;
122416  int rc = SQLITE_OK;
122417  Table *pTab;
122418  char *zErr = 0;
122419
122420#ifdef SQLITE_ENABLE_API_ARMOR
122421  if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
122422    return SQLITE_MISUSE_BKPT;
122423  }
122424#endif
122425  sqlite3_mutex_enter(db->mutex);
122426  pCtx = db->pVtabCtx;
122427  if( !pCtx || pCtx->bDeclared ){
122428    sqlite3Error(db, SQLITE_MISUSE);
122429    sqlite3_mutex_leave(db->mutex);
122430    return SQLITE_MISUSE_BKPT;
122431  }
122432  pTab = pCtx->pTab;
122433  assert( (pTab->tabFlags & TF_Virtual)!=0 );
122434
122435  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
122436  if( pParse==0 ){
122437    rc = SQLITE_NOMEM_BKPT;
122438  }else{
122439    pParse->declareVtab = 1;
122440    pParse->db = db;
122441    pParse->nQueryLoop = 1;
122442
122443    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
122444     && pParse->pNewTable
122445     && !db->mallocFailed
122446     && !pParse->pNewTable->pSelect
122447     && (pParse->pNewTable->tabFlags & TF_Virtual)==0
122448    ){
122449      if( !pTab->aCol ){
122450        Table *pNew = pParse->pNewTable;
122451        Index *pIdx;
122452        pTab->aCol = pNew->aCol;
122453        pTab->nCol = pNew->nCol;
122454        pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
122455        pNew->nCol = 0;
122456        pNew->aCol = 0;
122457        assert( pTab->pIndex==0 );
122458        if( !HasRowid(pNew) && pCtx->pVTable->pMod->pModule->xUpdate!=0 ){
122459          rc = SQLITE_ERROR;
122460        }
122461        pIdx = pNew->pIndex;
122462        if( pIdx ){
122463          assert( pIdx->pNext==0 );
122464          pTab->pIndex = pIdx;
122465          pNew->pIndex = 0;
122466          pIdx->pTable = pTab;
122467        }
122468      }
122469      pCtx->bDeclared = 1;
122470    }else{
122471      sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
122472      sqlite3DbFree(db, zErr);
122473      rc = SQLITE_ERROR;
122474    }
122475    pParse->declareVtab = 0;
122476
122477    if( pParse->pVdbe ){
122478      sqlite3VdbeFinalize(pParse->pVdbe);
122479    }
122480    sqlite3DeleteTable(db, pParse->pNewTable);
122481    sqlite3ParserReset(pParse);
122482    sqlite3StackFree(db, pParse);
122483  }
122484
122485  assert( (rc&0xff)==rc );
122486  rc = sqlite3ApiExit(db, rc);
122487  sqlite3_mutex_leave(db->mutex);
122488  return rc;
122489}
122490
122491/*
122492** This function is invoked by the vdbe to call the xDestroy method
122493** of the virtual table named zTab in database iDb. This occurs
122494** when a DROP TABLE is mentioned.
122495**
122496** This call is a no-op if zTab is not a virtual table.
122497*/
122498SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
122499  int rc = SQLITE_OK;
122500  Table *pTab;
122501
122502  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
122503  if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
122504    VTable *p;
122505    int (*xDestroy)(sqlite3_vtab *);
122506    for(p=pTab->pVTable; p; p=p->pNext){
122507      assert( p->pVtab );
122508      if( p->pVtab->nRef>0 ){
122509        return SQLITE_LOCKED;
122510      }
122511    }
122512    p = vtabDisconnectAll(db, pTab);
122513    xDestroy = p->pMod->pModule->xDestroy;
122514    assert( xDestroy!=0 );  /* Checked before the virtual table is created */
122515    rc = xDestroy(p->pVtab);
122516    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
122517    if( rc==SQLITE_OK ){
122518      assert( pTab->pVTable==p && p->pNext==0 );
122519      p->pVtab = 0;
122520      pTab->pVTable = 0;
122521      sqlite3VtabUnlock(p);
122522    }
122523  }
122524
122525  return rc;
122526}
122527
122528/*
122529** This function invokes either the xRollback or xCommit method
122530** of each of the virtual tables in the sqlite3.aVTrans array. The method
122531** called is identified by the second argument, "offset", which is
122532** the offset of the method to call in the sqlite3_module structure.
122533**
122534** The array is cleared after invoking the callbacks.
122535*/
122536static void callFinaliser(sqlite3 *db, int offset){
122537  int i;
122538  if( db->aVTrans ){
122539    VTable **aVTrans = db->aVTrans;
122540    db->aVTrans = 0;
122541    for(i=0; i<db->nVTrans; i++){
122542      VTable *pVTab = aVTrans[i];
122543      sqlite3_vtab *p = pVTab->pVtab;
122544      if( p ){
122545        int (*x)(sqlite3_vtab *);
122546        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
122547        if( x ) x(p);
122548      }
122549      pVTab->iSavepoint = 0;
122550      sqlite3VtabUnlock(pVTab);
122551    }
122552    sqlite3DbFree(db, aVTrans);
122553    db->nVTrans = 0;
122554  }
122555}
122556
122557/*
122558** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
122559** array. Return the error code for the first error that occurs, or
122560** SQLITE_OK if all xSync operations are successful.
122561**
122562** If an error message is available, leave it in p->zErrMsg.
122563*/
122564SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
122565  int i;
122566  int rc = SQLITE_OK;
122567  VTable **aVTrans = db->aVTrans;
122568
122569  db->aVTrans = 0;
122570  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
122571    int (*x)(sqlite3_vtab *);
122572    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
122573    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
122574      rc = x(pVtab);
122575      sqlite3VtabImportErrmsg(p, pVtab);
122576    }
122577  }
122578  db->aVTrans = aVTrans;
122579  return rc;
122580}
122581
122582/*
122583** Invoke the xRollback method of all virtual tables in the
122584** sqlite3.aVTrans array. Then clear the array itself.
122585*/
122586SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
122587  callFinaliser(db, offsetof(sqlite3_module,xRollback));
122588  return SQLITE_OK;
122589}
122590
122591/*
122592** Invoke the xCommit method of all virtual tables in the
122593** sqlite3.aVTrans array. Then clear the array itself.
122594*/
122595SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
122596  callFinaliser(db, offsetof(sqlite3_module,xCommit));
122597  return SQLITE_OK;
122598}
122599
122600/*
122601** If the virtual table pVtab supports the transaction interface
122602** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
122603** not currently open, invoke the xBegin method now.
122604**
122605** If the xBegin call is successful, place the sqlite3_vtab pointer
122606** in the sqlite3.aVTrans array.
122607*/
122608SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
122609  int rc = SQLITE_OK;
122610  const sqlite3_module *pModule;
122611
122612  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
122613  ** than zero, then this function is being called from within a
122614  ** virtual module xSync() callback. It is illegal to write to
122615  ** virtual module tables in this case, so return SQLITE_LOCKED.
122616  */
122617  if( sqlite3VtabInSync(db) ){
122618    return SQLITE_LOCKED;
122619  }
122620  if( !pVTab ){
122621    return SQLITE_OK;
122622  }
122623  pModule = pVTab->pVtab->pModule;
122624
122625  if( pModule->xBegin ){
122626    int i;
122627
122628    /* If pVtab is already in the aVTrans array, return early */
122629    for(i=0; i<db->nVTrans; i++){
122630      if( db->aVTrans[i]==pVTab ){
122631        return SQLITE_OK;
122632      }
122633    }
122634
122635    /* Invoke the xBegin method. If successful, add the vtab to the
122636    ** sqlite3.aVTrans[] array. */
122637    rc = growVTrans(db);
122638    if( rc==SQLITE_OK ){
122639      rc = pModule->xBegin(pVTab->pVtab);
122640      if( rc==SQLITE_OK ){
122641        int iSvpt = db->nStatement + db->nSavepoint;
122642        addToVTrans(db, pVTab);
122643        if( iSvpt && pModule->xSavepoint ){
122644          pVTab->iSavepoint = iSvpt;
122645          rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
122646        }
122647      }
122648    }
122649  }
122650  return rc;
122651}
122652
122653/*
122654** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
122655** virtual tables that currently have an open transaction. Pass iSavepoint
122656** as the second argument to the virtual table method invoked.
122657**
122658** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
122659** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
122660** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
122661** an open transaction is invoked.
122662**
122663** If any virtual table method returns an error code other than SQLITE_OK,
122664** processing is abandoned and the error returned to the caller of this
122665** function immediately. If all calls to virtual table methods are successful,
122666** SQLITE_OK is returned.
122667*/
122668SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
122669  int rc = SQLITE_OK;
122670
122671  assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
122672  assert( iSavepoint>=-1 );
122673  if( db->aVTrans ){
122674    int i;
122675    for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
122676      VTable *pVTab = db->aVTrans[i];
122677      const sqlite3_module *pMod = pVTab->pMod->pModule;
122678      if( pVTab->pVtab && pMod->iVersion>=2 ){
122679        int (*xMethod)(sqlite3_vtab *, int);
122680        switch( op ){
122681          case SAVEPOINT_BEGIN:
122682            xMethod = pMod->xSavepoint;
122683            pVTab->iSavepoint = iSavepoint+1;
122684            break;
122685          case SAVEPOINT_ROLLBACK:
122686            xMethod = pMod->xRollbackTo;
122687            break;
122688          default:
122689            xMethod = pMod->xRelease;
122690            break;
122691        }
122692        if( xMethod && pVTab->iSavepoint>iSavepoint ){
122693          rc = xMethod(pVTab->pVtab, iSavepoint);
122694        }
122695      }
122696    }
122697  }
122698  return rc;
122699}
122700
122701/*
122702** The first parameter (pDef) is a function implementation.  The
122703** second parameter (pExpr) is the first argument to this function.
122704** If pExpr is a column in a virtual table, then let the virtual
122705** table implementation have an opportunity to overload the function.
122706**
122707** This routine is used to allow virtual table implementations to
122708** overload MATCH, LIKE, GLOB, and REGEXP operators.
122709**
122710** Return either the pDef argument (indicating no change) or a
122711** new FuncDef structure that is marked as ephemeral using the
122712** SQLITE_FUNC_EPHEM flag.
122713*/
122714SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
122715  sqlite3 *db,    /* Database connection for reporting malloc problems */
122716  FuncDef *pDef,  /* Function to possibly overload */
122717  int nArg,       /* Number of arguments to the function */
122718  Expr *pExpr     /* First argument to the function */
122719){
122720  Table *pTab;
122721  sqlite3_vtab *pVtab;
122722  sqlite3_module *pMod;
122723  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
122724  void *pArg = 0;
122725  FuncDef *pNew;
122726  int rc = 0;
122727  char *zLowerName;
122728  unsigned char *z;
122729
122730
122731  /* Check to see the left operand is a column in a virtual table */
122732  if( NEVER(pExpr==0) ) return pDef;
122733  if( pExpr->op!=TK_COLUMN ) return pDef;
122734  pTab = pExpr->pTab;
122735  if( NEVER(pTab==0) ) return pDef;
122736  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
122737  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
122738  assert( pVtab!=0 );
122739  assert( pVtab->pModule!=0 );
122740  pMod = (sqlite3_module *)pVtab->pModule;
122741  if( pMod->xFindFunction==0 ) return pDef;
122742
122743  /* Call the xFindFunction method on the virtual table implementation
122744  ** to see if the implementation wants to overload this function
122745  */
122746  zLowerName = sqlite3DbStrDup(db, pDef->zName);
122747  if( zLowerName ){
122748    for(z=(unsigned char*)zLowerName; *z; z++){
122749      *z = sqlite3UpperToLower[*z];
122750    }
122751    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg);
122752    sqlite3DbFree(db, zLowerName);
122753  }
122754  if( rc==0 ){
122755    return pDef;
122756  }
122757
122758  /* Create a new ephemeral function definition for the overloaded
122759  ** function */
122760  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
122761                             + sqlite3Strlen30(pDef->zName) + 1);
122762  if( pNew==0 ){
122763    return pDef;
122764  }
122765  *pNew = *pDef;
122766  pNew->zName = (const char*)&pNew[1];
122767  memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
122768  pNew->xSFunc = xSFunc;
122769  pNew->pUserData = pArg;
122770  pNew->funcFlags |= SQLITE_FUNC_EPHEM;
122771  return pNew;
122772}
122773
122774/*
122775** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
122776** array so that an OP_VBegin will get generated for it.  Add pTab to the
122777** array if it is missing.  If pTab is already in the array, this routine
122778** is a no-op.
122779*/
122780SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
122781  Parse *pToplevel = sqlite3ParseToplevel(pParse);
122782  int i, n;
122783  Table **apVtabLock;
122784
122785  assert( IsVirtual(pTab) );
122786  for(i=0; i<pToplevel->nVtabLock; i++){
122787    if( pTab==pToplevel->apVtabLock[i] ) return;
122788  }
122789  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
122790  apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
122791  if( apVtabLock ){
122792    pToplevel->apVtabLock = apVtabLock;
122793    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
122794  }else{
122795    sqlite3OomFault(pToplevel->db);
122796  }
122797}
122798
122799/*
122800** Check to see if virtual table module pMod can be have an eponymous
122801** virtual table instance.  If it can, create one if one does not already
122802** exist. Return non-zero if the eponymous virtual table instance exists
122803** when this routine returns, and return zero if it does not exist.
122804**
122805** An eponymous virtual table instance is one that is named after its
122806** module, and more importantly, does not require a CREATE VIRTUAL TABLE
122807** statement in order to come into existance.  Eponymous virtual table
122808** instances always exist.  They cannot be DROP-ed.
122809**
122810** Any virtual table module for which xConnect and xCreate are the same
122811** method can have an eponymous virtual table instance.
122812*/
122813SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
122814  const sqlite3_module *pModule = pMod->pModule;
122815  Table *pTab;
122816  char *zErr = 0;
122817  int rc;
122818  sqlite3 *db = pParse->db;
122819  if( pMod->pEpoTab ) return 1;
122820  if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
122821  pTab = sqlite3DbMallocZero(db, sizeof(Table));
122822  if( pTab==0 ) return 0;
122823  pTab->zName = sqlite3DbStrDup(db, pMod->zName);
122824  if( pTab->zName==0 ){
122825    sqlite3DbFree(db, pTab);
122826    return 0;
122827  }
122828  pMod->pEpoTab = pTab;
122829  pTab->nRef = 1;
122830  pTab->pSchema = db->aDb[0].pSchema;
122831  pTab->tabFlags |= TF_Virtual;
122832  pTab->nModuleArg = 0;
122833  pTab->iPKey = -1;
122834  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
122835  addModuleArgument(db, pTab, 0);
122836  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
122837  rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
122838  if( rc ){
122839    sqlite3ErrorMsg(pParse, "%s", zErr);
122840    sqlite3DbFree(db, zErr);
122841    sqlite3VtabEponymousTableClear(db, pMod);
122842    return 0;
122843  }
122844  return 1;
122845}
122846
122847/*
122848** Erase the eponymous virtual table instance associated with
122849** virtual table module pMod, if it exists.
122850*/
122851SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
122852  Table *pTab = pMod->pEpoTab;
122853  if( pTab!=0 ){
122854    /* Mark the table as Ephemeral prior to deleting it, so that the
122855    ** sqlite3DeleteTable() routine will know that it is not stored in
122856    ** the schema. */
122857    pTab->tabFlags |= TF_Ephemeral;
122858    sqlite3DeleteTable(db, pTab);
122859    pMod->pEpoTab = 0;
122860  }
122861}
122862
122863/*
122864** Return the ON CONFLICT resolution mode in effect for the virtual
122865** table update operation currently in progress.
122866**
122867** The results of this routine are undefined unless it is called from
122868** within an xUpdate method.
122869*/
122870SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *db){
122871  static const unsigned char aMap[] = {
122872    SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
122873  };
122874#ifdef SQLITE_ENABLE_API_ARMOR
122875  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
122876#endif
122877  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
122878  assert( OE_Ignore==4 && OE_Replace==5 );
122879  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
122880  return (int)aMap[db->vtabOnConflict-1];
122881}
122882
122883/*
122884** Call from within the xCreate() or xConnect() methods to provide
122885** the SQLite core with additional information about the behavior
122886** of the virtual table being implemented.
122887*/
122888SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3 *db, int op, ...){
122889  va_list ap;
122890  int rc = SQLITE_OK;
122891
122892#ifdef SQLITE_ENABLE_API_ARMOR
122893  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
122894#endif
122895  sqlite3_mutex_enter(db->mutex);
122896  va_start(ap, op);
122897  switch( op ){
122898    case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
122899      VtabCtx *p = db->pVtabCtx;
122900      if( !p ){
122901        rc = SQLITE_MISUSE_BKPT;
122902      }else{
122903        assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
122904        p->pVTable->bConstraint = (u8)va_arg(ap, int);
122905      }
122906      break;
122907    }
122908    default:
122909      rc = SQLITE_MISUSE_BKPT;
122910      break;
122911  }
122912  va_end(ap);
122913
122914  if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
122915  sqlite3_mutex_leave(db->mutex);
122916  return rc;
122917}
122918
122919#endif /* SQLITE_OMIT_VIRTUALTABLE */
122920
122921/************** End of vtab.c ************************************************/
122922/************** Begin file wherecode.c ***************************************/
122923/*
122924** 2015-06-06
122925**
122926** The author disclaims copyright to this source code.  In place of
122927** a legal notice, here is a blessing:
122928**
122929**    May you do good and not evil.
122930**    May you find forgiveness for yourself and forgive others.
122931**    May you share freely, never taking more than you give.
122932**
122933*************************************************************************
122934** This module contains C code that generates VDBE code used to process
122935** the WHERE clause of SQL statements.
122936**
122937** This file was split off from where.c on 2015-06-06 in order to reduce the
122938** size of where.c and make it easier to edit.  This file contains the routines
122939** that actually generate the bulk of the WHERE loop code.  The original where.c
122940** file retains the code that does query planning and analysis.
122941*/
122942/* #include "sqliteInt.h" */
122943/************** Include whereInt.h in the middle of wherecode.c **************/
122944/************** Begin file whereInt.h ****************************************/
122945/*
122946** 2013-11-12
122947**
122948** The author disclaims copyright to this source code.  In place of
122949** a legal notice, here is a blessing:
122950**
122951**    May you do good and not evil.
122952**    May you find forgiveness for yourself and forgive others.
122953**    May you share freely, never taking more than you give.
122954**
122955*************************************************************************
122956**
122957** This file contains structure and macro definitions for the query
122958** planner logic in "where.c".  These definitions are broken out into
122959** a separate source file for easier editing.
122960*/
122961
122962/*
122963** Trace output macros
122964*/
122965#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
122966/***/ int sqlite3WhereTrace;
122967#endif
122968#if defined(SQLITE_DEBUG) \
122969    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
122970# define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
122971# define WHERETRACE_ENABLED 1
122972#else
122973# define WHERETRACE(K,X)
122974#endif
122975
122976/* Forward references
122977*/
122978typedef struct WhereClause WhereClause;
122979typedef struct WhereMaskSet WhereMaskSet;
122980typedef struct WhereOrInfo WhereOrInfo;
122981typedef struct WhereAndInfo WhereAndInfo;
122982typedef struct WhereLevel WhereLevel;
122983typedef struct WhereLoop WhereLoop;
122984typedef struct WherePath WherePath;
122985typedef struct WhereTerm WhereTerm;
122986typedef struct WhereLoopBuilder WhereLoopBuilder;
122987typedef struct WhereScan WhereScan;
122988typedef struct WhereOrCost WhereOrCost;
122989typedef struct WhereOrSet WhereOrSet;
122990
122991/*
122992** This object contains information needed to implement a single nested
122993** loop in WHERE clause.
122994**
122995** Contrast this object with WhereLoop.  This object describes the
122996** implementation of the loop.  WhereLoop describes the algorithm.
122997** This object contains a pointer to the WhereLoop algorithm as one of
122998** its elements.
122999**
123000** The WhereInfo object contains a single instance of this object for
123001** each term in the FROM clause (which is to say, for each of the
123002** nested loops as implemented).  The order of WhereLevel objects determines
123003** the loop nested order, with WhereInfo.a[0] being the outer loop and
123004** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
123005*/
123006struct WhereLevel {
123007  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
123008  int iTabCur;          /* The VDBE cursor used to access the table */
123009  int iIdxCur;          /* The VDBE cursor used to access pIdx */
123010  int addrBrk;          /* Jump here to break out of the loop */
123011  int addrNxt;          /* Jump here to start the next IN combination */
123012  int addrSkip;         /* Jump here for next iteration of skip-scan */
123013  int addrCont;         /* Jump here to continue with the next loop cycle */
123014  int addrFirst;        /* First instruction of interior of the loop */
123015  int addrBody;         /* Beginning of the body of this loop */
123016#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
123017  u32 iLikeRepCntr;     /* LIKE range processing counter register (times 2) */
123018  int addrLikeRep;      /* LIKE range processing address */
123019#endif
123020  u8 iFrom;             /* Which entry in the FROM clause */
123021  u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
123022  int p1, p2;           /* Operands of the opcode used to ends the loop */
123023  union {               /* Information that depends on pWLoop->wsFlags */
123024    struct {
123025      int nIn;              /* Number of entries in aInLoop[] */
123026      struct InLoop {
123027        int iCur;              /* The VDBE cursor used by this IN operator */
123028        int addrInTop;         /* Top of the IN loop */
123029        u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
123030      } *aInLoop;           /* Information about each nested IN operator */
123031    } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
123032    Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
123033  } u;
123034  struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
123035  Bitmask notReady;          /* FROM entries not usable at this level */
123036#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
123037  int addrVisit;        /* Address at which row is visited */
123038#endif
123039};
123040
123041/*
123042** Each instance of this object represents an algorithm for evaluating one
123043** term of a join.  Every term of the FROM clause will have at least
123044** one corresponding WhereLoop object (unless INDEXED BY constraints
123045** prevent a query solution - which is an error) and many terms of the
123046** FROM clause will have multiple WhereLoop objects, each describing a
123047** potential way of implementing that FROM-clause term, together with
123048** dependencies and cost estimates for using the chosen algorithm.
123049**
123050** Query planning consists of building up a collection of these WhereLoop
123051** objects, then computing a particular sequence of WhereLoop objects, with
123052** one WhereLoop object per FROM clause term, that satisfy all dependencies
123053** and that minimize the overall cost.
123054*/
123055struct WhereLoop {
123056  Bitmask prereq;       /* Bitmask of other loops that must run first */
123057  Bitmask maskSelf;     /* Bitmask identifying table iTab */
123058#ifdef SQLITE_DEBUG
123059  char cId;             /* Symbolic ID of this loop for debugging use */
123060#endif
123061  u8 iTab;              /* Position in FROM clause of table for this loop */
123062  u8 iSortIdx;          /* Sorting index number.  0==None */
123063  LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
123064  LogEst rRun;          /* Cost of running each loop */
123065  LogEst nOut;          /* Estimated number of output rows */
123066  union {
123067    struct {               /* Information for internal btree tables */
123068      u16 nEq;               /* Number of equality constraints */
123069      Index *pIndex;         /* Index used, or NULL */
123070    } btree;
123071    struct {               /* Information for virtual tables */
123072      int idxNum;            /* Index number */
123073      u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
123074      i8 isOrdered;          /* True if satisfies ORDER BY */
123075      u16 omitMask;          /* Terms that may be omitted */
123076      char *idxStr;          /* Index identifier string */
123077    } vtab;
123078  } u;
123079  u32 wsFlags;          /* WHERE_* flags describing the plan */
123080  u16 nLTerm;           /* Number of entries in aLTerm[] */
123081  u16 nSkip;            /* Number of NULL aLTerm[] entries */
123082  /**** whereLoopXfer() copies fields above ***********************/
123083# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
123084  u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
123085  WhereTerm **aLTerm;   /* WhereTerms used */
123086  WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
123087  WhereTerm *aLTermSpace[3];  /* Initial aLTerm[] space */
123088};
123089
123090/* This object holds the prerequisites and the cost of running a
123091** subquery on one operand of an OR operator in the WHERE clause.
123092** See WhereOrSet for additional information
123093*/
123094struct WhereOrCost {
123095  Bitmask prereq;     /* Prerequisites */
123096  LogEst rRun;        /* Cost of running this subquery */
123097  LogEst nOut;        /* Number of outputs for this subquery */
123098};
123099
123100/* The WhereOrSet object holds a set of possible WhereOrCosts that
123101** correspond to the subquery(s) of OR-clause processing.  Only the
123102** best N_OR_COST elements are retained.
123103*/
123104#define N_OR_COST 3
123105struct WhereOrSet {
123106  u16 n;                      /* Number of valid a[] entries */
123107  WhereOrCost a[N_OR_COST];   /* Set of best costs */
123108};
123109
123110/*
123111** Each instance of this object holds a sequence of WhereLoop objects
123112** that implement some or all of a query plan.
123113**
123114** Think of each WhereLoop object as a node in a graph with arcs
123115** showing dependencies and costs for travelling between nodes.  (That is
123116** not a completely accurate description because WhereLoop costs are a
123117** vector, not a scalar, and because dependencies are many-to-one, not
123118** one-to-one as are graph nodes.  But it is a useful visualization aid.)
123119** Then a WherePath object is a path through the graph that visits some
123120** or all of the WhereLoop objects once.
123121**
123122** The "solver" works by creating the N best WherePath objects of length
123123** 1.  Then using those as a basis to compute the N best WherePath objects
123124** of length 2.  And so forth until the length of WherePaths equals the
123125** number of nodes in the FROM clause.  The best (lowest cost) WherePath
123126** at the end is the chosen query plan.
123127*/
123128struct WherePath {
123129  Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
123130  Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
123131  LogEst nRow;          /* Estimated number of rows generated by this path */
123132  LogEst rCost;         /* Total cost of this path */
123133  LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */
123134  i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
123135  WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
123136};
123137
123138/*
123139** The query generator uses an array of instances of this structure to
123140** help it analyze the subexpressions of the WHERE clause.  Each WHERE
123141** clause subexpression is separated from the others by AND operators,
123142** usually, or sometimes subexpressions separated by OR.
123143**
123144** All WhereTerms are collected into a single WhereClause structure.
123145** The following identity holds:
123146**
123147**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
123148**
123149** When a term is of the form:
123150**
123151**              X <op> <expr>
123152**
123153** where X is a column name and <op> is one of certain operators,
123154** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
123155** cursor number and column number for X.  WhereTerm.eOperator records
123156** the <op> using a bitmask encoding defined by WO_xxx below.  The
123157** use of a bitmask encoding for the operator allows us to search
123158** quickly for terms that match any of several different operators.
123159**
123160** A WhereTerm might also be two or more subterms connected by OR:
123161**
123162**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
123163**
123164** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
123165** and the WhereTerm.u.pOrInfo field points to auxiliary information that
123166** is collected about the OR clause.
123167**
123168** If a term in the WHERE clause does not match either of the two previous
123169** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
123170** to the original subexpression content and wtFlags is set up appropriately
123171** but no other fields in the WhereTerm object are meaningful.
123172**
123173** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
123174** but they do so indirectly.  A single WhereMaskSet structure translates
123175** cursor number into bits and the translated bit is stored in the prereq
123176** fields.  The translation is used in order to maximize the number of
123177** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
123178** spread out over the non-negative integers.  For example, the cursor
123179** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
123180** translates these sparse cursor numbers into consecutive integers
123181** beginning with 0 in order to make the best possible use of the available
123182** bits in the Bitmask.  So, in the example above, the cursor numbers
123183** would be mapped into integers 0 through 7.
123184**
123185** The number of terms in a join is limited by the number of bits
123186** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
123187** is only able to process joins with 64 or fewer tables.
123188*/
123189struct WhereTerm {
123190  Expr *pExpr;            /* Pointer to the subexpression that is this term */
123191  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
123192  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
123193  union {
123194    int leftColumn;         /* Column number of X in "X <op> <expr>" */
123195    WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
123196    WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
123197  } u;
123198  LogEst truthProb;       /* Probability of truth for this expression */
123199  u16 eOperator;          /* A WO_xx value describing <op> */
123200  u16 wtFlags;            /* TERM_xxx bit flags.  See below */
123201  u8 nChild;              /* Number of children that must disable us */
123202  u8 eMatchOp;            /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
123203  WhereClause *pWC;       /* The clause this term is part of */
123204  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
123205  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
123206};
123207
123208/*
123209** Allowed values of WhereTerm.wtFlags
123210*/
123211#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
123212#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
123213#define TERM_CODED      0x04   /* This term is already coded */
123214#define TERM_COPIED     0x08   /* Has a child */
123215#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
123216#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
123217#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
123218#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
123219#  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
123220#else
123221#  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
123222#endif
123223#define TERM_LIKEOPT    0x100  /* Virtual terms from the LIKE optimization */
123224#define TERM_LIKECOND   0x200  /* Conditionally this LIKE operator term */
123225#define TERM_LIKE       0x400  /* The original LIKE operator */
123226#define TERM_IS         0x800  /* Term.pExpr is an IS operator */
123227
123228/*
123229** An instance of the WhereScan object is used as an iterator for locating
123230** terms in the WHERE clause that are useful to the query planner.
123231*/
123232struct WhereScan {
123233  WhereClause *pOrigWC;      /* Original, innermost WhereClause */
123234  WhereClause *pWC;          /* WhereClause currently being scanned */
123235  const char *zCollName;     /* Required collating sequence, if not NULL */
123236  Expr *pIdxExpr;            /* Search for this index expression */
123237  char idxaff;               /* Must match this affinity, if zCollName!=NULL */
123238  unsigned char nEquiv;      /* Number of entries in aEquiv[] */
123239  unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
123240  u32 opMask;                /* Acceptable operators */
123241  int k;                     /* Resume scanning at this->pWC->a[this->k] */
123242  int aiCur[11];             /* Cursors in the equivalence class */
123243  i16 aiColumn[11];          /* Corresponding column number in the eq-class */
123244};
123245
123246/*
123247** An instance of the following structure holds all information about a
123248** WHERE clause.  Mostly this is a container for one or more WhereTerms.
123249**
123250** Explanation of pOuter:  For a WHERE clause of the form
123251**
123252**           a AND ((b AND c) OR (d AND e)) AND f
123253**
123254** There are separate WhereClause objects for the whole clause and for
123255** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
123256** subclauses points to the WhereClause object for the whole clause.
123257*/
123258struct WhereClause {
123259  WhereInfo *pWInfo;       /* WHERE clause processing context */
123260  WhereClause *pOuter;     /* Outer conjunction */
123261  u8 op;                   /* Split operator.  TK_AND or TK_OR */
123262  int nTerm;               /* Number of terms */
123263  int nSlot;               /* Number of entries in a[] */
123264  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
123265#if defined(SQLITE_SMALL_STACK)
123266  WhereTerm aStatic[1];    /* Initial static space for a[] */
123267#else
123268  WhereTerm aStatic[8];    /* Initial static space for a[] */
123269#endif
123270};
123271
123272/*
123273** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
123274** a dynamically allocated instance of the following structure.
123275*/
123276struct WhereOrInfo {
123277  WhereClause wc;          /* Decomposition into subterms */
123278  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
123279};
123280
123281/*
123282** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
123283** a dynamically allocated instance of the following structure.
123284*/
123285struct WhereAndInfo {
123286  WhereClause wc;          /* The subexpression broken out */
123287};
123288
123289/*
123290** An instance of the following structure keeps track of a mapping
123291** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
123292**
123293** The VDBE cursor numbers are small integers contained in
123294** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
123295** clause, the cursor numbers might not begin with 0 and they might
123296** contain gaps in the numbering sequence.  But we want to make maximum
123297** use of the bits in our bitmasks.  This structure provides a mapping
123298** from the sparse cursor numbers into consecutive integers beginning
123299** with 0.
123300**
123301** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
123302** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
123303**
123304** For example, if the WHERE clause expression used these VDBE
123305** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
123306** would map those cursor numbers into bits 0 through 5.
123307**
123308** Note that the mapping is not necessarily ordered.  In the example
123309** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
123310** 57->5, 73->4.  Or one of 719 other combinations might be used. It
123311** does not really matter.  What is important is that sparse cursor
123312** numbers all get mapped into bit numbers that begin with 0 and contain
123313** no gaps.
123314*/
123315struct WhereMaskSet {
123316  int n;                        /* Number of assigned cursor values */
123317  int ix[BMS];                  /* Cursor assigned to each bit */
123318};
123319
123320/*
123321** Initialize a WhereMaskSet object
123322*/
123323#define initMaskSet(P)  (P)->n=0
123324
123325/*
123326** This object is a convenience wrapper holding all information needed
123327** to construct WhereLoop objects for a particular query.
123328*/
123329struct WhereLoopBuilder {
123330  WhereInfo *pWInfo;        /* Information about this WHERE */
123331  WhereClause *pWC;         /* WHERE clause terms */
123332  ExprList *pOrderBy;       /* ORDER BY clause */
123333  WhereLoop *pNew;          /* Template WhereLoop */
123334  WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
123335#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
123336  UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
123337  int nRecValid;            /* Number of valid fields currently in pRec */
123338#endif
123339};
123340
123341/*
123342** The WHERE clause processing routine has two halves.  The
123343** first part does the start of the WHERE loop and the second
123344** half does the tail of the WHERE loop.  An instance of
123345** this structure is returned by the first half and passed
123346** into the second half to give some continuity.
123347**
123348** An instance of this object holds the complete state of the query
123349** planner.
123350*/
123351struct WhereInfo {
123352  Parse *pParse;            /* Parsing and code generating context */
123353  SrcList *pTabList;        /* List of tables in the join */
123354  ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
123355  ExprList *pDistinctSet;   /* DISTINCT over all these values */
123356  WhereLoop *pLoops;        /* List of all WhereLoop objects */
123357  Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
123358  LogEst nRowOut;           /* Estimated number of output rows */
123359  LogEst iLimit;            /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
123360  u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
123361  i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
123362  u8 sorted;                /* True if really sorted (not just grouped) */
123363  u8 eOnePass;              /* ONEPASS_OFF, or _SINGLE, or _MULTI */
123364  u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
123365  u8 eDistinct;             /* One of the WHERE_DISTINCT_* values */
123366  u8 nLevel;                /* Number of nested loop */
123367  u8 bOrderedInnerLoop;     /* True if only the inner-most loop is ordered */
123368  int iTop;                 /* The very beginning of the WHERE loop */
123369  int iContinue;            /* Jump here to continue with next record */
123370  int iBreak;               /* Jump here to break out of the loop */
123371  int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
123372  int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
123373  WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
123374  WhereClause sWC;          /* Decomposition of the WHERE clause */
123375  WhereLevel a[1];          /* Information about each nest loop in WHERE */
123376};
123377
123378/*
123379** Private interfaces - callable only by other where.c routines.
123380**
123381** where.c:
123382*/
123383SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
123384#ifdef WHERETRACE_ENABLED
123385SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
123386#endif
123387SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
123388  WhereClause *pWC,     /* The WHERE clause to be searched */
123389  int iCur,             /* Cursor number of LHS */
123390  int iColumn,          /* Column number of LHS */
123391  Bitmask notReady,     /* RHS must not overlap with this mask */
123392  u32 op,               /* Mask of WO_xx values describing operator */
123393  Index *pIdx           /* Must be compatible with this index, if not NULL */
123394);
123395
123396/* wherecode.c: */
123397#ifndef SQLITE_OMIT_EXPLAIN
123398SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
123399  Parse *pParse,                  /* Parse context */
123400  SrcList *pTabList,              /* Table list this loop refers to */
123401  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
123402  int iLevel,                     /* Value for "level" column of output */
123403  int iFrom,                      /* Value for "from" column of output */
123404  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
123405);
123406#else
123407# define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
123408#endif /* SQLITE_OMIT_EXPLAIN */
123409#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
123410SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
123411  Vdbe *v,                        /* Vdbe to add scanstatus entry to */
123412  SrcList *pSrclist,              /* FROM clause pLvl reads data from */
123413  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
123414  int addrExplain                 /* Address of OP_Explain (or 0) */
123415);
123416#else
123417# define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
123418#endif
123419SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
123420  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
123421  int iLevel,          /* Which level of pWInfo->a[] should be coded */
123422  Bitmask notReady     /* Which tables are currently available */
123423);
123424
123425/* whereexpr.c: */
123426SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
123427SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
123428SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
123429SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
123430SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
123431SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
123432SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
123433
123434
123435
123436
123437
123438/*
123439** Bitmasks for the operators on WhereTerm objects.  These are all
123440** operators that are of interest to the query planner.  An
123441** OR-ed combination of these values can be used when searching for
123442** particular WhereTerms within a WhereClause.
123443**
123444** Value constraints:
123445**     WO_EQ    == SQLITE_INDEX_CONSTRAINT_EQ
123446**     WO_LT    == SQLITE_INDEX_CONSTRAINT_LT
123447**     WO_LE    == SQLITE_INDEX_CONSTRAINT_LE
123448**     WO_GT    == SQLITE_INDEX_CONSTRAINT_GT
123449**     WO_GE    == SQLITE_INDEX_CONSTRAINT_GE
123450**     WO_MATCH == SQLITE_INDEX_CONSTRAINT_MATCH
123451*/
123452#define WO_IN     0x0001
123453#define WO_EQ     0x0002
123454#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
123455#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
123456#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
123457#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
123458#define WO_MATCH  0x0040
123459#define WO_IS     0x0080
123460#define WO_ISNULL 0x0100
123461#define WO_OR     0x0200       /* Two or more OR-connected terms */
123462#define WO_AND    0x0400       /* Two or more AND-connected terms */
123463#define WO_EQUIV  0x0800       /* Of the form A==B, both columns */
123464#define WO_NOOP   0x1000       /* This term does not restrict search space */
123465
123466#define WO_ALL    0x1fff       /* Mask of all possible WO_* values */
123467#define WO_SINGLE 0x01ff       /* Mask of all non-compound WO_* values */
123468
123469/*
123470** These are definitions of bits in the WhereLoop.wsFlags field.
123471** The particular combination of bits in each WhereLoop help to
123472** determine the algorithm that WhereLoop represents.
123473*/
123474#define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
123475#define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
123476#define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
123477#define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
123478#define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
123479#define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
123480#define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
123481#define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
123482#define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
123483#define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
123484#define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
123485#define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
123486#define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
123487#define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
123488#define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
123489#define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
123490#define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
123491#define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
123492#define WHERE_PARTIALIDX   0x00020000  /* The automatic index is partial */
123493
123494/************** End of whereInt.h ********************************************/
123495/************** Continuing where we left off in wherecode.c ******************/
123496
123497#ifndef SQLITE_OMIT_EXPLAIN
123498/*
123499** This routine is a helper for explainIndexRange() below
123500**
123501** pStr holds the text of an expression that we are building up one term
123502** at a time.  This routine adds a new term to the end of the expression.
123503** Terms are separated by AND so add the "AND" text for second and subsequent
123504** terms only.
123505*/
123506static void explainAppendTerm(
123507  StrAccum *pStr,             /* The text expression being built */
123508  int iTerm,                  /* Index of this term.  First is zero */
123509  const char *zColumn,        /* Name of the column */
123510  const char *zOp             /* Name of the operator */
123511){
123512  if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
123513  sqlite3StrAccumAppendAll(pStr, zColumn);
123514  sqlite3StrAccumAppend(pStr, zOp, 1);
123515  sqlite3StrAccumAppend(pStr, "?", 1);
123516}
123517
123518/*
123519** Return the name of the i-th column of the pIdx index.
123520*/
123521static const char *explainIndexColumnName(Index *pIdx, int i){
123522  i = pIdx->aiColumn[i];
123523  if( i==XN_EXPR ) return "<expr>";
123524  if( i==XN_ROWID ) return "rowid";
123525  return pIdx->pTable->aCol[i].zName;
123526}
123527
123528/*
123529** Argument pLevel describes a strategy for scanning table pTab. This
123530** function appends text to pStr that describes the subset of table
123531** rows scanned by the strategy in the form of an SQL expression.
123532**
123533** For example, if the query:
123534**
123535**   SELECT * FROM t1 WHERE a=1 AND b>2;
123536**
123537** is run and there is an index on (a, b), then this function returns a
123538** string similar to:
123539**
123540**   "a=? AND b>?"
123541*/
123542static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
123543  Index *pIndex = pLoop->u.btree.pIndex;
123544  u16 nEq = pLoop->u.btree.nEq;
123545  u16 nSkip = pLoop->nSkip;
123546  int i, j;
123547
123548  if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
123549  sqlite3StrAccumAppend(pStr, " (", 2);
123550  for(i=0; i<nEq; i++){
123551    const char *z = explainIndexColumnName(pIndex, i);
123552    if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
123553    sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
123554  }
123555
123556  j = i;
123557  if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
123558    const char *z = explainIndexColumnName(pIndex, i);
123559    explainAppendTerm(pStr, i++, z, ">");
123560  }
123561  if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
123562    const char *z = explainIndexColumnName(pIndex, j);
123563    explainAppendTerm(pStr, i, z, "<");
123564  }
123565  sqlite3StrAccumAppend(pStr, ")", 1);
123566}
123567
123568/*
123569** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
123570** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
123571** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
123572** is added to the output to describe the table scan strategy in pLevel.
123573**
123574** If an OP_Explain opcode is added to the VM, its address is returned.
123575** Otherwise, if no OP_Explain is coded, zero is returned.
123576*/
123577SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
123578  Parse *pParse,                  /* Parse context */
123579  SrcList *pTabList,              /* Table list this loop refers to */
123580  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
123581  int iLevel,                     /* Value for "level" column of output */
123582  int iFrom,                      /* Value for "from" column of output */
123583  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
123584){
123585  int ret = 0;
123586#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
123587  if( pParse->explain==2 )
123588#endif
123589  {
123590    struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
123591    Vdbe *v = pParse->pVdbe;      /* VM being constructed */
123592    sqlite3 *db = pParse->db;     /* Database handle */
123593    int iId = pParse->iSelectId;  /* Select id (left-most output column) */
123594    int isSearch;                 /* True for a SEARCH. False for SCAN. */
123595    WhereLoop *pLoop;             /* The controlling WhereLoop object */
123596    u32 flags;                    /* Flags that describe this loop */
123597    char *zMsg;                   /* Text to add to EQP output */
123598    StrAccum str;                 /* EQP output string */
123599    char zBuf[100];               /* Initial space for EQP output string */
123600
123601    pLoop = pLevel->pWLoop;
123602    flags = pLoop->wsFlags;
123603    if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
123604
123605    isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
123606            || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
123607            || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
123608
123609    sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
123610    sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
123611    if( pItem->pSelect ){
123612      sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
123613    }else{
123614      sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
123615    }
123616
123617    if( pItem->zAlias ){
123618      sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
123619    }
123620    if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
123621      const char *zFmt = 0;
123622      Index *pIdx;
123623
123624      assert( pLoop->u.btree.pIndex!=0 );
123625      pIdx = pLoop->u.btree.pIndex;
123626      assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
123627      if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
123628        if( isSearch ){
123629          zFmt = "PRIMARY KEY";
123630        }
123631      }else if( flags & WHERE_PARTIALIDX ){
123632        zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
123633      }else if( flags & WHERE_AUTO_INDEX ){
123634        zFmt = "AUTOMATIC COVERING INDEX";
123635      }else if( flags & WHERE_IDX_ONLY ){
123636        zFmt = "COVERING INDEX %s";
123637      }else{
123638        zFmt = "INDEX %s";
123639      }
123640      if( zFmt ){
123641        sqlite3StrAccumAppend(&str, " USING ", 7);
123642        sqlite3XPrintf(&str, zFmt, pIdx->zName);
123643        explainIndexRange(&str, pLoop);
123644      }
123645    }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
123646      const char *zRangeOp;
123647      if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
123648        zRangeOp = "=";
123649      }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
123650        zRangeOp = ">? AND rowid<";
123651      }else if( flags&WHERE_BTM_LIMIT ){
123652        zRangeOp = ">";
123653      }else{
123654        assert( flags&WHERE_TOP_LIMIT);
123655        zRangeOp = "<";
123656      }
123657      sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
123658    }
123659#ifndef SQLITE_OMIT_VIRTUALTABLE
123660    else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
123661      sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
123662                  pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
123663    }
123664#endif
123665#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
123666    if( pLoop->nOut>=10 ){
123667      sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
123668    }else{
123669      sqlite3StrAccumAppend(&str, " (~1 row)", 9);
123670    }
123671#endif
123672    zMsg = sqlite3StrAccumFinish(&str);
123673    ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
123674  }
123675  return ret;
123676}
123677#endif /* SQLITE_OMIT_EXPLAIN */
123678
123679#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
123680/*
123681** Configure the VM passed as the first argument with an
123682** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
123683** implement level pLvl. Argument pSrclist is a pointer to the FROM
123684** clause that the scan reads data from.
123685**
123686** If argument addrExplain is not 0, it must be the address of an
123687** OP_Explain instruction that describes the same loop.
123688*/
123689SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
123690  Vdbe *v,                        /* Vdbe to add scanstatus entry to */
123691  SrcList *pSrclist,              /* FROM clause pLvl reads data from */
123692  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
123693  int addrExplain                 /* Address of OP_Explain (or 0) */
123694){
123695  const char *zObj = 0;
123696  WhereLoop *pLoop = pLvl->pWLoop;
123697  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){
123698    zObj = pLoop->u.btree.pIndex->zName;
123699  }else{
123700    zObj = pSrclist->a[pLvl->iFrom].zName;
123701  }
123702  sqlite3VdbeScanStatus(
123703      v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
123704  );
123705}
123706#endif
123707
123708
123709/*
123710** Disable a term in the WHERE clause.  Except, do not disable the term
123711** if it controls a LEFT OUTER JOIN and it did not originate in the ON
123712** or USING clause of that join.
123713**
123714** Consider the term t2.z='ok' in the following queries:
123715**
123716**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
123717**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
123718**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
123719**
123720** The t2.z='ok' is disabled in the in (2) because it originates
123721** in the ON clause.  The term is disabled in (3) because it is not part
123722** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
123723**
123724** Disabling a term causes that term to not be tested in the inner loop
123725** of the join.  Disabling is an optimization.  When terms are satisfied
123726** by indices, we disable them to prevent redundant tests in the inner
123727** loop.  We would get the correct results if nothing were ever disabled,
123728** but joins might run a little slower.  The trick is to disable as much
123729** as we can without disabling too much.  If we disabled in (1), we'd get
123730** the wrong answer.  See ticket #813.
123731**
123732** If all the children of a term are disabled, then that term is also
123733** automatically disabled.  In this way, terms get disabled if derived
123734** virtual terms are tested first.  For example:
123735**
123736**      x GLOB 'abc*' AND x>='abc' AND x<'acd'
123737**      \___________/     \______/     \_____/
123738**         parent          child1       child2
123739**
123740** Only the parent term was in the original WHERE clause.  The child1
123741** and child2 terms were added by the LIKE optimization.  If both of
123742** the virtual child terms are valid, then testing of the parent can be
123743** skipped.
123744**
123745** Usually the parent term is marked as TERM_CODED.  But if the parent
123746** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
123747** The TERM_LIKECOND marking indicates that the term should be coded inside
123748** a conditional such that is only evaluated on the second pass of a
123749** LIKE-optimization loop, when scanning BLOBs instead of strings.
123750*/
123751static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
123752  int nLoop = 0;
123753  while( pTerm
123754      && (pTerm->wtFlags & TERM_CODED)==0
123755      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
123756      && (pLevel->notReady & pTerm->prereqAll)==0
123757  ){
123758    if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
123759      pTerm->wtFlags |= TERM_LIKECOND;
123760    }else{
123761      pTerm->wtFlags |= TERM_CODED;
123762    }
123763    if( pTerm->iParent<0 ) break;
123764    pTerm = &pTerm->pWC->a[pTerm->iParent];
123765    pTerm->nChild--;
123766    if( pTerm->nChild!=0 ) break;
123767    nLoop++;
123768  }
123769}
123770
123771/*
123772** Code an OP_Affinity opcode to apply the column affinity string zAff
123773** to the n registers starting at base.
123774**
123775** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
123776** beginning and end of zAff are ignored.  If all entries in zAff are
123777** SQLITE_AFF_BLOB, then no code gets generated.
123778**
123779** This routine makes its own copy of zAff so that the caller is free
123780** to modify zAff after this routine returns.
123781*/
123782static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
123783  Vdbe *v = pParse->pVdbe;
123784  if( zAff==0 ){
123785    assert( pParse->db->mallocFailed );
123786    return;
123787  }
123788  assert( v!=0 );
123789
123790  /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
123791  ** and end of the affinity string.
123792  */
123793  while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
123794    n--;
123795    base++;
123796    zAff++;
123797  }
123798  while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
123799    n--;
123800  }
123801
123802  /* Code the OP_Affinity opcode if there is anything left to do. */
123803  if( n>0 ){
123804    sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
123805    sqlite3ExprCacheAffinityChange(pParse, base, n);
123806  }
123807}
123808
123809
123810/*
123811** Generate code for a single equality term of the WHERE clause.  An equality
123812** term can be either X=expr or X IN (...).   pTerm is the term to be
123813** coded.
123814**
123815** The current value for the constraint is left in register iReg.
123816**
123817** For a constraint of the form X=expr, the expression is evaluated and its
123818** result is left on the stack.  For constraints of the form X IN (...)
123819** this routine sets up a loop that will iterate over all values of X.
123820*/
123821static int codeEqualityTerm(
123822  Parse *pParse,      /* The parsing context */
123823  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
123824  WhereLevel *pLevel, /* The level of the FROM clause we are working on */
123825  int iEq,            /* Index of the equality term within this level */
123826  int bRev,           /* True for reverse-order IN operations */
123827  int iTarget         /* Attempt to leave results in this register */
123828){
123829  Expr *pX = pTerm->pExpr;
123830  Vdbe *v = pParse->pVdbe;
123831  int iReg;                  /* Register holding results */
123832
123833  assert( iTarget>0 );
123834  if( pX->op==TK_EQ || pX->op==TK_IS ){
123835    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
123836  }else if( pX->op==TK_ISNULL ){
123837    iReg = iTarget;
123838    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
123839#ifndef SQLITE_OMIT_SUBQUERY
123840  }else{
123841    int eType;
123842    int iTab;
123843    struct InLoop *pIn;
123844    WhereLoop *pLoop = pLevel->pWLoop;
123845
123846    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
123847      && pLoop->u.btree.pIndex!=0
123848      && pLoop->u.btree.pIndex->aSortOrder[iEq]
123849    ){
123850      testcase( iEq==0 );
123851      testcase( bRev );
123852      bRev = !bRev;
123853    }
123854    assert( pX->op==TK_IN );
123855    iReg = iTarget;
123856    eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
123857    if( eType==IN_INDEX_INDEX_DESC ){
123858      testcase( bRev );
123859      bRev = !bRev;
123860    }
123861    iTab = pX->iTable;
123862    sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
123863    VdbeCoverageIf(v, bRev);
123864    VdbeCoverageIf(v, !bRev);
123865    assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
123866    pLoop->wsFlags |= WHERE_IN_ABLE;
123867    if( pLevel->u.in.nIn==0 ){
123868      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
123869    }
123870    pLevel->u.in.nIn++;
123871    pLevel->u.in.aInLoop =
123872       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
123873                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
123874    pIn = pLevel->u.in.aInLoop;
123875    if( pIn ){
123876      pIn += pLevel->u.in.nIn - 1;
123877      pIn->iCur = iTab;
123878      if( eType==IN_INDEX_ROWID ){
123879        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
123880      }else{
123881        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
123882      }
123883      pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
123884      sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
123885    }else{
123886      pLevel->u.in.nIn = 0;
123887    }
123888#endif
123889  }
123890  disableTerm(pLevel, pTerm);
123891  return iReg;
123892}
123893
123894/*
123895** Generate code that will evaluate all == and IN constraints for an
123896** index scan.
123897**
123898** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
123899** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
123900** The index has as many as three equality constraints, but in this
123901** example, the third "c" value is an inequality.  So only two
123902** constraints are coded.  This routine will generate code to evaluate
123903** a==5 and b IN (1,2,3).  The current values for a and b will be stored
123904** in consecutive registers and the index of the first register is returned.
123905**
123906** In the example above nEq==2.  But this subroutine works for any value
123907** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
123908** The only thing it does is allocate the pLevel->iMem memory cell and
123909** compute the affinity string.
123910**
123911** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
123912** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
123913** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
123914** occurs after the nEq quality constraints.
123915**
123916** This routine allocates a range of nEq+nExtraReg memory cells and returns
123917** the index of the first memory cell in that range. The code that
123918** calls this routine will use that memory range to store keys for
123919** start and termination conditions of the loop.
123920** key value of the loop.  If one or more IN operators appear, then
123921** this routine allocates an additional nEq memory cells for internal
123922** use.
123923**
123924** Before returning, *pzAff is set to point to a buffer containing a
123925** copy of the column affinity string of the index allocated using
123926** sqlite3DbMalloc(). Except, entries in the copy of the string associated
123927** with equality constraints that use BLOB or NONE affinity are set to
123928** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
123929**
123930**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
123931**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
123932**
123933** In the example above, the index on t1(a) has TEXT affinity. But since
123934** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
123935** no conversion should be attempted before using a t2.b value as part of
123936** a key to search the index. Hence the first byte in the returned affinity
123937** string in this example would be set to SQLITE_AFF_BLOB.
123938*/
123939static int codeAllEqualityTerms(
123940  Parse *pParse,        /* Parsing context */
123941  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
123942  int bRev,             /* Reverse the order of IN operators */
123943  int nExtraReg,        /* Number of extra registers to allocate */
123944  char **pzAff          /* OUT: Set to point to affinity string */
123945){
123946  u16 nEq;                      /* The number of == or IN constraints to code */
123947  u16 nSkip;                    /* Number of left-most columns to skip */
123948  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
123949  Index *pIdx;                  /* The index being used for this loop */
123950  WhereTerm *pTerm;             /* A single constraint term */
123951  WhereLoop *pLoop;             /* The WhereLoop object */
123952  int j;                        /* Loop counter */
123953  int regBase;                  /* Base register */
123954  int nReg;                     /* Number of registers to allocate */
123955  char *zAff;                   /* Affinity string to return */
123956
123957  /* This module is only called on query plans that use an index. */
123958  pLoop = pLevel->pWLoop;
123959  assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
123960  nEq = pLoop->u.btree.nEq;
123961  nSkip = pLoop->nSkip;
123962  pIdx = pLoop->u.btree.pIndex;
123963  assert( pIdx!=0 );
123964
123965  /* Figure out how many memory cells we will need then allocate them.
123966  */
123967  regBase = pParse->nMem + 1;
123968  nReg = pLoop->u.btree.nEq + nExtraReg;
123969  pParse->nMem += nReg;
123970
123971  zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
123972  assert( zAff!=0 || pParse->db->mallocFailed );
123973
123974  if( nSkip ){
123975    int iIdxCur = pLevel->iIdxCur;
123976    sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
123977    VdbeCoverageIf(v, bRev==0);
123978    VdbeCoverageIf(v, bRev!=0);
123979    VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
123980    j = sqlite3VdbeAddOp0(v, OP_Goto);
123981    pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
123982                            iIdxCur, 0, regBase, nSkip);
123983    VdbeCoverageIf(v, bRev==0);
123984    VdbeCoverageIf(v, bRev!=0);
123985    sqlite3VdbeJumpHere(v, j);
123986    for(j=0; j<nSkip; j++){
123987      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
123988      testcase( pIdx->aiColumn[j]==XN_EXPR );
123989      VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
123990    }
123991  }
123992
123993  /* Evaluate the equality constraints
123994  */
123995  assert( zAff==0 || (int)strlen(zAff)>=nEq );
123996  for(j=nSkip; j<nEq; j++){
123997    int r1;
123998    pTerm = pLoop->aLTerm[j];
123999    assert( pTerm!=0 );
124000    /* The following testcase is true for indices with redundant columns.
124001    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
124002    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
124003    testcase( pTerm->wtFlags & TERM_VIRTUAL );
124004    r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
124005    if( r1!=regBase+j ){
124006      if( nReg==1 ){
124007        sqlite3ReleaseTempReg(pParse, regBase);
124008        regBase = r1;
124009      }else{
124010        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
124011      }
124012    }
124013    testcase( pTerm->eOperator & WO_ISNULL );
124014    testcase( pTerm->eOperator & WO_IN );
124015    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
124016      Expr *pRight = pTerm->pExpr->pRight;
124017      if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
124018        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
124019        VdbeCoverage(v);
124020      }
124021      if( zAff ){
124022        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
124023          zAff[j] = SQLITE_AFF_BLOB;
124024        }
124025        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
124026          zAff[j] = SQLITE_AFF_BLOB;
124027        }
124028      }
124029    }
124030  }
124031  *pzAff = zAff;
124032  return regBase;
124033}
124034
124035#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
124036/*
124037** If the most recently coded instruction is a constant range constraint
124038** (a string literal) that originated from the LIKE optimization, then
124039** set P3 and P5 on the OP_String opcode so that the string will be cast
124040** to a BLOB at appropriate times.
124041**
124042** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
124043** expression: "x>='ABC' AND x<'abd'".  But this requires that the range
124044** scan loop run twice, once for strings and a second time for BLOBs.
124045** The OP_String opcodes on the second pass convert the upper and lower
124046** bound string constants to blobs.  This routine makes the necessary changes
124047** to the OP_String opcodes for that to happen.
124048**
124049** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
124050** only the one pass through the string space is required, so this routine
124051** becomes a no-op.
124052*/
124053static void whereLikeOptimizationStringFixup(
124054  Vdbe *v,                /* prepared statement under construction */
124055  WhereLevel *pLevel,     /* The loop that contains the LIKE operator */
124056  WhereTerm *pTerm        /* The upper or lower bound just coded */
124057){
124058  if( pTerm->wtFlags & TERM_LIKEOPT ){
124059    VdbeOp *pOp;
124060    assert( pLevel->iLikeRepCntr>0 );
124061    pOp = sqlite3VdbeGetOp(v, -1);
124062    assert( pOp!=0 );
124063    assert( pOp->opcode==OP_String8
124064            || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
124065    pOp->p3 = (int)(pLevel->iLikeRepCntr>>1);  /* Register holding counter */
124066    pOp->p5 = (u8)(pLevel->iLikeRepCntr&1);    /* ASC or DESC */
124067  }
124068}
124069#else
124070# define whereLikeOptimizationStringFixup(A,B,C)
124071#endif
124072
124073#ifdef SQLITE_ENABLE_CURSOR_HINTS
124074/*
124075** Information is passed from codeCursorHint() down to individual nodes of
124076** the expression tree (by sqlite3WalkExpr()) using an instance of this
124077** structure.
124078*/
124079struct CCurHint {
124080  int iTabCur;    /* Cursor for the main table */
124081  int iIdxCur;    /* Cursor for the index, if pIdx!=0.  Unused otherwise */
124082  Index *pIdx;    /* The index used to access the table */
124083};
124084
124085/*
124086** This function is called for every node of an expression that is a candidate
124087** for a cursor hint on an index cursor.  For TK_COLUMN nodes that reference
124088** the table CCurHint.iTabCur, verify that the same column can be
124089** accessed through the index.  If it cannot, then set pWalker->eCode to 1.
124090*/
124091static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
124092  struct CCurHint *pHint = pWalker->u.pCCurHint;
124093  assert( pHint->pIdx!=0 );
124094  if( pExpr->op==TK_COLUMN
124095   && pExpr->iTable==pHint->iTabCur
124096   && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
124097  ){
124098    pWalker->eCode = 1;
124099  }
124100  return WRC_Continue;
124101}
124102
124103/*
124104** Test whether or not expression pExpr, which was part of a WHERE clause,
124105** should be included in the cursor-hint for a table that is on the rhs
124106** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
124107** expression is not suitable.
124108**
124109** An expression is unsuitable if it might evaluate to non NULL even if
124110** a TK_COLUMN node that does affect the value of the expression is set
124111** to NULL. For example:
124112**
124113**   col IS NULL
124114**   col IS NOT NULL
124115**   coalesce(col, 1)
124116**   CASE WHEN col THEN 0 ELSE 1 END
124117*/
124118static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
124119  if( pExpr->op==TK_IS
124120   || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
124121   || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
124122  ){
124123    pWalker->eCode = 1;
124124  }else if( pExpr->op==TK_FUNCTION ){
124125    int d1;
124126    char d2[3];
124127    if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
124128      pWalker->eCode = 1;
124129    }
124130  }
124131
124132  return WRC_Continue;
124133}
124134
124135
124136/*
124137** This function is called on every node of an expression tree used as an
124138** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
124139** that accesses any table other than the one identified by
124140** CCurHint.iTabCur, then do the following:
124141**
124142**   1) allocate a register and code an OP_Column instruction to read
124143**      the specified column into the new register, and
124144**
124145**   2) transform the expression node to a TK_REGISTER node that reads
124146**      from the newly populated register.
124147**
124148** Also, if the node is a TK_COLUMN that does access the table idenified
124149** by pCCurHint.iTabCur, and an index is being used (which we will
124150** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
124151** an access of the index rather than the original table.
124152*/
124153static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
124154  int rc = WRC_Continue;
124155  struct CCurHint *pHint = pWalker->u.pCCurHint;
124156  if( pExpr->op==TK_COLUMN ){
124157    if( pExpr->iTable!=pHint->iTabCur ){
124158      Vdbe *v = pWalker->pParse->pVdbe;
124159      int reg = ++pWalker->pParse->nMem;   /* Register for column value */
124160      sqlite3ExprCodeGetColumnOfTable(
124161          v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
124162      );
124163      pExpr->op = TK_REGISTER;
124164      pExpr->iTable = reg;
124165    }else if( pHint->pIdx!=0 ){
124166      pExpr->iTable = pHint->iIdxCur;
124167      pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
124168      assert( pExpr->iColumn>=0 );
124169    }
124170  }else if( pExpr->op==TK_AGG_FUNCTION ){
124171    /* An aggregate function in the WHERE clause of a query means this must
124172    ** be a correlated sub-query, and expression pExpr is an aggregate from
124173    ** the parent context. Do not walk the function arguments in this case.
124174    **
124175    ** todo: It should be possible to replace this node with a TK_REGISTER
124176    ** expression, as the result of the expression must be stored in a
124177    ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
124178    rc = WRC_Prune;
124179  }
124180  return rc;
124181}
124182
124183/*
124184** Insert an OP_CursorHint instruction if it is appropriate to do so.
124185*/
124186static void codeCursorHint(
124187  struct SrcList_item *pTabItem,  /* FROM clause item */
124188  WhereInfo *pWInfo,    /* The where clause */
124189  WhereLevel *pLevel,   /* Which loop to provide hints for */
124190  WhereTerm *pEndRange  /* Hint this end-of-scan boundary term if not NULL */
124191){
124192  Parse *pParse = pWInfo->pParse;
124193  sqlite3 *db = pParse->db;
124194  Vdbe *v = pParse->pVdbe;
124195  Expr *pExpr = 0;
124196  WhereLoop *pLoop = pLevel->pWLoop;
124197  int iCur;
124198  WhereClause *pWC;
124199  WhereTerm *pTerm;
124200  int i, j;
124201  struct CCurHint sHint;
124202  Walker sWalker;
124203
124204  if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
124205  iCur = pLevel->iTabCur;
124206  assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
124207  sHint.iTabCur = iCur;
124208  sHint.iIdxCur = pLevel->iIdxCur;
124209  sHint.pIdx = pLoop->u.btree.pIndex;
124210  memset(&sWalker, 0, sizeof(sWalker));
124211  sWalker.pParse = pParse;
124212  sWalker.u.pCCurHint = &sHint;
124213  pWC = &pWInfo->sWC;
124214  for(i=0; i<pWC->nTerm; i++){
124215    pTerm = &pWC->a[i];
124216    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
124217    if( pTerm->prereqAll & pLevel->notReady ) continue;
124218
124219    /* Any terms specified as part of the ON(...) clause for any LEFT
124220    ** JOIN for which the current table is not the rhs are omitted
124221    ** from the cursor-hint.
124222    **
124223    ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
124224    ** that were specified as part of the WHERE clause must be excluded.
124225    ** This is to address the following:
124226    **
124227    **   SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
124228    **
124229    ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
124230    ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
124231    ** pushed down to the cursor, this row is filtered out, causing
124232    ** SQLite to synthesize a row of NULL values. Which does match the
124233    ** WHERE clause, and so the query returns a row. Which is incorrect.
124234    **
124235    ** For the same reason, WHERE terms such as:
124236    **
124237    **   WHERE 1 = (t2.c IS NULL)
124238    **
124239    ** are also excluded. See codeCursorHintIsOrFunction() for details.
124240    */
124241    if( pTabItem->fg.jointype & JT_LEFT ){
124242      Expr *pExpr = pTerm->pExpr;
124243      if( !ExprHasProperty(pExpr, EP_FromJoin)
124244       || pExpr->iRightJoinTable!=pTabItem->iCursor
124245      ){
124246        sWalker.eCode = 0;
124247        sWalker.xExprCallback = codeCursorHintIsOrFunction;
124248        sqlite3WalkExpr(&sWalker, pTerm->pExpr);
124249        if( sWalker.eCode ) continue;
124250      }
124251    }else{
124252      if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
124253    }
124254
124255    /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
124256    ** the cursor.  These terms are not needed as hints for a pure range
124257    ** scan (that has no == terms) so omit them. */
124258    if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
124259      for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
124260      if( j<pLoop->nLTerm ) continue;
124261    }
124262
124263    /* No subqueries or non-deterministic functions allowed */
124264    if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
124265
124266    /* For an index scan, make sure referenced columns are actually in
124267    ** the index. */
124268    if( sHint.pIdx!=0 ){
124269      sWalker.eCode = 0;
124270      sWalker.xExprCallback = codeCursorHintCheckExpr;
124271      sqlite3WalkExpr(&sWalker, pTerm->pExpr);
124272      if( sWalker.eCode ) continue;
124273    }
124274
124275    /* If we survive all prior tests, that means this term is worth hinting */
124276    pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
124277  }
124278  if( pExpr!=0 ){
124279    sWalker.xExprCallback = codeCursorHintFixExpr;
124280    sqlite3WalkExpr(&sWalker, pExpr);
124281    sqlite3VdbeAddOp4(v, OP_CursorHint,
124282                      (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
124283                      (const char*)pExpr, P4_EXPR);
124284  }
124285}
124286#else
124287# define codeCursorHint(A,B,C,D)  /* No-op */
124288#endif /* SQLITE_ENABLE_CURSOR_HINTS */
124289
124290/*
124291** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
124292** a rowid value just read from cursor iIdxCur, open on index pIdx. This
124293** function generates code to do a deferred seek of cursor iCur to the
124294** rowid stored in register iRowid.
124295**
124296** Normally, this is just:
124297**
124298**   OP_Seek $iCur $iRowid
124299**
124300** However, if the scan currently being coded is a branch of an OR-loop and
124301** the statement currently being coded is a SELECT, then P3 of the OP_Seek
124302** is set to iIdxCur and P4 is set to point to an array of integers
124303** containing one entry for each column of the table cursor iCur is open
124304** on. For each table column, if the column is the i'th column of the
124305** index, then the corresponding array entry is set to (i+1). If the column
124306** does not appear in the index at all, the array entry is set to 0.
124307*/
124308static void codeDeferredSeek(
124309  WhereInfo *pWInfo,              /* Where clause context */
124310  Index *pIdx,                    /* Index scan is using */
124311  int iCur,                       /* Cursor for IPK b-tree */
124312  int iIdxCur                     /* Index cursor */
124313){
124314  Parse *pParse = pWInfo->pParse; /* Parse context */
124315  Vdbe *v = pParse->pVdbe;        /* Vdbe to generate code within */
124316
124317  assert( iIdxCur>0 );
124318  assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
124319
124320  sqlite3VdbeAddOp3(v, OP_Seek, iIdxCur, 0, iCur);
124321  if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
124322   && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
124323  ){
124324    int i;
124325    Table *pTab = pIdx->pTable;
124326    int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
124327    if( ai ){
124328      ai[0] = pTab->nCol;
124329      for(i=0; i<pIdx->nColumn-1; i++){
124330        assert( pIdx->aiColumn[i]<pTab->nCol );
124331        if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
124332      }
124333      sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
124334    }
124335  }
124336}
124337
124338/*
124339** Generate code for the start of the iLevel-th loop in the WHERE clause
124340** implementation described by pWInfo.
124341*/
124342SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
124343  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
124344  int iLevel,          /* Which level of pWInfo->a[] should be coded */
124345  Bitmask notReady     /* Which tables are currently available */
124346){
124347  int j, k;            /* Loop counters */
124348  int iCur;            /* The VDBE cursor for the table */
124349  int addrNxt;         /* Where to jump to continue with the next IN case */
124350  int omitTable;       /* True if we use the index only */
124351  int bRev;            /* True if we need to scan in reverse order */
124352  WhereLevel *pLevel;  /* The where level to be coded */
124353  WhereLoop *pLoop;    /* The WhereLoop object being coded */
124354  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
124355  WhereTerm *pTerm;               /* A WHERE clause term */
124356  Parse *pParse;                  /* Parsing context */
124357  sqlite3 *db;                    /* Database connection */
124358  Vdbe *v;                        /* The prepared stmt under constructions */
124359  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
124360  int addrBrk;                    /* Jump here to break out of the loop */
124361  int addrCont;                   /* Jump here to continue with next cycle */
124362  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
124363  int iReleaseReg = 0;      /* Temp register to free before returning */
124364
124365  pParse = pWInfo->pParse;
124366  v = pParse->pVdbe;
124367  pWC = &pWInfo->sWC;
124368  db = pParse->db;
124369  pLevel = &pWInfo->a[iLevel];
124370  pLoop = pLevel->pWLoop;
124371  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
124372  iCur = pTabItem->iCursor;
124373  pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
124374  bRev = (pWInfo->revMask>>iLevel)&1;
124375  omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
124376           && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
124377  VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
124378
124379  /* Create labels for the "break" and "continue" instructions
124380  ** for the current loop.  Jump to addrBrk to break out of a loop.
124381  ** Jump to cont to go immediately to the next iteration of the
124382  ** loop.
124383  **
124384  ** When there is an IN operator, we also have a "addrNxt" label that
124385  ** means to continue with the next IN value combination.  When
124386  ** there are no IN operators in the constraints, the "addrNxt" label
124387  ** is the same as "addrBrk".
124388  */
124389  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
124390  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
124391
124392  /* If this is the right table of a LEFT OUTER JOIN, allocate and
124393  ** initialize a memory cell that records if this table matches any
124394  ** row of the left table of the join.
124395  */
124396  if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
124397    pLevel->iLeftJoin = ++pParse->nMem;
124398    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
124399    VdbeComment((v, "init LEFT JOIN no-match flag"));
124400  }
124401
124402  /* Special case of a FROM clause subquery implemented as a co-routine */
124403  if( pTabItem->fg.viaCoroutine ){
124404    int regYield = pTabItem->regReturn;
124405    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
124406    pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
124407    VdbeCoverage(v);
124408    VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
124409    pLevel->op = OP_Goto;
124410  }else
124411
124412#ifndef SQLITE_OMIT_VIRTUALTABLE
124413  if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
124414    /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
124415    **          to access the data.
124416    */
124417    int iReg;   /* P3 Value for OP_VFilter */
124418    int addrNotFound;
124419    int nConstraint = pLoop->nLTerm;
124420    int iIn;    /* Counter for IN constraints */
124421
124422    sqlite3ExprCachePush(pParse);
124423    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
124424    addrNotFound = pLevel->addrBrk;
124425    for(j=0; j<nConstraint; j++){
124426      int iTarget = iReg+j+2;
124427      pTerm = pLoop->aLTerm[j];
124428      if( NEVER(pTerm==0) ) continue;
124429      if( pTerm->eOperator & WO_IN ){
124430        codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
124431        addrNotFound = pLevel->addrNxt;
124432      }else{
124433        sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
124434      }
124435    }
124436    sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
124437    sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
124438    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
124439                      pLoop->u.vtab.idxStr,
124440                      pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
124441    VdbeCoverage(v);
124442    pLoop->u.vtab.needFree = 0;
124443    pLevel->p1 = iCur;
124444    pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
124445    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
124446    iIn = pLevel->u.in.nIn;
124447    for(j=nConstraint-1; j>=0; j--){
124448      pTerm = pLoop->aLTerm[j];
124449      if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
124450        disableTerm(pLevel, pTerm);
124451      }else if( (pTerm->eOperator & WO_IN)!=0 ){
124452        Expr *pCompare;  /* The comparison operator */
124453        Expr *pRight;    /* RHS of the comparison */
124454        VdbeOp *pOp;     /* Opcode to access the value of the IN constraint */
124455
124456        /* Reload the constraint value into reg[iReg+j+2].  The same value
124457        ** was loaded into the same register prior to the OP_VFilter, but
124458        ** the xFilter implementation might have changed the datatype or
124459        ** encoding of the value in the register, so it *must* be reloaded. */
124460        assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
124461        if( !db->mallocFailed ){
124462          assert( iIn>0 );
124463          pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
124464          assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
124465          assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
124466          assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
124467          testcase( pOp->opcode==OP_Rowid );
124468          sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
124469        }
124470
124471        /* Generate code that will continue to the next row if
124472        ** the IN constraint is not satisfied */
124473        pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0, 0);
124474        assert( pCompare!=0 || db->mallocFailed );
124475        if( pCompare ){
124476          pCompare->pLeft = pTerm->pExpr->pLeft;
124477          pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
124478          if( pRight ){
124479            pRight->iTable = iReg+j+2;
124480            sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
124481          }
124482          pCompare->pLeft = 0;
124483          sqlite3ExprDelete(db, pCompare);
124484        }
124485      }
124486    }
124487    /* These registers need to be preserved in case there is an IN operator
124488    ** loop.  So we could deallocate the registers here (and potentially
124489    ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0.  But it seems
124490    ** simpler and safer to simply not reuse the registers.
124491    **
124492    **    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
124493    */
124494    sqlite3ExprCachePop(pParse);
124495  }else
124496#endif /* SQLITE_OMIT_VIRTUALTABLE */
124497
124498  if( (pLoop->wsFlags & WHERE_IPK)!=0
124499   && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
124500  ){
124501    /* Case 2:  We can directly reference a single row using an
124502    **          equality comparison against the ROWID field.  Or
124503    **          we reference multiple rows using a "rowid IN (...)"
124504    **          construct.
124505    */
124506    assert( pLoop->u.btree.nEq==1 );
124507    pTerm = pLoop->aLTerm[0];
124508    assert( pTerm!=0 );
124509    assert( pTerm->pExpr!=0 );
124510    assert( omitTable==0 );
124511    testcase( pTerm->wtFlags & TERM_VIRTUAL );
124512    iReleaseReg = ++pParse->nMem;
124513    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
124514    if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
124515    addrNxt = pLevel->addrNxt;
124516    sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
124517    VdbeCoverage(v);
124518    sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
124519    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
124520    VdbeComment((v, "pk"));
124521    pLevel->op = OP_Noop;
124522  }else if( (pLoop->wsFlags & WHERE_IPK)!=0
124523         && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
124524  ){
124525    /* Case 3:  We have an inequality comparison against the ROWID field.
124526    */
124527    int testOp = OP_Noop;
124528    int start;
124529    int memEndValue = 0;
124530    WhereTerm *pStart, *pEnd;
124531
124532    assert( omitTable==0 );
124533    j = 0;
124534    pStart = pEnd = 0;
124535    if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
124536    if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
124537    assert( pStart!=0 || pEnd!=0 );
124538    if( bRev ){
124539      pTerm = pStart;
124540      pStart = pEnd;
124541      pEnd = pTerm;
124542    }
124543    codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
124544    if( pStart ){
124545      Expr *pX;             /* The expression that defines the start bound */
124546      int r1, rTemp;        /* Registers for holding the start boundary */
124547
124548      /* The following constant maps TK_xx codes into corresponding
124549      ** seek opcodes.  It depends on a particular ordering of TK_xx
124550      */
124551      const u8 aMoveOp[] = {
124552           /* TK_GT */  OP_SeekGT,
124553           /* TK_LE */  OP_SeekLE,
124554           /* TK_LT */  OP_SeekLT,
124555           /* TK_GE */  OP_SeekGE
124556      };
124557      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
124558      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
124559      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
124560
124561      assert( (pStart->wtFlags & TERM_VNULL)==0 );
124562      testcase( pStart->wtFlags & TERM_VIRTUAL );
124563      pX = pStart->pExpr;
124564      assert( pX!=0 );
124565      testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
124566      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
124567      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
124568      VdbeComment((v, "pk"));
124569      VdbeCoverageIf(v, pX->op==TK_GT);
124570      VdbeCoverageIf(v, pX->op==TK_LE);
124571      VdbeCoverageIf(v, pX->op==TK_LT);
124572      VdbeCoverageIf(v, pX->op==TK_GE);
124573      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
124574      sqlite3ReleaseTempReg(pParse, rTemp);
124575      disableTerm(pLevel, pStart);
124576    }else{
124577      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
124578      VdbeCoverageIf(v, bRev==0);
124579      VdbeCoverageIf(v, bRev!=0);
124580    }
124581    if( pEnd ){
124582      Expr *pX;
124583      pX = pEnd->pExpr;
124584      assert( pX!=0 );
124585      assert( (pEnd->wtFlags & TERM_VNULL)==0 );
124586      testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
124587      testcase( pEnd->wtFlags & TERM_VIRTUAL );
124588      memEndValue = ++pParse->nMem;
124589      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
124590      if( pX->op==TK_LT || pX->op==TK_GT ){
124591        testOp = bRev ? OP_Le : OP_Ge;
124592      }else{
124593        testOp = bRev ? OP_Lt : OP_Gt;
124594      }
124595      disableTerm(pLevel, pEnd);
124596    }
124597    start = sqlite3VdbeCurrentAddr(v);
124598    pLevel->op = bRev ? OP_Prev : OP_Next;
124599    pLevel->p1 = iCur;
124600    pLevel->p2 = start;
124601    assert( pLevel->p5==0 );
124602    if( testOp!=OP_Noop ){
124603      iRowidReg = ++pParse->nMem;
124604      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
124605      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
124606      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
124607      VdbeCoverageIf(v, testOp==OP_Le);
124608      VdbeCoverageIf(v, testOp==OP_Lt);
124609      VdbeCoverageIf(v, testOp==OP_Ge);
124610      VdbeCoverageIf(v, testOp==OP_Gt);
124611      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
124612    }
124613  }else if( pLoop->wsFlags & WHERE_INDEXED ){
124614    /* Case 4: A scan using an index.
124615    **
124616    **         The WHERE clause may contain zero or more equality
124617    **         terms ("==" or "IN" operators) that refer to the N
124618    **         left-most columns of the index. It may also contain
124619    **         inequality constraints (>, <, >= or <=) on the indexed
124620    **         column that immediately follows the N equalities. Only
124621    **         the right-most column can be an inequality - the rest must
124622    **         use the "==" and "IN" operators. For example, if the
124623    **         index is on (x,y,z), then the following clauses are all
124624    **         optimized:
124625    **
124626    **            x=5
124627    **            x=5 AND y=10
124628    **            x=5 AND y<10
124629    **            x=5 AND y>5 AND y<10
124630    **            x=5 AND y=5 AND z<=10
124631    **
124632    **         The z<10 term of the following cannot be used, only
124633    **         the x=5 term:
124634    **
124635    **            x=5 AND z<10
124636    **
124637    **         N may be zero if there are inequality constraints.
124638    **         If there are no inequality constraints, then N is at
124639    **         least one.
124640    **
124641    **         This case is also used when there are no WHERE clause
124642    **         constraints but an index is selected anyway, in order
124643    **         to force the output order to conform to an ORDER BY.
124644    */
124645    static const u8 aStartOp[] = {
124646      0,
124647      0,
124648      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
124649      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
124650      OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
124651      OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
124652      OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
124653      OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
124654    };
124655    static const u8 aEndOp[] = {
124656      OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
124657      OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
124658      OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
124659      OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
124660    };
124661    u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
124662    int regBase;                 /* Base register holding constraint values */
124663    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
124664    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
124665    int startEq;                 /* True if range start uses ==, >= or <= */
124666    int endEq;                   /* True if range end uses ==, >= or <= */
124667    int start_constraints;       /* Start of range is constrained */
124668    int nConstraint;             /* Number of constraint terms */
124669    Index *pIdx;                 /* The index we will be using */
124670    int iIdxCur;                 /* The VDBE cursor for the index */
124671    int nExtraReg = 0;           /* Number of extra registers needed */
124672    int op;                      /* Instruction opcode */
124673    char *zStartAff;             /* Affinity for start of range constraint */
124674    char cEndAff = 0;            /* Affinity for end of range constraint */
124675    u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
124676    u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
124677
124678    pIdx = pLoop->u.btree.pIndex;
124679    iIdxCur = pLevel->iIdxCur;
124680    assert( nEq>=pLoop->nSkip );
124681
124682    /* If this loop satisfies a sort order (pOrderBy) request that
124683    ** was passed to this function to implement a "SELECT min(x) ..."
124684    ** query, then the caller will only allow the loop to run for
124685    ** a single iteration. This means that the first row returned
124686    ** should not have a NULL value stored in 'x'. If column 'x' is
124687    ** the first one after the nEq equality constraints in the index,
124688    ** this requires some special handling.
124689    */
124690    assert( pWInfo->pOrderBy==0
124691         || pWInfo->pOrderBy->nExpr==1
124692         || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
124693    if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
124694     && pWInfo->nOBSat>0
124695     && (pIdx->nKeyCol>nEq)
124696    ){
124697      assert( pLoop->nSkip==0 );
124698      bSeekPastNull = 1;
124699      nExtraReg = 1;
124700    }
124701
124702    /* Find any inequality constraint terms for the start and end
124703    ** of the range.
124704    */
124705    j = nEq;
124706    if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
124707      pRangeStart = pLoop->aLTerm[j++];
124708      nExtraReg = 1;
124709      /* Like optimization range constraints always occur in pairs */
124710      assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
124711              (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
124712    }
124713    if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
124714      pRangeEnd = pLoop->aLTerm[j++];
124715      nExtraReg = 1;
124716#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
124717      if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
124718        assert( pRangeStart!=0 );                     /* LIKE opt constraints */
124719        assert( pRangeStart->wtFlags & TERM_LIKEOPT );   /* occur in pairs */
124720        pLevel->iLikeRepCntr = (u32)++pParse->nMem;
124721        sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
124722        VdbeComment((v, "LIKE loop counter"));
124723        pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
124724        /* iLikeRepCntr actually stores 2x the counter register number.  The
124725        ** bottom bit indicates whether the search order is ASC or DESC. */
124726        testcase( bRev );
124727        testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
124728        assert( (bRev & ~1)==0 );
124729        pLevel->iLikeRepCntr <<=1;
124730        pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
124731      }
124732#endif
124733      if( pRangeStart==0
124734       && (j = pIdx->aiColumn[nEq])>=0
124735       && pIdx->pTable->aCol[j].notNull==0
124736      ){
124737        bSeekPastNull = 1;
124738      }
124739    }
124740    assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
124741
124742    /* If we are doing a reverse order scan on an ascending index, or
124743    ** a forward order scan on a descending index, interchange the
124744    ** start and end terms (pRangeStart and pRangeEnd).
124745    */
124746    if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
124747     || (bRev && pIdx->nKeyCol==nEq)
124748    ){
124749      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
124750      SWAP(u8, bSeekPastNull, bStopAtNull);
124751    }
124752
124753    /* Generate code to evaluate all constraint terms using == or IN
124754    ** and store the values of those terms in an array of registers
124755    ** starting at regBase.
124756    */
124757    codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
124758    regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
124759    assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
124760    if( zStartAff ) cEndAff = zStartAff[nEq];
124761    addrNxt = pLevel->addrNxt;
124762
124763    testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
124764    testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
124765    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
124766    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
124767    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
124768    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
124769    start_constraints = pRangeStart || nEq>0;
124770
124771    /* Seek the index cursor to the start of the range. */
124772    nConstraint = nEq;
124773    if( pRangeStart ){
124774      Expr *pRight = pRangeStart->pExpr->pRight;
124775      sqlite3ExprCode(pParse, pRight, regBase+nEq);
124776      whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
124777      if( (pRangeStart->wtFlags & TERM_VNULL)==0
124778       && sqlite3ExprCanBeNull(pRight)
124779      ){
124780        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
124781        VdbeCoverage(v);
124782      }
124783      if( zStartAff ){
124784        if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){
124785          /* Since the comparison is to be performed with no conversions
124786          ** applied to the operands, set the affinity to apply to pRight to
124787          ** SQLITE_AFF_BLOB.  */
124788          zStartAff[nEq] = SQLITE_AFF_BLOB;
124789        }
124790        if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
124791          zStartAff[nEq] = SQLITE_AFF_BLOB;
124792        }
124793      }
124794      nConstraint++;
124795      testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
124796      bSeekPastNull = 0;
124797    }else if( bSeekPastNull ){
124798      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
124799      nConstraint++;
124800      startEq = 0;
124801      start_constraints = 1;
124802    }
124803    codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
124804    if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
124805      /* The skip-scan logic inside the call to codeAllEqualityConstraints()
124806      ** above has already left the cursor sitting on the correct row,
124807      ** so no further seeking is needed */
124808    }else{
124809      op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
124810      assert( op!=0 );
124811      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
124812      VdbeCoverage(v);
124813      VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
124814      VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
124815      VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
124816      VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
124817      VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
124818      VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
124819    }
124820
124821    /* Load the value for the inequality constraint at the end of the
124822    ** range (if any).
124823    */
124824    nConstraint = nEq;
124825    if( pRangeEnd ){
124826      Expr *pRight = pRangeEnd->pExpr->pRight;
124827      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
124828      sqlite3ExprCode(pParse, pRight, regBase+nEq);
124829      whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
124830      if( (pRangeEnd->wtFlags & TERM_VNULL)==0
124831       && sqlite3ExprCanBeNull(pRight)
124832      ){
124833        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
124834        VdbeCoverage(v);
124835      }
124836      if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB
124837       && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
124838      ){
124839        codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
124840      }
124841      nConstraint++;
124842      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
124843    }else if( bStopAtNull ){
124844      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
124845      endEq = 0;
124846      nConstraint++;
124847    }
124848    sqlite3DbFree(db, zStartAff);
124849
124850    /* Top of the loop body */
124851    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
124852
124853    /* Check if the index cursor is past the end of the range. */
124854    if( nConstraint ){
124855      op = aEndOp[bRev*2 + endEq];
124856      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
124857      testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
124858      testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
124859      testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
124860      testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
124861    }
124862
124863    /* Seek the table cursor, if required */
124864    disableTerm(pLevel, pRangeStart);
124865    disableTerm(pLevel, pRangeEnd);
124866    if( omitTable ){
124867      /* pIdx is a covering index.  No need to access the main table. */
124868    }else if( HasRowid(pIdx->pTable) ){
124869      if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE)!=0 ){
124870        iRowidReg = ++pParse->nMem;
124871        sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
124872        sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
124873        sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
124874        VdbeCoverage(v);
124875      }else{
124876        codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
124877      }
124878    }else if( iCur!=iIdxCur ){
124879      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
124880      iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
124881      for(j=0; j<pPk->nKeyCol; j++){
124882        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
124883        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
124884      }
124885      sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
124886                           iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
124887    }
124888
124889    /* Record the instruction used to terminate the loop. Disable
124890    ** WHERE clause terms made redundant by the index range scan.
124891    */
124892    if( pLoop->wsFlags & WHERE_ONEROW ){
124893      pLevel->op = OP_Noop;
124894    }else if( bRev ){
124895      pLevel->op = OP_Prev;
124896    }else{
124897      pLevel->op = OP_Next;
124898    }
124899    pLevel->p1 = iIdxCur;
124900    pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
124901    if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
124902      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
124903    }else{
124904      assert( pLevel->p5==0 );
124905    }
124906  }else
124907
124908#ifndef SQLITE_OMIT_OR_OPTIMIZATION
124909  if( pLoop->wsFlags & WHERE_MULTI_OR ){
124910    /* Case 5:  Two or more separately indexed terms connected by OR
124911    **
124912    ** Example:
124913    **
124914    **   CREATE TABLE t1(a,b,c,d);
124915    **   CREATE INDEX i1 ON t1(a);
124916    **   CREATE INDEX i2 ON t1(b);
124917    **   CREATE INDEX i3 ON t1(c);
124918    **
124919    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
124920    **
124921    ** In the example, there are three indexed terms connected by OR.
124922    ** The top of the loop looks like this:
124923    **
124924    **          Null       1                # Zero the rowset in reg 1
124925    **
124926    ** Then, for each indexed term, the following. The arguments to
124927    ** RowSetTest are such that the rowid of the current row is inserted
124928    ** into the RowSet. If it is already present, control skips the
124929    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
124930    **
124931    **        sqlite3WhereBegin(<term>)
124932    **          RowSetTest                  # Insert rowid into rowset
124933    **          Gosub      2 A
124934    **        sqlite3WhereEnd()
124935    **
124936    ** Following the above, code to terminate the loop. Label A, the target
124937    ** of the Gosub above, jumps to the instruction right after the Goto.
124938    **
124939    **          Null       1                # Zero the rowset in reg 1
124940    **          Goto       B                # The loop is finished.
124941    **
124942    **       A: <loop body>                 # Return data, whatever.
124943    **
124944    **          Return     2                # Jump back to the Gosub
124945    **
124946    **       B: <after the loop>
124947    **
124948    ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
124949    ** use an ephemeral index instead of a RowSet to record the primary
124950    ** keys of the rows we have already seen.
124951    **
124952    */
124953    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
124954    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
124955    Index *pCov = 0;             /* Potential covering index (or NULL) */
124956    int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
124957
124958    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
124959    int regRowset = 0;                        /* Register for RowSet object */
124960    int regRowid = 0;                         /* Register holding rowid */
124961    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
124962    int iRetInit;                             /* Address of regReturn init */
124963    int untestedTerms = 0;             /* Some terms not completely tested */
124964    int ii;                            /* Loop counter */
124965    u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
124966    Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
124967    Table *pTab = pTabItem->pTab;
124968
124969    pTerm = pLoop->aLTerm[0];
124970    assert( pTerm!=0 );
124971    assert( pTerm->eOperator & WO_OR );
124972    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
124973    pOrWc = &pTerm->u.pOrInfo->wc;
124974    pLevel->op = OP_Return;
124975    pLevel->p1 = regReturn;
124976
124977    /* Set up a new SrcList in pOrTab containing the table being scanned
124978    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
124979    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
124980    */
124981    if( pWInfo->nLevel>1 ){
124982      int nNotReady;                 /* The number of notReady tables */
124983      struct SrcList_item *origSrc;     /* Original list of tables */
124984      nNotReady = pWInfo->nLevel - iLevel - 1;
124985      pOrTab = sqlite3StackAllocRaw(db,
124986                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
124987      if( pOrTab==0 ) return notReady;
124988      pOrTab->nAlloc = (u8)(nNotReady + 1);
124989      pOrTab->nSrc = pOrTab->nAlloc;
124990      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
124991      origSrc = pWInfo->pTabList->a;
124992      for(k=1; k<=nNotReady; k++){
124993        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
124994      }
124995    }else{
124996      pOrTab = pWInfo->pTabList;
124997    }
124998
124999    /* Initialize the rowset register to contain NULL. An SQL NULL is
125000    ** equivalent to an empty rowset.  Or, create an ephemeral index
125001    ** capable of holding primary keys in the case of a WITHOUT ROWID.
125002    **
125003    ** Also initialize regReturn to contain the address of the instruction
125004    ** immediately following the OP_Return at the bottom of the loop. This
125005    ** is required in a few obscure LEFT JOIN cases where control jumps
125006    ** over the top of the loop into the body of it. In this case the
125007    ** correct response for the end-of-loop code (the OP_Return) is to
125008    ** fall through to the next instruction, just as an OP_Next does if
125009    ** called on an uninitialized cursor.
125010    */
125011    if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
125012      if( HasRowid(pTab) ){
125013        regRowset = ++pParse->nMem;
125014        sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
125015      }else{
125016        Index *pPk = sqlite3PrimaryKeyIndex(pTab);
125017        regRowset = pParse->nTab++;
125018        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
125019        sqlite3VdbeSetP4KeyInfo(pParse, pPk);
125020      }
125021      regRowid = ++pParse->nMem;
125022    }
125023    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
125024
125025    /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
125026    ** Then for every term xN, evaluate as the subexpression: xN AND z
125027    ** That way, terms in y that are factored into the disjunction will
125028    ** be picked up by the recursive calls to sqlite3WhereBegin() below.
125029    **
125030    ** Actually, each subexpression is converted to "xN AND w" where w is
125031    ** the "interesting" terms of z - terms that did not originate in the
125032    ** ON or USING clause of a LEFT JOIN, and terms that are usable as
125033    ** indices.
125034    **
125035    ** This optimization also only applies if the (x1 OR x2 OR ...) term
125036    ** is not contained in the ON clause of a LEFT JOIN.
125037    ** See ticket http://www.sqlite.org/src/info/f2369304e4
125038    */
125039    if( pWC->nTerm>1 ){
125040      int iTerm;
125041      for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
125042        Expr *pExpr = pWC->a[iTerm].pExpr;
125043        if( &pWC->a[iTerm] == pTerm ) continue;
125044        if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
125045        testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
125046        testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
125047        if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
125048        if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
125049        testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
125050        pExpr = sqlite3ExprDup(db, pExpr, 0);
125051        pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
125052      }
125053      if( pAndExpr ){
125054        pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr, 0);
125055      }
125056    }
125057
125058    /* Run a separate WHERE clause for each term of the OR clause.  After
125059    ** eliminating duplicates from other WHERE clauses, the action for each
125060    ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
125061    */
125062    wctrlFlags =  WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
125063    for(ii=0; ii<pOrWc->nTerm; ii++){
125064      WhereTerm *pOrTerm = &pOrWc->a[ii];
125065      if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
125066        WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
125067        Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
125068        int jmp1 = 0;                   /* Address of jump operation */
125069        if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
125070          pAndExpr->pLeft = pOrExpr;
125071          pOrExpr = pAndExpr;
125072        }
125073        /* Loop through table entries that match term pOrTerm. */
125074        WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
125075        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
125076                                      wctrlFlags, iCovCur);
125077        assert( pSubWInfo || pParse->nErr || db->mallocFailed );
125078        if( pSubWInfo ){
125079          WhereLoop *pSubLoop;
125080          int addrExplain = sqlite3WhereExplainOneScan(
125081              pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
125082          );
125083          sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
125084
125085          /* This is the sub-WHERE clause body.  First skip over
125086          ** duplicate rows from prior sub-WHERE clauses, and record the
125087          ** rowid (or PRIMARY KEY) for the current row so that the same
125088          ** row will be skipped in subsequent sub-WHERE clauses.
125089          */
125090          if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
125091            int r;
125092            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
125093            if( HasRowid(pTab) ){
125094              r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
125095              jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
125096                                           r,iSet);
125097              VdbeCoverage(v);
125098            }else{
125099              Index *pPk = sqlite3PrimaryKeyIndex(pTab);
125100              int nPk = pPk->nKeyCol;
125101              int iPk;
125102
125103              /* Read the PK into an array of temp registers. */
125104              r = sqlite3GetTempRange(pParse, nPk);
125105              for(iPk=0; iPk<nPk; iPk++){
125106                int iCol = pPk->aiColumn[iPk];
125107                sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
125108              }
125109
125110              /* Check if the temp table already contains this key. If so,
125111              ** the row has already been included in the result set and
125112              ** can be ignored (by jumping past the Gosub below). Otherwise,
125113              ** insert the key into the temp table and proceed with processing
125114              ** the row.
125115              **
125116              ** Use some of the same optimizations as OP_RowSetTest: If iSet
125117              ** is zero, assume that the key cannot already be present in
125118              ** the temp table. And if iSet is -1, assume that there is no
125119              ** need to insert the key into the temp table, as it will never
125120              ** be tested for.  */
125121              if( iSet ){
125122                jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
125123                VdbeCoverage(v);
125124              }
125125              if( iSet>=0 ){
125126                sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
125127                sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
125128                if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
125129              }
125130
125131              /* Release the array of temp registers */
125132              sqlite3ReleaseTempRange(pParse, r, nPk);
125133            }
125134          }
125135
125136          /* Invoke the main loop body as a subroutine */
125137          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
125138
125139          /* Jump here (skipping the main loop body subroutine) if the
125140          ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
125141          if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
125142
125143          /* The pSubWInfo->untestedTerms flag means that this OR term
125144          ** contained one or more AND term from a notReady table.  The
125145          ** terms from the notReady table could not be tested and will
125146          ** need to be tested later.
125147          */
125148          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
125149
125150          /* If all of the OR-connected terms are optimized using the same
125151          ** index, and the index is opened using the same cursor number
125152          ** by each call to sqlite3WhereBegin() made by this loop, it may
125153          ** be possible to use that index as a covering index.
125154          **
125155          ** If the call to sqlite3WhereBegin() above resulted in a scan that
125156          ** uses an index, and this is either the first OR-connected term
125157          ** processed or the index is the same as that used by all previous
125158          ** terms, set pCov to the candidate covering index. Otherwise, set
125159          ** pCov to NULL to indicate that no candidate covering index will
125160          ** be available.
125161          */
125162          pSubLoop = pSubWInfo->a[0].pWLoop;
125163          assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
125164          if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
125165           && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
125166           && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
125167          ){
125168            assert( pSubWInfo->a[0].iIdxCur==iCovCur );
125169            pCov = pSubLoop->u.btree.pIndex;
125170          }else{
125171            pCov = 0;
125172          }
125173
125174          /* Finish the loop through table entries that match term pOrTerm. */
125175          sqlite3WhereEnd(pSubWInfo);
125176        }
125177      }
125178    }
125179    pLevel->u.pCovidx = pCov;
125180    if( pCov ) pLevel->iIdxCur = iCovCur;
125181    if( pAndExpr ){
125182      pAndExpr->pLeft = 0;
125183      sqlite3ExprDelete(db, pAndExpr);
125184    }
125185    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
125186    sqlite3VdbeGoto(v, pLevel->addrBrk);
125187    sqlite3VdbeResolveLabel(v, iLoopBody);
125188
125189    if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
125190    if( !untestedTerms ) disableTerm(pLevel, pTerm);
125191  }else
125192#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
125193
125194  {
125195    /* Case 6:  There is no usable index.  We must do a complete
125196    **          scan of the entire table.
125197    */
125198    static const u8 aStep[] = { OP_Next, OP_Prev };
125199    static const u8 aStart[] = { OP_Rewind, OP_Last };
125200    assert( bRev==0 || bRev==1 );
125201    if( pTabItem->fg.isRecursive ){
125202      /* Tables marked isRecursive have only a single row that is stored in
125203      ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
125204      pLevel->op = OP_Noop;
125205    }else{
125206      codeCursorHint(pTabItem, pWInfo, pLevel, 0);
125207      pLevel->op = aStep[bRev];
125208      pLevel->p1 = iCur;
125209      pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
125210      VdbeCoverageIf(v, bRev==0);
125211      VdbeCoverageIf(v, bRev!=0);
125212      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
125213    }
125214  }
125215
125216#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
125217  pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
125218#endif
125219
125220  /* Insert code to test every subexpression that can be completely
125221  ** computed using the current set of tables.
125222  */
125223  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
125224    Expr *pE;
125225    int skipLikeAddr = 0;
125226    testcase( pTerm->wtFlags & TERM_VIRTUAL );
125227    testcase( pTerm->wtFlags & TERM_CODED );
125228    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
125229    if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
125230      testcase( pWInfo->untestedTerms==0
125231               && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
125232      pWInfo->untestedTerms = 1;
125233      continue;
125234    }
125235    pE = pTerm->pExpr;
125236    assert( pE!=0 );
125237    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
125238      continue;
125239    }
125240    if( pTerm->wtFlags & TERM_LIKECOND ){
125241      /* If the TERM_LIKECOND flag is set, that means that the range search
125242      ** is sufficient to guarantee that the LIKE operator is true, so we
125243      ** can skip the call to the like(A,B) function.  But this only works
125244      ** for strings.  So do not skip the call to the function on the pass
125245      ** that compares BLOBs. */
125246#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
125247      continue;
125248#else
125249      u32 x = pLevel->iLikeRepCntr;
125250      assert( x>0 );
125251      skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)? OP_IfNot : OP_If, (int)(x>>1));
125252      VdbeCoverage(v);
125253#endif
125254    }
125255    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
125256    if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
125257    pTerm->wtFlags |= TERM_CODED;
125258  }
125259
125260  /* Insert code to test for implied constraints based on transitivity
125261  ** of the "==" operator.
125262  **
125263  ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
125264  ** and we are coding the t1 loop and the t2 loop has not yet coded,
125265  ** then we cannot use the "t1.a=t2.b" constraint, but we can code
125266  ** the implied "t1.a=123" constraint.
125267  */
125268  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
125269    Expr *pE, *pEAlt;
125270    WhereTerm *pAlt;
125271    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
125272    if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
125273    if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
125274    if( pTerm->leftCursor!=iCur ) continue;
125275    if( pLevel->iLeftJoin ) continue;
125276    pE = pTerm->pExpr;
125277    assert( !ExprHasProperty(pE, EP_FromJoin) );
125278    assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
125279    pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
125280                    WO_EQ|WO_IN|WO_IS, 0);
125281    if( pAlt==0 ) continue;
125282    if( pAlt->wtFlags & (TERM_CODED) ) continue;
125283    testcase( pAlt->eOperator & WO_EQ );
125284    testcase( pAlt->eOperator & WO_IS );
125285    testcase( pAlt->eOperator & WO_IN );
125286    VdbeModuleComment((v, "begin transitive constraint"));
125287    pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
125288    if( pEAlt ){
125289      *pEAlt = *pAlt->pExpr;
125290      pEAlt->pLeft = pE->pLeft;
125291      sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
125292      sqlite3StackFree(db, pEAlt);
125293    }
125294  }
125295
125296  /* For a LEFT OUTER JOIN, generate code that will record the fact that
125297  ** at least one row of the right table has matched the left table.
125298  */
125299  if( pLevel->iLeftJoin ){
125300    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
125301    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
125302    VdbeComment((v, "record LEFT JOIN hit"));
125303    sqlite3ExprCacheClear(pParse);
125304    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
125305      testcase( pTerm->wtFlags & TERM_VIRTUAL );
125306      testcase( pTerm->wtFlags & TERM_CODED );
125307      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
125308      if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
125309        assert( pWInfo->untestedTerms );
125310        continue;
125311      }
125312      assert( pTerm->pExpr );
125313      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
125314      pTerm->wtFlags |= TERM_CODED;
125315    }
125316  }
125317
125318  return pLevel->notReady;
125319}
125320
125321/************** End of wherecode.c *******************************************/
125322/************** Begin file whereexpr.c ***************************************/
125323/*
125324** 2015-06-08
125325**
125326** The author disclaims copyright to this source code.  In place of
125327** a legal notice, here is a blessing:
125328**
125329**    May you do good and not evil.
125330**    May you find forgiveness for yourself and forgive others.
125331**    May you share freely, never taking more than you give.
125332**
125333*************************************************************************
125334** This module contains C code that generates VDBE code used to process
125335** the WHERE clause of SQL statements.
125336**
125337** This file was originally part of where.c but was split out to improve
125338** readability and editabiliity.  This file contains utility routines for
125339** analyzing Expr objects in the WHERE clause.
125340*/
125341/* #include "sqliteInt.h" */
125342/* #include "whereInt.h" */
125343
125344/* Forward declarations */
125345static void exprAnalyze(SrcList*, WhereClause*, int);
125346
125347/*
125348** Deallocate all memory associated with a WhereOrInfo object.
125349*/
125350static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
125351  sqlite3WhereClauseClear(&p->wc);
125352  sqlite3DbFree(db, p);
125353}
125354
125355/*
125356** Deallocate all memory associated with a WhereAndInfo object.
125357*/
125358static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
125359  sqlite3WhereClauseClear(&p->wc);
125360  sqlite3DbFree(db, p);
125361}
125362
125363/*
125364** Add a single new WhereTerm entry to the WhereClause object pWC.
125365** The new WhereTerm object is constructed from Expr p and with wtFlags.
125366** The index in pWC->a[] of the new WhereTerm is returned on success.
125367** 0 is returned if the new WhereTerm could not be added due to a memory
125368** allocation error.  The memory allocation failure will be recorded in
125369** the db->mallocFailed flag so that higher-level functions can detect it.
125370**
125371** This routine will increase the size of the pWC->a[] array as necessary.
125372**
125373** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
125374** for freeing the expression p is assumed by the WhereClause object pWC.
125375** This is true even if this routine fails to allocate a new WhereTerm.
125376**
125377** WARNING:  This routine might reallocate the space used to store
125378** WhereTerms.  All pointers to WhereTerms should be invalidated after
125379** calling this routine.  Such pointers may be reinitialized by referencing
125380** the pWC->a[] array.
125381*/
125382static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
125383  WhereTerm *pTerm;
125384  int idx;
125385  testcase( wtFlags & TERM_VIRTUAL );
125386  if( pWC->nTerm>=pWC->nSlot ){
125387    WhereTerm *pOld = pWC->a;
125388    sqlite3 *db = pWC->pWInfo->pParse->db;
125389    pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
125390    if( pWC->a==0 ){
125391      if( wtFlags & TERM_DYNAMIC ){
125392        sqlite3ExprDelete(db, p);
125393      }
125394      pWC->a = pOld;
125395      return 0;
125396    }
125397    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
125398    if( pOld!=pWC->aStatic ){
125399      sqlite3DbFree(db, pOld);
125400    }
125401    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
125402    memset(&pWC->a[pWC->nTerm], 0, sizeof(pWC->a[0])*(pWC->nSlot-pWC->nTerm));
125403  }
125404  pTerm = &pWC->a[idx = pWC->nTerm++];
125405  if( p && ExprHasProperty(p, EP_Unlikely) ){
125406    pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
125407  }else{
125408    pTerm->truthProb = 1;
125409  }
125410  pTerm->pExpr = sqlite3ExprSkipCollate(p);
125411  pTerm->wtFlags = wtFlags;
125412  pTerm->pWC = pWC;
125413  pTerm->iParent = -1;
125414  return idx;
125415}
125416
125417/*
125418** Return TRUE if the given operator is one of the operators that is
125419** allowed for an indexable WHERE clause term.  The allowed operators are
125420** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
125421*/
125422static int allowedOp(int op){
125423  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
125424  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
125425  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
125426  assert( TK_GE==TK_EQ+4 );
125427  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
125428}
125429
125430/*
125431** Commute a comparison operator.  Expressions of the form "X op Y"
125432** are converted into "Y op X".
125433**
125434** If left/right precedence rules come into play when determining the
125435** collating sequence, then COLLATE operators are adjusted to ensure
125436** that the collating sequence does not change.  For example:
125437** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
125438** the left hand side of a comparison overrides any collation sequence
125439** attached to the right. For the same reason the EP_Collate flag
125440** is not commuted.
125441*/
125442static void exprCommute(Parse *pParse, Expr *pExpr){
125443  u16 expRight = (pExpr->pRight->flags & EP_Collate);
125444  u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
125445  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
125446  if( expRight==expLeft ){
125447    /* Either X and Y both have COLLATE operator or neither do */
125448    if( expRight ){
125449      /* Both X and Y have COLLATE operators.  Make sure X is always
125450      ** used by clearing the EP_Collate flag from Y. */
125451      pExpr->pRight->flags &= ~EP_Collate;
125452    }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
125453      /* Neither X nor Y have COLLATE operators, but X has a non-default
125454      ** collating sequence.  So add the EP_Collate marker on X to cause
125455      ** it to be searched first. */
125456      pExpr->pLeft->flags |= EP_Collate;
125457    }
125458  }
125459  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
125460  if( pExpr->op>=TK_GT ){
125461    assert( TK_LT==TK_GT+2 );
125462    assert( TK_GE==TK_LE+2 );
125463    assert( TK_GT>TK_EQ );
125464    assert( TK_GT<TK_LE );
125465    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
125466    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
125467  }
125468}
125469
125470/*
125471** Translate from TK_xx operator to WO_xx bitmask.
125472*/
125473static u16 operatorMask(int op){
125474  u16 c;
125475  assert( allowedOp(op) );
125476  if( op==TK_IN ){
125477    c = WO_IN;
125478  }else if( op==TK_ISNULL ){
125479    c = WO_ISNULL;
125480  }else if( op==TK_IS ){
125481    c = WO_IS;
125482  }else{
125483    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
125484    c = (u16)(WO_EQ<<(op-TK_EQ));
125485  }
125486  assert( op!=TK_ISNULL || c==WO_ISNULL );
125487  assert( op!=TK_IN || c==WO_IN );
125488  assert( op!=TK_EQ || c==WO_EQ );
125489  assert( op!=TK_LT || c==WO_LT );
125490  assert( op!=TK_LE || c==WO_LE );
125491  assert( op!=TK_GT || c==WO_GT );
125492  assert( op!=TK_GE || c==WO_GE );
125493  assert( op!=TK_IS || c==WO_IS );
125494  return c;
125495}
125496
125497
125498#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
125499/*
125500** Check to see if the given expression is a LIKE or GLOB operator that
125501** can be optimized using inequality constraints.  Return TRUE if it is
125502** so and false if not.
125503**
125504** In order for the operator to be optimizible, the RHS must be a string
125505** literal that does not begin with a wildcard.  The LHS must be a column
125506** that may only be NULL, a string, or a BLOB, never a number. (This means
125507** that virtual tables cannot participate in the LIKE optimization.)  The
125508** collating sequence for the column on the LHS must be appropriate for
125509** the operator.
125510*/
125511static int isLikeOrGlob(
125512  Parse *pParse,    /* Parsing and code generating context */
125513  Expr *pExpr,      /* Test this expression */
125514  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
125515  int *pisComplete, /* True if the only wildcard is % in the last character */
125516  int *pnoCase      /* True if uppercase is equivalent to lowercase */
125517){
125518  const char *z = 0;         /* String on RHS of LIKE operator */
125519  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
125520  ExprList *pList;           /* List of operands to the LIKE operator */
125521  int c;                     /* One character in z[] */
125522  int cnt;                   /* Number of non-wildcard prefix characters */
125523  char wc[3];                /* Wildcard characters */
125524  sqlite3 *db = pParse->db;  /* Database connection */
125525  sqlite3_value *pVal = 0;
125526  int op;                    /* Opcode of pRight */
125527  int rc;                    /* Result code to return */
125528
125529  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
125530    return 0;
125531  }
125532#ifdef SQLITE_EBCDIC
125533  if( *pnoCase ) return 0;
125534#endif
125535  pList = pExpr->x.pList;
125536  pLeft = pList->a[1].pExpr;
125537  if( pLeft->op!=TK_COLUMN
125538   || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
125539   || IsVirtual(pLeft->pTab)  /* Value might be numeric */
125540  ){
125541    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
125542    ** be the name of an indexed column with TEXT affinity. */
125543    return 0;
125544  }
125545  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
125546
125547  pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
125548  op = pRight->op;
125549  if( op==TK_VARIABLE ){
125550    Vdbe *pReprepare = pParse->pReprepare;
125551    int iCol = pRight->iColumn;
125552    pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
125553    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
125554      z = (char *)sqlite3_value_text(pVal);
125555    }
125556    sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
125557    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
125558  }else if( op==TK_STRING ){
125559    z = pRight->u.zToken;
125560  }
125561  if( z ){
125562    cnt = 0;
125563    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
125564      cnt++;
125565    }
125566    if( cnt!=0 && 255!=(u8)z[cnt-1] ){
125567      Expr *pPrefix;
125568      *pisComplete = c==wc[0] && z[cnt+1]==0;
125569      pPrefix = sqlite3Expr(db, TK_STRING, z);
125570      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
125571      *ppPrefix = pPrefix;
125572      if( op==TK_VARIABLE ){
125573        Vdbe *v = pParse->pVdbe;
125574        sqlite3VdbeSetVarmask(v, pRight->iColumn);
125575        if( *pisComplete && pRight->u.zToken[1] ){
125576          /* If the rhs of the LIKE expression is a variable, and the current
125577          ** value of the variable means there is no need to invoke the LIKE
125578          ** function, then no OP_Variable will be added to the program.
125579          ** This causes problems for the sqlite3_bind_parameter_name()
125580          ** API. To work around them, add a dummy OP_Variable here.
125581          */
125582          int r1 = sqlite3GetTempReg(pParse);
125583          sqlite3ExprCodeTarget(pParse, pRight, r1);
125584          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
125585          sqlite3ReleaseTempReg(pParse, r1);
125586        }
125587      }
125588    }else{
125589      z = 0;
125590    }
125591  }
125592
125593  rc = (z!=0);
125594  sqlite3ValueFree(pVal);
125595  return rc;
125596}
125597#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
125598
125599
125600#ifndef SQLITE_OMIT_VIRTUALTABLE
125601/*
125602** Check to see if the given expression is of the form
125603**
125604**         column OP expr
125605**
125606** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a
125607** column of a virtual table.
125608**
125609** If it is then return TRUE.  If not, return FALSE.
125610*/
125611static int isMatchOfColumn(
125612  Expr *pExpr,                    /* Test this expression */
125613  unsigned char *peOp2            /* OUT: 0 for MATCH, or else an op2 value */
125614){
125615  struct Op2 {
125616    const char *zOp;
125617    unsigned char eOp2;
125618  } aOp[] = {
125619    { "match",  SQLITE_INDEX_CONSTRAINT_MATCH },
125620    { "glob",   SQLITE_INDEX_CONSTRAINT_GLOB },
125621    { "like",   SQLITE_INDEX_CONSTRAINT_LIKE },
125622    { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
125623  };
125624  ExprList *pList;
125625  Expr *pCol;                     /* Column reference */
125626  int i;
125627
125628  if( pExpr->op!=TK_FUNCTION ){
125629    return 0;
125630  }
125631  pList = pExpr->x.pList;
125632  if( pList==0 || pList->nExpr!=2 ){
125633    return 0;
125634  }
125635  pCol = pList->a[1].pExpr;
125636  if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
125637    return 0;
125638  }
125639  for(i=0; i<ArraySize(aOp); i++){
125640    if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
125641      *peOp2 = aOp[i].eOp2;
125642      return 1;
125643    }
125644  }
125645  return 0;
125646}
125647#endif /* SQLITE_OMIT_VIRTUALTABLE */
125648
125649/*
125650** If the pBase expression originated in the ON or USING clause of
125651** a join, then transfer the appropriate markings over to derived.
125652*/
125653static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
125654  if( pDerived ){
125655    pDerived->flags |= pBase->flags & EP_FromJoin;
125656    pDerived->iRightJoinTable = pBase->iRightJoinTable;
125657  }
125658}
125659
125660/*
125661** Mark term iChild as being a child of term iParent
125662*/
125663static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
125664  pWC->a[iChild].iParent = iParent;
125665  pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
125666  pWC->a[iParent].nChild++;
125667}
125668
125669/*
125670** Return the N-th AND-connected subterm of pTerm.  Or if pTerm is not
125671** a conjunction, then return just pTerm when N==0.  If N is exceeds
125672** the number of available subterms, return NULL.
125673*/
125674static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
125675  if( pTerm->eOperator!=WO_AND ){
125676    return N==0 ? pTerm : 0;
125677  }
125678  if( N<pTerm->u.pAndInfo->wc.nTerm ){
125679    return &pTerm->u.pAndInfo->wc.a[N];
125680  }
125681  return 0;
125682}
125683
125684/*
125685** Subterms pOne and pTwo are contained within WHERE clause pWC.  The
125686** two subterms are in disjunction - they are OR-ed together.
125687**
125688** If these two terms are both of the form:  "A op B" with the same
125689** A and B values but different operators and if the operators are
125690** compatible (if one is = and the other is <, for example) then
125691** add a new virtual AND term to pWC that is the combination of the
125692** two.
125693**
125694** Some examples:
125695**
125696**    x<y OR x=y    -->     x<=y
125697**    x=y OR x=y    -->     x=y
125698**    x<=y OR x<y   -->     x<=y
125699**
125700** The following is NOT generated:
125701**
125702**    x<y OR x>y    -->     x!=y
125703*/
125704static void whereCombineDisjuncts(
125705  SrcList *pSrc,         /* the FROM clause */
125706  WhereClause *pWC,      /* The complete WHERE clause */
125707  WhereTerm *pOne,       /* First disjunct */
125708  WhereTerm *pTwo        /* Second disjunct */
125709){
125710  u16 eOp = pOne->eOperator | pTwo->eOperator;
125711  sqlite3 *db;           /* Database connection (for malloc) */
125712  Expr *pNew;            /* New virtual expression */
125713  int op;                /* Operator for the combined expression */
125714  int idxNew;            /* Index in pWC of the next virtual term */
125715
125716  if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
125717  if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
125718  if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
125719   && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
125720  assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
125721  assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
125722  if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
125723  if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
125724  /* If we reach this point, it means the two subterms can be combined */
125725  if( (eOp & (eOp-1))!=0 ){
125726    if( eOp & (WO_LT|WO_LE) ){
125727      eOp = WO_LE;
125728    }else{
125729      assert( eOp & (WO_GT|WO_GE) );
125730      eOp = WO_GE;
125731    }
125732  }
125733  db = pWC->pWInfo->pParse->db;
125734  pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
125735  if( pNew==0 ) return;
125736  for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
125737  pNew->op = op;
125738  idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
125739  exprAnalyze(pSrc, pWC, idxNew);
125740}
125741
125742#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
125743/*
125744** Analyze a term that consists of two or more OR-connected
125745** subterms.  So in:
125746**
125747**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
125748**                          ^^^^^^^^^^^^^^^^^^^^
125749**
125750** This routine analyzes terms such as the middle term in the above example.
125751** A WhereOrTerm object is computed and attached to the term under
125752** analysis, regardless of the outcome of the analysis.  Hence:
125753**
125754**     WhereTerm.wtFlags   |=  TERM_ORINFO
125755**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
125756**
125757** The term being analyzed must have two or more of OR-connected subterms.
125758** A single subterm might be a set of AND-connected sub-subterms.
125759** Examples of terms under analysis:
125760**
125761**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
125762**     (B)     x=expr1 OR expr2=x OR x=expr3
125763**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
125764**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
125765**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
125766**     (F)     x>A OR (x=A AND y>=B)
125767**
125768** CASE 1:
125769**
125770** If all subterms are of the form T.C=expr for some single column of C and
125771** a single table T (as shown in example B above) then create a new virtual
125772** term that is an equivalent IN expression.  In other words, if the term
125773** being analyzed is:
125774**
125775**      x = expr1  OR  expr2 = x  OR  x = expr3
125776**
125777** then create a new virtual term like this:
125778**
125779**      x IN (expr1,expr2,expr3)
125780**
125781** CASE 2:
125782**
125783** If there are exactly two disjuncts and one side has x>A and the other side
125784** has x=A (for the same x and A) then add a new virtual conjunct term to the
125785** WHERE clause of the form "x>=A".  Example:
125786**
125787**      x>A OR (x=A AND y>B)    adds:    x>=A
125788**
125789** The added conjunct can sometimes be helpful in query planning.
125790**
125791** CASE 3:
125792**
125793** If all subterms are indexable by a single table T, then set
125794**
125795**     WhereTerm.eOperator              =  WO_OR
125796**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
125797**
125798** A subterm is "indexable" if it is of the form
125799** "T.C <op> <expr>" where C is any column of table T and
125800** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
125801** A subterm is also indexable if it is an AND of two or more
125802** subsubterms at least one of which is indexable.  Indexable AND
125803** subterms have their eOperator set to WO_AND and they have
125804** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
125805**
125806** From another point of view, "indexable" means that the subterm could
125807** potentially be used with an index if an appropriate index exists.
125808** This analysis does not consider whether or not the index exists; that
125809** is decided elsewhere.  This analysis only looks at whether subterms
125810** appropriate for indexing exist.
125811**
125812** All examples A through E above satisfy case 3.  But if a term
125813** also satisfies case 1 (such as B) we know that the optimizer will
125814** always prefer case 1, so in that case we pretend that case 3 is not
125815** satisfied.
125816**
125817** It might be the case that multiple tables are indexable.  For example,
125818** (E) above is indexable on tables P, Q, and R.
125819**
125820** Terms that satisfy case 3 are candidates for lookup by using
125821** separate indices to find rowids for each subterm and composing
125822** the union of all rowids using a RowSet object.  This is similar
125823** to "bitmap indices" in other database engines.
125824**
125825** OTHERWISE:
125826**
125827** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
125828** zero.  This term is not useful for search.
125829*/
125830static void exprAnalyzeOrTerm(
125831  SrcList *pSrc,            /* the FROM clause */
125832  WhereClause *pWC,         /* the complete WHERE clause */
125833  int idxTerm               /* Index of the OR-term to be analyzed */
125834){
125835  WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
125836  Parse *pParse = pWInfo->pParse;         /* Parser context */
125837  sqlite3 *db = pParse->db;               /* Database connection */
125838  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
125839  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
125840  int i;                                  /* Loop counters */
125841  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
125842  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
125843  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
125844  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
125845  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
125846
125847  /*
125848  ** Break the OR clause into its separate subterms.  The subterms are
125849  ** stored in a WhereClause structure containing within the WhereOrInfo
125850  ** object that is attached to the original OR clause term.
125851  */
125852  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
125853  assert( pExpr->op==TK_OR );
125854  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
125855  if( pOrInfo==0 ) return;
125856  pTerm->wtFlags |= TERM_ORINFO;
125857  pOrWc = &pOrInfo->wc;
125858  memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
125859  sqlite3WhereClauseInit(pOrWc, pWInfo);
125860  sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
125861  sqlite3WhereExprAnalyze(pSrc, pOrWc);
125862  if( db->mallocFailed ) return;
125863  assert( pOrWc->nTerm>=2 );
125864
125865  /*
125866  ** Compute the set of tables that might satisfy cases 1 or 3.
125867  */
125868  indexable = ~(Bitmask)0;
125869  chngToIN = ~(Bitmask)0;
125870  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
125871    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
125872      WhereAndInfo *pAndInfo;
125873      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
125874      chngToIN = 0;
125875      pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
125876      if( pAndInfo ){
125877        WhereClause *pAndWC;
125878        WhereTerm *pAndTerm;
125879        int j;
125880        Bitmask b = 0;
125881        pOrTerm->u.pAndInfo = pAndInfo;
125882        pOrTerm->wtFlags |= TERM_ANDINFO;
125883        pOrTerm->eOperator = WO_AND;
125884        pAndWC = &pAndInfo->wc;
125885        memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
125886        sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
125887        sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
125888        sqlite3WhereExprAnalyze(pSrc, pAndWC);
125889        pAndWC->pOuter = pWC;
125890        if( !db->mallocFailed ){
125891          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
125892            assert( pAndTerm->pExpr );
125893            if( allowedOp(pAndTerm->pExpr->op)
125894             || pAndTerm->eOperator==WO_MATCH
125895            ){
125896              b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
125897            }
125898          }
125899        }
125900        indexable &= b;
125901      }
125902    }else if( pOrTerm->wtFlags & TERM_COPIED ){
125903      /* Skip this term for now.  We revisit it when we process the
125904      ** corresponding TERM_VIRTUAL term */
125905    }else{
125906      Bitmask b;
125907      b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
125908      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
125909        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
125910        b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
125911      }
125912      indexable &= b;
125913      if( (pOrTerm->eOperator & WO_EQ)==0 ){
125914        chngToIN = 0;
125915      }else{
125916        chngToIN &= b;
125917      }
125918    }
125919  }
125920
125921  /*
125922  ** Record the set of tables that satisfy case 3.  The set might be
125923  ** empty.
125924  */
125925  pOrInfo->indexable = indexable;
125926  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
125927
125928  /* For a two-way OR, attempt to implementation case 2.
125929  */
125930  if( indexable && pOrWc->nTerm==2 ){
125931    int iOne = 0;
125932    WhereTerm *pOne;
125933    while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
125934      int iTwo = 0;
125935      WhereTerm *pTwo;
125936      while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
125937        whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
125938      }
125939    }
125940  }
125941
125942  /*
125943  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
125944  ** we have to do some additional checking to see if case 1 really
125945  ** is satisfied.
125946  **
125947  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
125948  ** that there is no possibility of transforming the OR clause into an
125949  ** IN operator because one or more terms in the OR clause contain
125950  ** something other than == on a column in the single table.  The 1-bit
125951  ** case means that every term of the OR clause is of the form
125952  ** "table.column=expr" for some single table.  The one bit that is set
125953  ** will correspond to the common table.  We still need to check to make
125954  ** sure the same column is used on all terms.  The 2-bit case is when
125955  ** the all terms are of the form "table1.column=table2.column".  It
125956  ** might be possible to form an IN operator with either table1.column
125957  ** or table2.column as the LHS if either is common to every term of
125958  ** the OR clause.
125959  **
125960  ** Note that terms of the form "table.column1=table.column2" (the
125961  ** same table on both sizes of the ==) cannot be optimized.
125962  */
125963  if( chngToIN ){
125964    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
125965    int iColumn = -1;         /* Column index on lhs of IN operator */
125966    int iCursor = -1;         /* Table cursor common to all terms */
125967    int j = 0;                /* Loop counter */
125968
125969    /* Search for a table and column that appears on one side or the
125970    ** other of the == operator in every subterm.  That table and column
125971    ** will be recorded in iCursor and iColumn.  There might not be any
125972    ** such table and column.  Set okToChngToIN if an appropriate table
125973    ** and column is found but leave okToChngToIN false if not found.
125974    */
125975    for(j=0; j<2 && !okToChngToIN; j++){
125976      pOrTerm = pOrWc->a;
125977      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
125978        assert( pOrTerm->eOperator & WO_EQ );
125979        pOrTerm->wtFlags &= ~TERM_OR_OK;
125980        if( pOrTerm->leftCursor==iCursor ){
125981          /* This is the 2-bit case and we are on the second iteration and
125982          ** current term is from the first iteration.  So skip this term. */
125983          assert( j==1 );
125984          continue;
125985        }
125986        if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
125987                                            pOrTerm->leftCursor))==0 ){
125988          /* This term must be of the form t1.a==t2.b where t2 is in the
125989          ** chngToIN set but t1 is not.  This term will be either preceded
125990          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
125991          ** and use its inversion. */
125992          testcase( pOrTerm->wtFlags & TERM_COPIED );
125993          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
125994          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
125995          continue;
125996        }
125997        iColumn = pOrTerm->u.leftColumn;
125998        iCursor = pOrTerm->leftCursor;
125999        break;
126000      }
126001      if( i<0 ){
126002        /* No candidate table+column was found.  This can only occur
126003        ** on the second iteration */
126004        assert( j==1 );
126005        assert( IsPowerOfTwo(chngToIN) );
126006        assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
126007        break;
126008      }
126009      testcase( j==1 );
126010
126011      /* We have found a candidate table and column.  Check to see if that
126012      ** table and column is common to every term in the OR clause */
126013      okToChngToIN = 1;
126014      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
126015        assert( pOrTerm->eOperator & WO_EQ );
126016        if( pOrTerm->leftCursor!=iCursor ){
126017          pOrTerm->wtFlags &= ~TERM_OR_OK;
126018        }else if( pOrTerm->u.leftColumn!=iColumn ){
126019          okToChngToIN = 0;
126020        }else{
126021          int affLeft, affRight;
126022          /* If the right-hand side is also a column, then the affinities
126023          ** of both right and left sides must be such that no type
126024          ** conversions are required on the right.  (Ticket #2249)
126025          */
126026          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
126027          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
126028          if( affRight!=0 && affRight!=affLeft ){
126029            okToChngToIN = 0;
126030          }else{
126031            pOrTerm->wtFlags |= TERM_OR_OK;
126032          }
126033        }
126034      }
126035    }
126036
126037    /* At this point, okToChngToIN is true if original pTerm satisfies
126038    ** case 1.  In that case, construct a new virtual term that is
126039    ** pTerm converted into an IN operator.
126040    */
126041    if( okToChngToIN ){
126042      Expr *pDup;            /* A transient duplicate expression */
126043      ExprList *pList = 0;   /* The RHS of the IN operator */
126044      Expr *pLeft = 0;       /* The LHS of the IN operator */
126045      Expr *pNew;            /* The complete IN operator */
126046
126047      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
126048        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
126049        assert( pOrTerm->eOperator & WO_EQ );
126050        assert( pOrTerm->leftCursor==iCursor );
126051        assert( pOrTerm->u.leftColumn==iColumn );
126052        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
126053        pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
126054        pLeft = pOrTerm->pExpr->pLeft;
126055      }
126056      assert( pLeft!=0 );
126057      pDup = sqlite3ExprDup(db, pLeft, 0);
126058      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
126059      if( pNew ){
126060        int idxNew;
126061        transferJoinMarkings(pNew, pExpr);
126062        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
126063        pNew->x.pList = pList;
126064        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
126065        testcase( idxNew==0 );
126066        exprAnalyze(pSrc, pWC, idxNew);
126067        pTerm = &pWC->a[idxTerm];
126068        markTermAsChild(pWC, idxNew, idxTerm);
126069      }else{
126070        sqlite3ExprListDelete(db, pList);
126071      }
126072      pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 3 */
126073    }
126074  }
126075}
126076#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
126077
126078/*
126079** We already know that pExpr is a binary operator where both operands are
126080** column references.  This routine checks to see if pExpr is an equivalence
126081** relation:
126082**   1.  The SQLITE_Transitive optimization must be enabled
126083**   2.  Must be either an == or an IS operator
126084**   3.  Not originating in the ON clause of an OUTER JOIN
126085**   4.  The affinities of A and B must be compatible
126086**   5a. Both operands use the same collating sequence OR
126087**   5b. The overall collating sequence is BINARY
126088** If this routine returns TRUE, that means that the RHS can be substituted
126089** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
126090** This is an optimization.  No harm comes from returning 0.  But if 1 is
126091** returned when it should not be, then incorrect answers might result.
126092*/
126093static int termIsEquivalence(Parse *pParse, Expr *pExpr){
126094  char aff1, aff2;
126095  CollSeq *pColl;
126096  const char *zColl1, *zColl2;
126097  if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
126098  if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
126099  if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
126100  aff1 = sqlite3ExprAffinity(pExpr->pLeft);
126101  aff2 = sqlite3ExprAffinity(pExpr->pRight);
126102  if( aff1!=aff2
126103   && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
126104  ){
126105    return 0;
126106  }
126107  pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
126108  if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
126109  pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
126110  zColl1 = pColl ? pColl->zName : 0;
126111  pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
126112  zColl2 = pColl ? pColl->zName : 0;
126113  return sqlite3_stricmp(zColl1, zColl2)==0;
126114}
126115
126116/*
126117** Recursively walk the expressions of a SELECT statement and generate
126118** a bitmask indicating which tables are used in that expression
126119** tree.
126120*/
126121static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
126122  Bitmask mask = 0;
126123  while( pS ){
126124    SrcList *pSrc = pS->pSrc;
126125    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
126126    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
126127    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
126128    mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
126129    mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
126130    if( ALWAYS(pSrc!=0) ){
126131      int i;
126132      for(i=0; i<pSrc->nSrc; i++){
126133        mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
126134        mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
126135      }
126136    }
126137    pS = pS->pPrior;
126138  }
126139  return mask;
126140}
126141
126142/*
126143** Expression pExpr is one operand of a comparison operator that might
126144** be useful for indexing.  This routine checks to see if pExpr appears
126145** in any index.  Return TRUE (1) if pExpr is an indexed term and return
126146** FALSE (0) if not.  If TRUE is returned, also set *piCur to the cursor
126147** number of the table that is indexed and *piColumn to the column number
126148** of the column that is indexed, or -2 if an expression is being indexed.
126149**
126150** If pExpr is a TK_COLUMN column reference, then this routine always returns
126151** true even if that particular column is not indexed, because the column
126152** might be added to an automatic index later.
126153*/
126154static int exprMightBeIndexed(
126155  SrcList *pFrom,        /* The FROM clause */
126156  Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */
126157  Expr *pExpr,           /* An operand of a comparison operator */
126158  int *piCur,            /* Write the referenced table cursor number here */
126159  int *piColumn          /* Write the referenced table column number here */
126160){
126161  Index *pIdx;
126162  int i;
126163  int iCur;
126164  if( pExpr->op==TK_COLUMN ){
126165    *piCur = pExpr->iTable;
126166    *piColumn = pExpr->iColumn;
126167    return 1;
126168  }
126169  if( mPrereq==0 ) return 0;                 /* No table references */
126170  if( (mPrereq&(mPrereq-1))!=0 ) return 0;   /* Refs more than one table */
126171  for(i=0; mPrereq>1; i++, mPrereq>>=1){}
126172  iCur = pFrom->a[i].iCursor;
126173  for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
126174    if( pIdx->aColExpr==0 ) continue;
126175    for(i=0; i<pIdx->nKeyCol; i++){
126176      if( pIdx->aiColumn[i]!=(-2) ) continue;
126177      if( sqlite3ExprCompare(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
126178        *piCur = iCur;
126179        *piColumn = -2;
126180        return 1;
126181      }
126182    }
126183  }
126184  return 0;
126185}
126186
126187/*
126188** The input to this routine is an WhereTerm structure with only the
126189** "pExpr" field filled in.  The job of this routine is to analyze the
126190** subexpression and populate all the other fields of the WhereTerm
126191** structure.
126192**
126193** If the expression is of the form "<expr> <op> X" it gets commuted
126194** to the standard form of "X <op> <expr>".
126195**
126196** If the expression is of the form "X <op> Y" where both X and Y are
126197** columns, then the original expression is unchanged and a new virtual
126198** term of the form "Y <op> X" is added to the WHERE clause and
126199** analyzed separately.  The original term is marked with TERM_COPIED
126200** and the new term is marked with TERM_DYNAMIC (because it's pExpr
126201** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
126202** is a commuted copy of a prior term.)  The original term has nChild=1
126203** and the copy has idxParent set to the index of the original term.
126204*/
126205static void exprAnalyze(
126206  SrcList *pSrc,            /* the FROM clause */
126207  WhereClause *pWC,         /* the WHERE clause */
126208  int idxTerm               /* Index of the term to be analyzed */
126209){
126210  WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
126211  WhereTerm *pTerm;                /* The term to be analyzed */
126212  WhereMaskSet *pMaskSet;          /* Set of table index masks */
126213  Expr *pExpr;                     /* The expression to be analyzed */
126214  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
126215  Bitmask prereqAll;               /* Prerequesites of pExpr */
126216  Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
126217  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
126218  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
126219  int noCase = 0;                  /* uppercase equivalent to lowercase */
126220  int op;                          /* Top-level operator.  pExpr->op */
126221  Parse *pParse = pWInfo->pParse;  /* Parsing context */
126222  sqlite3 *db = pParse->db;        /* Database connection */
126223  unsigned char eOp2;              /* op2 value for LIKE/REGEXP/GLOB */
126224
126225  if( db->mallocFailed ){
126226    return;
126227  }
126228  pTerm = &pWC->a[idxTerm];
126229  pMaskSet = &pWInfo->sMaskSet;
126230  pExpr = pTerm->pExpr;
126231  assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
126232  prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
126233  op = pExpr->op;
126234  if( op==TK_IN ){
126235    assert( pExpr->pRight==0 );
126236    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
126237      pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
126238    }else{
126239      pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
126240    }
126241  }else if( op==TK_ISNULL ){
126242    pTerm->prereqRight = 0;
126243  }else{
126244    pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
126245  }
126246  prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
126247  if( ExprHasProperty(pExpr, EP_FromJoin) ){
126248    Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
126249    prereqAll |= x;
126250    extraRight = x-1;  /* ON clause terms may not be used with an index
126251                       ** on left table of a LEFT JOIN.  Ticket #3015 */
126252  }
126253  pTerm->prereqAll = prereqAll;
126254  pTerm->leftCursor = -1;
126255  pTerm->iParent = -1;
126256  pTerm->eOperator = 0;
126257  if( allowedOp(op) ){
126258    int iCur, iColumn;
126259    Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
126260    Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
126261    u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
126262    if( exprMightBeIndexed(pSrc, prereqLeft, pLeft, &iCur, &iColumn) ){
126263      pTerm->leftCursor = iCur;
126264      pTerm->u.leftColumn = iColumn;
126265      pTerm->eOperator = operatorMask(op) & opMask;
126266    }
126267    if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
126268    if( pRight
126269     && exprMightBeIndexed(pSrc, pTerm->prereqRight, pRight, &iCur, &iColumn)
126270    ){
126271      WhereTerm *pNew;
126272      Expr *pDup;
126273      u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
126274      if( pTerm->leftCursor>=0 ){
126275        int idxNew;
126276        pDup = sqlite3ExprDup(db, pExpr, 0);
126277        if( db->mallocFailed ){
126278          sqlite3ExprDelete(db, pDup);
126279          return;
126280        }
126281        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
126282        if( idxNew==0 ) return;
126283        pNew = &pWC->a[idxNew];
126284        markTermAsChild(pWC, idxNew, idxTerm);
126285        if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
126286        pTerm = &pWC->a[idxTerm];
126287        pTerm->wtFlags |= TERM_COPIED;
126288
126289        if( termIsEquivalence(pParse, pDup) ){
126290          pTerm->eOperator |= WO_EQUIV;
126291          eExtraOp = WO_EQUIV;
126292        }
126293      }else{
126294        pDup = pExpr;
126295        pNew = pTerm;
126296      }
126297      exprCommute(pParse, pDup);
126298      pNew->leftCursor = iCur;
126299      pNew->u.leftColumn = iColumn;
126300      testcase( (prereqLeft | extraRight) != prereqLeft );
126301      pNew->prereqRight = prereqLeft | extraRight;
126302      pNew->prereqAll = prereqAll;
126303      pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
126304    }
126305  }
126306
126307#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
126308  /* If a term is the BETWEEN operator, create two new virtual terms
126309  ** that define the range that the BETWEEN implements.  For example:
126310  **
126311  **      a BETWEEN b AND c
126312  **
126313  ** is converted into:
126314  **
126315  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
126316  **
126317  ** The two new terms are added onto the end of the WhereClause object.
126318  ** The new terms are "dynamic" and are children of the original BETWEEN
126319  ** term.  That means that if the BETWEEN term is coded, the children are
126320  ** skipped.  Or, if the children are satisfied by an index, the original
126321  ** BETWEEN term is skipped.
126322  */
126323  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
126324    ExprList *pList = pExpr->x.pList;
126325    int i;
126326    static const u8 ops[] = {TK_GE, TK_LE};
126327    assert( pList!=0 );
126328    assert( pList->nExpr==2 );
126329    for(i=0; i<2; i++){
126330      Expr *pNewExpr;
126331      int idxNew;
126332      pNewExpr = sqlite3PExpr(pParse, ops[i],
126333                             sqlite3ExprDup(db, pExpr->pLeft, 0),
126334                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
126335      transferJoinMarkings(pNewExpr, pExpr);
126336      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
126337      testcase( idxNew==0 );
126338      exprAnalyze(pSrc, pWC, idxNew);
126339      pTerm = &pWC->a[idxTerm];
126340      markTermAsChild(pWC, idxNew, idxTerm);
126341    }
126342  }
126343#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
126344
126345#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
126346  /* Analyze a term that is composed of two or more subterms connected by
126347  ** an OR operator.
126348  */
126349  else if( pExpr->op==TK_OR ){
126350    assert( pWC->op==TK_AND );
126351    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
126352    pTerm = &pWC->a[idxTerm];
126353  }
126354#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
126355
126356#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
126357  /* Add constraints to reduce the search space on a LIKE or GLOB
126358  ** operator.
126359  **
126360  ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
126361  **
126362  **          x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
126363  **
126364  ** The last character of the prefix "abc" is incremented to form the
126365  ** termination condition "abd".  If case is not significant (the default
126366  ** for LIKE) then the lower-bound is made all uppercase and the upper-
126367  ** bound is made all lowercase so that the bounds also work when comparing
126368  ** BLOBs.
126369  */
126370  if( pWC->op==TK_AND
126371   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
126372  ){
126373    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
126374    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
126375    Expr *pNewExpr1;
126376    Expr *pNewExpr2;
126377    int idxNew1;
126378    int idxNew2;
126379    const char *zCollSeqName;     /* Name of collating sequence */
126380    const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
126381
126382    pLeft = pExpr->x.pList->a[1].pExpr;
126383    pStr2 = sqlite3ExprDup(db, pStr1, 0);
126384
126385    /* Convert the lower bound to upper-case and the upper bound to
126386    ** lower-case (upper-case is less than lower-case in ASCII) so that
126387    ** the range constraints also work for BLOBs
126388    */
126389    if( noCase && !pParse->db->mallocFailed ){
126390      int i;
126391      char c;
126392      pTerm->wtFlags |= TERM_LIKE;
126393      for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
126394        pStr1->u.zToken[i] = sqlite3Toupper(c);
126395        pStr2->u.zToken[i] = sqlite3Tolower(c);
126396      }
126397    }
126398
126399    if( !db->mallocFailed ){
126400      u8 c, *pC;       /* Last character before the first wildcard */
126401      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
126402      c = *pC;
126403      if( noCase ){
126404        /* The point is to increment the last character before the first
126405        ** wildcard.  But if we increment '@', that will push it into the
126406        ** alphabetic range where case conversions will mess up the
126407        ** inequality.  To avoid this, make sure to also run the full
126408        ** LIKE on all candidate expressions by clearing the isComplete flag
126409        */
126410        if( c=='A'-1 ) isComplete = 0;
126411        c = sqlite3UpperToLower[c];
126412      }
126413      *pC = c + 1;
126414    }
126415    zCollSeqName = noCase ? "NOCASE" : "BINARY";
126416    pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
126417    pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
126418           sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
126419           pStr1, 0);
126420    transferJoinMarkings(pNewExpr1, pExpr);
126421    idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
126422    testcase( idxNew1==0 );
126423    exprAnalyze(pSrc, pWC, idxNew1);
126424    pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
126425    pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
126426           sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
126427           pStr2, 0);
126428    transferJoinMarkings(pNewExpr2, pExpr);
126429    idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
126430    testcase( idxNew2==0 );
126431    exprAnalyze(pSrc, pWC, idxNew2);
126432    pTerm = &pWC->a[idxTerm];
126433    if( isComplete ){
126434      markTermAsChild(pWC, idxNew1, idxTerm);
126435      markTermAsChild(pWC, idxNew2, idxTerm);
126436    }
126437  }
126438#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
126439
126440#ifndef SQLITE_OMIT_VIRTUALTABLE
126441  /* Add a WO_MATCH auxiliary term to the constraint set if the
126442  ** current expression is of the form:  column MATCH expr.
126443  ** This information is used by the xBestIndex methods of
126444  ** virtual tables.  The native query optimizer does not attempt
126445  ** to do anything with MATCH functions.
126446  */
126447  if( pWC->op==TK_AND && isMatchOfColumn(pExpr, &eOp2) ){
126448    int idxNew;
126449    Expr *pRight, *pLeft;
126450    WhereTerm *pNewTerm;
126451    Bitmask prereqColumn, prereqExpr;
126452
126453    pRight = pExpr->x.pList->a[0].pExpr;
126454    pLeft = pExpr->x.pList->a[1].pExpr;
126455    prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
126456    prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
126457    if( (prereqExpr & prereqColumn)==0 ){
126458      Expr *pNewExpr;
126459      pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
126460                              0, sqlite3ExprDup(db, pRight, 0), 0);
126461      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
126462      testcase( idxNew==0 );
126463      pNewTerm = &pWC->a[idxNew];
126464      pNewTerm->prereqRight = prereqExpr;
126465      pNewTerm->leftCursor = pLeft->iTable;
126466      pNewTerm->u.leftColumn = pLeft->iColumn;
126467      pNewTerm->eOperator = WO_MATCH;
126468      pNewTerm->eMatchOp = eOp2;
126469      markTermAsChild(pWC, idxNew, idxTerm);
126470      pTerm = &pWC->a[idxTerm];
126471      pTerm->wtFlags |= TERM_COPIED;
126472      pNewTerm->prereqAll = pTerm->prereqAll;
126473    }
126474  }
126475#endif /* SQLITE_OMIT_VIRTUALTABLE */
126476
126477#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
126478  /* When sqlite_stat3 histogram data is available an operator of the
126479  ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
126480  ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
126481  ** virtual term of that form.
126482  **
126483  ** Note that the virtual term must be tagged with TERM_VNULL.
126484  */
126485  if( pExpr->op==TK_NOTNULL
126486   && pExpr->pLeft->op==TK_COLUMN
126487   && pExpr->pLeft->iColumn>=0
126488   && OptimizationEnabled(db, SQLITE_Stat34)
126489  ){
126490    Expr *pNewExpr;
126491    Expr *pLeft = pExpr->pLeft;
126492    int idxNew;
126493    WhereTerm *pNewTerm;
126494
126495    pNewExpr = sqlite3PExpr(pParse, TK_GT,
126496                            sqlite3ExprDup(db, pLeft, 0),
126497                            sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
126498
126499    idxNew = whereClauseInsert(pWC, pNewExpr,
126500                              TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
126501    if( idxNew ){
126502      pNewTerm = &pWC->a[idxNew];
126503      pNewTerm->prereqRight = 0;
126504      pNewTerm->leftCursor = pLeft->iTable;
126505      pNewTerm->u.leftColumn = pLeft->iColumn;
126506      pNewTerm->eOperator = WO_GT;
126507      markTermAsChild(pWC, idxNew, idxTerm);
126508      pTerm = &pWC->a[idxTerm];
126509      pTerm->wtFlags |= TERM_COPIED;
126510      pNewTerm->prereqAll = pTerm->prereqAll;
126511    }
126512  }
126513#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
126514
126515  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
126516  ** an index for tables to the left of the join.
126517  */
126518  pTerm->prereqRight |= extraRight;
126519}
126520
126521/***************************************************************************
126522** Routines with file scope above.  Interface to the rest of the where.c
126523** subsystem follows.
126524***************************************************************************/
126525
126526/*
126527** This routine identifies subexpressions in the WHERE clause where
126528** each subexpression is separated by the AND operator or some other
126529** operator specified in the op parameter.  The WhereClause structure
126530** is filled with pointers to subexpressions.  For example:
126531**
126532**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
126533**           \________/     \_______________/     \________________/
126534**            slot[0]            slot[1]               slot[2]
126535**
126536** The original WHERE clause in pExpr is unaltered.  All this routine
126537** does is make slot[] entries point to substructure within pExpr.
126538**
126539** In the previous sentence and in the diagram, "slot[]" refers to
126540** the WhereClause.a[] array.  The slot[] array grows as needed to contain
126541** all terms of the WHERE clause.
126542*/
126543SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
126544  Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
126545  pWC->op = op;
126546  if( pE2==0 ) return;
126547  if( pE2->op!=op ){
126548    whereClauseInsert(pWC, pExpr, 0);
126549  }else{
126550    sqlite3WhereSplit(pWC, pE2->pLeft, op);
126551    sqlite3WhereSplit(pWC, pE2->pRight, op);
126552  }
126553}
126554
126555/*
126556** Initialize a preallocated WhereClause structure.
126557*/
126558SQLITE_PRIVATE void sqlite3WhereClauseInit(
126559  WhereClause *pWC,        /* The WhereClause to be initialized */
126560  WhereInfo *pWInfo        /* The WHERE processing context */
126561){
126562  pWC->pWInfo = pWInfo;
126563  pWC->pOuter = 0;
126564  pWC->nTerm = 0;
126565  pWC->nSlot = ArraySize(pWC->aStatic);
126566  pWC->a = pWC->aStatic;
126567}
126568
126569/*
126570** Deallocate a WhereClause structure.  The WhereClause structure
126571** itself is not freed.  This routine is the inverse of
126572** sqlite3WhereClauseInit().
126573*/
126574SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
126575  int i;
126576  WhereTerm *a;
126577  sqlite3 *db = pWC->pWInfo->pParse->db;
126578  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
126579    if( a->wtFlags & TERM_DYNAMIC ){
126580      sqlite3ExprDelete(db, a->pExpr);
126581    }
126582    if( a->wtFlags & TERM_ORINFO ){
126583      whereOrInfoDelete(db, a->u.pOrInfo);
126584    }else if( a->wtFlags & TERM_ANDINFO ){
126585      whereAndInfoDelete(db, a->u.pAndInfo);
126586    }
126587  }
126588  if( pWC->a!=pWC->aStatic ){
126589    sqlite3DbFree(db, pWC->a);
126590  }
126591}
126592
126593
126594/*
126595** These routines walk (recursively) an expression tree and generate
126596** a bitmask indicating which tables are used in that expression
126597** tree.
126598*/
126599SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
126600  Bitmask mask = 0;
126601  if( p==0 ) return 0;
126602  if( p->op==TK_COLUMN ){
126603    mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
126604    return mask;
126605  }
126606  mask = sqlite3WhereExprUsage(pMaskSet, p->pRight);
126607  if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
126608  if( ExprHasProperty(p, EP_xIsSelect) ){
126609    mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
126610  }else if( p->x.pList ){
126611    mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
126612  }
126613  return mask;
126614}
126615SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
126616  int i;
126617  Bitmask mask = 0;
126618  if( pList ){
126619    for(i=0; i<pList->nExpr; i++){
126620      mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
126621    }
126622  }
126623  return mask;
126624}
126625
126626
126627/*
126628** Call exprAnalyze on all terms in a WHERE clause.
126629**
126630** Note that exprAnalyze() might add new virtual terms onto the
126631** end of the WHERE clause.  We do not want to analyze these new
126632** virtual terms, so start analyzing at the end and work forward
126633** so that the added virtual terms are never processed.
126634*/
126635SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
126636  SrcList *pTabList,       /* the FROM clause */
126637  WhereClause *pWC         /* the WHERE clause to be analyzed */
126638){
126639  int i;
126640  for(i=pWC->nTerm-1; i>=0; i--){
126641    exprAnalyze(pTabList, pWC, i);
126642  }
126643}
126644
126645/*
126646** For table-valued-functions, transform the function arguments into
126647** new WHERE clause terms.
126648**
126649** Each function argument translates into an equality constraint against
126650** a HIDDEN column in the table.
126651*/
126652SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
126653  Parse *pParse,                    /* Parsing context */
126654  struct SrcList_item *pItem,       /* The FROM clause term to process */
126655  WhereClause *pWC                  /* Xfer function arguments to here */
126656){
126657  Table *pTab;
126658  int j, k;
126659  ExprList *pArgs;
126660  Expr *pColRef;
126661  Expr *pTerm;
126662  if( pItem->fg.isTabFunc==0 ) return;
126663  pTab = pItem->pTab;
126664  assert( pTab!=0 );
126665  pArgs = pItem->u1.pFuncArg;
126666  if( pArgs==0 ) return;
126667  for(j=k=0; j<pArgs->nExpr; j++){
126668    while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
126669    if( k>=pTab->nCol ){
126670      sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
126671                      pTab->zName, j);
126672      return;
126673    }
126674    pColRef = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
126675    if( pColRef==0 ) return;
126676    pColRef->iTable = pItem->iCursor;
126677    pColRef->iColumn = k++;
126678    pColRef->pTab = pTab;
126679    pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
126680                         sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
126681    whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
126682  }
126683}
126684
126685/************** End of whereexpr.c *******************************************/
126686/************** Begin file where.c *******************************************/
126687/*
126688** 2001 September 15
126689**
126690** The author disclaims copyright to this source code.  In place of
126691** a legal notice, here is a blessing:
126692**
126693**    May you do good and not evil.
126694**    May you find forgiveness for yourself and forgive others.
126695**    May you share freely, never taking more than you give.
126696**
126697*************************************************************************
126698** This module contains C code that generates VDBE code used to process
126699** the WHERE clause of SQL statements.  This module is responsible for
126700** generating the code that loops through a table looking for applicable
126701** rows.  Indices are selected and used to speed the search when doing
126702** so is applicable.  Because this module is responsible for selecting
126703** indices, you might also think of this module as the "query optimizer".
126704*/
126705/* #include "sqliteInt.h" */
126706/* #include "whereInt.h" */
126707
126708/* Forward declaration of methods */
126709static int whereLoopResize(sqlite3*, WhereLoop*, int);
126710
126711/* Test variable that can be set to enable WHERE tracing */
126712#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
126713/***/ int sqlite3WhereTrace = 0;
126714#endif
126715
126716
126717/*
126718** Return the estimated number of output rows from a WHERE clause
126719*/
126720SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
126721  return pWInfo->nRowOut;
126722}
126723
126724/*
126725** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
126726** WHERE clause returns outputs for DISTINCT processing.
126727*/
126728SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
126729  return pWInfo->eDistinct;
126730}
126731
126732/*
126733** Return TRUE if the WHERE clause returns rows in ORDER BY order.
126734** Return FALSE if the output needs to be sorted.
126735*/
126736SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
126737  return pWInfo->nOBSat;
126738}
126739
126740/*
126741** Return TRUE if the innermost loop of the WHERE clause implementation
126742** returns rows in ORDER BY order for complete run of the inner loop.
126743**
126744** Across multiple iterations of outer loops, the output rows need not be
126745** sorted.  As long as rows are sorted for just the innermost loop, this
126746** routine can return TRUE.
126747*/
126748SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){
126749  return pWInfo->bOrderedInnerLoop;
126750}
126751
126752/*
126753** Return the VDBE address or label to jump to in order to continue
126754** immediately with the next row of a WHERE clause.
126755*/
126756SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
126757  assert( pWInfo->iContinue!=0 );
126758  return pWInfo->iContinue;
126759}
126760
126761/*
126762** Return the VDBE address or label to jump to in order to break
126763** out of a WHERE loop.
126764*/
126765SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
126766  return pWInfo->iBreak;
126767}
126768
126769/*
126770** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
126771** operate directly on the rowis returned by a WHERE clause.  Return
126772** ONEPASS_SINGLE (1) if the statement can operation directly because only
126773** a single row is to be changed.  Return ONEPASS_MULTI (2) if the one-pass
126774** optimization can be used on multiple
126775**
126776** If the ONEPASS optimization is used (if this routine returns true)
126777** then also write the indices of open cursors used by ONEPASS
126778** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
126779** table and iaCur[1] gets the cursor used by an auxiliary index.
126780** Either value may be -1, indicating that cursor is not used.
126781** Any cursors returned will have been opened for writing.
126782**
126783** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
126784** unable to use the ONEPASS optimization.
126785*/
126786SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
126787  memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
126788#ifdef WHERETRACE_ENABLED
126789  if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
126790    sqlite3DebugPrintf("%s cursors: %d %d\n",
126791         pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
126792         aiCur[0], aiCur[1]);
126793  }
126794#endif
126795  return pWInfo->eOnePass;
126796}
126797
126798/*
126799** Move the content of pSrc into pDest
126800*/
126801static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
126802  pDest->n = pSrc->n;
126803  memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
126804}
126805
126806/*
126807** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
126808**
126809** The new entry might overwrite an existing entry, or it might be
126810** appended, or it might be discarded.  Do whatever is the right thing
126811** so that pSet keeps the N_OR_COST best entries seen so far.
126812*/
126813static int whereOrInsert(
126814  WhereOrSet *pSet,      /* The WhereOrSet to be updated */
126815  Bitmask prereq,        /* Prerequisites of the new entry */
126816  LogEst rRun,           /* Run-cost of the new entry */
126817  LogEst nOut            /* Number of outputs for the new entry */
126818){
126819  u16 i;
126820  WhereOrCost *p;
126821  for(i=pSet->n, p=pSet->a; i>0; i--, p++){
126822    if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
126823      goto whereOrInsert_done;
126824    }
126825    if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
126826      return 0;
126827    }
126828  }
126829  if( pSet->n<N_OR_COST ){
126830    p = &pSet->a[pSet->n++];
126831    p->nOut = nOut;
126832  }else{
126833    p = pSet->a;
126834    for(i=1; i<pSet->n; i++){
126835      if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
126836    }
126837    if( p->rRun<=rRun ) return 0;
126838  }
126839whereOrInsert_done:
126840  p->prereq = prereq;
126841  p->rRun = rRun;
126842  if( p->nOut>nOut ) p->nOut = nOut;
126843  return 1;
126844}
126845
126846/*
126847** Return the bitmask for the given cursor number.  Return 0 if
126848** iCursor is not in the set.
126849*/
126850SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
126851  int i;
126852  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
126853  for(i=0; i<pMaskSet->n; i++){
126854    if( pMaskSet->ix[i]==iCursor ){
126855      return MASKBIT(i);
126856    }
126857  }
126858  return 0;
126859}
126860
126861/*
126862** Create a new mask for cursor iCursor.
126863**
126864** There is one cursor per table in the FROM clause.  The number of
126865** tables in the FROM clause is limited by a test early in the
126866** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
126867** array will never overflow.
126868*/
126869static void createMask(WhereMaskSet *pMaskSet, int iCursor){
126870  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
126871  pMaskSet->ix[pMaskSet->n++] = iCursor;
126872}
126873
126874/*
126875** Advance to the next WhereTerm that matches according to the criteria
126876** established when the pScan object was initialized by whereScanInit().
126877** Return NULL if there are no more matching WhereTerms.
126878*/
126879static WhereTerm *whereScanNext(WhereScan *pScan){
126880  int iCur;            /* The cursor on the LHS of the term */
126881  i16 iColumn;         /* The column on the LHS of the term.  -1 for IPK */
126882  Expr *pX;            /* An expression being tested */
126883  WhereClause *pWC;    /* Shorthand for pScan->pWC */
126884  WhereTerm *pTerm;    /* The term being tested */
126885  int k = pScan->k;    /* Where to start scanning */
126886
126887  while( pScan->iEquiv<=pScan->nEquiv ){
126888    iCur = pScan->aiCur[pScan->iEquiv-1];
126889    iColumn = pScan->aiColumn[pScan->iEquiv-1];
126890    if( iColumn==XN_EXPR && pScan->pIdxExpr==0 ) return 0;
126891    while( (pWC = pScan->pWC)!=0 ){
126892      for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
126893        if( pTerm->leftCursor==iCur
126894         && pTerm->u.leftColumn==iColumn
126895         && (iColumn!=XN_EXPR
126896             || sqlite3ExprCompare(pTerm->pExpr->pLeft,pScan->pIdxExpr,iCur)==0)
126897         && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
126898        ){
126899          if( (pTerm->eOperator & WO_EQUIV)!=0
126900           && pScan->nEquiv<ArraySize(pScan->aiCur)
126901           && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
126902          ){
126903            int j;
126904            for(j=0; j<pScan->nEquiv; j++){
126905              if( pScan->aiCur[j]==pX->iTable
126906               && pScan->aiColumn[j]==pX->iColumn ){
126907                  break;
126908              }
126909            }
126910            if( j==pScan->nEquiv ){
126911              pScan->aiCur[j] = pX->iTable;
126912              pScan->aiColumn[j] = pX->iColumn;
126913              pScan->nEquiv++;
126914            }
126915          }
126916          if( (pTerm->eOperator & pScan->opMask)!=0 ){
126917            /* Verify the affinity and collating sequence match */
126918            if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
126919              CollSeq *pColl;
126920              Parse *pParse = pWC->pWInfo->pParse;
126921              pX = pTerm->pExpr;
126922              if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
126923                continue;
126924              }
126925              assert(pX->pLeft);
126926              pColl = sqlite3BinaryCompareCollSeq(pParse,
126927                                                  pX->pLeft, pX->pRight);
126928              if( pColl==0 ) pColl = pParse->db->pDfltColl;
126929              if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
126930                continue;
126931              }
126932            }
126933            if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
126934             && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
126935             && pX->iTable==pScan->aiCur[0]
126936             && pX->iColumn==pScan->aiColumn[0]
126937            ){
126938              testcase( pTerm->eOperator & WO_IS );
126939              continue;
126940            }
126941            pScan->k = k+1;
126942            return pTerm;
126943          }
126944        }
126945      }
126946      pScan->pWC = pScan->pWC->pOuter;
126947      k = 0;
126948    }
126949    pScan->pWC = pScan->pOrigWC;
126950    k = 0;
126951    pScan->iEquiv++;
126952  }
126953  return 0;
126954}
126955
126956/*
126957** Initialize a WHERE clause scanner object.  Return a pointer to the
126958** first match.  Return NULL if there are no matches.
126959**
126960** The scanner will be searching the WHERE clause pWC.  It will look
126961** for terms of the form "X <op> <expr>" where X is column iColumn of table
126962** iCur.   Or if pIdx!=0 then X is column iColumn of index pIdx.  pIdx
126963** must be one of the indexes of table iCur.
126964**
126965** The <op> must be one of the operators described by opMask.
126966**
126967** If the search is for X and the WHERE clause contains terms of the
126968** form X=Y then this routine might also return terms of the form
126969** "Y <op> <expr>".  The number of levels of transitivity is limited,
126970** but is enough to handle most commonly occurring SQL statements.
126971**
126972** If X is not the INTEGER PRIMARY KEY then X must be compatible with
126973** index pIdx.
126974*/
126975static WhereTerm *whereScanInit(
126976  WhereScan *pScan,       /* The WhereScan object being initialized */
126977  WhereClause *pWC,       /* The WHERE clause to be scanned */
126978  int iCur,               /* Cursor to scan for */
126979  int iColumn,            /* Column to scan for */
126980  u32 opMask,             /* Operator(s) to scan for */
126981  Index *pIdx             /* Must be compatible with this index */
126982){
126983  int j = 0;
126984
126985  /* memset(pScan, 0, sizeof(*pScan)); */
126986  pScan->pOrigWC = pWC;
126987  pScan->pWC = pWC;
126988  pScan->pIdxExpr = 0;
126989  if( pIdx ){
126990    j = iColumn;
126991    iColumn = pIdx->aiColumn[j];
126992    if( iColumn==XN_EXPR ) pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
126993    if( iColumn==pIdx->pTable->iPKey ) iColumn = XN_ROWID;
126994  }
126995  if( pIdx && iColumn>=0 ){
126996    pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
126997    pScan->zCollName = pIdx->azColl[j];
126998  }else{
126999    pScan->idxaff = 0;
127000    pScan->zCollName = 0;
127001  }
127002  pScan->opMask = opMask;
127003  pScan->k = 0;
127004  pScan->aiCur[0] = iCur;
127005  pScan->aiColumn[0] = iColumn;
127006  pScan->nEquiv = 1;
127007  pScan->iEquiv = 1;
127008  return whereScanNext(pScan);
127009}
127010
127011/*
127012** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
127013** where X is a reference to the iColumn of table iCur or of index pIdx
127014** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
127015** the op parameter.  Return a pointer to the term.  Return 0 if not found.
127016**
127017** If pIdx!=0 then it must be one of the indexes of table iCur.
127018** Search for terms matching the iColumn-th column of pIdx
127019** rather than the iColumn-th column of table iCur.
127020**
127021** The term returned might by Y=<expr> if there is another constraint in
127022** the WHERE clause that specifies that X=Y.  Any such constraints will be
127023** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
127024** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
127025** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
127026** other equivalent values.  Hence a search for X will return <expr> if X=A1
127027** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
127028**
127029** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
127030** then try for the one with no dependencies on <expr> - in other words where
127031** <expr> is a constant expression of some kind.  Only return entries of
127032** the form "X <op> Y" where Y is a column in another table if no terms of
127033** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
127034** exist, try to return a term that does not use WO_EQUIV.
127035*/
127036SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
127037  WhereClause *pWC,     /* The WHERE clause to be searched */
127038  int iCur,             /* Cursor number of LHS */
127039  int iColumn,          /* Column number of LHS */
127040  Bitmask notReady,     /* RHS must not overlap with this mask */
127041  u32 op,               /* Mask of WO_xx values describing operator */
127042  Index *pIdx           /* Must be compatible with this index, if not NULL */
127043){
127044  WhereTerm *pResult = 0;
127045  WhereTerm *p;
127046  WhereScan scan;
127047
127048  p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
127049  op &= WO_EQ|WO_IS;
127050  while( p ){
127051    if( (p->prereqRight & notReady)==0 ){
127052      if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
127053        testcase( p->eOperator & WO_IS );
127054        return p;
127055      }
127056      if( pResult==0 ) pResult = p;
127057    }
127058    p = whereScanNext(&scan);
127059  }
127060  return pResult;
127061}
127062
127063/*
127064** This function searches pList for an entry that matches the iCol-th column
127065** of index pIdx.
127066**
127067** If such an expression is found, its index in pList->a[] is returned. If
127068** no expression is found, -1 is returned.
127069*/
127070static int findIndexCol(
127071  Parse *pParse,                  /* Parse context */
127072  ExprList *pList,                /* Expression list to search */
127073  int iBase,                      /* Cursor for table associated with pIdx */
127074  Index *pIdx,                    /* Index to match column of */
127075  int iCol                        /* Column of index to match */
127076){
127077  int i;
127078  const char *zColl = pIdx->azColl[iCol];
127079
127080  for(i=0; i<pList->nExpr; i++){
127081    Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
127082    if( p->op==TK_COLUMN
127083     && p->iColumn==pIdx->aiColumn[iCol]
127084     && p->iTable==iBase
127085    ){
127086      CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
127087      if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
127088        return i;
127089      }
127090    }
127091  }
127092
127093  return -1;
127094}
127095
127096/*
127097** Return TRUE if the iCol-th column of index pIdx is NOT NULL
127098*/
127099static int indexColumnNotNull(Index *pIdx, int iCol){
127100  int j;
127101  assert( pIdx!=0 );
127102  assert( iCol>=0 && iCol<pIdx->nColumn );
127103  j = pIdx->aiColumn[iCol];
127104  if( j>=0 ){
127105    return pIdx->pTable->aCol[j].notNull;
127106  }else if( j==(-1) ){
127107    return 1;
127108  }else{
127109    assert( j==(-2) );
127110    return 0;  /* Assume an indexed expression can always yield a NULL */
127111
127112  }
127113}
127114
127115/*
127116** Return true if the DISTINCT expression-list passed as the third argument
127117** is redundant.
127118**
127119** A DISTINCT list is redundant if any subset of the columns in the
127120** DISTINCT list are collectively unique and individually non-null.
127121*/
127122static int isDistinctRedundant(
127123  Parse *pParse,            /* Parsing context */
127124  SrcList *pTabList,        /* The FROM clause */
127125  WhereClause *pWC,         /* The WHERE clause */
127126  ExprList *pDistinct       /* The result set that needs to be DISTINCT */
127127){
127128  Table *pTab;
127129  Index *pIdx;
127130  int i;
127131  int iBase;
127132
127133  /* If there is more than one table or sub-select in the FROM clause of
127134  ** this query, then it will not be possible to show that the DISTINCT
127135  ** clause is redundant. */
127136  if( pTabList->nSrc!=1 ) return 0;
127137  iBase = pTabList->a[0].iCursor;
127138  pTab = pTabList->a[0].pTab;
127139
127140  /* If any of the expressions is an IPK column on table iBase, then return
127141  ** true. Note: The (p->iTable==iBase) part of this test may be false if the
127142  ** current SELECT is a correlated sub-query.
127143  */
127144  for(i=0; i<pDistinct->nExpr; i++){
127145    Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
127146    if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
127147  }
127148
127149  /* Loop through all indices on the table, checking each to see if it makes
127150  ** the DISTINCT qualifier redundant. It does so if:
127151  **
127152  **   1. The index is itself UNIQUE, and
127153  **
127154  **   2. All of the columns in the index are either part of the pDistinct
127155  **      list, or else the WHERE clause contains a term of the form "col=X",
127156  **      where X is a constant value. The collation sequences of the
127157  **      comparison and select-list expressions must match those of the index.
127158  **
127159  **   3. All of those index columns for which the WHERE clause does not
127160  **      contain a "col=X" term are subject to a NOT NULL constraint.
127161  */
127162  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
127163    if( !IsUniqueIndex(pIdx) ) continue;
127164    for(i=0; i<pIdx->nKeyCol; i++){
127165      if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
127166        if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
127167        if( indexColumnNotNull(pIdx, i)==0 ) break;
127168      }
127169    }
127170    if( i==pIdx->nKeyCol ){
127171      /* This index implies that the DISTINCT qualifier is redundant. */
127172      return 1;
127173    }
127174  }
127175
127176  return 0;
127177}
127178
127179
127180/*
127181** Estimate the logarithm of the input value to base 2.
127182*/
127183static LogEst estLog(LogEst N){
127184  return N<=10 ? 0 : sqlite3LogEst(N) - 33;
127185}
127186
127187/*
127188** Convert OP_Column opcodes to OP_Copy in previously generated code.
127189**
127190** This routine runs over generated VDBE code and translates OP_Column
127191** opcodes into OP_Copy when the table is being accessed via co-routine
127192** instead of via table lookup.
127193**
127194** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
127195** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
127196** then each OP_Rowid is transformed into an instruction to increment the
127197** value stored in its output register.
127198*/
127199static void translateColumnToCopy(
127200  Vdbe *v,            /* The VDBE containing code to translate */
127201  int iStart,         /* Translate from this opcode to the end */
127202  int iTabCur,        /* OP_Column/OP_Rowid references to this table */
127203  int iRegister,      /* The first column is in this register */
127204  int bIncrRowid      /* If non-zero, transform OP_rowid to OP_AddImm(1) */
127205){
127206  VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
127207  int iEnd = sqlite3VdbeCurrentAddr(v);
127208  for(; iStart<iEnd; iStart++, pOp++){
127209    if( pOp->p1!=iTabCur ) continue;
127210    if( pOp->opcode==OP_Column ){
127211      pOp->opcode = OP_Copy;
127212      pOp->p1 = pOp->p2 + iRegister;
127213      pOp->p2 = pOp->p3;
127214      pOp->p3 = 0;
127215    }else if( pOp->opcode==OP_Rowid ){
127216      if( bIncrRowid ){
127217        /* Increment the value stored in the P2 operand of the OP_Rowid. */
127218        pOp->opcode = OP_AddImm;
127219        pOp->p1 = pOp->p2;
127220        pOp->p2 = 1;
127221      }else{
127222        pOp->opcode = OP_Null;
127223        pOp->p1 = 0;
127224        pOp->p3 = 0;
127225      }
127226    }
127227  }
127228}
127229
127230/*
127231** Two routines for printing the content of an sqlite3_index_info
127232** structure.  Used for testing and debugging only.  If neither
127233** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
127234** are no-ops.
127235*/
127236#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
127237static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
127238  int i;
127239  if( !sqlite3WhereTrace ) return;
127240  for(i=0; i<p->nConstraint; i++){
127241    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
127242       i,
127243       p->aConstraint[i].iColumn,
127244       p->aConstraint[i].iTermOffset,
127245       p->aConstraint[i].op,
127246       p->aConstraint[i].usable);
127247  }
127248  for(i=0; i<p->nOrderBy; i++){
127249    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
127250       i,
127251       p->aOrderBy[i].iColumn,
127252       p->aOrderBy[i].desc);
127253  }
127254}
127255static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
127256  int i;
127257  if( !sqlite3WhereTrace ) return;
127258  for(i=0; i<p->nConstraint; i++){
127259    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
127260       i,
127261       p->aConstraintUsage[i].argvIndex,
127262       p->aConstraintUsage[i].omit);
127263  }
127264  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
127265  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
127266  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
127267  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
127268  sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
127269}
127270#else
127271#define TRACE_IDX_INPUTS(A)
127272#define TRACE_IDX_OUTPUTS(A)
127273#endif
127274
127275#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
127276/*
127277** Return TRUE if the WHERE clause term pTerm is of a form where it
127278** could be used with an index to access pSrc, assuming an appropriate
127279** index existed.
127280*/
127281static int termCanDriveIndex(
127282  WhereTerm *pTerm,              /* WHERE clause term to check */
127283  struct SrcList_item *pSrc,     /* Table we are trying to access */
127284  Bitmask notReady               /* Tables in outer loops of the join */
127285){
127286  char aff;
127287  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
127288  if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
127289  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
127290  if( pTerm->u.leftColumn<0 ) return 0;
127291  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
127292  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
127293  testcase( pTerm->pExpr->op==TK_IS );
127294  return 1;
127295}
127296#endif
127297
127298
127299#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
127300/*
127301** Generate code to construct the Index object for an automatic index
127302** and to set up the WhereLevel object pLevel so that the code generator
127303** makes use of the automatic index.
127304*/
127305static void constructAutomaticIndex(
127306  Parse *pParse,              /* The parsing context */
127307  WhereClause *pWC,           /* The WHERE clause */
127308  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
127309  Bitmask notReady,           /* Mask of cursors that are not available */
127310  WhereLevel *pLevel          /* Write new index here */
127311){
127312  int nKeyCol;                /* Number of columns in the constructed index */
127313  WhereTerm *pTerm;           /* A single term of the WHERE clause */
127314  WhereTerm *pWCEnd;          /* End of pWC->a[] */
127315  Index *pIdx;                /* Object describing the transient index */
127316  Vdbe *v;                    /* Prepared statement under construction */
127317  int addrInit;               /* Address of the initialization bypass jump */
127318  Table *pTable;              /* The table being indexed */
127319  int addrTop;                /* Top of the index fill loop */
127320  int regRecord;              /* Register holding an index record */
127321  int n;                      /* Column counter */
127322  int i;                      /* Loop counter */
127323  int mxBitCol;               /* Maximum column in pSrc->colUsed */
127324  CollSeq *pColl;             /* Collating sequence to on a column */
127325  WhereLoop *pLoop;           /* The Loop object */
127326  char *zNotUsed;             /* Extra space on the end of pIdx */
127327  Bitmask idxCols;            /* Bitmap of columns used for indexing */
127328  Bitmask extraCols;          /* Bitmap of additional columns */
127329  u8 sentWarning = 0;         /* True if a warnning has been issued */
127330  Expr *pPartial = 0;         /* Partial Index Expression */
127331  int iContinue = 0;          /* Jump here to skip excluded rows */
127332  struct SrcList_item *pTabItem;  /* FROM clause term being indexed */
127333  int addrCounter = 0;        /* Address where integer counter is initialized */
127334  int regBase;                /* Array of registers where record is assembled */
127335
127336  /* Generate code to skip over the creation and initialization of the
127337  ** transient index on 2nd and subsequent iterations of the loop. */
127338  v = pParse->pVdbe;
127339  assert( v!=0 );
127340  addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
127341
127342  /* Count the number of columns that will be added to the index
127343  ** and used to match WHERE clause constraints */
127344  nKeyCol = 0;
127345  pTable = pSrc->pTab;
127346  pWCEnd = &pWC->a[pWC->nTerm];
127347  pLoop = pLevel->pWLoop;
127348  idxCols = 0;
127349  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
127350    Expr *pExpr = pTerm->pExpr;
127351    assert( !ExprHasProperty(pExpr, EP_FromJoin)    /* prereq always non-zero */
127352         || pExpr->iRightJoinTable!=pSrc->iCursor   /*   for the right-hand   */
127353         || pLoop->prereq!=0 );                     /*   table of a LEFT JOIN */
127354    if( pLoop->prereq==0
127355     && (pTerm->wtFlags & TERM_VIRTUAL)==0
127356     && !ExprHasProperty(pExpr, EP_FromJoin)
127357     && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
127358      pPartial = sqlite3ExprAnd(pParse->db, pPartial,
127359                                sqlite3ExprDup(pParse->db, pExpr, 0));
127360    }
127361    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
127362      int iCol = pTerm->u.leftColumn;
127363      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
127364      testcase( iCol==BMS );
127365      testcase( iCol==BMS-1 );
127366      if( !sentWarning ){
127367        sqlite3_log(SQLITE_WARNING_AUTOINDEX,
127368            "automatic index on %s(%s)", pTable->zName,
127369            pTable->aCol[iCol].zName);
127370        sentWarning = 1;
127371      }
127372      if( (idxCols & cMask)==0 ){
127373        if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
127374          goto end_auto_index_create;
127375        }
127376        pLoop->aLTerm[nKeyCol++] = pTerm;
127377        idxCols |= cMask;
127378      }
127379    }
127380  }
127381  assert( nKeyCol>0 );
127382  pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
127383  pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
127384                     | WHERE_AUTO_INDEX;
127385
127386  /* Count the number of additional columns needed to create a
127387  ** covering index.  A "covering index" is an index that contains all
127388  ** columns that are needed by the query.  With a covering index, the
127389  ** original table never needs to be accessed.  Automatic indices must
127390  ** be a covering index because the index will not be updated if the
127391  ** original table changes and the index and table cannot both be used
127392  ** if they go out of sync.
127393  */
127394  extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
127395  mxBitCol = MIN(BMS-1,pTable->nCol);
127396  testcase( pTable->nCol==BMS-1 );
127397  testcase( pTable->nCol==BMS-2 );
127398  for(i=0; i<mxBitCol; i++){
127399    if( extraCols & MASKBIT(i) ) nKeyCol++;
127400  }
127401  if( pSrc->colUsed & MASKBIT(BMS-1) ){
127402    nKeyCol += pTable->nCol - BMS + 1;
127403  }
127404
127405  /* Construct the Index object to describe this index */
127406  pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
127407  if( pIdx==0 ) goto end_auto_index_create;
127408  pLoop->u.btree.pIndex = pIdx;
127409  pIdx->zName = "auto-index";
127410  pIdx->pTable = pTable;
127411  n = 0;
127412  idxCols = 0;
127413  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
127414    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
127415      int iCol = pTerm->u.leftColumn;
127416      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
127417      testcase( iCol==BMS-1 );
127418      testcase( iCol==BMS );
127419      if( (idxCols & cMask)==0 ){
127420        Expr *pX = pTerm->pExpr;
127421        idxCols |= cMask;
127422        pIdx->aiColumn[n] = pTerm->u.leftColumn;
127423        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
127424        pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
127425        n++;
127426      }
127427    }
127428  }
127429  assert( (u32)n==pLoop->u.btree.nEq );
127430
127431  /* Add additional columns needed to make the automatic index into
127432  ** a covering index */
127433  for(i=0; i<mxBitCol; i++){
127434    if( extraCols & MASKBIT(i) ){
127435      pIdx->aiColumn[n] = i;
127436      pIdx->azColl[n] = sqlite3StrBINARY;
127437      n++;
127438    }
127439  }
127440  if( pSrc->colUsed & MASKBIT(BMS-1) ){
127441    for(i=BMS-1; i<pTable->nCol; i++){
127442      pIdx->aiColumn[n] = i;
127443      pIdx->azColl[n] = sqlite3StrBINARY;
127444      n++;
127445    }
127446  }
127447  assert( n==nKeyCol );
127448  pIdx->aiColumn[n] = XN_ROWID;
127449  pIdx->azColl[n] = sqlite3StrBINARY;
127450
127451  /* Create the automatic index */
127452  assert( pLevel->iIdxCur>=0 );
127453  pLevel->iIdxCur = pParse->nTab++;
127454  sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
127455  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
127456  VdbeComment((v, "for %s", pTable->zName));
127457
127458  /* Fill the automatic index with content */
127459  sqlite3ExprCachePush(pParse);
127460  pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
127461  if( pTabItem->fg.viaCoroutine ){
127462    int regYield = pTabItem->regReturn;
127463    addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
127464    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
127465    addrTop =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
127466    VdbeCoverage(v);
127467    VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
127468  }else{
127469    addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
127470  }
127471  if( pPartial ){
127472    iContinue = sqlite3VdbeMakeLabel(v);
127473    sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
127474    pLoop->wsFlags |= WHERE_PARTIALIDX;
127475  }
127476  regRecord = sqlite3GetTempReg(pParse);
127477  regBase = sqlite3GenerateIndexKey(
127478      pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
127479  );
127480  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
127481  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
127482  if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
127483  if( pTabItem->fg.viaCoroutine ){
127484    sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
127485    translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult, 1);
127486    sqlite3VdbeGoto(v, addrTop);
127487    pTabItem->fg.viaCoroutine = 0;
127488  }else{
127489    sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
127490  }
127491  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
127492  sqlite3VdbeJumpHere(v, addrTop);
127493  sqlite3ReleaseTempReg(pParse, regRecord);
127494  sqlite3ExprCachePop(pParse);
127495
127496  /* Jump here when skipping the initialization */
127497  sqlite3VdbeJumpHere(v, addrInit);
127498
127499end_auto_index_create:
127500  sqlite3ExprDelete(pParse->db, pPartial);
127501}
127502#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
127503
127504#ifndef SQLITE_OMIT_VIRTUALTABLE
127505/*
127506** Allocate and populate an sqlite3_index_info structure. It is the
127507** responsibility of the caller to eventually release the structure
127508** by passing the pointer returned by this function to sqlite3_free().
127509*/
127510static sqlite3_index_info *allocateIndexInfo(
127511  Parse *pParse,
127512  WhereClause *pWC,
127513  Bitmask mUnusable,              /* Ignore terms with these prereqs */
127514  struct SrcList_item *pSrc,
127515  ExprList *pOrderBy
127516){
127517  int i, j;
127518  int nTerm;
127519  struct sqlite3_index_constraint *pIdxCons;
127520  struct sqlite3_index_orderby *pIdxOrderBy;
127521  struct sqlite3_index_constraint_usage *pUsage;
127522  WhereTerm *pTerm;
127523  int nOrderBy;
127524  sqlite3_index_info *pIdxInfo;
127525
127526  /* Count the number of possible WHERE clause constraints referring
127527  ** to this virtual table */
127528  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
127529    if( pTerm->leftCursor != pSrc->iCursor ) continue;
127530    if( pTerm->prereqRight & mUnusable ) continue;
127531    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
127532    testcase( pTerm->eOperator & WO_IN );
127533    testcase( pTerm->eOperator & WO_ISNULL );
127534    testcase( pTerm->eOperator & WO_IS );
127535    testcase( pTerm->eOperator & WO_ALL );
127536    if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
127537    if( pTerm->wtFlags & TERM_VNULL ) continue;
127538    assert( pTerm->u.leftColumn>=(-1) );
127539    nTerm++;
127540  }
127541
127542  /* If the ORDER BY clause contains only columns in the current
127543  ** virtual table then allocate space for the aOrderBy part of
127544  ** the sqlite3_index_info structure.
127545  */
127546  nOrderBy = 0;
127547  if( pOrderBy ){
127548    int n = pOrderBy->nExpr;
127549    for(i=0; i<n; i++){
127550      Expr *pExpr = pOrderBy->a[i].pExpr;
127551      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
127552    }
127553    if( i==n){
127554      nOrderBy = n;
127555    }
127556  }
127557
127558  /* Allocate the sqlite3_index_info structure
127559  */
127560  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
127561                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
127562                           + sizeof(*pIdxOrderBy)*nOrderBy );
127563  if( pIdxInfo==0 ){
127564    sqlite3ErrorMsg(pParse, "out of memory");
127565    return 0;
127566  }
127567
127568  /* Initialize the structure.  The sqlite3_index_info structure contains
127569  ** many fields that are declared "const" to prevent xBestIndex from
127570  ** changing them.  We have to do some funky casting in order to
127571  ** initialize those fields.
127572  */
127573  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
127574  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
127575  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
127576  *(int*)&pIdxInfo->nConstraint = nTerm;
127577  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
127578  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
127579  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
127580  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
127581                                                                   pUsage;
127582
127583  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
127584    u8 op;
127585    if( pTerm->leftCursor != pSrc->iCursor ) continue;
127586    if( pTerm->prereqRight & mUnusable ) continue;
127587    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
127588    testcase( pTerm->eOperator & WO_IN );
127589    testcase( pTerm->eOperator & WO_IS );
127590    testcase( pTerm->eOperator & WO_ISNULL );
127591    testcase( pTerm->eOperator & WO_ALL );
127592    if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
127593    if( pTerm->wtFlags & TERM_VNULL ) continue;
127594    assert( pTerm->u.leftColumn>=(-1) );
127595    pIdxCons[j].iColumn = pTerm->u.leftColumn;
127596    pIdxCons[j].iTermOffset = i;
127597    op = (u8)pTerm->eOperator & WO_ALL;
127598    if( op==WO_IN ) op = WO_EQ;
127599    if( op==WO_MATCH ){
127600      op = pTerm->eMatchOp;
127601    }
127602    pIdxCons[j].op = op;
127603    /* The direct assignment in the previous line is possible only because
127604    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
127605    ** following asserts verify this fact. */
127606    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
127607    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
127608    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
127609    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
127610    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
127611    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
127612    assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
127613    j++;
127614  }
127615  for(i=0; i<nOrderBy; i++){
127616    Expr *pExpr = pOrderBy->a[i].pExpr;
127617    pIdxOrderBy[i].iColumn = pExpr->iColumn;
127618    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
127619  }
127620
127621  return pIdxInfo;
127622}
127623
127624/*
127625** The table object reference passed as the second argument to this function
127626** must represent a virtual table. This function invokes the xBestIndex()
127627** method of the virtual table with the sqlite3_index_info object that
127628** comes in as the 3rd argument to this function.
127629**
127630** If an error occurs, pParse is populated with an error message and a
127631** non-zero value is returned. Otherwise, 0 is returned and the output
127632** part of the sqlite3_index_info structure is left populated.
127633**
127634** Whether or not an error is returned, it is the responsibility of the
127635** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
127636** that this is required.
127637*/
127638static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
127639  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
127640  int rc;
127641
127642  TRACE_IDX_INPUTS(p);
127643  rc = pVtab->pModule->xBestIndex(pVtab, p);
127644  TRACE_IDX_OUTPUTS(p);
127645
127646  if( rc!=SQLITE_OK ){
127647    if( rc==SQLITE_NOMEM ){
127648      sqlite3OomFault(pParse->db);
127649    }else if( !pVtab->zErrMsg ){
127650      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
127651    }else{
127652      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
127653    }
127654  }
127655  sqlite3_free(pVtab->zErrMsg);
127656  pVtab->zErrMsg = 0;
127657
127658#if 0
127659  /* This error is now caught by the caller.
127660  ** Search for "xBestIndex malfunction" below */
127661  for(i=0; i<p->nConstraint; i++){
127662    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
127663      sqlite3ErrorMsg(pParse,
127664          "table %s: xBestIndex returned an invalid plan", pTab->zName);
127665    }
127666  }
127667#endif
127668
127669  return pParse->nErr;
127670}
127671#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
127672
127673#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127674/*
127675** Estimate the location of a particular key among all keys in an
127676** index.  Store the results in aStat as follows:
127677**
127678**    aStat[0]      Est. number of rows less than pRec
127679**    aStat[1]      Est. number of rows equal to pRec
127680**
127681** Return the index of the sample that is the smallest sample that
127682** is greater than or equal to pRec. Note that this index is not an index
127683** into the aSample[] array - it is an index into a virtual set of samples
127684** based on the contents of aSample[] and the number of fields in record
127685** pRec.
127686*/
127687static int whereKeyStats(
127688  Parse *pParse,              /* Database connection */
127689  Index *pIdx,                /* Index to consider domain of */
127690  UnpackedRecord *pRec,       /* Vector of values to consider */
127691  int roundUp,                /* Round up if true.  Round down if false */
127692  tRowcnt *aStat              /* OUT: stats written here */
127693){
127694  IndexSample *aSample = pIdx->aSample;
127695  int iCol;                   /* Index of required stats in anEq[] etc. */
127696  int i;                      /* Index of first sample >= pRec */
127697  int iSample;                /* Smallest sample larger than or equal to pRec */
127698  int iMin = 0;               /* Smallest sample not yet tested */
127699  int iTest;                  /* Next sample to test */
127700  int res;                    /* Result of comparison operation */
127701  int nField;                 /* Number of fields in pRec */
127702  tRowcnt iLower = 0;         /* anLt[] + anEq[] of largest sample pRec is > */
127703
127704#ifndef SQLITE_DEBUG
127705  UNUSED_PARAMETER( pParse );
127706#endif
127707  assert( pRec!=0 );
127708  assert( pIdx->nSample>0 );
127709  assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
127710
127711  /* Do a binary search to find the first sample greater than or equal
127712  ** to pRec. If pRec contains a single field, the set of samples to search
127713  ** is simply the aSample[] array. If the samples in aSample[] contain more
127714  ** than one fields, all fields following the first are ignored.
127715  **
127716  ** If pRec contains N fields, where N is more than one, then as well as the
127717  ** samples in aSample[] (truncated to N fields), the search also has to
127718  ** consider prefixes of those samples. For example, if the set of samples
127719  ** in aSample is:
127720  **
127721  **     aSample[0] = (a, 5)
127722  **     aSample[1] = (a, 10)
127723  **     aSample[2] = (b, 5)
127724  **     aSample[3] = (c, 100)
127725  **     aSample[4] = (c, 105)
127726  **
127727  ** Then the search space should ideally be the samples above and the
127728  ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
127729  ** the code actually searches this set:
127730  **
127731  **     0: (a)
127732  **     1: (a, 5)
127733  **     2: (a, 10)
127734  **     3: (a, 10)
127735  **     4: (b)
127736  **     5: (b, 5)
127737  **     6: (c)
127738  **     7: (c, 100)
127739  **     8: (c, 105)
127740  **     9: (c, 105)
127741  **
127742  ** For each sample in the aSample[] array, N samples are present in the
127743  ** effective sample array. In the above, samples 0 and 1 are based on
127744  ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
127745  **
127746  ** Often, sample i of each block of N effective samples has (i+1) fields.
127747  ** Except, each sample may be extended to ensure that it is greater than or
127748  ** equal to the previous sample in the array. For example, in the above,
127749  ** sample 2 is the first sample of a block of N samples, so at first it
127750  ** appears that it should be 1 field in size. However, that would make it
127751  ** smaller than sample 1, so the binary search would not work. As a result,
127752  ** it is extended to two fields. The duplicates that this creates do not
127753  ** cause any problems.
127754  */
127755  nField = pRec->nField;
127756  iCol = 0;
127757  iSample = pIdx->nSample * nField;
127758  do{
127759    int iSamp;                    /* Index in aSample[] of test sample */
127760    int n;                        /* Number of fields in test sample */
127761
127762    iTest = (iMin+iSample)/2;
127763    iSamp = iTest / nField;
127764    if( iSamp>0 ){
127765      /* The proposed effective sample is a prefix of sample aSample[iSamp].
127766      ** Specifically, the shortest prefix of at least (1 + iTest%nField)
127767      ** fields that is greater than the previous effective sample.  */
127768      for(n=(iTest % nField) + 1; n<nField; n++){
127769        if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
127770      }
127771    }else{
127772      n = iTest + 1;
127773    }
127774
127775    pRec->nField = n;
127776    res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
127777    if( res<0 ){
127778      iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
127779      iMin = iTest+1;
127780    }else if( res==0 && n<nField ){
127781      iLower = aSample[iSamp].anLt[n-1];
127782      iMin = iTest+1;
127783      res = -1;
127784    }else{
127785      iSample = iTest;
127786      iCol = n-1;
127787    }
127788  }while( res && iMin<iSample );
127789  i = iSample / nField;
127790
127791#ifdef SQLITE_DEBUG
127792  /* The following assert statements check that the binary search code
127793  ** above found the right answer. This block serves no purpose other
127794  ** than to invoke the asserts.  */
127795  if( pParse->db->mallocFailed==0 ){
127796    if( res==0 ){
127797      /* If (res==0) is true, then pRec must be equal to sample i. */
127798      assert( i<pIdx->nSample );
127799      assert( iCol==nField-1 );
127800      pRec->nField = nField;
127801      assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
127802           || pParse->db->mallocFailed
127803      );
127804    }else{
127805      /* Unless i==pIdx->nSample, indicating that pRec is larger than
127806      ** all samples in the aSample[] array, pRec must be smaller than the
127807      ** (iCol+1) field prefix of sample i.  */
127808      assert( i<=pIdx->nSample && i>=0 );
127809      pRec->nField = iCol+1;
127810      assert( i==pIdx->nSample
127811           || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
127812           || pParse->db->mallocFailed );
127813
127814      /* if i==0 and iCol==0, then record pRec is smaller than all samples
127815      ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
127816      ** be greater than or equal to the (iCol) field prefix of sample i.
127817      ** If (i>0), then pRec must also be greater than sample (i-1).  */
127818      if( iCol>0 ){
127819        pRec->nField = iCol;
127820        assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
127821             || pParse->db->mallocFailed );
127822      }
127823      if( i>0 ){
127824        pRec->nField = nField;
127825        assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
127826             || pParse->db->mallocFailed );
127827      }
127828    }
127829  }
127830#endif /* ifdef SQLITE_DEBUG */
127831
127832  if( res==0 ){
127833    /* Record pRec is equal to sample i */
127834    assert( iCol==nField-1 );
127835    aStat[0] = aSample[i].anLt[iCol];
127836    aStat[1] = aSample[i].anEq[iCol];
127837  }else{
127838    /* At this point, the (iCol+1) field prefix of aSample[i] is the first
127839    ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
127840    ** is larger than all samples in the array. */
127841    tRowcnt iUpper, iGap;
127842    if( i>=pIdx->nSample ){
127843      iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
127844    }else{
127845      iUpper = aSample[i].anLt[iCol];
127846    }
127847
127848    if( iLower>=iUpper ){
127849      iGap = 0;
127850    }else{
127851      iGap = iUpper - iLower;
127852    }
127853    if( roundUp ){
127854      iGap = (iGap*2)/3;
127855    }else{
127856      iGap = iGap/3;
127857    }
127858    aStat[0] = iLower + iGap;
127859    aStat[1] = pIdx->aAvgEq[iCol];
127860  }
127861
127862  /* Restore the pRec->nField value before returning.  */
127863  pRec->nField = nField;
127864  return i;
127865}
127866#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
127867
127868/*
127869** If it is not NULL, pTerm is a term that provides an upper or lower
127870** bound on a range scan. Without considering pTerm, it is estimated
127871** that the scan will visit nNew rows. This function returns the number
127872** estimated to be visited after taking pTerm into account.
127873**
127874** If the user explicitly specified a likelihood() value for this term,
127875** then the return value is the likelihood multiplied by the number of
127876** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
127877** has a likelihood of 0.50, and any other term a likelihood of 0.25.
127878*/
127879static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
127880  LogEst nRet = nNew;
127881  if( pTerm ){
127882    if( pTerm->truthProb<=0 ){
127883      nRet += pTerm->truthProb;
127884    }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
127885      nRet -= 20;        assert( 20==sqlite3LogEst(4) );
127886    }
127887  }
127888  return nRet;
127889}
127890
127891
127892#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127893/*
127894** Return the affinity for a single column of an index.
127895*/
127896static char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
127897  assert( iCol>=0 && iCol<pIdx->nColumn );
127898  if( !pIdx->zColAff ){
127899    if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
127900  }
127901  return pIdx->zColAff[iCol];
127902}
127903#endif
127904
127905
127906#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127907/*
127908** This function is called to estimate the number of rows visited by a
127909** range-scan on a skip-scan index. For example:
127910**
127911**   CREATE INDEX i1 ON t1(a, b, c);
127912**   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
127913**
127914** Value pLoop->nOut is currently set to the estimated number of rows
127915** visited for scanning (a=? AND b=?). This function reduces that estimate
127916** by some factor to account for the (c BETWEEN ? AND ?) expression based
127917** on the stat4 data for the index. this scan will be peformed multiple
127918** times (once for each (a,b) combination that matches a=?) is dealt with
127919** by the caller.
127920**
127921** It does this by scanning through all stat4 samples, comparing values
127922** extracted from pLower and pUpper with the corresponding column in each
127923** sample. If L and U are the number of samples found to be less than or
127924** equal to the values extracted from pLower and pUpper respectively, and
127925** N is the total number of samples, the pLoop->nOut value is adjusted
127926** as follows:
127927**
127928**   nOut = nOut * ( min(U - L, 1) / N )
127929**
127930** If pLower is NULL, or a value cannot be extracted from the term, L is
127931** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
127932** U is set to N.
127933**
127934** Normally, this function sets *pbDone to 1 before returning. However,
127935** if no value can be extracted from either pLower or pUpper (and so the
127936** estimate of the number of rows delivered remains unchanged), *pbDone
127937** is left as is.
127938**
127939** If an error occurs, an SQLite error code is returned. Otherwise,
127940** SQLITE_OK.
127941*/
127942static int whereRangeSkipScanEst(
127943  Parse *pParse,       /* Parsing & code generating context */
127944  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
127945  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
127946  WhereLoop *pLoop,    /* Update the .nOut value of this loop */
127947  int *pbDone          /* Set to true if at least one expr. value extracted */
127948){
127949  Index *p = pLoop->u.btree.pIndex;
127950  int nEq = pLoop->u.btree.nEq;
127951  sqlite3 *db = pParse->db;
127952  int nLower = -1;
127953  int nUpper = p->nSample+1;
127954  int rc = SQLITE_OK;
127955  u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
127956  CollSeq *pColl;
127957
127958  sqlite3_value *p1 = 0;          /* Value extracted from pLower */
127959  sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
127960  sqlite3_value *pVal = 0;        /* Value extracted from record */
127961
127962  pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
127963  if( pLower ){
127964    rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
127965    nLower = 0;
127966  }
127967  if( pUpper && rc==SQLITE_OK ){
127968    rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
127969    nUpper = p2 ? 0 : p->nSample;
127970  }
127971
127972  if( p1 || p2 ){
127973    int i;
127974    int nDiff;
127975    for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
127976      rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
127977      if( rc==SQLITE_OK && p1 ){
127978        int res = sqlite3MemCompare(p1, pVal, pColl);
127979        if( res>=0 ) nLower++;
127980      }
127981      if( rc==SQLITE_OK && p2 ){
127982        int res = sqlite3MemCompare(p2, pVal, pColl);
127983        if( res>=0 ) nUpper++;
127984      }
127985    }
127986    nDiff = (nUpper - nLower);
127987    if( nDiff<=0 ) nDiff = 1;
127988
127989    /* If there is both an upper and lower bound specified, and the
127990    ** comparisons indicate that they are close together, use the fallback
127991    ** method (assume that the scan visits 1/64 of the rows) for estimating
127992    ** the number of rows visited. Otherwise, estimate the number of rows
127993    ** using the method described in the header comment for this function. */
127994    if( nDiff!=1 || pUpper==0 || pLower==0 ){
127995      int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
127996      pLoop->nOut -= nAdjust;
127997      *pbDone = 1;
127998      WHERETRACE(0x10, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
127999                           nLower, nUpper, nAdjust*-1, pLoop->nOut));
128000    }
128001
128002  }else{
128003    assert( *pbDone==0 );
128004  }
128005
128006  sqlite3ValueFree(p1);
128007  sqlite3ValueFree(p2);
128008  sqlite3ValueFree(pVal);
128009
128010  return rc;
128011}
128012#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
128013
128014/*
128015** This function is used to estimate the number of rows that will be visited
128016** by scanning an index for a range of values. The range may have an upper
128017** bound, a lower bound, or both. The WHERE clause terms that set the upper
128018** and lower bounds are represented by pLower and pUpper respectively. For
128019** example, assuming that index p is on t1(a):
128020**
128021**   ... FROM t1 WHERE a > ? AND a < ? ...
128022**                    |_____|   |_____|
128023**                       |         |
128024**                     pLower    pUpper
128025**
128026** If either of the upper or lower bound is not present, then NULL is passed in
128027** place of the corresponding WhereTerm.
128028**
128029** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
128030** column subject to the range constraint. Or, equivalently, the number of
128031** equality constraints optimized by the proposed index scan. For example,
128032** assuming index p is on t1(a, b), and the SQL query is:
128033**
128034**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
128035**
128036** then nEq is set to 1 (as the range restricted column, b, is the second
128037** left-most column of the index). Or, if the query is:
128038**
128039**   ... FROM t1 WHERE a > ? AND a < ? ...
128040**
128041** then nEq is set to 0.
128042**
128043** When this function is called, *pnOut is set to the sqlite3LogEst() of the
128044** number of rows that the index scan is expected to visit without
128045** considering the range constraints. If nEq is 0, then *pnOut is the number of
128046** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
128047** to account for the range constraints pLower and pUpper.
128048**
128049** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
128050** used, a single range inequality reduces the search space by a factor of 4.
128051** and a pair of constraints (x>? AND x<?) reduces the expected number of
128052** rows visited by a factor of 64.
128053*/
128054static int whereRangeScanEst(
128055  Parse *pParse,       /* Parsing & code generating context */
128056  WhereLoopBuilder *pBuilder,
128057  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
128058  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
128059  WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
128060){
128061  int rc = SQLITE_OK;
128062  int nOut = pLoop->nOut;
128063  LogEst nNew;
128064
128065#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128066  Index *p = pLoop->u.btree.pIndex;
128067  int nEq = pLoop->u.btree.nEq;
128068
128069  if( p->nSample>0 && nEq<p->nSampleCol ){
128070    if( nEq==pBuilder->nRecValid ){
128071      UnpackedRecord *pRec = pBuilder->pRec;
128072      tRowcnt a[2];
128073      u8 aff;
128074
128075      /* Variable iLower will be set to the estimate of the number of rows in
128076      ** the index that are less than the lower bound of the range query. The
128077      ** lower bound being the concatenation of $P and $L, where $P is the
128078      ** key-prefix formed by the nEq values matched against the nEq left-most
128079      ** columns of the index, and $L is the value in pLower.
128080      **
128081      ** Or, if pLower is NULL or $L cannot be extracted from it (because it
128082      ** is not a simple variable or literal value), the lower bound of the
128083      ** range is $P. Due to a quirk in the way whereKeyStats() works, even
128084      ** if $L is available, whereKeyStats() is called for both ($P) and
128085      ** ($P:$L) and the larger of the two returned values is used.
128086      **
128087      ** Similarly, iUpper is to be set to the estimate of the number of rows
128088      ** less than the upper bound of the range query. Where the upper bound
128089      ** is either ($P) or ($P:$U). Again, even if $U is available, both values
128090      ** of iUpper are requested of whereKeyStats() and the smaller used.
128091      **
128092      ** The number of rows between the two bounds is then just iUpper-iLower.
128093      */
128094      tRowcnt iLower;     /* Rows less than the lower bound */
128095      tRowcnt iUpper;     /* Rows less than the upper bound */
128096      int iLwrIdx = -2;   /* aSample[] for the lower bound */
128097      int iUprIdx = -1;   /* aSample[] for the upper bound */
128098
128099      if( pRec ){
128100        testcase( pRec->nField!=pBuilder->nRecValid );
128101        pRec->nField = pBuilder->nRecValid;
128102      }
128103      aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq);
128104      assert( nEq!=p->nKeyCol || aff==SQLITE_AFF_INTEGER );
128105      /* Determine iLower and iUpper using ($P) only. */
128106      if( nEq==0 ){
128107        iLower = 0;
128108        iUpper = p->nRowEst0;
128109      }else{
128110        /* Note: this call could be optimized away - since the same values must
128111        ** have been requested when testing key $P in whereEqualScanEst().  */
128112        whereKeyStats(pParse, p, pRec, 0, a);
128113        iLower = a[0];
128114        iUpper = a[0] + a[1];
128115      }
128116
128117      assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
128118      assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
128119      assert( p->aSortOrder!=0 );
128120      if( p->aSortOrder[nEq] ){
128121        /* The roles of pLower and pUpper are swapped for a DESC index */
128122        SWAP(WhereTerm*, pLower, pUpper);
128123      }
128124
128125      /* If possible, improve on the iLower estimate using ($P:$L). */
128126      if( pLower ){
128127        int bOk;                    /* True if value is extracted from pExpr */
128128        Expr *pExpr = pLower->pExpr->pRight;
128129        rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
128130        if( rc==SQLITE_OK && bOk ){
128131          tRowcnt iNew;
128132          iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
128133          iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
128134          if( iNew>iLower ) iLower = iNew;
128135          nOut--;
128136          pLower = 0;
128137        }
128138      }
128139
128140      /* If possible, improve on the iUpper estimate using ($P:$U). */
128141      if( pUpper ){
128142        int bOk;                    /* True if value is extracted from pExpr */
128143        Expr *pExpr = pUpper->pExpr->pRight;
128144        rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
128145        if( rc==SQLITE_OK && bOk ){
128146          tRowcnt iNew;
128147          iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
128148          iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
128149          if( iNew<iUpper ) iUpper = iNew;
128150          nOut--;
128151          pUpper = 0;
128152        }
128153      }
128154
128155      pBuilder->pRec = pRec;
128156      if( rc==SQLITE_OK ){
128157        if( iUpper>iLower ){
128158          nNew = sqlite3LogEst(iUpper - iLower);
128159          /* TUNING:  If both iUpper and iLower are derived from the same
128160          ** sample, then assume they are 4x more selective.  This brings
128161          ** the estimated selectivity more in line with what it would be
128162          ** if estimated without the use of STAT3/4 tables. */
128163          if( iLwrIdx==iUprIdx ) nNew -= 20;  assert( 20==sqlite3LogEst(4) );
128164        }else{
128165          nNew = 10;        assert( 10==sqlite3LogEst(2) );
128166        }
128167        if( nNew<nOut ){
128168          nOut = nNew;
128169        }
128170        WHERETRACE(0x10, ("STAT4 range scan: %u..%u  est=%d\n",
128171                           (u32)iLower, (u32)iUpper, nOut));
128172      }
128173    }else{
128174      int bDone = 0;
128175      rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
128176      if( bDone ) return rc;
128177    }
128178  }
128179#else
128180  UNUSED_PARAMETER(pParse);
128181  UNUSED_PARAMETER(pBuilder);
128182  assert( pLower || pUpper );
128183#endif
128184  assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
128185  nNew = whereRangeAdjust(pLower, nOut);
128186  nNew = whereRangeAdjust(pUpper, nNew);
128187
128188  /* TUNING: If there is both an upper and lower limit and neither limit
128189  ** has an application-defined likelihood(), assume the range is
128190  ** reduced by an additional 75%. This means that, by default, an open-ended
128191  ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
128192  ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
128193  ** match 1/64 of the index. */
128194  if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
128195    nNew -= 20;
128196  }
128197
128198  nOut -= (pLower!=0) + (pUpper!=0);
128199  if( nNew<10 ) nNew = 10;
128200  if( nNew<nOut ) nOut = nNew;
128201#if defined(WHERETRACE_ENABLED)
128202  if( pLoop->nOut>nOut ){
128203    WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
128204                    pLoop->nOut, nOut));
128205  }
128206#endif
128207  pLoop->nOut = (LogEst)nOut;
128208  return rc;
128209}
128210
128211#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128212/*
128213** Estimate the number of rows that will be returned based on
128214** an equality constraint x=VALUE and where that VALUE occurs in
128215** the histogram data.  This only works when x is the left-most
128216** column of an index and sqlite_stat3 histogram data is available
128217** for that index.  When pExpr==NULL that means the constraint is
128218** "x IS NULL" instead of "x=VALUE".
128219**
128220** Write the estimated row count into *pnRow and return SQLITE_OK.
128221** If unable to make an estimate, leave *pnRow unchanged and return
128222** non-zero.
128223**
128224** This routine can fail if it is unable to load a collating sequence
128225** required for string comparison, or if unable to allocate memory
128226** for a UTF conversion required for comparison.  The error is stored
128227** in the pParse structure.
128228*/
128229static int whereEqualScanEst(
128230  Parse *pParse,       /* Parsing & code generating context */
128231  WhereLoopBuilder *pBuilder,
128232  Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
128233  tRowcnt *pnRow       /* Write the revised row estimate here */
128234){
128235  Index *p = pBuilder->pNew->u.btree.pIndex;
128236  int nEq = pBuilder->pNew->u.btree.nEq;
128237  UnpackedRecord *pRec = pBuilder->pRec;
128238  u8 aff;                   /* Column affinity */
128239  int rc;                   /* Subfunction return code */
128240  tRowcnt a[2];             /* Statistics */
128241  int bOk;
128242
128243  assert( nEq>=1 );
128244  assert( nEq<=p->nColumn );
128245  assert( p->aSample!=0 );
128246  assert( p->nSample>0 );
128247  assert( pBuilder->nRecValid<nEq );
128248
128249  /* If values are not available for all fields of the index to the left
128250  ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
128251  if( pBuilder->nRecValid<(nEq-1) ){
128252    return SQLITE_NOTFOUND;
128253  }
128254
128255  /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
128256  ** below would return the same value.  */
128257  if( nEq>=p->nColumn ){
128258    *pnRow = 1;
128259    return SQLITE_OK;
128260  }
128261
128262  aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq-1);
128263  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
128264  pBuilder->pRec = pRec;
128265  if( rc!=SQLITE_OK ) return rc;
128266  if( bOk==0 ) return SQLITE_NOTFOUND;
128267  pBuilder->nRecValid = nEq;
128268
128269  whereKeyStats(pParse, p, pRec, 0, a);
128270  WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
128271                   p->zName, nEq-1, (int)a[1]));
128272  *pnRow = a[1];
128273
128274  return rc;
128275}
128276#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
128277
128278#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128279/*
128280** Estimate the number of rows that will be returned based on
128281** an IN constraint where the right-hand side of the IN operator
128282** is a list of values.  Example:
128283**
128284**        WHERE x IN (1,2,3,4)
128285**
128286** Write the estimated row count into *pnRow and return SQLITE_OK.
128287** If unable to make an estimate, leave *pnRow unchanged and return
128288** non-zero.
128289**
128290** This routine can fail if it is unable to load a collating sequence
128291** required for string comparison, or if unable to allocate memory
128292** for a UTF conversion required for comparison.  The error is stored
128293** in the pParse structure.
128294*/
128295static int whereInScanEst(
128296  Parse *pParse,       /* Parsing & code generating context */
128297  WhereLoopBuilder *pBuilder,
128298  ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
128299  tRowcnt *pnRow       /* Write the revised row estimate here */
128300){
128301  Index *p = pBuilder->pNew->u.btree.pIndex;
128302  i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
128303  int nRecValid = pBuilder->nRecValid;
128304  int rc = SQLITE_OK;     /* Subfunction return code */
128305  tRowcnt nEst;           /* Number of rows for a single term */
128306  tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
128307  int i;                  /* Loop counter */
128308
128309  assert( p->aSample!=0 );
128310  for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
128311    nEst = nRow0;
128312    rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
128313    nRowEst += nEst;
128314    pBuilder->nRecValid = nRecValid;
128315  }
128316
128317  if( rc==SQLITE_OK ){
128318    if( nRowEst > nRow0 ) nRowEst = nRow0;
128319    *pnRow = nRowEst;
128320    WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
128321  }
128322  assert( pBuilder->nRecValid==nRecValid );
128323  return rc;
128324}
128325#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
128326
128327
128328#ifdef WHERETRACE_ENABLED
128329/*
128330** Print the content of a WhereTerm object
128331*/
128332static void whereTermPrint(WhereTerm *pTerm, int iTerm){
128333  if( pTerm==0 ){
128334    sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
128335  }else{
128336    char zType[4];
128337    char zLeft[50];
128338    memcpy(zType, "...", 4);
128339    if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
128340    if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
128341    if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
128342    if( pTerm->eOperator & WO_SINGLE ){
128343      sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
128344                       pTerm->leftCursor, pTerm->u.leftColumn);
128345    }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
128346      sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
128347                       pTerm->u.pOrInfo->indexable);
128348    }else{
128349      sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
128350    }
128351    sqlite3DebugPrintf(
128352       "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x\n",
128353       iTerm, pTerm, zType, zLeft, pTerm->truthProb,
128354       pTerm->eOperator, pTerm->wtFlags);
128355    sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
128356  }
128357}
128358#endif
128359
128360#ifdef WHERETRACE_ENABLED
128361/*
128362** Show the complete content of a WhereClause
128363*/
128364SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
128365  int i;
128366  for(i=0; i<pWC->nTerm; i++){
128367    whereTermPrint(&pWC->a[i], i);
128368  }
128369}
128370#endif
128371
128372#ifdef WHERETRACE_ENABLED
128373/*
128374** Print a WhereLoop object for debugging purposes
128375*/
128376static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
128377  WhereInfo *pWInfo = pWC->pWInfo;
128378  int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
128379  struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
128380  Table *pTab = pItem->pTab;
128381  Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
128382  sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
128383                     p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
128384  sqlite3DebugPrintf(" %12s",
128385                     pItem->zAlias ? pItem->zAlias : pTab->zName);
128386  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
128387    const char *zName;
128388    if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
128389      if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
128390        int i = sqlite3Strlen30(zName) - 1;
128391        while( zName[i]!='_' ) i--;
128392        zName += i;
128393      }
128394      sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
128395    }else{
128396      sqlite3DebugPrintf("%20s","");
128397    }
128398  }else{
128399    char *z;
128400    if( p->u.vtab.idxStr ){
128401      z = sqlite3_mprintf("(%d,\"%s\",%x)",
128402                p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
128403    }else{
128404      z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
128405    }
128406    sqlite3DebugPrintf(" %-19s", z);
128407    sqlite3_free(z);
128408  }
128409  if( p->wsFlags & WHERE_SKIPSCAN ){
128410    sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
128411  }else{
128412    sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
128413  }
128414  sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
128415  if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
128416    int i;
128417    for(i=0; i<p->nLTerm; i++){
128418      whereTermPrint(p->aLTerm[i], i);
128419    }
128420  }
128421}
128422#endif
128423
128424/*
128425** Convert bulk memory into a valid WhereLoop that can be passed
128426** to whereLoopClear harmlessly.
128427*/
128428static void whereLoopInit(WhereLoop *p){
128429  p->aLTerm = p->aLTermSpace;
128430  p->nLTerm = 0;
128431  p->nLSlot = ArraySize(p->aLTermSpace);
128432  p->wsFlags = 0;
128433}
128434
128435/*
128436** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
128437*/
128438static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
128439  if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
128440    if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
128441      sqlite3_free(p->u.vtab.idxStr);
128442      p->u.vtab.needFree = 0;
128443      p->u.vtab.idxStr = 0;
128444    }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
128445      sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
128446      sqlite3DbFree(db, p->u.btree.pIndex);
128447      p->u.btree.pIndex = 0;
128448    }
128449  }
128450}
128451
128452/*
128453** Deallocate internal memory used by a WhereLoop object
128454*/
128455static void whereLoopClear(sqlite3 *db, WhereLoop *p){
128456  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
128457  whereLoopClearUnion(db, p);
128458  whereLoopInit(p);
128459}
128460
128461/*
128462** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
128463*/
128464static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
128465  WhereTerm **paNew;
128466  if( p->nLSlot>=n ) return SQLITE_OK;
128467  n = (n+7)&~7;
128468  paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
128469  if( paNew==0 ) return SQLITE_NOMEM_BKPT;
128470  memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
128471  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
128472  p->aLTerm = paNew;
128473  p->nLSlot = n;
128474  return SQLITE_OK;
128475}
128476
128477/*
128478** Transfer content from the second pLoop into the first.
128479*/
128480static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
128481  whereLoopClearUnion(db, pTo);
128482  if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
128483    memset(&pTo->u, 0, sizeof(pTo->u));
128484    return SQLITE_NOMEM_BKPT;
128485  }
128486  memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
128487  memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
128488  if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
128489    pFrom->u.vtab.needFree = 0;
128490  }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
128491    pFrom->u.btree.pIndex = 0;
128492  }
128493  return SQLITE_OK;
128494}
128495
128496/*
128497** Delete a WhereLoop object
128498*/
128499static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
128500  whereLoopClear(db, p);
128501  sqlite3DbFree(db, p);
128502}
128503
128504/*
128505** Free a WhereInfo structure
128506*/
128507static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
128508  if( ALWAYS(pWInfo) ){
128509    int i;
128510    for(i=0; i<pWInfo->nLevel; i++){
128511      WhereLevel *pLevel = &pWInfo->a[i];
128512      if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
128513        sqlite3DbFree(db, pLevel->u.in.aInLoop);
128514      }
128515    }
128516    sqlite3WhereClauseClear(&pWInfo->sWC);
128517    while( pWInfo->pLoops ){
128518      WhereLoop *p = pWInfo->pLoops;
128519      pWInfo->pLoops = p->pNextLoop;
128520      whereLoopDelete(db, p);
128521    }
128522    sqlite3DbFree(db, pWInfo);
128523  }
128524}
128525
128526/*
128527** Return TRUE if all of the following are true:
128528**
128529**   (1)  X has the same or lower cost that Y
128530**   (2)  X is a proper subset of Y
128531**   (3)  X skips at least as many columns as Y
128532**
128533** By "proper subset" we mean that X uses fewer WHERE clause terms
128534** than Y and that every WHERE clause term used by X is also used
128535** by Y.
128536**
128537** If X is a proper subset of Y then Y is a better choice and ought
128538** to have a lower cost.  This routine returns TRUE when that cost
128539** relationship is inverted and needs to be adjusted.  The third rule
128540** was added because if X uses skip-scan less than Y it still might
128541** deserve a lower cost even if it is a proper subset of Y.
128542*/
128543static int whereLoopCheaperProperSubset(
128544  const WhereLoop *pX,       /* First WhereLoop to compare */
128545  const WhereLoop *pY        /* Compare against this WhereLoop */
128546){
128547  int i, j;
128548  if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
128549    return 0; /* X is not a subset of Y */
128550  }
128551  if( pY->nSkip > pX->nSkip ) return 0;
128552  if( pX->rRun >= pY->rRun ){
128553    if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
128554    if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
128555  }
128556  for(i=pX->nLTerm-1; i>=0; i--){
128557    if( pX->aLTerm[i]==0 ) continue;
128558    for(j=pY->nLTerm-1; j>=0; j--){
128559      if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
128560    }
128561    if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
128562  }
128563  return 1;  /* All conditions meet */
128564}
128565
128566/*
128567** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
128568** that:
128569**
128570**   (1) pTemplate costs less than any other WhereLoops that are a proper
128571**       subset of pTemplate
128572**
128573**   (2) pTemplate costs more than any other WhereLoops for which pTemplate
128574**       is a proper subset.
128575**
128576** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
128577** WHERE clause terms than Y and that every WHERE clause term used by X is
128578** also used by Y.
128579*/
128580static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
128581  if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
128582  for(; p; p=p->pNextLoop){
128583    if( p->iTab!=pTemplate->iTab ) continue;
128584    if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
128585    if( whereLoopCheaperProperSubset(p, pTemplate) ){
128586      /* Adjust pTemplate cost downward so that it is cheaper than its
128587      ** subset p. */
128588      WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
128589                       pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
128590      pTemplate->rRun = p->rRun;
128591      pTemplate->nOut = p->nOut - 1;
128592    }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
128593      /* Adjust pTemplate cost upward so that it is costlier than p since
128594      ** pTemplate is a proper subset of p */
128595      WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
128596                       pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
128597      pTemplate->rRun = p->rRun;
128598      pTemplate->nOut = p->nOut + 1;
128599    }
128600  }
128601}
128602
128603/*
128604** Search the list of WhereLoops in *ppPrev looking for one that can be
128605** supplanted by pTemplate.
128606**
128607** Return NULL if the WhereLoop list contains an entry that can supplant
128608** pTemplate, in other words if pTemplate does not belong on the list.
128609**
128610** If pX is a WhereLoop that pTemplate can supplant, then return the
128611** link that points to pX.
128612**
128613** If pTemplate cannot supplant any existing element of the list but needs
128614** to be added to the list, then return a pointer to the tail of the list.
128615*/
128616static WhereLoop **whereLoopFindLesser(
128617  WhereLoop **ppPrev,
128618  const WhereLoop *pTemplate
128619){
128620  WhereLoop *p;
128621  for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
128622    if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
128623      /* If either the iTab or iSortIdx values for two WhereLoop are different
128624      ** then those WhereLoops need to be considered separately.  Neither is
128625      ** a candidate to replace the other. */
128626      continue;
128627    }
128628    /* In the current implementation, the rSetup value is either zero
128629    ** or the cost of building an automatic index (NlogN) and the NlogN
128630    ** is the same for compatible WhereLoops. */
128631    assert( p->rSetup==0 || pTemplate->rSetup==0
128632                 || p->rSetup==pTemplate->rSetup );
128633
128634    /* whereLoopAddBtree() always generates and inserts the automatic index
128635    ** case first.  Hence compatible candidate WhereLoops never have a larger
128636    ** rSetup. Call this SETUP-INVARIANT */
128637    assert( p->rSetup>=pTemplate->rSetup );
128638
128639    /* Any loop using an appliation-defined index (or PRIMARY KEY or
128640    ** UNIQUE constraint) with one or more == constraints is better
128641    ** than an automatic index. Unless it is a skip-scan. */
128642    if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
128643     && (pTemplate->nSkip)==0
128644     && (pTemplate->wsFlags & WHERE_INDEXED)!=0
128645     && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
128646     && (p->prereq & pTemplate->prereq)==pTemplate->prereq
128647    ){
128648      break;
128649    }
128650
128651    /* If existing WhereLoop p is better than pTemplate, pTemplate can be
128652    ** discarded.  WhereLoop p is better if:
128653    **   (1)  p has no more dependencies than pTemplate, and
128654    **   (2)  p has an equal or lower cost than pTemplate
128655    */
128656    if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
128657     && p->rSetup<=pTemplate->rSetup                  /* (2a) */
128658     && p->rRun<=pTemplate->rRun                      /* (2b) */
128659     && p->nOut<=pTemplate->nOut                      /* (2c) */
128660    ){
128661      return 0;  /* Discard pTemplate */
128662    }
128663
128664    /* If pTemplate is always better than p, then cause p to be overwritten
128665    ** with pTemplate.  pTemplate is better than p if:
128666    **   (1)  pTemplate has no more dependences than p, and
128667    **   (2)  pTemplate has an equal or lower cost than p.
128668    */
128669    if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
128670     && p->rRun>=pTemplate->rRun                             /* (2a) */
128671     && p->nOut>=pTemplate->nOut                             /* (2b) */
128672    ){
128673      assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
128674      break;   /* Cause p to be overwritten by pTemplate */
128675    }
128676  }
128677  return ppPrev;
128678}
128679
128680/*
128681** Insert or replace a WhereLoop entry using the template supplied.
128682**
128683** An existing WhereLoop entry might be overwritten if the new template
128684** is better and has fewer dependencies.  Or the template will be ignored
128685** and no insert will occur if an existing WhereLoop is faster and has
128686** fewer dependencies than the template.  Otherwise a new WhereLoop is
128687** added based on the template.
128688**
128689** If pBuilder->pOrSet is not NULL then we care about only the
128690** prerequisites and rRun and nOut costs of the N best loops.  That
128691** information is gathered in the pBuilder->pOrSet object.  This special
128692** processing mode is used only for OR clause processing.
128693**
128694** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
128695** still might overwrite similar loops with the new template if the
128696** new template is better.  Loops may be overwritten if the following
128697** conditions are met:
128698**
128699**    (1)  They have the same iTab.
128700**    (2)  They have the same iSortIdx.
128701**    (3)  The template has same or fewer dependencies than the current loop
128702**    (4)  The template has the same or lower cost than the current loop
128703*/
128704static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
128705  WhereLoop **ppPrev, *p;
128706  WhereInfo *pWInfo = pBuilder->pWInfo;
128707  sqlite3 *db = pWInfo->pParse->db;
128708  int rc;
128709
128710  /* If pBuilder->pOrSet is defined, then only keep track of the costs
128711  ** and prereqs.
128712  */
128713  if( pBuilder->pOrSet!=0 ){
128714    if( pTemplate->nLTerm ){
128715#if WHERETRACE_ENABLED
128716      u16 n = pBuilder->pOrSet->n;
128717      int x =
128718#endif
128719      whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
128720                                    pTemplate->nOut);
128721#if WHERETRACE_ENABLED /* 0x8 */
128722      if( sqlite3WhereTrace & 0x8 ){
128723        sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
128724        whereLoopPrint(pTemplate, pBuilder->pWC);
128725      }
128726#endif
128727    }
128728    return SQLITE_OK;
128729  }
128730
128731  /* Look for an existing WhereLoop to replace with pTemplate
128732  */
128733  whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
128734  ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
128735
128736  if( ppPrev==0 ){
128737    /* There already exists a WhereLoop on the list that is better
128738    ** than pTemplate, so just ignore pTemplate */
128739#if WHERETRACE_ENABLED /* 0x8 */
128740    if( sqlite3WhereTrace & 0x8 ){
128741      sqlite3DebugPrintf("   skip: ");
128742      whereLoopPrint(pTemplate, pBuilder->pWC);
128743    }
128744#endif
128745    return SQLITE_OK;
128746  }else{
128747    p = *ppPrev;
128748  }
128749
128750  /* If we reach this point it means that either p[] should be overwritten
128751  ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
128752  ** WhereLoop and insert it.
128753  */
128754#if WHERETRACE_ENABLED /* 0x8 */
128755  if( sqlite3WhereTrace & 0x8 ){
128756    if( p!=0 ){
128757      sqlite3DebugPrintf("replace: ");
128758      whereLoopPrint(p, pBuilder->pWC);
128759    }
128760    sqlite3DebugPrintf("    add: ");
128761    whereLoopPrint(pTemplate, pBuilder->pWC);
128762  }
128763#endif
128764  if( p==0 ){
128765    /* Allocate a new WhereLoop to add to the end of the list */
128766    *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
128767    if( p==0 ) return SQLITE_NOMEM_BKPT;
128768    whereLoopInit(p);
128769    p->pNextLoop = 0;
128770  }else{
128771    /* We will be overwriting WhereLoop p[].  But before we do, first
128772    ** go through the rest of the list and delete any other entries besides
128773    ** p[] that are also supplated by pTemplate */
128774    WhereLoop **ppTail = &p->pNextLoop;
128775    WhereLoop *pToDel;
128776    while( *ppTail ){
128777      ppTail = whereLoopFindLesser(ppTail, pTemplate);
128778      if( ppTail==0 ) break;
128779      pToDel = *ppTail;
128780      if( pToDel==0 ) break;
128781      *ppTail = pToDel->pNextLoop;
128782#if WHERETRACE_ENABLED /* 0x8 */
128783      if( sqlite3WhereTrace & 0x8 ){
128784        sqlite3DebugPrintf(" delete: ");
128785        whereLoopPrint(pToDel, pBuilder->pWC);
128786      }
128787#endif
128788      whereLoopDelete(db, pToDel);
128789    }
128790  }
128791  rc = whereLoopXfer(db, p, pTemplate);
128792  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
128793    Index *pIndex = p->u.btree.pIndex;
128794    if( pIndex && pIndex->tnum==0 ){
128795      p->u.btree.pIndex = 0;
128796    }
128797  }
128798  return rc;
128799}
128800
128801/*
128802** Adjust the WhereLoop.nOut value downward to account for terms of the
128803** WHERE clause that reference the loop but which are not used by an
128804** index.
128805*
128806** For every WHERE clause term that is not used by the index
128807** and which has a truth probability assigned by one of the likelihood(),
128808** likely(), or unlikely() SQL functions, reduce the estimated number
128809** of output rows by the probability specified.
128810**
128811** TUNING:  For every WHERE clause term that is not used by the index
128812** and which does not have an assigned truth probability, heuristics
128813** described below are used to try to estimate the truth probability.
128814** TODO --> Perhaps this is something that could be improved by better
128815** table statistics.
128816**
128817** Heuristic 1:  Estimate the truth probability as 93.75%.  The 93.75%
128818** value corresponds to -1 in LogEst notation, so this means decrement
128819** the WhereLoop.nOut field for every such WHERE clause term.
128820**
128821** Heuristic 2:  If there exists one or more WHERE clause terms of the
128822** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
128823** final output row estimate is no greater than 1/4 of the total number
128824** of rows in the table.  In other words, assume that x==EXPR will filter
128825** out at least 3 out of 4 rows.  If EXPR is -1 or 0 or 1, then maybe the
128826** "x" column is boolean or else -1 or 0 or 1 is a common default value
128827** on the "x" column and so in that case only cap the output row estimate
128828** at 1/2 instead of 1/4.
128829*/
128830static void whereLoopOutputAdjust(
128831  WhereClause *pWC,      /* The WHERE clause */
128832  WhereLoop *pLoop,      /* The loop to adjust downward */
128833  LogEst nRow            /* Number of rows in the entire table */
128834){
128835  WhereTerm *pTerm, *pX;
128836  Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
128837  int i, j, k;
128838  LogEst iReduce = 0;    /* pLoop->nOut should not exceed nRow-iReduce */
128839
128840  assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
128841  for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
128842    if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
128843    if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
128844    if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
128845    for(j=pLoop->nLTerm-1; j>=0; j--){
128846      pX = pLoop->aLTerm[j];
128847      if( pX==0 ) continue;
128848      if( pX==pTerm ) break;
128849      if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
128850    }
128851    if( j<0 ){
128852      if( pTerm->truthProb<=0 ){
128853        /* If a truth probability is specified using the likelihood() hints,
128854        ** then use the probability provided by the application. */
128855        pLoop->nOut += pTerm->truthProb;
128856      }else{
128857        /* In the absence of explicit truth probabilities, use heuristics to
128858        ** guess a reasonable truth probability. */
128859        pLoop->nOut--;
128860        if( pTerm->eOperator&(WO_EQ|WO_IS) ){
128861          Expr *pRight = pTerm->pExpr->pRight;
128862          testcase( pTerm->pExpr->op==TK_IS );
128863          if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
128864            k = 10;
128865          }else{
128866            k = 20;
128867          }
128868          if( iReduce<k ) iReduce = k;
128869        }
128870      }
128871    }
128872  }
128873  if( pLoop->nOut > nRow-iReduce )  pLoop->nOut = nRow - iReduce;
128874}
128875
128876/*
128877** Adjust the cost C by the costMult facter T.  This only occurs if
128878** compiled with -DSQLITE_ENABLE_COSTMULT
128879*/
128880#ifdef SQLITE_ENABLE_COSTMULT
128881# define ApplyCostMultiplier(C,T)  C += T
128882#else
128883# define ApplyCostMultiplier(C,T)
128884#endif
128885
128886/*
128887** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
128888** index pIndex. Try to match one more.
128889**
128890** When this function is called, pBuilder->pNew->nOut contains the
128891** number of rows expected to be visited by filtering using the nEq
128892** terms only. If it is modified, this value is restored before this
128893** function returns.
128894**
128895** If pProbe->tnum==0, that means pIndex is a fake index used for the
128896** INTEGER PRIMARY KEY.
128897*/
128898static int whereLoopAddBtreeIndex(
128899  WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
128900  struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
128901  Index *pProbe,                  /* An index on pSrc */
128902  LogEst nInMul                   /* log(Number of iterations due to IN) */
128903){
128904  WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
128905  Parse *pParse = pWInfo->pParse;        /* Parsing context */
128906  sqlite3 *db = pParse->db;       /* Database connection malloc context */
128907  WhereLoop *pNew;                /* Template WhereLoop under construction */
128908  WhereTerm *pTerm;               /* A WhereTerm under consideration */
128909  int opMask;                     /* Valid operators for constraints */
128910  WhereScan scan;                 /* Iterator for WHERE terms */
128911  Bitmask saved_prereq;           /* Original value of pNew->prereq */
128912  u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
128913  u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
128914  u16 saved_nSkip;                /* Original value of pNew->nSkip */
128915  u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
128916  LogEst saved_nOut;              /* Original value of pNew->nOut */
128917  int rc = SQLITE_OK;             /* Return code */
128918  LogEst rSize;                   /* Number of rows in the table */
128919  LogEst rLogSize;                /* Logarithm of table size */
128920  WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
128921
128922  pNew = pBuilder->pNew;
128923  if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
128924
128925  assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
128926  assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
128927  if( pNew->wsFlags & WHERE_BTM_LIMIT ){
128928    opMask = WO_LT|WO_LE;
128929  }else{
128930    opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
128931  }
128932  if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
128933
128934  assert( pNew->u.btree.nEq<pProbe->nColumn );
128935
128936  saved_nEq = pNew->u.btree.nEq;
128937  saved_nSkip = pNew->nSkip;
128938  saved_nLTerm = pNew->nLTerm;
128939  saved_wsFlags = pNew->wsFlags;
128940  saved_prereq = pNew->prereq;
128941  saved_nOut = pNew->nOut;
128942  pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
128943                        opMask, pProbe);
128944  pNew->rSetup = 0;
128945  rSize = pProbe->aiRowLogEst[0];
128946  rLogSize = estLog(rSize);
128947  for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
128948    u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
128949    LogEst rCostIdx;
128950    LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
128951    int nIn = 0;
128952#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128953    int nRecValid = pBuilder->nRecValid;
128954#endif
128955    if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
128956     && indexColumnNotNull(pProbe, saved_nEq)
128957    ){
128958      continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
128959    }
128960    if( pTerm->prereqRight & pNew->maskSelf ) continue;
128961
128962    /* Do not allow the upper bound of a LIKE optimization range constraint
128963    ** to mix with a lower range bound from some other source */
128964    if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
128965
128966    /* Do not allow IS constraints from the WHERE clause to be used by the
128967    ** right table of a LEFT JOIN.  Only constraints in the ON clause are
128968    ** allowed */
128969    if( (pSrc->fg.jointype & JT_LEFT)!=0
128970     && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
128971     && (eOp & (WO_IS|WO_ISNULL))!=0
128972    ){
128973      testcase( eOp & WO_IS );
128974      testcase( eOp & WO_ISNULL );
128975      continue;
128976    }
128977
128978    pNew->wsFlags = saved_wsFlags;
128979    pNew->u.btree.nEq = saved_nEq;
128980    pNew->nLTerm = saved_nLTerm;
128981    if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
128982    pNew->aLTerm[pNew->nLTerm++] = pTerm;
128983    pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
128984
128985    assert( nInMul==0
128986        || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
128987        || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
128988        || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
128989    );
128990
128991    if( eOp & WO_IN ){
128992      Expr *pExpr = pTerm->pExpr;
128993      pNew->wsFlags |= WHERE_COLUMN_IN;
128994      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
128995        /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
128996        nIn = 46;  assert( 46==sqlite3LogEst(25) );
128997      }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
128998        /* "x IN (value, value, ...)" */
128999        nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
129000      }
129001      assert( nIn>0 );  /* RHS always has 2 or more terms...  The parser
129002                        ** changes "x IN (?)" into "x=?". */
129003
129004    }else if( eOp & (WO_EQ|WO_IS) ){
129005      int iCol = pProbe->aiColumn[saved_nEq];
129006      pNew->wsFlags |= WHERE_COLUMN_EQ;
129007      assert( saved_nEq==pNew->u.btree.nEq );
129008      if( iCol==XN_ROWID
129009       || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
129010      ){
129011        if( iCol>=0 && pProbe->uniqNotNull==0 ){
129012          pNew->wsFlags |= WHERE_UNQ_WANTED;
129013        }else{
129014          pNew->wsFlags |= WHERE_ONEROW;
129015        }
129016      }
129017    }else if( eOp & WO_ISNULL ){
129018      pNew->wsFlags |= WHERE_COLUMN_NULL;
129019    }else if( eOp & (WO_GT|WO_GE) ){
129020      testcase( eOp & WO_GT );
129021      testcase( eOp & WO_GE );
129022      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
129023      pBtm = pTerm;
129024      pTop = 0;
129025      if( pTerm->wtFlags & TERM_LIKEOPT ){
129026        /* Range contraints that come from the LIKE optimization are
129027        ** always used in pairs. */
129028        pTop = &pTerm[1];
129029        assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
129030        assert( pTop->wtFlags & TERM_LIKEOPT );
129031        assert( pTop->eOperator==WO_LT );
129032        if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
129033        pNew->aLTerm[pNew->nLTerm++] = pTop;
129034        pNew->wsFlags |= WHERE_TOP_LIMIT;
129035      }
129036    }else{
129037      assert( eOp & (WO_LT|WO_LE) );
129038      testcase( eOp & WO_LT );
129039      testcase( eOp & WO_LE );
129040      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
129041      pTop = pTerm;
129042      pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
129043                     pNew->aLTerm[pNew->nLTerm-2] : 0;
129044    }
129045
129046    /* At this point pNew->nOut is set to the number of rows expected to
129047    ** be visited by the index scan before considering term pTerm, or the
129048    ** values of nIn and nInMul. In other words, assuming that all
129049    ** "x IN(...)" terms are replaced with "x = ?". This block updates
129050    ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
129051    assert( pNew->nOut==saved_nOut );
129052    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
129053      /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
129054      ** data, using some other estimate.  */
129055      whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
129056    }else{
129057      int nEq = ++pNew->u.btree.nEq;
129058      assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
129059
129060      assert( pNew->nOut==saved_nOut );
129061      if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
129062        assert( (eOp & WO_IN) || nIn==0 );
129063        testcase( eOp & WO_IN );
129064        pNew->nOut += pTerm->truthProb;
129065        pNew->nOut -= nIn;
129066      }else{
129067#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129068        tRowcnt nOut = 0;
129069        if( nInMul==0
129070         && pProbe->nSample
129071         && pNew->u.btree.nEq<=pProbe->nSampleCol
129072         && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
129073        ){
129074          Expr *pExpr = pTerm->pExpr;
129075          if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
129076            testcase( eOp & WO_EQ );
129077            testcase( eOp & WO_IS );
129078            testcase( eOp & WO_ISNULL );
129079            rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
129080          }else{
129081            rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
129082          }
129083          if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
129084          if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
129085          if( nOut ){
129086            pNew->nOut = sqlite3LogEst(nOut);
129087            if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
129088            pNew->nOut -= nIn;
129089          }
129090        }
129091        if( nOut==0 )
129092#endif
129093        {
129094          pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
129095          if( eOp & WO_ISNULL ){
129096            /* TUNING: If there is no likelihood() value, assume that a
129097            ** "col IS NULL" expression matches twice as many rows
129098            ** as (col=?). */
129099            pNew->nOut += 10;
129100          }
129101        }
129102      }
129103    }
129104
129105    /* Set rCostIdx to the cost of visiting selected rows in index. Add
129106    ** it to pNew->rRun, which is currently set to the cost of the index
129107    ** seek only. Then, if this is a non-covering index, add the cost of
129108    ** visiting the rows in the main table.  */
129109    rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
129110    pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
129111    if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
129112      pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
129113    }
129114    ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
129115
129116    nOutUnadjusted = pNew->nOut;
129117    pNew->rRun += nInMul + nIn;
129118    pNew->nOut += nInMul + nIn;
129119    whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
129120    rc = whereLoopInsert(pBuilder, pNew);
129121
129122    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
129123      pNew->nOut = saved_nOut;
129124    }else{
129125      pNew->nOut = nOutUnadjusted;
129126    }
129127
129128    if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
129129     && pNew->u.btree.nEq<pProbe->nColumn
129130    ){
129131      whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
129132    }
129133    pNew->nOut = saved_nOut;
129134#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129135    pBuilder->nRecValid = nRecValid;
129136#endif
129137  }
129138  pNew->prereq = saved_prereq;
129139  pNew->u.btree.nEq = saved_nEq;
129140  pNew->nSkip = saved_nSkip;
129141  pNew->wsFlags = saved_wsFlags;
129142  pNew->nOut = saved_nOut;
129143  pNew->nLTerm = saved_nLTerm;
129144
129145  /* Consider using a skip-scan if there are no WHERE clause constraints
129146  ** available for the left-most terms of the index, and if the average
129147  ** number of repeats in the left-most terms is at least 18.
129148  **
129149  ** The magic number 18 is selected on the basis that scanning 17 rows
129150  ** is almost always quicker than an index seek (even though if the index
129151  ** contains fewer than 2^17 rows we assume otherwise in other parts of
129152  ** the code). And, even if it is not, it should not be too much slower.
129153  ** On the other hand, the extra seeks could end up being significantly
129154  ** more expensive.  */
129155  assert( 42==sqlite3LogEst(18) );
129156  if( saved_nEq==saved_nSkip
129157   && saved_nEq+1<pProbe->nKeyCol
129158   && pProbe->noSkipScan==0
129159   && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
129160   && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
129161  ){
129162    LogEst nIter;
129163    pNew->u.btree.nEq++;
129164    pNew->nSkip++;
129165    pNew->aLTerm[pNew->nLTerm++] = 0;
129166    pNew->wsFlags |= WHERE_SKIPSCAN;
129167    nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
129168    pNew->nOut -= nIter;
129169    /* TUNING:  Because uncertainties in the estimates for skip-scan queries,
129170    ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
129171    nIter += 5;
129172    whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
129173    pNew->nOut = saved_nOut;
129174    pNew->u.btree.nEq = saved_nEq;
129175    pNew->nSkip = saved_nSkip;
129176    pNew->wsFlags = saved_wsFlags;
129177  }
129178
129179  return rc;
129180}
129181
129182/*
129183** Return True if it is possible that pIndex might be useful in
129184** implementing the ORDER BY clause in pBuilder.
129185**
129186** Return False if pBuilder does not contain an ORDER BY clause or
129187** if there is no way for pIndex to be useful in implementing that
129188** ORDER BY clause.
129189*/
129190static int indexMightHelpWithOrderBy(
129191  WhereLoopBuilder *pBuilder,
129192  Index *pIndex,
129193  int iCursor
129194){
129195  ExprList *pOB;
129196  ExprList *aColExpr;
129197  int ii, jj;
129198
129199  if( pIndex->bUnordered ) return 0;
129200  if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
129201  for(ii=0; ii<pOB->nExpr; ii++){
129202    Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
129203    if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
129204      if( pExpr->iColumn<0 ) return 1;
129205      for(jj=0; jj<pIndex->nKeyCol; jj++){
129206        if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
129207      }
129208    }else if( (aColExpr = pIndex->aColExpr)!=0 ){
129209      for(jj=0; jj<pIndex->nKeyCol; jj++){
129210        if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
129211        if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
129212          return 1;
129213        }
129214      }
129215    }
129216  }
129217  return 0;
129218}
129219
129220/*
129221** Return a bitmask where 1s indicate that the corresponding column of
129222** the table is used by an index.  Only the first 63 columns are considered.
129223*/
129224static Bitmask columnsInIndex(Index *pIdx){
129225  Bitmask m = 0;
129226  int j;
129227  for(j=pIdx->nColumn-1; j>=0; j--){
129228    int x = pIdx->aiColumn[j];
129229    if( x>=0 ){
129230      testcase( x==BMS-1 );
129231      testcase( x==BMS-2 );
129232      if( x<BMS-1 ) m |= MASKBIT(x);
129233    }
129234  }
129235  return m;
129236}
129237
129238/* Check to see if a partial index with pPartIndexWhere can be used
129239** in the current query.  Return true if it can be and false if not.
129240*/
129241static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
129242  int i;
129243  WhereTerm *pTerm;
129244  while( pWhere->op==TK_AND ){
129245    if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
129246    pWhere = pWhere->pRight;
129247  }
129248  for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
129249    Expr *pExpr = pTerm->pExpr;
129250    if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
129251     && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
129252    ){
129253      return 1;
129254    }
129255  }
129256  return 0;
129257}
129258
129259/*
129260** Add all WhereLoop objects for a single table of the join where the table
129261** is idenfied by pBuilder->pNew->iTab.  That table is guaranteed to be
129262** a b-tree table, not a virtual table.
129263**
129264** The costs (WhereLoop.rRun) of the b-tree loops added by this function
129265** are calculated as follows:
129266**
129267** For a full scan, assuming the table (or index) contains nRow rows:
129268**
129269**     cost = nRow * 3.0                    // full-table scan
129270**     cost = nRow * K                      // scan of covering index
129271**     cost = nRow * (K+3.0)                // scan of non-covering index
129272**
129273** where K is a value between 1.1 and 3.0 set based on the relative
129274** estimated average size of the index and table records.
129275**
129276** For an index scan, where nVisit is the number of index rows visited
129277** by the scan, and nSeek is the number of seek operations required on
129278** the index b-tree:
129279**
129280**     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
129281**     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
129282**
129283** Normally, nSeek is 1. nSeek values greater than 1 come about if the
129284** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
129285** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
129286**
129287** The estimated values (nRow, nVisit, nSeek) often contain a large amount
129288** of uncertainty.  For this reason, scoring is designed to pick plans that
129289** "do the least harm" if the estimates are inaccurate.  For example, a
129290** log(nRow) factor is omitted from a non-covering index scan in order to
129291** bias the scoring in favor of using an index, since the worst-case
129292** performance of using an index is far better than the worst-case performance
129293** of a full table scan.
129294*/
129295static int whereLoopAddBtree(
129296  WhereLoopBuilder *pBuilder, /* WHERE clause information */
129297  Bitmask mPrereq             /* Extra prerequesites for using this table */
129298){
129299  WhereInfo *pWInfo;          /* WHERE analysis context */
129300  Index *pProbe;              /* An index we are evaluating */
129301  Index sPk;                  /* A fake index object for the primary key */
129302  LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
129303  i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
129304  SrcList *pTabList;          /* The FROM clause */
129305  struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
129306  WhereLoop *pNew;            /* Template WhereLoop object */
129307  int rc = SQLITE_OK;         /* Return code */
129308  int iSortIdx = 1;           /* Index number */
129309  int b;                      /* A boolean value */
129310  LogEst rSize;               /* number of rows in the table */
129311  LogEst rLogSize;            /* Logarithm of the number of rows in the table */
129312  WhereClause *pWC;           /* The parsed WHERE clause */
129313  Table *pTab;                /* Table being queried */
129314
129315  pNew = pBuilder->pNew;
129316  pWInfo = pBuilder->pWInfo;
129317  pTabList = pWInfo->pTabList;
129318  pSrc = pTabList->a + pNew->iTab;
129319  pTab = pSrc->pTab;
129320  pWC = pBuilder->pWC;
129321  assert( !IsVirtual(pSrc->pTab) );
129322
129323  if( pSrc->pIBIndex ){
129324    /* An INDEXED BY clause specifies a particular index to use */
129325    pProbe = pSrc->pIBIndex;
129326  }else if( !HasRowid(pTab) ){
129327    pProbe = pTab->pIndex;
129328  }else{
129329    /* There is no INDEXED BY clause.  Create a fake Index object in local
129330    ** variable sPk to represent the rowid primary key index.  Make this
129331    ** fake index the first in a chain of Index objects with all of the real
129332    ** indices to follow */
129333    Index *pFirst;                  /* First of real indices on the table */
129334    memset(&sPk, 0, sizeof(Index));
129335    sPk.nKeyCol = 1;
129336    sPk.nColumn = 1;
129337    sPk.aiColumn = &aiColumnPk;
129338    sPk.aiRowLogEst = aiRowEstPk;
129339    sPk.onError = OE_Replace;
129340    sPk.pTable = pTab;
129341    sPk.szIdxRow = pTab->szTabRow;
129342    aiRowEstPk[0] = pTab->nRowLogEst;
129343    aiRowEstPk[1] = 0;
129344    pFirst = pSrc->pTab->pIndex;
129345    if( pSrc->fg.notIndexed==0 ){
129346      /* The real indices of the table are only considered if the
129347      ** NOT INDEXED qualifier is omitted from the FROM clause */
129348      sPk.pNext = pFirst;
129349    }
129350    pProbe = &sPk;
129351  }
129352  rSize = pTab->nRowLogEst;
129353  rLogSize = estLog(rSize);
129354
129355#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
129356  /* Automatic indexes */
129357  if( !pBuilder->pOrSet      /* Not part of an OR optimization */
129358   && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
129359   && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
129360   && pSrc->pIBIndex==0      /* Has no INDEXED BY clause */
129361   && !pSrc->fg.notIndexed   /* Has no NOT INDEXED clause */
129362   && HasRowid(pTab)         /* Not WITHOUT ROWID table. (FIXME: Why not?) */
129363   && !pSrc->fg.isCorrelated /* Not a correlated subquery */
129364   && !pSrc->fg.isRecursive  /* Not a recursive common table expression. */
129365  ){
129366    /* Generate auto-index WhereLoops */
129367    WhereTerm *pTerm;
129368    WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
129369    for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
129370      if( pTerm->prereqRight & pNew->maskSelf ) continue;
129371      if( termCanDriveIndex(pTerm, pSrc, 0) ){
129372        pNew->u.btree.nEq = 1;
129373        pNew->nSkip = 0;
129374        pNew->u.btree.pIndex = 0;
129375        pNew->nLTerm = 1;
129376        pNew->aLTerm[0] = pTerm;
129377        /* TUNING: One-time cost for computing the automatic index is
129378        ** estimated to be X*N*log2(N) where N is the number of rows in
129379        ** the table being indexed and where X is 7 (LogEst=28) for normal
129380        ** tables or 1.375 (LogEst=4) for views and subqueries.  The value
129381        ** of X is smaller for views and subqueries so that the query planner
129382        ** will be more aggressive about generating automatic indexes for
129383        ** those objects, since there is no opportunity to add schema
129384        ** indexes on subqueries and views. */
129385        pNew->rSetup = rLogSize + rSize + 4;
129386        if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
129387          pNew->rSetup += 24;
129388        }
129389        ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
129390        if( pNew->rSetup<0 ) pNew->rSetup = 0;
129391        /* TUNING: Each index lookup yields 20 rows in the table.  This
129392        ** is more than the usual guess of 10 rows, since we have no way
129393        ** of knowing how selective the index will ultimately be.  It would
129394        ** not be unreasonable to make this value much larger. */
129395        pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
129396        pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
129397        pNew->wsFlags = WHERE_AUTO_INDEX;
129398        pNew->prereq = mPrereq | pTerm->prereqRight;
129399        rc = whereLoopInsert(pBuilder, pNew);
129400      }
129401    }
129402  }
129403#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
129404
129405  /* Loop over all indices
129406  */
129407  for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
129408    if( pProbe->pPartIdxWhere!=0
129409     && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
129410      testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */
129411      continue;  /* Partial index inappropriate for this query */
129412    }
129413    rSize = pProbe->aiRowLogEst[0];
129414    pNew->u.btree.nEq = 0;
129415    pNew->nSkip = 0;
129416    pNew->nLTerm = 0;
129417    pNew->iSortIdx = 0;
129418    pNew->rSetup = 0;
129419    pNew->prereq = mPrereq;
129420    pNew->nOut = rSize;
129421    pNew->u.btree.pIndex = pProbe;
129422    b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
129423    /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
129424    assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
129425    if( pProbe->tnum<=0 ){
129426      /* Integer primary key index */
129427      pNew->wsFlags = WHERE_IPK;
129428
129429      /* Full table scan */
129430      pNew->iSortIdx = b ? iSortIdx : 0;
129431      /* TUNING: Cost of full table scan is (N*3.0). */
129432      pNew->rRun = rSize + 16;
129433      ApplyCostMultiplier(pNew->rRun, pTab->costMult);
129434      whereLoopOutputAdjust(pWC, pNew, rSize);
129435      rc = whereLoopInsert(pBuilder, pNew);
129436      pNew->nOut = rSize;
129437      if( rc ) break;
129438    }else{
129439      Bitmask m;
129440      if( pProbe->isCovering ){
129441        pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
129442        m = 0;
129443      }else{
129444        m = pSrc->colUsed & ~columnsInIndex(pProbe);
129445        pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
129446      }
129447
129448      /* Full scan via index */
129449      if( b
129450       || !HasRowid(pTab)
129451       || pProbe->pPartIdxWhere!=0
129452       || ( m==0
129453         && pProbe->bUnordered==0
129454         && (pProbe->szIdxRow<pTab->szTabRow)
129455         && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
129456         && sqlite3GlobalConfig.bUseCis
129457         && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
129458          )
129459      ){
129460        pNew->iSortIdx = b ? iSortIdx : 0;
129461
129462        /* The cost of visiting the index rows is N*K, where K is
129463        ** between 1.1 and 3.0, depending on the relative sizes of the
129464        ** index and table rows. */
129465        pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
129466        if( m!=0 ){
129467          /* If this is a non-covering index scan, add in the cost of
129468          ** doing table lookups.  The cost will be 3x the number of
129469          ** lookups.  Take into account WHERE clause terms that can be
129470          ** satisfied using just the index, and that do not require a
129471          ** table lookup. */
129472          LogEst nLookup = rSize + 16;  /* Base cost:  N*3 */
129473          int ii;
129474          int iCur = pSrc->iCursor;
129475          WhereClause *pWC2 = &pWInfo->sWC;
129476          for(ii=0; ii<pWC2->nTerm; ii++){
129477            WhereTerm *pTerm = &pWC2->a[ii];
129478            if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
129479              break;
129480            }
129481            /* pTerm can be evaluated using just the index.  So reduce
129482            ** the expected number of table lookups accordingly */
129483            if( pTerm->truthProb<=0 ){
129484              nLookup += pTerm->truthProb;
129485            }else{
129486              nLookup--;
129487              if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
129488            }
129489          }
129490
129491          pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
129492        }
129493        ApplyCostMultiplier(pNew->rRun, pTab->costMult);
129494        whereLoopOutputAdjust(pWC, pNew, rSize);
129495        rc = whereLoopInsert(pBuilder, pNew);
129496        pNew->nOut = rSize;
129497        if( rc ) break;
129498      }
129499    }
129500
129501    rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
129502#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129503    sqlite3Stat4ProbeFree(pBuilder->pRec);
129504    pBuilder->nRecValid = 0;
129505    pBuilder->pRec = 0;
129506#endif
129507
129508    /* If there was an INDEXED BY clause, then only that one index is
129509    ** considered. */
129510    if( pSrc->pIBIndex ) break;
129511  }
129512  return rc;
129513}
129514
129515#ifndef SQLITE_OMIT_VIRTUALTABLE
129516
129517/*
129518** Argument pIdxInfo is already populated with all constraints that may
129519** be used by the virtual table identified by pBuilder->pNew->iTab. This
129520** function marks a subset of those constraints usable, invokes the
129521** xBestIndex method and adds the returned plan to pBuilder.
129522**
129523** A constraint is marked usable if:
129524**
129525**   * Argument mUsable indicates that its prerequisites are available, and
129526**
129527**   * It is not one of the operators specified in the mExclude mask passed
129528**     as the fourth argument (which in practice is either WO_IN or 0).
129529**
129530** Argument mPrereq is a mask of tables that must be scanned before the
129531** virtual table in question. These are added to the plans prerequisites
129532** before it is added to pBuilder.
129533**
129534** Output parameter *pbIn is set to true if the plan added to pBuilder
129535** uses one or more WO_IN terms, or false otherwise.
129536*/
129537static int whereLoopAddVirtualOne(
129538  WhereLoopBuilder *pBuilder,
129539  Bitmask mPrereq,                /* Mask of tables that must be used. */
129540  Bitmask mUsable,                /* Mask of usable tables */
129541  u16 mExclude,                   /* Exclude terms using these operators */
129542  sqlite3_index_info *pIdxInfo,   /* Populated object for xBestIndex */
129543  int *pbIn                       /* OUT: True if plan uses an IN(...) op */
129544){
129545  WhereClause *pWC = pBuilder->pWC;
129546  struct sqlite3_index_constraint *pIdxCons;
129547  struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
129548  int i;
129549  int mxTerm;
129550  int rc = SQLITE_OK;
129551  WhereLoop *pNew = pBuilder->pNew;
129552  Parse *pParse = pBuilder->pWInfo->pParse;
129553  struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
129554  int nConstraint = pIdxInfo->nConstraint;
129555
129556  assert( (mUsable & mPrereq)==mPrereq );
129557  *pbIn = 0;
129558  pNew->prereq = mPrereq;
129559
129560  /* Set the usable flag on the subset of constraints identified by
129561  ** arguments mUsable and mExclude. */
129562  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
129563  for(i=0; i<nConstraint; i++, pIdxCons++){
129564    WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
129565    pIdxCons->usable = 0;
129566    if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
129567     && (pTerm->eOperator & mExclude)==0
129568    ){
129569      pIdxCons->usable = 1;
129570    }
129571  }
129572
129573  /* Initialize the output fields of the sqlite3_index_info structure */
129574  memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
129575  assert( pIdxInfo->needToFreeIdxStr==0 );
129576  pIdxInfo->idxStr = 0;
129577  pIdxInfo->idxNum = 0;
129578  pIdxInfo->orderByConsumed = 0;
129579  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
129580  pIdxInfo->estimatedRows = 25;
129581  pIdxInfo->idxFlags = 0;
129582  pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
129583
129584  /* Invoke the virtual table xBestIndex() method */
129585  rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
129586  if( rc ) return rc;
129587
129588  mxTerm = -1;
129589  assert( pNew->nLSlot>=nConstraint );
129590  for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
129591  pNew->u.vtab.omitMask = 0;
129592  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
129593  for(i=0; i<nConstraint; i++, pIdxCons++){
129594    int iTerm;
129595    if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
129596      WhereTerm *pTerm;
129597      int j = pIdxCons->iTermOffset;
129598      if( iTerm>=nConstraint
129599       || j<0
129600       || j>=pWC->nTerm
129601       || pNew->aLTerm[iTerm]!=0
129602       || pIdxCons->usable==0
129603      ){
129604        rc = SQLITE_ERROR;
129605        sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
129606        return rc;
129607      }
129608      testcase( iTerm==nConstraint-1 );
129609      testcase( j==0 );
129610      testcase( j==pWC->nTerm-1 );
129611      pTerm = &pWC->a[j];
129612      pNew->prereq |= pTerm->prereqRight;
129613      assert( iTerm<pNew->nLSlot );
129614      pNew->aLTerm[iTerm] = pTerm;
129615      if( iTerm>mxTerm ) mxTerm = iTerm;
129616      testcase( iTerm==15 );
129617      testcase( iTerm==16 );
129618      if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
129619      if( (pTerm->eOperator & WO_IN)!=0 ){
129620        /* A virtual table that is constrained by an IN clause may not
129621        ** consume the ORDER BY clause because (1) the order of IN terms
129622        ** is not necessarily related to the order of output terms and
129623        ** (2) Multiple outputs from a single IN value will not merge
129624        ** together.  */
129625        pIdxInfo->orderByConsumed = 0;
129626        pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
129627        *pbIn = 1; assert( (mExclude & WO_IN)==0 );
129628      }
129629    }
129630  }
129631
129632  pNew->nLTerm = mxTerm+1;
129633  assert( pNew->nLTerm<=pNew->nLSlot );
129634  pNew->u.vtab.idxNum = pIdxInfo->idxNum;
129635  pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
129636  pIdxInfo->needToFreeIdxStr = 0;
129637  pNew->u.vtab.idxStr = pIdxInfo->idxStr;
129638  pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
129639      pIdxInfo->nOrderBy : 0);
129640  pNew->rSetup = 0;
129641  pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
129642  pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
129643
129644  /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
129645  ** that the scan will visit at most one row. Clear it otherwise. */
129646  if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
129647    pNew->wsFlags |= WHERE_ONEROW;
129648  }else{
129649    pNew->wsFlags &= ~WHERE_ONEROW;
129650  }
129651  rc = whereLoopInsert(pBuilder, pNew);
129652  if( pNew->u.vtab.needFree ){
129653    sqlite3_free(pNew->u.vtab.idxStr);
129654    pNew->u.vtab.needFree = 0;
129655  }
129656  WHERETRACE(0xffff, ("  bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
129657                      *pbIn, (sqlite3_uint64)mPrereq,
129658                      (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
129659
129660  return rc;
129661}
129662
129663
129664/*
129665** Add all WhereLoop objects for a table of the join identified by
129666** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
129667**
129668** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
129669** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
129670** entries that occur before the virtual table in the FROM clause and are
129671** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
129672** mUnusable mask contains all FROM clause entries that occur after the
129673** virtual table and are separated from it by at least one LEFT or
129674** CROSS JOIN.
129675**
129676** For example, if the query were:
129677**
129678**   ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
129679**
129680** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
129681**
129682** All the tables in mPrereq must be scanned before the current virtual
129683** table. So any terms for which all prerequisites are satisfied by
129684** mPrereq may be specified as "usable" in all calls to xBestIndex.
129685** Conversely, all tables in mUnusable must be scanned after the current
129686** virtual table, so any terms for which the prerequisites overlap with
129687** mUnusable should always be configured as "not-usable" for xBestIndex.
129688*/
129689static int whereLoopAddVirtual(
129690  WhereLoopBuilder *pBuilder,  /* WHERE clause information */
129691  Bitmask mPrereq,             /* Tables that must be scanned before this one */
129692  Bitmask mUnusable            /* Tables that must be scanned after this one */
129693){
129694  int rc = SQLITE_OK;          /* Return code */
129695  WhereInfo *pWInfo;           /* WHERE analysis context */
129696  Parse *pParse;               /* The parsing context */
129697  WhereClause *pWC;            /* The WHERE clause */
129698  struct SrcList_item *pSrc;   /* The FROM clause term to search */
129699  sqlite3_index_info *p;       /* Object to pass to xBestIndex() */
129700  int nConstraint;             /* Number of constraints in p */
129701  int bIn;                     /* True if plan uses IN(...) operator */
129702  WhereLoop *pNew;
129703  Bitmask mBest;               /* Tables used by best possible plan */
129704
129705  assert( (mPrereq & mUnusable)==0 );
129706  pWInfo = pBuilder->pWInfo;
129707  pParse = pWInfo->pParse;
129708  pWC = pBuilder->pWC;
129709  pNew = pBuilder->pNew;
129710  pSrc = &pWInfo->pTabList->a[pNew->iTab];
129711  assert( IsVirtual(pSrc->pTab) );
129712  p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy);
129713  if( p==0 ) return SQLITE_NOMEM_BKPT;
129714  pNew->rSetup = 0;
129715  pNew->wsFlags = WHERE_VIRTUALTABLE;
129716  pNew->nLTerm = 0;
129717  pNew->u.vtab.needFree = 0;
129718  nConstraint = p->nConstraint;
129719  if( whereLoopResize(pParse->db, pNew, nConstraint) ){
129720    sqlite3DbFree(pParse->db, p);
129721    return SQLITE_NOMEM_BKPT;
129722  }
129723
129724  /* First call xBestIndex() with all constraints usable. */
129725  WHERETRACE(0x40, ("  VirtualOne: all usable\n"));
129726  rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, &bIn);
129727
129728  /* If the call to xBestIndex() with all terms enabled produced a plan
129729  ** that does not require any source tables (IOW: a plan with mBest==0),
129730  ** then there is no point in making any further calls to xBestIndex()
129731  ** since they will all return the same result (if the xBestIndex()
129732  ** implementation is sane). */
129733  if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
129734    int seenZero = 0;             /* True if a plan with no prereqs seen */
129735    int seenZeroNoIN = 0;         /* Plan with no prereqs and no IN(...) seen */
129736    Bitmask mPrev = 0;
129737    Bitmask mBestNoIn = 0;
129738
129739    /* If the plan produced by the earlier call uses an IN(...) term, call
129740    ** xBestIndex again, this time with IN(...) terms disabled. */
129741    if( bIn ){
129742      WHERETRACE(0x40, ("  VirtualOne: all usable w/o IN\n"));
129743      rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, WO_IN, p, &bIn);
129744      assert( bIn==0 );
129745      mBestNoIn = pNew->prereq & ~mPrereq;
129746      if( mBestNoIn==0 ){
129747        seenZero = 1;
129748        seenZeroNoIN = 1;
129749      }
129750    }
129751
129752    /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
129753    ** in the set of terms that apply to the current virtual table.  */
129754    while( rc==SQLITE_OK ){
129755      int i;
129756      Bitmask mNext = ALLBITS;
129757      assert( mNext>0 );
129758      for(i=0; i<nConstraint; i++){
129759        Bitmask mThis = (
129760            pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
129761        );
129762        if( mThis>mPrev && mThis<mNext ) mNext = mThis;
129763      }
129764      mPrev = mNext;
129765      if( mNext==ALLBITS ) break;
129766      if( mNext==mBest || mNext==mBestNoIn ) continue;
129767      WHERETRACE(0x40, ("  VirtualOne: mPrev=%04llx mNext=%04llx\n",
129768                       (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
129769      rc = whereLoopAddVirtualOne(pBuilder, mPrereq, mNext|mPrereq, 0, p, &bIn);
129770      if( pNew->prereq==mPrereq ){
129771        seenZero = 1;
129772        if( bIn==0 ) seenZeroNoIN = 1;
129773      }
129774    }
129775
129776    /* If the calls to xBestIndex() in the above loop did not find a plan
129777    ** that requires no source tables at all (i.e. one guaranteed to be
129778    ** usable), make a call here with all source tables disabled */
129779    if( rc==SQLITE_OK && seenZero==0 ){
129780      WHERETRACE(0x40, ("  VirtualOne: all disabled\n"));
129781      rc = whereLoopAddVirtualOne(pBuilder, mPrereq, mPrereq, 0, p, &bIn);
129782      if( bIn==0 ) seenZeroNoIN = 1;
129783    }
129784
129785    /* If the calls to xBestIndex() have so far failed to find a plan
129786    ** that requires no source tables at all and does not use an IN(...)
129787    ** operator, make a final call to obtain one here.  */
129788    if( rc==SQLITE_OK && seenZeroNoIN==0 ){
129789      WHERETRACE(0x40, ("  VirtualOne: all disabled and w/o IN\n"));
129790      rc = whereLoopAddVirtualOne(pBuilder, mPrereq, mPrereq, WO_IN, p, &bIn);
129791    }
129792  }
129793
129794  if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
129795  sqlite3DbFree(pParse->db, p);
129796  return rc;
129797}
129798#endif /* SQLITE_OMIT_VIRTUALTABLE */
129799
129800/*
129801** Add WhereLoop entries to handle OR terms.  This works for either
129802** btrees or virtual tables.
129803*/
129804static int whereLoopAddOr(
129805  WhereLoopBuilder *pBuilder,
129806  Bitmask mPrereq,
129807  Bitmask mUnusable
129808){
129809  WhereInfo *pWInfo = pBuilder->pWInfo;
129810  WhereClause *pWC;
129811  WhereLoop *pNew;
129812  WhereTerm *pTerm, *pWCEnd;
129813  int rc = SQLITE_OK;
129814  int iCur;
129815  WhereClause tempWC;
129816  WhereLoopBuilder sSubBuild;
129817  WhereOrSet sSum, sCur;
129818  struct SrcList_item *pItem;
129819
129820  pWC = pBuilder->pWC;
129821  pWCEnd = pWC->a + pWC->nTerm;
129822  pNew = pBuilder->pNew;
129823  memset(&sSum, 0, sizeof(sSum));
129824  pItem = pWInfo->pTabList->a + pNew->iTab;
129825  iCur = pItem->iCursor;
129826
129827  for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
129828    if( (pTerm->eOperator & WO_OR)!=0
129829     && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
129830    ){
129831      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
129832      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
129833      WhereTerm *pOrTerm;
129834      int once = 1;
129835      int i, j;
129836
129837      sSubBuild = *pBuilder;
129838      sSubBuild.pOrderBy = 0;
129839      sSubBuild.pOrSet = &sCur;
129840
129841      WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
129842      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
129843        if( (pOrTerm->eOperator & WO_AND)!=0 ){
129844          sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
129845        }else if( pOrTerm->leftCursor==iCur ){
129846          tempWC.pWInfo = pWC->pWInfo;
129847          tempWC.pOuter = pWC;
129848          tempWC.op = TK_AND;
129849          tempWC.nTerm = 1;
129850          tempWC.a = pOrTerm;
129851          sSubBuild.pWC = &tempWC;
129852        }else{
129853          continue;
129854        }
129855        sCur.n = 0;
129856#ifdef WHERETRACE_ENABLED
129857        WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
129858                   (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
129859        if( sqlite3WhereTrace & 0x400 ){
129860          sqlite3WhereClausePrint(sSubBuild.pWC);
129861        }
129862#endif
129863#ifndef SQLITE_OMIT_VIRTUALTABLE
129864        if( IsVirtual(pItem->pTab) ){
129865          rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
129866        }else
129867#endif
129868        {
129869          rc = whereLoopAddBtree(&sSubBuild, mPrereq);
129870        }
129871        if( rc==SQLITE_OK ){
129872          rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
129873        }
129874        assert( rc==SQLITE_OK || sCur.n==0 );
129875        if( sCur.n==0 ){
129876          sSum.n = 0;
129877          break;
129878        }else if( once ){
129879          whereOrMove(&sSum, &sCur);
129880          once = 0;
129881        }else{
129882          WhereOrSet sPrev;
129883          whereOrMove(&sPrev, &sSum);
129884          sSum.n = 0;
129885          for(i=0; i<sPrev.n; i++){
129886            for(j=0; j<sCur.n; j++){
129887              whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
129888                            sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
129889                            sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
129890            }
129891          }
129892        }
129893      }
129894      pNew->nLTerm = 1;
129895      pNew->aLTerm[0] = pTerm;
129896      pNew->wsFlags = WHERE_MULTI_OR;
129897      pNew->rSetup = 0;
129898      pNew->iSortIdx = 0;
129899      memset(&pNew->u, 0, sizeof(pNew->u));
129900      for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
129901        /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
129902        ** of all sub-scans required by the OR-scan. However, due to rounding
129903        ** errors, it may be that the cost of the OR-scan is equal to its
129904        ** most expensive sub-scan. Add the smallest possible penalty
129905        ** (equivalent to multiplying the cost by 1.07) to ensure that
129906        ** this does not happen. Otherwise, for WHERE clauses such as the
129907        ** following where there is an index on "y":
129908        **
129909        **     WHERE likelihood(x=?, 0.99) OR y=?
129910        **
129911        ** the planner may elect to "OR" together a full-table scan and an
129912        ** index lookup. And other similarly odd results.  */
129913        pNew->rRun = sSum.a[i].rRun + 1;
129914        pNew->nOut = sSum.a[i].nOut;
129915        pNew->prereq = sSum.a[i].prereq;
129916        rc = whereLoopInsert(pBuilder, pNew);
129917      }
129918      WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
129919    }
129920  }
129921  return rc;
129922}
129923
129924/*
129925** Add all WhereLoop objects for all tables
129926*/
129927static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
129928  WhereInfo *pWInfo = pBuilder->pWInfo;
129929  Bitmask mPrereq = 0;
129930  Bitmask mPrior = 0;
129931  int iTab;
129932  SrcList *pTabList = pWInfo->pTabList;
129933  struct SrcList_item *pItem;
129934  struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
129935  sqlite3 *db = pWInfo->pParse->db;
129936  int rc = SQLITE_OK;
129937  WhereLoop *pNew;
129938  u8 priorJointype = 0;
129939
129940  /* Loop over the tables in the join, from left to right */
129941  pNew = pBuilder->pNew;
129942  whereLoopInit(pNew);
129943  for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
129944    Bitmask mUnusable = 0;
129945    pNew->iTab = iTab;
129946    pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
129947    if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
129948      /* This condition is true when pItem is the FROM clause term on the
129949      ** right-hand-side of a LEFT or CROSS JOIN.  */
129950      mPrereq = mPrior;
129951    }
129952    priorJointype = pItem->fg.jointype;
129953#ifndef SQLITE_OMIT_VIRTUALTABLE
129954    if( IsVirtual(pItem->pTab) ){
129955      struct SrcList_item *p;
129956      for(p=&pItem[1]; p<pEnd; p++){
129957        if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
129958          mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
129959        }
129960      }
129961      rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
129962    }else
129963#endif /* SQLITE_OMIT_VIRTUALTABLE */
129964    {
129965      rc = whereLoopAddBtree(pBuilder, mPrereq);
129966    }
129967    if( rc==SQLITE_OK ){
129968      rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
129969    }
129970    mPrior |= pNew->maskSelf;
129971    if( rc || db->mallocFailed ) break;
129972  }
129973
129974  whereLoopClear(db, pNew);
129975  return rc;
129976}
129977
129978/*
129979** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
129980** parameters) to see if it outputs rows in the requested ORDER BY
129981** (or GROUP BY) without requiring a separate sort operation.  Return N:
129982**
129983**   N>0:   N terms of the ORDER BY clause are satisfied
129984**   N==0:  No terms of the ORDER BY clause are satisfied
129985**   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.
129986**
129987** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
129988** strict.  With GROUP BY and DISTINCT the only requirement is that
129989** equivalent rows appear immediately adjacent to one another.  GROUP BY
129990** and DISTINCT do not require rows to appear in any particular order as long
129991** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT
129992** the pOrderBy terms can be matched in any order.  With ORDER BY, the
129993** pOrderBy terms must be matched in strict left-to-right order.
129994*/
129995static i8 wherePathSatisfiesOrderBy(
129996  WhereInfo *pWInfo,    /* The WHERE clause */
129997  ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
129998  WherePath *pPath,     /* The WherePath to check */
129999  u16 wctrlFlags,       /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
130000  u16 nLoop,            /* Number of entries in pPath->aLoop[] */
130001  WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
130002  Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
130003){
130004  u8 revSet;            /* True if rev is known */
130005  u8 rev;               /* Composite sort order */
130006  u8 revIdx;            /* Index sort order */
130007  u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
130008  u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
130009  u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
130010  u16 eqOpMask;         /* Allowed equality operators */
130011  u16 nKeyCol;          /* Number of key columns in pIndex */
130012  u16 nColumn;          /* Total number of ordered columns in the index */
130013  u16 nOrderBy;         /* Number terms in the ORDER BY clause */
130014  int iLoop;            /* Index of WhereLoop in pPath being processed */
130015  int i, j;             /* Loop counters */
130016  int iCur;             /* Cursor number for current WhereLoop */
130017  int iColumn;          /* A column number within table iCur */
130018  WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
130019  WhereTerm *pTerm;     /* A single term of the WHERE clause */
130020  Expr *pOBExpr;        /* An expression from the ORDER BY clause */
130021  CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
130022  Index *pIndex;        /* The index associated with pLoop */
130023  sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
130024  Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
130025  Bitmask obDone;       /* Mask of all ORDER BY terms */
130026  Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
130027  Bitmask ready;              /* Mask of inner loops */
130028
130029  /*
130030  ** We say the WhereLoop is "one-row" if it generates no more than one
130031  ** row of output.  A WhereLoop is one-row if all of the following are true:
130032  **  (a) All index columns match with WHERE_COLUMN_EQ.
130033  **  (b) The index is unique
130034  ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
130035  ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
130036  **
130037  ** We say the WhereLoop is "order-distinct" if the set of columns from
130038  ** that WhereLoop that are in the ORDER BY clause are different for every
130039  ** row of the WhereLoop.  Every one-row WhereLoop is automatically
130040  ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
130041  ** is not order-distinct. To be order-distinct is not quite the same as being
130042  ** UNIQUE since a UNIQUE column or index can have multiple rows that
130043  ** are NULL and NULL values are equivalent for the purpose of order-distinct.
130044  ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
130045  **
130046  ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
130047  ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
130048  ** automatically order-distinct.
130049  */
130050
130051  assert( pOrderBy!=0 );
130052  if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
130053
130054  nOrderBy = pOrderBy->nExpr;
130055  testcase( nOrderBy==BMS-1 );
130056  if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
130057  isOrderDistinct = 1;
130058  obDone = MASKBIT(nOrderBy)-1;
130059  orderDistinctMask = 0;
130060  ready = 0;
130061  eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
130062  if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
130063  for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
130064    if( iLoop>0 ) ready |= pLoop->maskSelf;
130065    if( iLoop<nLoop ){
130066      pLoop = pPath->aLoop[iLoop];
130067      if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
130068    }else{
130069      pLoop = pLast;
130070    }
130071    if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
130072      if( pLoop->u.vtab.isOrdered ) obSat = obDone;
130073      break;
130074    }
130075    iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
130076
130077    /* Mark off any ORDER BY term X that is a column in the table of
130078    ** the current loop for which there is term in the WHERE
130079    ** clause of the form X IS NULL or X=? that reference only outer
130080    ** loops.
130081    */
130082    for(i=0; i<nOrderBy; i++){
130083      if( MASKBIT(i) & obSat ) continue;
130084      pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
130085      if( pOBExpr->op!=TK_COLUMN ) continue;
130086      if( pOBExpr->iTable!=iCur ) continue;
130087      pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
130088                       ~ready, eqOpMask, 0);
130089      if( pTerm==0 ) continue;
130090      if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
130091        const char *z1, *z2;
130092        pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
130093        if( !pColl ) pColl = db->pDfltColl;
130094        z1 = pColl->zName;
130095        pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
130096        if( !pColl ) pColl = db->pDfltColl;
130097        z2 = pColl->zName;
130098        if( sqlite3StrICmp(z1, z2)!=0 ) continue;
130099        testcase( pTerm->pExpr->op==TK_IS );
130100      }
130101      obSat |= MASKBIT(i);
130102    }
130103
130104    if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
130105      if( pLoop->wsFlags & WHERE_IPK ){
130106        pIndex = 0;
130107        nKeyCol = 0;
130108        nColumn = 1;
130109      }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
130110        return 0;
130111      }else{
130112        nKeyCol = pIndex->nKeyCol;
130113        nColumn = pIndex->nColumn;
130114        assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
130115        assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
130116                          || !HasRowid(pIndex->pTable));
130117        isOrderDistinct = IsUniqueIndex(pIndex);
130118      }
130119
130120      /* Loop through all columns of the index and deal with the ones
130121      ** that are not constrained by == or IN.
130122      */
130123      rev = revSet = 0;
130124      distinctColumns = 0;
130125      for(j=0; j<nColumn; j++){
130126        u8 bOnce;   /* True to run the ORDER BY search loop */
130127
130128        /* Skip over == and IS and ISNULL terms.
130129        ** (Also skip IN terms when doing WHERE_ORDERBY_LIMIT processing)
130130        */
130131        if( j<pLoop->u.btree.nEq
130132         && pLoop->nSkip==0
130133         && ((i = pLoop->aLTerm[j]->eOperator) & eqOpMask)!=0
130134        ){
130135          if( i & WO_ISNULL ){
130136            testcase( isOrderDistinct );
130137            isOrderDistinct = 0;
130138          }
130139          continue;
130140        }
130141
130142        /* Get the column number in the table (iColumn) and sort order
130143        ** (revIdx) for the j-th column of the index.
130144        */
130145        if( pIndex ){
130146          iColumn = pIndex->aiColumn[j];
130147          revIdx = pIndex->aSortOrder[j];
130148          if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
130149        }else{
130150          iColumn = XN_ROWID;
130151          revIdx = 0;
130152        }
130153
130154        /* An unconstrained column that might be NULL means that this
130155        ** WhereLoop is not well-ordered
130156        */
130157        if( isOrderDistinct
130158         && iColumn>=0
130159         && j>=pLoop->u.btree.nEq
130160         && pIndex->pTable->aCol[iColumn].notNull==0
130161        ){
130162          isOrderDistinct = 0;
130163        }
130164
130165        /* Find the ORDER BY term that corresponds to the j-th column
130166        ** of the index and mark that ORDER BY term off
130167        */
130168        bOnce = 1;
130169        isMatch = 0;
130170        for(i=0; bOnce && i<nOrderBy; i++){
130171          if( MASKBIT(i) & obSat ) continue;
130172          pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
130173          testcase( wctrlFlags & WHERE_GROUPBY );
130174          testcase( wctrlFlags & WHERE_DISTINCTBY );
130175          if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
130176          if( iColumn>=(-1) ){
130177            if( pOBExpr->op!=TK_COLUMN ) continue;
130178            if( pOBExpr->iTable!=iCur ) continue;
130179            if( pOBExpr->iColumn!=iColumn ) continue;
130180          }else{
130181            if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){
130182              continue;
130183            }
130184          }
130185          if( iColumn>=0 ){
130186            pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
130187            if( !pColl ) pColl = db->pDfltColl;
130188            if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
130189          }
130190          isMatch = 1;
130191          break;
130192        }
130193        if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
130194          /* Make sure the sort order is compatible in an ORDER BY clause.
130195          ** Sort order is irrelevant for a GROUP BY clause. */
130196          if( revSet ){
130197            if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
130198          }else{
130199            rev = revIdx ^ pOrderBy->a[i].sortOrder;
130200            if( rev ) *pRevMask |= MASKBIT(iLoop);
130201            revSet = 1;
130202          }
130203        }
130204        if( isMatch ){
130205          if( iColumn<0 ){
130206            testcase( distinctColumns==0 );
130207            distinctColumns = 1;
130208          }
130209          obSat |= MASKBIT(i);
130210        }else{
130211          /* No match found */
130212          if( j==0 || j<nKeyCol ){
130213            testcase( isOrderDistinct!=0 );
130214            isOrderDistinct = 0;
130215          }
130216          break;
130217        }
130218      } /* end Loop over all index columns */
130219      if( distinctColumns ){
130220        testcase( isOrderDistinct==0 );
130221        isOrderDistinct = 1;
130222      }
130223    } /* end-if not one-row */
130224
130225    /* Mark off any other ORDER BY terms that reference pLoop */
130226    if( isOrderDistinct ){
130227      orderDistinctMask |= pLoop->maskSelf;
130228      for(i=0; i<nOrderBy; i++){
130229        Expr *p;
130230        Bitmask mTerm;
130231        if( MASKBIT(i) & obSat ) continue;
130232        p = pOrderBy->a[i].pExpr;
130233        mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
130234        if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
130235        if( (mTerm&~orderDistinctMask)==0 ){
130236          obSat |= MASKBIT(i);
130237        }
130238      }
130239    }
130240  } /* End the loop over all WhereLoops from outer-most down to inner-most */
130241  if( obSat==obDone ) return (i8)nOrderBy;
130242  if( !isOrderDistinct ){
130243    for(i=nOrderBy-1; i>0; i--){
130244      Bitmask m = MASKBIT(i) - 1;
130245      if( (obSat&m)==m ) return i;
130246    }
130247    return 0;
130248  }
130249  return -1;
130250}
130251
130252
130253/*
130254** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
130255** the planner assumes that the specified pOrderBy list is actually a GROUP
130256** BY clause - and so any order that groups rows as required satisfies the
130257** request.
130258**
130259** Normally, in this case it is not possible for the caller to determine
130260** whether or not the rows are really being delivered in sorted order, or
130261** just in some other order that provides the required grouping. However,
130262** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
130263** this function may be called on the returned WhereInfo object. It returns
130264** true if the rows really will be sorted in the specified order, or false
130265** otherwise.
130266**
130267** For example, assuming:
130268**
130269**   CREATE INDEX i1 ON t1(x, Y);
130270**
130271** then
130272**
130273**   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
130274**   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
130275*/
130276SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
130277  assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
130278  assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
130279  return pWInfo->sorted;
130280}
130281
130282#ifdef WHERETRACE_ENABLED
130283/* For debugging use only: */
130284static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
130285  static char zName[65];
130286  int i;
130287  for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
130288  if( pLast ) zName[i++] = pLast->cId;
130289  zName[i] = 0;
130290  return zName;
130291}
130292#endif
130293
130294/*
130295** Return the cost of sorting nRow rows, assuming that the keys have
130296** nOrderby columns and that the first nSorted columns are already in
130297** order.
130298*/
130299static LogEst whereSortingCost(
130300  WhereInfo *pWInfo,
130301  LogEst nRow,
130302  int nOrderBy,
130303  int nSorted
130304){
130305  /* TUNING: Estimated cost of a full external sort, where N is
130306  ** the number of rows to sort is:
130307  **
130308  **   cost = (3.0 * N * log(N)).
130309  **
130310  ** Or, if the order-by clause has X terms but only the last Y
130311  ** terms are out of order, then block-sorting will reduce the
130312  ** sorting cost to:
130313  **
130314  **   cost = (3.0 * N * log(N)) * (Y/X)
130315  **
130316  ** The (Y/X) term is implemented using stack variable rScale
130317  ** below.  */
130318  LogEst rScale, rSortCost;
130319  assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
130320  rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
130321  rSortCost = nRow + rScale + 16;
130322
130323  /* Multiple by log(M) where M is the number of output rows.
130324  ** Use the LIMIT for M if it is smaller */
130325  if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
130326    nRow = pWInfo->iLimit;
130327  }
130328  rSortCost += estLog(nRow);
130329  return rSortCost;
130330}
130331
130332/*
130333** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
130334** attempts to find the lowest cost path that visits each WhereLoop
130335** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
130336**
130337** Assume that the total number of output rows that will need to be sorted
130338** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
130339** costs if nRowEst==0.
130340**
130341** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
130342** error occurs.
130343*/
130344static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
130345  int mxChoice;             /* Maximum number of simultaneous paths tracked */
130346  int nLoop;                /* Number of terms in the join */
130347  Parse *pParse;            /* Parsing context */
130348  sqlite3 *db;              /* The database connection */
130349  int iLoop;                /* Loop counter over the terms of the join */
130350  int ii, jj;               /* Loop counters */
130351  int mxI = 0;              /* Index of next entry to replace */
130352  int nOrderBy;             /* Number of ORDER BY clause terms */
130353  LogEst mxCost = 0;        /* Maximum cost of a set of paths */
130354  LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
130355  int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
130356  WherePath *aFrom;         /* All nFrom paths at the previous level */
130357  WherePath *aTo;           /* The nTo best paths at the current level */
130358  WherePath *pFrom;         /* An element of aFrom[] that we are working on */
130359  WherePath *pTo;           /* An element of aTo[] that we are working on */
130360  WhereLoop *pWLoop;        /* One of the WhereLoop objects */
130361  WhereLoop **pX;           /* Used to divy up the pSpace memory */
130362  LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
130363  char *pSpace;             /* Temporary memory used by this routine */
130364  int nSpace;               /* Bytes of space allocated at pSpace */
130365
130366  pParse = pWInfo->pParse;
130367  db = pParse->db;
130368  nLoop = pWInfo->nLevel;
130369  /* TUNING: For simple queries, only the best path is tracked.
130370  ** For 2-way joins, the 5 best paths are followed.
130371  ** For joins of 3 or more tables, track the 10 best paths */
130372  mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
130373  assert( nLoop<=pWInfo->pTabList->nSrc );
130374  WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
130375
130376  /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
130377  ** case the purpose of this call is to estimate the number of rows returned
130378  ** by the overall query. Once this estimate has been obtained, the caller
130379  ** will invoke this function a second time, passing the estimate as the
130380  ** nRowEst parameter.  */
130381  if( pWInfo->pOrderBy==0 || nRowEst==0 ){
130382    nOrderBy = 0;
130383  }else{
130384    nOrderBy = pWInfo->pOrderBy->nExpr;
130385  }
130386
130387  /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
130388  nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
130389  nSpace += sizeof(LogEst) * nOrderBy;
130390  pSpace = sqlite3DbMallocRawNN(db, nSpace);
130391  if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
130392  aTo = (WherePath*)pSpace;
130393  aFrom = aTo+mxChoice;
130394  memset(aFrom, 0, sizeof(aFrom[0]));
130395  pX = (WhereLoop**)(aFrom+mxChoice);
130396  for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
130397    pFrom->aLoop = pX;
130398  }
130399  if( nOrderBy ){
130400    /* If there is an ORDER BY clause and it is not being ignored, set up
130401    ** space for the aSortCost[] array. Each element of the aSortCost array
130402    ** is either zero - meaning it has not yet been initialized - or the
130403    ** cost of sorting nRowEst rows of data where the first X terms of
130404    ** the ORDER BY clause are already in order, where X is the array
130405    ** index.  */
130406    aSortCost = (LogEst*)pX;
130407    memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
130408  }
130409  assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
130410  assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
130411
130412  /* Seed the search with a single WherePath containing zero WhereLoops.
130413  **
130414  ** TUNING: Do not let the number of iterations go above 28.  If the cost
130415  ** of computing an automatic index is not paid back within the first 28
130416  ** rows, then do not use the automatic index. */
130417  aFrom[0].nRow = MIN(pParse->nQueryLoop, 48);  assert( 48==sqlite3LogEst(28) );
130418  nFrom = 1;
130419  assert( aFrom[0].isOrdered==0 );
130420  if( nOrderBy ){
130421    /* If nLoop is zero, then there are no FROM terms in the query. Since
130422    ** in this case the query may return a maximum of one row, the results
130423    ** are already in the requested order. Set isOrdered to nOrderBy to
130424    ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
130425    ** -1, indicating that the result set may or may not be ordered,
130426    ** depending on the loops added to the current plan.  */
130427    aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
130428  }
130429
130430  /* Compute successively longer WherePaths using the previous generation
130431  ** of WherePaths as the basis for the next.  Keep track of the mxChoice
130432  ** best paths at each generation */
130433  for(iLoop=0; iLoop<nLoop; iLoop++){
130434    nTo = 0;
130435    for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
130436      for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
130437        LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
130438        LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
130439        LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
130440        i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
130441        Bitmask maskNew;                  /* Mask of src visited by (..) */
130442        Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
130443
130444        if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
130445        if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
130446        if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){
130447          /* Do not use an automatic index if the this loop is expected
130448          ** to run less than 2 times. */
130449          assert( 10==sqlite3LogEst(2) );
130450          continue;
130451        }
130452        /* At this point, pWLoop is a candidate to be the next loop.
130453        ** Compute its cost */
130454        rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
130455        rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
130456        nOut = pFrom->nRow + pWLoop->nOut;
130457        maskNew = pFrom->maskLoop | pWLoop->maskSelf;
130458        if( isOrdered<0 ){
130459          isOrdered = wherePathSatisfiesOrderBy(pWInfo,
130460                       pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
130461                       iLoop, pWLoop, &revMask);
130462        }else{
130463          revMask = pFrom->revLoop;
130464        }
130465        if( isOrdered>=0 && isOrdered<nOrderBy ){
130466          if( aSortCost[isOrdered]==0 ){
130467            aSortCost[isOrdered] = whereSortingCost(
130468                pWInfo, nRowEst, nOrderBy, isOrdered
130469            );
130470          }
130471          rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
130472
130473          WHERETRACE(0x002,
130474              ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
130475               aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
130476               rUnsorted, rCost));
130477        }else{
130478          rCost = rUnsorted;
130479        }
130480
130481        /* Check to see if pWLoop should be added to the set of
130482        ** mxChoice best-so-far paths.
130483        **
130484        ** First look for an existing path among best-so-far paths
130485        ** that covers the same set of loops and has the same isOrdered
130486        ** setting as the current path candidate.
130487        **
130488        ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
130489        ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
130490        ** of legal values for isOrdered, -1..64.
130491        */
130492        for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
130493          if( pTo->maskLoop==maskNew
130494           && ((pTo->isOrdered^isOrdered)&0x80)==0
130495          ){
130496            testcase( jj==nTo-1 );
130497            break;
130498          }
130499        }
130500        if( jj>=nTo ){
130501          /* None of the existing best-so-far paths match the candidate. */
130502          if( nTo>=mxChoice
130503           && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
130504          ){
130505            /* The current candidate is no better than any of the mxChoice
130506            ** paths currently in the best-so-far buffer.  So discard
130507            ** this candidate as not viable. */
130508#ifdef WHERETRACE_ENABLED /* 0x4 */
130509            if( sqlite3WhereTrace&0x4 ){
130510              sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d order=%c\n",
130511                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
130512                  isOrdered>=0 ? isOrdered+'0' : '?');
130513            }
130514#endif
130515            continue;
130516          }
130517          /* If we reach this points it means that the new candidate path
130518          ** needs to be added to the set of best-so-far paths. */
130519          if( nTo<mxChoice ){
130520            /* Increase the size of the aTo set by one */
130521            jj = nTo++;
130522          }else{
130523            /* New path replaces the prior worst to keep count below mxChoice */
130524            jj = mxI;
130525          }
130526          pTo = &aTo[jj];
130527#ifdef WHERETRACE_ENABLED /* 0x4 */
130528          if( sqlite3WhereTrace&0x4 ){
130529            sqlite3DebugPrintf("New    %s cost=%-3d,%3d order=%c\n",
130530                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
130531                isOrdered>=0 ? isOrdered+'0' : '?');
130532          }
130533#endif
130534        }else{
130535          /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
130536          ** same set of loops and has the sam isOrdered setting as the
130537          ** candidate path.  Check to see if the candidate should replace
130538          ** pTo or if the candidate should be skipped */
130539          if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
130540#ifdef WHERETRACE_ENABLED /* 0x4 */
130541            if( sqlite3WhereTrace&0x4 ){
130542              sqlite3DebugPrintf(
130543                  "Skip   %s cost=%-3d,%3d order=%c",
130544                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
130545                  isOrdered>=0 ? isOrdered+'0' : '?');
130546              sqlite3DebugPrintf("   vs %s cost=%-3d,%d order=%c\n",
130547                  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
130548                  pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
130549            }
130550#endif
130551            /* Discard the candidate path from further consideration */
130552            testcase( pTo->rCost==rCost );
130553            continue;
130554          }
130555          testcase( pTo->rCost==rCost+1 );
130556          /* Control reaches here if the candidate path is better than the
130557          ** pTo path.  Replace pTo with the candidate. */
130558#ifdef WHERETRACE_ENABLED /* 0x4 */
130559          if( sqlite3WhereTrace&0x4 ){
130560            sqlite3DebugPrintf(
130561                "Update %s cost=%-3d,%3d order=%c",
130562                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
130563                isOrdered>=0 ? isOrdered+'0' : '?');
130564            sqlite3DebugPrintf("  was %s cost=%-3d,%3d order=%c\n",
130565                wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
130566                pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
130567          }
130568#endif
130569        }
130570        /* pWLoop is a winner.  Add it to the set of best so far */
130571        pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
130572        pTo->revLoop = revMask;
130573        pTo->nRow = nOut;
130574        pTo->rCost = rCost;
130575        pTo->rUnsorted = rUnsorted;
130576        pTo->isOrdered = isOrdered;
130577        memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
130578        pTo->aLoop[iLoop] = pWLoop;
130579        if( nTo>=mxChoice ){
130580          mxI = 0;
130581          mxCost = aTo[0].rCost;
130582          mxUnsorted = aTo[0].nRow;
130583          for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
130584            if( pTo->rCost>mxCost
130585             || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
130586            ){
130587              mxCost = pTo->rCost;
130588              mxUnsorted = pTo->rUnsorted;
130589              mxI = jj;
130590            }
130591          }
130592        }
130593      }
130594    }
130595
130596#ifdef WHERETRACE_ENABLED  /* >=2 */
130597    if( sqlite3WhereTrace & 0x02 ){
130598      sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
130599      for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
130600        sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
130601           wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
130602           pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
130603        if( pTo->isOrdered>0 ){
130604          sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
130605        }else{
130606          sqlite3DebugPrintf("\n");
130607        }
130608      }
130609    }
130610#endif
130611
130612    /* Swap the roles of aFrom and aTo for the next generation */
130613    pFrom = aTo;
130614    aTo = aFrom;
130615    aFrom = pFrom;
130616    nFrom = nTo;
130617  }
130618
130619  if( nFrom==0 ){
130620    sqlite3ErrorMsg(pParse, "no query solution");
130621    sqlite3DbFree(db, pSpace);
130622    return SQLITE_ERROR;
130623  }
130624
130625  /* Find the lowest cost path.  pFrom will be left pointing to that path */
130626  pFrom = aFrom;
130627  for(ii=1; ii<nFrom; ii++){
130628    if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
130629  }
130630  assert( pWInfo->nLevel==nLoop );
130631  /* Load the lowest cost path into pWInfo */
130632  for(iLoop=0; iLoop<nLoop; iLoop++){
130633    WhereLevel *pLevel = pWInfo->a + iLoop;
130634    pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
130635    pLevel->iFrom = pWLoop->iTab;
130636    pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
130637  }
130638  if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
130639   && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
130640   && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
130641   && nRowEst
130642  ){
130643    Bitmask notUsed;
130644    int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pDistinctSet, pFrom,
130645                 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
130646    if( rc==pWInfo->pDistinctSet->nExpr ){
130647      pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
130648    }
130649  }
130650  if( pWInfo->pOrderBy ){
130651    if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
130652      if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
130653        pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
130654      }
130655    }else{
130656      pWInfo->nOBSat = pFrom->isOrdered;
130657      pWInfo->revMask = pFrom->revLoop;
130658      if( pWInfo->nOBSat<=0 ){
130659        pWInfo->nOBSat = 0;
130660        if( nLoop>0 && (pFrom->aLoop[nLoop-1]->wsFlags & WHERE_ONEROW)==0 ){
130661          Bitmask m = 0;
130662          int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
130663                      WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
130664          if( rc==pWInfo->pOrderBy->nExpr ){
130665            pWInfo->bOrderedInnerLoop = 1;
130666            pWInfo->revMask = m;
130667          }
130668        }
130669      }
130670    }
130671    if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
130672        && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
130673    ){
130674      Bitmask revMask = 0;
130675      int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
130676          pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
130677      );
130678      assert( pWInfo->sorted==0 );
130679      if( nOrder==pWInfo->pOrderBy->nExpr ){
130680        pWInfo->sorted = 1;
130681        pWInfo->revMask = revMask;
130682      }
130683    }
130684  }
130685
130686
130687  pWInfo->nRowOut = pFrom->nRow;
130688
130689  /* Free temporary memory and return success */
130690  sqlite3DbFree(db, pSpace);
130691  return SQLITE_OK;
130692}
130693
130694/*
130695** Most queries use only a single table (they are not joins) and have
130696** simple == constraints against indexed fields.  This routine attempts
130697** to plan those simple cases using much less ceremony than the
130698** general-purpose query planner, and thereby yield faster sqlite3_prepare()
130699** times for the common case.
130700**
130701** Return non-zero on success, if this query can be handled by this
130702** no-frills query planner.  Return zero if this query needs the
130703** general-purpose query planner.
130704*/
130705static int whereShortCut(WhereLoopBuilder *pBuilder){
130706  WhereInfo *pWInfo;
130707  struct SrcList_item *pItem;
130708  WhereClause *pWC;
130709  WhereTerm *pTerm;
130710  WhereLoop *pLoop;
130711  int iCur;
130712  int j;
130713  Table *pTab;
130714  Index *pIdx;
130715
130716  pWInfo = pBuilder->pWInfo;
130717  if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
130718  assert( pWInfo->pTabList->nSrc>=1 );
130719  pItem = pWInfo->pTabList->a;
130720  pTab = pItem->pTab;
130721  if( IsVirtual(pTab) ) return 0;
130722  if( pItem->fg.isIndexedBy ) return 0;
130723  iCur = pItem->iCursor;
130724  pWC = &pWInfo->sWC;
130725  pLoop = pBuilder->pNew;
130726  pLoop->wsFlags = 0;
130727  pLoop->nSkip = 0;
130728  pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
130729  if( pTerm ){
130730    testcase( pTerm->eOperator & WO_IS );
130731    pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
130732    pLoop->aLTerm[0] = pTerm;
130733    pLoop->nLTerm = 1;
130734    pLoop->u.btree.nEq = 1;
130735    /* TUNING: Cost of a rowid lookup is 10 */
130736    pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
130737  }else{
130738    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
130739      int opMask;
130740      assert( pLoop->aLTermSpace==pLoop->aLTerm );
130741      if( !IsUniqueIndex(pIdx)
130742       || pIdx->pPartIdxWhere!=0
130743       || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
130744      ) continue;
130745      opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
130746      for(j=0; j<pIdx->nKeyCol; j++){
130747        pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
130748        if( pTerm==0 ) break;
130749        testcase( pTerm->eOperator & WO_IS );
130750        pLoop->aLTerm[j] = pTerm;
130751      }
130752      if( j!=pIdx->nKeyCol ) continue;
130753      pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
130754      if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
130755        pLoop->wsFlags |= WHERE_IDX_ONLY;
130756      }
130757      pLoop->nLTerm = j;
130758      pLoop->u.btree.nEq = j;
130759      pLoop->u.btree.pIndex = pIdx;
130760      /* TUNING: Cost of a unique index lookup is 15 */
130761      pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
130762      break;
130763    }
130764  }
130765  if( pLoop->wsFlags ){
130766    pLoop->nOut = (LogEst)1;
130767    pWInfo->a[0].pWLoop = pLoop;
130768    pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
130769    pWInfo->a[0].iTabCur = iCur;
130770    pWInfo->nRowOut = 1;
130771    if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
130772    if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
130773      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
130774    }
130775#ifdef SQLITE_DEBUG
130776    pLoop->cId = '0';
130777#endif
130778    return 1;
130779  }
130780  return 0;
130781}
130782
130783/*
130784** Generate the beginning of the loop used for WHERE clause processing.
130785** The return value is a pointer to an opaque structure that contains
130786** information needed to terminate the loop.  Later, the calling routine
130787** should invoke sqlite3WhereEnd() with the return value of this function
130788** in order to complete the WHERE clause processing.
130789**
130790** If an error occurs, this routine returns NULL.
130791**
130792** The basic idea is to do a nested loop, one loop for each table in
130793** the FROM clause of a select.  (INSERT and UPDATE statements are the
130794** same as a SELECT with only a single table in the FROM clause.)  For
130795** example, if the SQL is this:
130796**
130797**       SELECT * FROM t1, t2, t3 WHERE ...;
130798**
130799** Then the code generated is conceptually like the following:
130800**
130801**      foreach row1 in t1 do       \    Code generated
130802**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
130803**          foreach row3 in t3 do   /
130804**            ...
130805**          end                     \    Code generated
130806**        end                        |-- by sqlite3WhereEnd()
130807**      end                         /
130808**
130809** Note that the loops might not be nested in the order in which they
130810** appear in the FROM clause if a different order is better able to make
130811** use of indices.  Note also that when the IN operator appears in
130812** the WHERE clause, it might result in additional nested loops for
130813** scanning through all values on the right-hand side of the IN.
130814**
130815** There are Btree cursors associated with each table.  t1 uses cursor
130816** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
130817** And so forth.  This routine generates code to open those VDBE cursors
130818** and sqlite3WhereEnd() generates the code to close them.
130819**
130820** The code that sqlite3WhereBegin() generates leaves the cursors named
130821** in pTabList pointing at their appropriate entries.  The [...] code
130822** can use OP_Column and OP_Rowid opcodes on these cursors to extract
130823** data from the various tables of the loop.
130824**
130825** If the WHERE clause is empty, the foreach loops must each scan their
130826** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
130827** the tables have indices and there are terms in the WHERE clause that
130828** refer to those indices, a complete table scan can be avoided and the
130829** code will run much faster.  Most of the work of this routine is checking
130830** to see if there are indices that can be used to speed up the loop.
130831**
130832** Terms of the WHERE clause are also used to limit which rows actually
130833** make it to the "..." in the middle of the loop.  After each "foreach",
130834** terms of the WHERE clause that use only terms in that loop and outer
130835** loops are evaluated and if false a jump is made around all subsequent
130836** inner loops (or around the "..." if the test occurs within the inner-
130837** most loop)
130838**
130839** OUTER JOINS
130840**
130841** An outer join of tables t1 and t2 is conceptally coded as follows:
130842**
130843**    foreach row1 in t1 do
130844**      flag = 0
130845**      foreach row2 in t2 do
130846**        start:
130847**          ...
130848**          flag = 1
130849**      end
130850**      if flag==0 then
130851**        move the row2 cursor to a null row
130852**        goto start
130853**      fi
130854**    end
130855**
130856** ORDER BY CLAUSE PROCESSING
130857**
130858** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
130859** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
130860** if there is one.  If there is no ORDER BY clause or if this routine
130861** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
130862**
130863** The iIdxCur parameter is the cursor number of an index.  If
130864** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
130865** to use for OR clause processing.  The WHERE clause should use this
130866** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
130867** the first cursor in an array of cursors for all indices.  iIdxCur should
130868** be used to compute the appropriate cursor depending on which index is
130869** used.
130870*/
130871SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
130872  Parse *pParse,          /* The parser context */
130873  SrcList *pTabList,      /* FROM clause: A list of all tables to be scanned */
130874  Expr *pWhere,           /* The WHERE clause */
130875  ExprList *pOrderBy,     /* An ORDER BY (or GROUP BY) clause, or NULL */
130876  ExprList *pDistinctSet, /* Try not to output two rows that duplicate these */
130877  u16 wctrlFlags,         /* The WHERE_* flags defined in sqliteInt.h */
130878  int iAuxArg             /* If WHERE_OR_SUBCLAUSE is set, index cursor number
130879                          ** If WHERE_USE_LIMIT, then the limit amount */
130880){
130881  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
130882  int nTabList;              /* Number of elements in pTabList */
130883  WhereInfo *pWInfo;         /* Will become the return value of this function */
130884  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
130885  Bitmask notReady;          /* Cursors that are not yet positioned */
130886  WhereLoopBuilder sWLB;     /* The WhereLoop builder */
130887  WhereMaskSet *pMaskSet;    /* The expression mask set */
130888  WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
130889  WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
130890  int ii;                    /* Loop counter */
130891  sqlite3 *db;               /* Database connection */
130892  int rc;                    /* Return code */
130893  u8 bFordelete = 0;         /* OPFLAG_FORDELETE or zero, as appropriate */
130894
130895  assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
130896        (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
130897     && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
130898  ));
130899
130900  /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
130901  assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
130902            || (wctrlFlags & WHERE_USE_LIMIT)==0 );
130903
130904  /* Variable initialization */
130905  db = pParse->db;
130906  memset(&sWLB, 0, sizeof(sWLB));
130907
130908  /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
130909  testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
130910  if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
130911  sWLB.pOrderBy = pOrderBy;
130912
130913  /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
130914  ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
130915  if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
130916    wctrlFlags &= ~WHERE_WANT_DISTINCT;
130917  }
130918
130919  /* The number of tables in the FROM clause is limited by the number of
130920  ** bits in a Bitmask
130921  */
130922  testcase( pTabList->nSrc==BMS );
130923  if( pTabList->nSrc>BMS ){
130924    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
130925    return 0;
130926  }
130927
130928  /* This function normally generates a nested loop for all tables in
130929  ** pTabList.  But if the WHERE_OR_SUBCLAUSE flag is set, then we should
130930  ** only generate code for the first table in pTabList and assume that
130931  ** any cursors associated with subsequent tables are uninitialized.
130932  */
130933  nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
130934
130935  /* Allocate and initialize the WhereInfo structure that will become the
130936  ** return value. A single allocation is used to store the WhereInfo
130937  ** struct, the contents of WhereInfo.a[], the WhereClause structure
130938  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
130939  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
130940  ** some architectures. Hence the ROUND8() below.
130941  */
130942  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
130943  pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
130944  if( db->mallocFailed ){
130945    sqlite3DbFree(db, pWInfo);
130946    pWInfo = 0;
130947    goto whereBeginError;
130948  }
130949  pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
130950  pWInfo->nLevel = nTabList;
130951  pWInfo->pParse = pParse;
130952  pWInfo->pTabList = pTabList;
130953  pWInfo->pOrderBy = pOrderBy;
130954  pWInfo->pDistinctSet = pDistinctSet;
130955  pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
130956  pWInfo->wctrlFlags = wctrlFlags;
130957  pWInfo->iLimit = iAuxArg;
130958  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
130959  assert( pWInfo->eOnePass==ONEPASS_OFF );  /* ONEPASS defaults to OFF */
130960  pMaskSet = &pWInfo->sMaskSet;
130961  sWLB.pWInfo = pWInfo;
130962  sWLB.pWC = &pWInfo->sWC;
130963  sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
130964  assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
130965  whereLoopInit(sWLB.pNew);
130966#ifdef SQLITE_DEBUG
130967  sWLB.pNew->cId = '*';
130968#endif
130969
130970  /* Split the WHERE clause into separate subexpressions where each
130971  ** subexpression is separated by an AND operator.
130972  */
130973  initMaskSet(pMaskSet);
130974  sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
130975  sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
130976
130977  /* Special case: a WHERE clause that is constant.  Evaluate the
130978  ** expression and either jump over all of the code or fall thru.
130979  */
130980  for(ii=0; ii<sWLB.pWC->nTerm; ii++){
130981    if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
130982      sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
130983                         SQLITE_JUMPIFNULL);
130984      sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
130985    }
130986  }
130987
130988  /* Special case: No FROM clause
130989  */
130990  if( nTabList==0 ){
130991    if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
130992    if( wctrlFlags & WHERE_WANT_DISTINCT ){
130993      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
130994    }
130995  }
130996
130997  /* Assign a bit from the bitmask to every term in the FROM clause.
130998  **
130999  ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
131000  **
131001  ** The rule of the previous sentence ensures thta if X is the bitmask for
131002  ** a table T, then X-1 is the bitmask for all other tables to the left of T.
131003  ** Knowing the bitmask for all tables to the left of a left join is
131004  ** important.  Ticket #3015.
131005  **
131006  ** Note that bitmasks are created for all pTabList->nSrc tables in
131007  ** pTabList, not just the first nTabList tables.  nTabList is normally
131008  ** equal to pTabList->nSrc but might be shortened to 1 if the
131009  ** WHERE_OR_SUBCLAUSE flag is set.
131010  */
131011  for(ii=0; ii<pTabList->nSrc; ii++){
131012    createMask(pMaskSet, pTabList->a[ii].iCursor);
131013    sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
131014  }
131015#ifdef SQLITE_DEBUG
131016  for(ii=0; ii<pTabList->nSrc; ii++){
131017    Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
131018    assert( m==MASKBIT(ii) );
131019  }
131020#endif
131021
131022  /* Analyze all of the subexpressions. */
131023  sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
131024  if( db->mallocFailed ) goto whereBeginError;
131025
131026  if( wctrlFlags & WHERE_WANT_DISTINCT ){
131027    if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pDistinctSet) ){
131028      /* The DISTINCT marking is pointless.  Ignore it. */
131029      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
131030    }else if( pOrderBy==0 ){
131031      /* Try to ORDER BY the result set to make distinct processing easier */
131032      pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
131033      pWInfo->pOrderBy = pDistinctSet;
131034    }
131035  }
131036
131037  /* Construct the WhereLoop objects */
131038#if defined(WHERETRACE_ENABLED)
131039  if( sqlite3WhereTrace & 0xffff ){
131040    sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
131041    if( wctrlFlags & WHERE_USE_LIMIT ){
131042      sqlite3DebugPrintf(", limit: %d", iAuxArg);
131043    }
131044    sqlite3DebugPrintf(")\n");
131045  }
131046  if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
131047    sqlite3WhereClausePrint(sWLB.pWC);
131048  }
131049#endif
131050
131051  if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
131052    rc = whereLoopAddAll(&sWLB);
131053    if( rc ) goto whereBeginError;
131054
131055#ifdef WHERETRACE_ENABLED
131056    if( sqlite3WhereTrace ){    /* Display all of the WhereLoop objects */
131057      WhereLoop *p;
131058      int i;
131059      static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
131060                                             "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
131061      for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
131062        p->cId = zLabel[i%sizeof(zLabel)];
131063        whereLoopPrint(p, sWLB.pWC);
131064      }
131065    }
131066#endif
131067
131068    wherePathSolver(pWInfo, 0);
131069    if( db->mallocFailed ) goto whereBeginError;
131070    if( pWInfo->pOrderBy ){
131071       wherePathSolver(pWInfo, pWInfo->nRowOut+1);
131072       if( db->mallocFailed ) goto whereBeginError;
131073    }
131074  }
131075  if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
131076     pWInfo->revMask = ALLBITS;
131077  }
131078  if( pParse->nErr || NEVER(db->mallocFailed) ){
131079    goto whereBeginError;
131080  }
131081#ifdef WHERETRACE_ENABLED
131082  if( sqlite3WhereTrace ){
131083    sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
131084    if( pWInfo->nOBSat>0 ){
131085      sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
131086    }
131087    switch( pWInfo->eDistinct ){
131088      case WHERE_DISTINCT_UNIQUE: {
131089        sqlite3DebugPrintf("  DISTINCT=unique");
131090        break;
131091      }
131092      case WHERE_DISTINCT_ORDERED: {
131093        sqlite3DebugPrintf("  DISTINCT=ordered");
131094        break;
131095      }
131096      case WHERE_DISTINCT_UNORDERED: {
131097        sqlite3DebugPrintf("  DISTINCT=unordered");
131098        break;
131099      }
131100    }
131101    sqlite3DebugPrintf("\n");
131102    for(ii=0; ii<pWInfo->nLevel; ii++){
131103      whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
131104    }
131105  }
131106#endif
131107  /* Attempt to omit tables from the join that do not effect the result */
131108  if( pWInfo->nLevel>=2
131109   && pDistinctSet!=0
131110   && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
131111  ){
131112    Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pDistinctSet);
131113    if( sWLB.pOrderBy ){
131114      tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
131115    }
131116    while( pWInfo->nLevel>=2 ){
131117      WhereTerm *pTerm, *pEnd;
131118      pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
131119      if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
131120      if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
131121       && (pLoop->wsFlags & WHERE_ONEROW)==0
131122      ){
131123        break;
131124      }
131125      if( (tabUsed & pLoop->maskSelf)!=0 ) break;
131126      pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
131127      for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
131128        if( (pTerm->prereqAll & pLoop->maskSelf)!=0
131129         && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
131130        ){
131131          break;
131132        }
131133      }
131134      if( pTerm<pEnd ) break;
131135      WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
131136      pWInfo->nLevel--;
131137      nTabList--;
131138    }
131139  }
131140  WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
131141  pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
131142
131143  /* If the caller is an UPDATE or DELETE statement that is requesting
131144  ** to use a one-pass algorithm, determine if this is appropriate.
131145  */
131146  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
131147  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
131148    int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
131149    int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
131150    if( bOnerow
131151     || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0
131152           && 0==(wsFlags & WHERE_VIRTUALTABLE))
131153    ){
131154      pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
131155      if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
131156        if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
131157          bFordelete = OPFLAG_FORDELETE;
131158        }
131159        pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
131160      }
131161    }
131162  }
131163
131164  /* Open all tables in the pTabList and any indices selected for
131165  ** searching those tables.
131166  */
131167  for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
131168    Table *pTab;     /* Table to open */
131169    int iDb;         /* Index of database containing table/index */
131170    struct SrcList_item *pTabItem;
131171
131172    pTabItem = &pTabList->a[pLevel->iFrom];
131173    pTab = pTabItem->pTab;
131174    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
131175    pLoop = pLevel->pWLoop;
131176    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
131177      /* Do nothing */
131178    }else
131179#ifndef SQLITE_OMIT_VIRTUALTABLE
131180    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
131181      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
131182      int iCur = pTabItem->iCursor;
131183      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
131184    }else if( IsVirtual(pTab) ){
131185      /* noop */
131186    }else
131187#endif
131188    if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
131189         && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
131190      int op = OP_OpenRead;
131191      if( pWInfo->eOnePass!=ONEPASS_OFF ){
131192        op = OP_OpenWrite;
131193        pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
131194      };
131195      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
131196      assert( pTabItem->iCursor==pLevel->iTabCur );
131197      testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
131198      testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
131199      if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
131200        Bitmask b = pTabItem->colUsed;
131201        int n = 0;
131202        for(; b; b=b>>1, n++){}
131203        sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
131204        assert( n<=pTab->nCol );
131205      }
131206#ifdef SQLITE_ENABLE_CURSOR_HINTS
131207      if( pLoop->u.btree.pIndex!=0 ){
131208        sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
131209      }else
131210#endif
131211      {
131212        sqlite3VdbeChangeP5(v, bFordelete);
131213      }
131214#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
131215      sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
131216                            (const u8*)&pTabItem->colUsed, P4_INT64);
131217#endif
131218    }else{
131219      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
131220    }
131221    if( pLoop->wsFlags & WHERE_INDEXED ){
131222      Index *pIx = pLoop->u.btree.pIndex;
131223      int iIndexCur;
131224      int op = OP_OpenRead;
131225      /* iAuxArg is always set if to a positive value if ONEPASS is possible */
131226      assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
131227      if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
131228       && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
131229      ){
131230        /* This is one term of an OR-optimization using the PRIMARY KEY of a
131231        ** WITHOUT ROWID table.  No need for a separate index */
131232        iIndexCur = pLevel->iTabCur;
131233        op = 0;
131234      }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
131235        Index *pJ = pTabItem->pTab->pIndex;
131236        iIndexCur = iAuxArg;
131237        assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
131238        while( ALWAYS(pJ) && pJ!=pIx ){
131239          iIndexCur++;
131240          pJ = pJ->pNext;
131241        }
131242        op = OP_OpenWrite;
131243        pWInfo->aiCurOnePass[1] = iIndexCur;
131244      }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
131245        iIndexCur = iAuxArg;
131246        op = OP_ReopenIdx;
131247      }else{
131248        iIndexCur = pParse->nTab++;
131249      }
131250      pLevel->iIdxCur = iIndexCur;
131251      assert( pIx->pSchema==pTab->pSchema );
131252      assert( iIndexCur>=0 );
131253      if( op ){
131254        sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
131255        sqlite3VdbeSetP4KeyInfo(pParse, pIx);
131256        if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
131257         && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
131258         && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
131259        ){
131260          sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
131261        }
131262        VdbeComment((v, "%s", pIx->zName));
131263#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
131264        {
131265          u64 colUsed = 0;
131266          int ii, jj;
131267          for(ii=0; ii<pIx->nColumn; ii++){
131268            jj = pIx->aiColumn[ii];
131269            if( jj<0 ) continue;
131270            if( jj>63 ) jj = 63;
131271            if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
131272            colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
131273          }
131274          sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
131275                                (u8*)&colUsed, P4_INT64);
131276        }
131277#endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
131278      }
131279    }
131280    if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
131281  }
131282  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
131283  if( db->mallocFailed ) goto whereBeginError;
131284
131285  /* Generate the code to do the search.  Each iteration of the for
131286  ** loop below generates code for a single nested loop of the VM
131287  ** program.
131288  */
131289  notReady = ~(Bitmask)0;
131290  for(ii=0; ii<nTabList; ii++){
131291    int addrExplain;
131292    int wsFlags;
131293    pLevel = &pWInfo->a[ii];
131294    wsFlags = pLevel->pWLoop->wsFlags;
131295#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
131296    if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
131297      constructAutomaticIndex(pParse, &pWInfo->sWC,
131298                &pTabList->a[pLevel->iFrom], notReady, pLevel);
131299      if( db->mallocFailed ) goto whereBeginError;
131300    }
131301#endif
131302    addrExplain = sqlite3WhereExplainOneScan(
131303        pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
131304    );
131305    pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
131306    notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
131307    pWInfo->iContinue = pLevel->addrCont;
131308    if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
131309      sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
131310    }
131311  }
131312
131313  /* Done. */
131314  VdbeModuleComment((v, "Begin WHERE-core"));
131315  return pWInfo;
131316
131317  /* Jump here if malloc fails */
131318whereBeginError:
131319  if( pWInfo ){
131320    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
131321    whereInfoFree(db, pWInfo);
131322  }
131323  return 0;
131324}
131325
131326/*
131327** Generate the end of the WHERE loop.  See comments on
131328** sqlite3WhereBegin() for additional information.
131329*/
131330SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
131331  Parse *pParse = pWInfo->pParse;
131332  Vdbe *v = pParse->pVdbe;
131333  int i;
131334  WhereLevel *pLevel;
131335  WhereLoop *pLoop;
131336  SrcList *pTabList = pWInfo->pTabList;
131337  sqlite3 *db = pParse->db;
131338
131339  /* Generate loop termination code.
131340  */
131341  VdbeModuleComment((v, "End WHERE-core"));
131342  sqlite3ExprCacheClear(pParse);
131343  for(i=pWInfo->nLevel-1; i>=0; i--){
131344    int addr;
131345    pLevel = &pWInfo->a[i];
131346    pLoop = pLevel->pWLoop;
131347    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
131348    if( pLevel->op!=OP_Noop ){
131349      sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
131350      sqlite3VdbeChangeP5(v, pLevel->p5);
131351      VdbeCoverage(v);
131352      VdbeCoverageIf(v, pLevel->op==OP_Next);
131353      VdbeCoverageIf(v, pLevel->op==OP_Prev);
131354      VdbeCoverageIf(v, pLevel->op==OP_VNext);
131355    }
131356    if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
131357      struct InLoop *pIn;
131358      int j;
131359      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
131360      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
131361        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
131362        sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
131363        VdbeCoverage(v);
131364        VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
131365        VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
131366        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
131367      }
131368    }
131369    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
131370    if( pLevel->addrSkip ){
131371      sqlite3VdbeGoto(v, pLevel->addrSkip);
131372      VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
131373      sqlite3VdbeJumpHere(v, pLevel->addrSkip);
131374      sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
131375    }
131376#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
131377    if( pLevel->addrLikeRep ){
131378      sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
131379                        pLevel->addrLikeRep);
131380      VdbeCoverage(v);
131381    }
131382#endif
131383    if( pLevel->iLeftJoin ){
131384      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
131385      assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
131386           || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
131387      if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
131388        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
131389      }
131390      if( pLoop->wsFlags & WHERE_INDEXED ){
131391        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
131392      }
131393      if( pLevel->op==OP_Return ){
131394        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
131395      }else{
131396        sqlite3VdbeGoto(v, pLevel->addrFirst);
131397      }
131398      sqlite3VdbeJumpHere(v, addr);
131399    }
131400    VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
131401                     pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
131402  }
131403
131404  /* The "break" point is here, just past the end of the outer loop.
131405  ** Set it.
131406  */
131407  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
131408
131409  assert( pWInfo->nLevel<=pTabList->nSrc );
131410  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
131411    int k, last;
131412    VdbeOp *pOp;
131413    Index *pIdx = 0;
131414    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
131415    Table *pTab = pTabItem->pTab;
131416    assert( pTab!=0 );
131417    pLoop = pLevel->pWLoop;
131418
131419    /* For a co-routine, change all OP_Column references to the table of
131420    ** the co-routine into OP_Copy of result contained in a register.
131421    ** OP_Rowid becomes OP_Null.
131422    */
131423    if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){
131424      translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur,
131425                            pTabItem->regResult, 0);
131426      continue;
131427    }
131428
131429    /* Close all of the cursors that were opened by sqlite3WhereBegin.
131430    ** Except, do not close cursors that will be reused by the OR optimization
131431    ** (WHERE_OR_SUBCLAUSE).  And do not close the OP_OpenWrite cursors
131432    ** created for the ONEPASS optimization.
131433    */
131434    if( (pTab->tabFlags & TF_Ephemeral)==0
131435     && pTab->pSelect==0
131436     && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
131437    ){
131438      int ws = pLoop->wsFlags;
131439      if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
131440        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
131441      }
131442      if( (ws & WHERE_INDEXED)!=0
131443       && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
131444       && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
131445      ){
131446        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
131447      }
131448    }
131449
131450    /* If this scan uses an index, make VDBE code substitutions to read data
131451    ** from the index instead of from the table where possible.  In some cases
131452    ** this optimization prevents the table from ever being read, which can
131453    ** yield a significant performance boost.
131454    **
131455    ** Calls to the code generator in between sqlite3WhereBegin and
131456    ** sqlite3WhereEnd will have created code that references the table
131457    ** directly.  This loop scans all that code looking for opcodes
131458    ** that reference the table and converts them into opcodes that
131459    ** reference the index.
131460    */
131461    if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
131462      pIdx = pLoop->u.btree.pIndex;
131463    }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
131464      pIdx = pLevel->u.pCovidx;
131465    }
131466    if( pIdx
131467     && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
131468     && !db->mallocFailed
131469    ){
131470      last = sqlite3VdbeCurrentAddr(v);
131471      k = pLevel->addrBody;
131472      pOp = sqlite3VdbeGetOp(v, k);
131473      for(; k<last; k++, pOp++){
131474        if( pOp->p1!=pLevel->iTabCur ) continue;
131475        if( pOp->opcode==OP_Column ){
131476          int x = pOp->p2;
131477          assert( pIdx->pTable==pTab );
131478          if( !HasRowid(pTab) ){
131479            Index *pPk = sqlite3PrimaryKeyIndex(pTab);
131480            x = pPk->aiColumn[x];
131481            assert( x>=0 );
131482          }
131483          x = sqlite3ColumnOfIndex(pIdx, x);
131484          if( x>=0 ){
131485            pOp->p2 = x;
131486            pOp->p1 = pLevel->iIdxCur;
131487          }
131488          assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
131489        }else if( pOp->opcode==OP_Rowid ){
131490          pOp->p1 = pLevel->iIdxCur;
131491          pOp->opcode = OP_IdxRowid;
131492        }
131493      }
131494    }
131495  }
131496
131497  /* Final cleanup
131498  */
131499  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
131500  whereInfoFree(db, pWInfo);
131501  return;
131502}
131503
131504/************** End of where.c ***********************************************/
131505/************** Begin file parse.c *******************************************/
131506/*
131507** 2000-05-29
131508**
131509** The author disclaims copyright to this source code.  In place of
131510** a legal notice, here is a blessing:
131511**
131512**    May you do good and not evil.
131513**    May you find forgiveness for yourself and forgive others.
131514**    May you share freely, never taking more than you give.
131515**
131516*************************************************************************
131517** Driver template for the LEMON parser generator.
131518**
131519** The "lemon" program processes an LALR(1) input grammar file, then uses
131520** this template to construct a parser.  The "lemon" program inserts text
131521** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
131522** interstitial "-" characters) contained in this template is changed into
131523** the value of the %name directive from the grammar.  Otherwise, the content
131524** of this template is copied straight through into the generate parser
131525** source file.
131526**
131527** The following is the concatenation of all %include directives from the
131528** input grammar file:
131529*/
131530/* #include <stdio.h> */
131531/************ Begin %include sections from the grammar ************************/
131532
131533/* #include "sqliteInt.h" */
131534
131535/*
131536** Disable all error recovery processing in the parser push-down
131537** automaton.
131538*/
131539#define YYNOERRORRECOVERY 1
131540
131541/*
131542** Make yytestcase() the same as testcase()
131543*/
131544#define yytestcase(X) testcase(X)
131545
131546/*
131547** Indicate that sqlite3ParserFree() will never be called with a null
131548** pointer.
131549*/
131550#define YYPARSEFREENEVERNULL 1
131551
131552/*
131553** Alternative datatype for the argument to the malloc() routine passed
131554** into sqlite3ParserAlloc().  The default is size_t.
131555*/
131556#define YYMALLOCARGTYPE  u64
131557
131558/*
131559** An instance of this structure holds information about the
131560** LIMIT clause of a SELECT statement.
131561*/
131562struct LimitVal {
131563  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
131564  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
131565};
131566
131567/*
131568** An instance of this structure is used to store the LIKE,
131569** GLOB, NOT LIKE, and NOT GLOB operators.
131570*/
131571struct LikeOp {
131572  Token eOperator;  /* "like" or "glob" or "regexp" */
131573  int bNot;         /* True if the NOT keyword is present */
131574};
131575
131576/*
131577** An instance of the following structure describes the event of a
131578** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
131579** TK_DELETE, or TK_INSTEAD.  If the event is of the form
131580**
131581**      UPDATE ON (a,b,c)
131582**
131583** Then the "b" IdList records the list "a,b,c".
131584*/
131585struct TrigEvent { int a; IdList * b; };
131586
131587/*
131588** An instance of this structure holds the ATTACH key and the key type.
131589*/
131590struct AttachKey { int type;  Token key; };
131591
131592/*
131593** Disable lookaside memory allocation for objects that might be
131594** shared across database connections.
131595*/
131596static void disableLookaside(Parse *pParse){
131597  pParse->disableLookaside++;
131598  pParse->db->lookaside.bDisable++;
131599}
131600
131601
131602  /*
131603  ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
131604  ** all elements in the list.  And make sure list length does not exceed
131605  ** SQLITE_LIMIT_COMPOUND_SELECT.
131606  */
131607  static void parserDoubleLinkSelect(Parse *pParse, Select *p){
131608    if( p->pPrior ){
131609      Select *pNext = 0, *pLoop;
131610      int mxSelect, cnt = 0;
131611      for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
131612        pLoop->pNext = pNext;
131613        pLoop->selFlags |= SF_Compound;
131614      }
131615      if( (p->selFlags & SF_MultiValue)==0 &&
131616        (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
131617        cnt>mxSelect
131618      ){
131619        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
131620      }
131621    }
131622  }
131623
131624  /* This is a utility routine used to set the ExprSpan.zStart and
131625  ** ExprSpan.zEnd values of pOut so that the span covers the complete
131626  ** range of text beginning with pStart and going to the end of pEnd.
131627  */
131628  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
131629    pOut->zStart = pStart->z;
131630    pOut->zEnd = &pEnd->z[pEnd->n];
131631  }
131632
131633  /* Construct a new Expr object from a single identifier.  Use the
131634  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
131635  ** that created the expression.
131636  */
131637  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){
131638    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, &t);
131639    pOut->zStart = t.z;
131640    pOut->zEnd = &t.z[t.n];
131641  }
131642
131643  /* This routine constructs a binary expression node out of two ExprSpan
131644  ** objects and uses the result to populate a new ExprSpan object.
131645  */
131646  static void spanBinaryExpr(
131647    Parse *pParse,      /* The parsing context.  Errors accumulate here */
131648    int op,             /* The binary operation */
131649    ExprSpan *pLeft,    /* The left operand, and output */
131650    ExprSpan *pRight    /* The right operand */
131651  ){
131652    pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
131653    pLeft->zEnd = pRight->zEnd;
131654  }
131655
131656  /* If doNot is true, then add a TK_NOT Expr-node wrapper around the
131657  ** outside of *ppExpr.
131658  */
131659  static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){
131660    if( doNot ){
131661      pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0, 0);
131662    }
131663  }
131664
131665  /* Construct an expression node for a unary postfix operator
131666  */
131667  static void spanUnaryPostfix(
131668    Parse *pParse,         /* Parsing context to record errors */
131669    int op,                /* The operator */
131670    ExprSpan *pOperand,    /* The operand, and output */
131671    Token *pPostOp         /* The operand token for setting the span */
131672  ){
131673    pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
131674    pOperand->zEnd = &pPostOp->z[pPostOp->n];
131675  }
131676
131677  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
131678  ** unary TK_ISNULL or TK_NOTNULL expression. */
131679  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
131680    sqlite3 *db = pParse->db;
131681    if( pA && pY && pY->op==TK_NULL ){
131682      pA->op = (u8)op;
131683      sqlite3ExprDelete(db, pA->pRight);
131684      pA->pRight = 0;
131685    }
131686  }
131687
131688  /* Construct an expression node for a unary prefix operator
131689  */
131690  static void spanUnaryPrefix(
131691    ExprSpan *pOut,        /* Write the new expression node here */
131692    Parse *pParse,         /* Parsing context to record errors */
131693    int op,                /* The operator */
131694    ExprSpan *pOperand,    /* The operand */
131695    Token *pPreOp         /* The operand token for setting the span */
131696  ){
131697    pOut->zStart = pPreOp->z;
131698    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
131699    pOut->zEnd = pOperand->zEnd;
131700  }
131701
131702  /* Add a single new term to an ExprList that is used to store a
131703  ** list of identifiers.  Report an error if the ID list contains
131704  ** a COLLATE clause or an ASC or DESC keyword, except ignore the
131705  ** error while parsing a legacy schema.
131706  */
131707  static ExprList *parserAddExprIdListTerm(
131708    Parse *pParse,
131709    ExprList *pPrior,
131710    Token *pIdToken,
131711    int hasCollate,
131712    int sortOrder
131713  ){
131714    ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
131715    if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
131716        && pParse->db->init.busy==0
131717    ){
131718      sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
131719                         pIdToken->n, pIdToken->z);
131720    }
131721    sqlite3ExprListSetName(pParse, p, pIdToken, 1);
131722    return p;
131723  }
131724/**************** End of %include directives **********************************/
131725/* These constants specify the various numeric values for terminal symbols
131726** in a format understandable to "makeheaders".  This section is blank unless
131727** "lemon" is run with the "-m" command-line option.
131728***************** Begin makeheaders token definitions *************************/
131729/**************** End makeheaders token definitions ***************************/
131730
131731/* The next sections is a series of control #defines.
131732** various aspects of the generated parser.
131733**    YYCODETYPE         is the data type used to store the integer codes
131734**                       that represent terminal and non-terminal symbols.
131735**                       "unsigned char" is used if there are fewer than
131736**                       256 symbols.  Larger types otherwise.
131737**    YYNOCODE           is a number of type YYCODETYPE that is not used for
131738**                       any terminal or nonterminal symbol.
131739**    YYFALLBACK         If defined, this indicates that one or more tokens
131740**                       (also known as: "terminal symbols") have fall-back
131741**                       values which should be used if the original symbol
131742**                       would not parse.  This permits keywords to sometimes
131743**                       be used as identifiers, for example.
131744**    YYACTIONTYPE       is the data type used for "action codes" - numbers
131745**                       that indicate what to do in response to the next
131746**                       token.
131747**    sqlite3ParserTOKENTYPE     is the data type used for minor type for terminal
131748**                       symbols.  Background: A "minor type" is a semantic
131749**                       value associated with a terminal or non-terminal
131750**                       symbols.  For example, for an "ID" terminal symbol,
131751**                       the minor type might be the name of the identifier.
131752**                       Each non-terminal can have a different minor type.
131753**                       Terminal symbols all have the same minor type, though.
131754**                       This macros defines the minor type for terminal
131755**                       symbols.
131756**    YYMINORTYPE        is the data type used for all minor types.
131757**                       This is typically a union of many types, one of
131758**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
131759**                       for terminal symbols is called "yy0".
131760**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
131761**                       zero the stack is dynamically sized using realloc()
131762**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
131763**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
131764**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
131765**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
131766**    YYERRORSYMBOL      is the code number of the error symbol.  If not
131767**                       defined, then do no error processing.
131768**    YYNSTATE           the combined number of states.
131769**    YYNRULE            the number of rules in the grammar
131770**    YY_MAX_SHIFT       Maximum value for shift actions
131771**    YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
131772**    YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
131773**    YY_MIN_REDUCE      Maximum value for reduce actions
131774**    YY_ERROR_ACTION    The yy_action[] code for syntax error
131775**    YY_ACCEPT_ACTION   The yy_action[] code for accept
131776**    YY_NO_ACTION       The yy_action[] code for no-op
131777*/
131778#ifndef INTERFACE
131779# define INTERFACE 1
131780#endif
131781/************* Begin control #defines *****************************************/
131782#define YYCODETYPE unsigned char
131783#define YYNOCODE 252
131784#define YYACTIONTYPE unsigned short int
131785#define YYWILDCARD 96
131786#define sqlite3ParserTOKENTYPE Token
131787typedef union {
131788  int yyinit;
131789  sqlite3ParserTOKENTYPE yy0;
131790  Expr* yy72;
131791  TriggerStep* yy145;
131792  ExprList* yy148;
131793  SrcList* yy185;
131794  ExprSpan yy190;
131795  int yy194;
131796  Select* yy243;
131797  IdList* yy254;
131798  With* yy285;
131799  struct TrigEvent yy332;
131800  struct LimitVal yy354;
131801  struct LikeOp yy392;
131802  struct {int value; int mask;} yy497;
131803} YYMINORTYPE;
131804#ifndef YYSTACKDEPTH
131805#define YYSTACKDEPTH 100
131806#endif
131807#define sqlite3ParserARG_SDECL Parse *pParse;
131808#define sqlite3ParserARG_PDECL ,Parse *pParse
131809#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
131810#define sqlite3ParserARG_STORE yypParser->pParse = pParse
131811#define YYFALLBACK 1
131812#define YYNSTATE             443
131813#define YYNRULE              328
131814#define YY_MAX_SHIFT         442
131815#define YY_MIN_SHIFTREDUCE   653
131816#define YY_MAX_SHIFTREDUCE   980
131817#define YY_MIN_REDUCE        981
131818#define YY_MAX_REDUCE        1308
131819#define YY_ERROR_ACTION      1309
131820#define YY_ACCEPT_ACTION     1310
131821#define YY_NO_ACTION         1311
131822/************* End control #defines *******************************************/
131823
131824/* Define the yytestcase() macro to be a no-op if is not already defined
131825** otherwise.
131826**
131827** Applications can choose to define yytestcase() in the %include section
131828** to a macro that can assist in verifying code coverage.  For production
131829** code the yytestcase() macro should be turned off.  But it is useful
131830** for testing.
131831*/
131832#ifndef yytestcase
131833# define yytestcase(X)
131834#endif
131835
131836
131837/* Next are the tables used to determine what action to take based on the
131838** current state and lookahead token.  These tables are used to implement
131839** functions that take a state number and lookahead value and return an
131840** action integer.
131841**
131842** Suppose the action integer is N.  Then the action is determined as
131843** follows
131844**
131845**   0 <= N <= YY_MAX_SHIFT             Shift N.  That is, push the lookahead
131846**                                      token onto the stack and goto state N.
131847**
131848**   N between YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
131849**     and YY_MAX_SHIFTREDUCE           reduce by rule N-YY_MIN_SHIFTREDUCE.
131850**
131851**   N between YY_MIN_REDUCE            Reduce by rule N-YY_MIN_REDUCE
131852**     and YY_MAX_REDUCE
131853
131854**   N == YY_ERROR_ACTION               A syntax error has occurred.
131855**
131856**   N == YY_ACCEPT_ACTION              The parser accepts its input.
131857**
131858**   N == YY_NO_ACTION                  No such action.  Denotes unused
131859**                                      slots in the yy_action[] table.
131860**
131861** The action table is constructed as a single large table named yy_action[].
131862** Given state S and lookahead X, the action is computed as
131863**
131864**      yy_action[ yy_shift_ofst[S] + X ]
131865**
131866** If the index value yy_shift_ofst[S]+X is out of range or if the value
131867** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
131868** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
131869** and that yy_default[S] should be used instead.
131870**
131871** The formula above is for computing the action when the lookahead is
131872** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
131873** a reduce action) then the yy_reduce_ofst[] array is used in place of
131874** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
131875** YY_SHIFT_USE_DFLT.
131876**
131877** The following are the tables generated in this section:
131878**
131879**  yy_action[]        A single table containing all actions.
131880**  yy_lookahead[]     A table containing the lookahead for each entry in
131881**                     yy_action.  Used to detect hash collisions.
131882**  yy_shift_ofst[]    For each state, the offset into yy_action for
131883**                     shifting terminals.
131884**  yy_reduce_ofst[]   For each state, the offset into yy_action for
131885**                     shifting non-terminals after a reduce.
131886**  yy_default[]       Default action for each state.
131887**
131888*********** Begin parsing tables **********************************************/
131889#define YY_ACTTAB_COUNT (1507)
131890static const YYACTIONTYPE yy_action[] = {
131891 /*     0 */   317,  814,  341,  808,    5,  195,  195,  802,   93,   94,
131892 /*    10 */    84,  823,  823,  835,  838,  827,  827,   91,   91,   92,
131893 /*    20 */    92,   92,   92,  293,   90,   90,   90,   90,   89,   89,
131894 /*    30 */    88,   88,   88,   87,  341,  317,  958,  958,  807,  807,
131895 /*    40 */   807,  928,  344,   93,   94,   84,  823,  823,  835,  838,
131896 /*    50 */   827,  827,   91,   91,   92,   92,   92,   92,  328,   90,
131897 /*    60 */    90,   90,   90,   89,   89,   88,   88,   88,   87,  341,
131898 /*    70 */    89,   89,   88,   88,   88,   87,  341,  776,  958,  958,
131899 /*    80 */   317,   88,   88,   88,   87,  341,  777,   69,   93,   94,
131900 /*    90 */    84,  823,  823,  835,  838,  827,  827,   91,   91,   92,
131901 /*   100 */    92,   92,   92,  437,   90,   90,   90,   90,   89,   89,
131902 /*   110 */    88,   88,   88,   87,  341, 1310,  147,  147,    2,  317,
131903 /*   120 */    76,   25,   74,   49,   49,   87,  341,   93,   94,   84,
131904 /*   130 */   823,  823,  835,  838,  827,  827,   91,   91,   92,   92,
131905 /*   140 */    92,   92,   95,   90,   90,   90,   90,   89,   89,   88,
131906 /*   150 */    88,   88,   87,  341,  939,  939,  317,  260,  415,  400,
131907 /*   160 */   398,   58,  737,  737,   93,   94,   84,  823,  823,  835,
131908 /*   170 */   838,  827,  827,   91,   91,   92,   92,   92,   92,   57,
131909 /*   180 */    90,   90,   90,   90,   89,   89,   88,   88,   88,   87,
131910 /*   190 */   341,  317, 1253,  928,  344,  269,  940,  941,  242,   93,
131911 /*   200 */    94,   84,  823,  823,  835,  838,  827,  827,   91,   91,
131912 /*   210 */    92,   92,   92,   92,  293,   90,   90,   90,   90,   89,
131913 /*   220 */    89,   88,   88,   88,   87,  341,  317,  919, 1303,  793,
131914 /*   230 */   691, 1303,  724,  724,   93,   94,   84,  823,  823,  835,
131915 /*   240 */   838,  827,  827,   91,   91,   92,   92,   92,   92,  337,
131916 /*   250 */    90,   90,   90,   90,   89,   89,   88,   88,   88,   87,
131917 /*   260 */   341,  317,  114,  919, 1304,  684,  395, 1304,  124,   93,
131918 /*   270 */    94,   84,  823,  823,  835,  838,  827,  827,   91,   91,
131919 /*   280 */    92,   92,   92,   92,  683,   90,   90,   90,   90,   89,
131920 /*   290 */    89,   88,   88,   88,   87,  341,  317,   86,   83,  169,
131921 /*   300 */   801,  917,  234,  399,   93,   94,   84,  823,  823,  835,
131922 /*   310 */   838,  827,  827,   91,   91,   92,   92,   92,   92,  686,
131923 /*   320 */    90,   90,   90,   90,   89,   89,   88,   88,   88,   87,
131924 /*   330 */   341,  317,  436,  742,   86,   83,  169,  917,  741,   93,
131925 /*   340 */    94,   84,  823,  823,  835,  838,  827,  827,   91,   91,
131926 /*   350 */    92,   92,   92,   92,  902,   90,   90,   90,   90,   89,
131927 /*   360 */    89,   88,   88,   88,   87,  341,  317,  321,  434,  434,
131928 /*   370 */   434,    1,  722,  722,   93,   94,   84,  823,  823,  835,
131929 /*   380 */   838,  827,  827,   91,   91,   92,   92,   92,   92,  190,
131930 /*   390 */    90,   90,   90,   90,   89,   89,   88,   88,   88,   87,
131931 /*   400 */   341,  317,  685,  292,  939,  939,  150,  977,  310,   93,
131932 /*   410 */    94,   84,  823,  823,  835,  838,  827,  827,   91,   91,
131933 /*   420 */    92,   92,   92,   92,  437,   90,   90,   90,   90,   89,
131934 /*   430 */    89,   88,   88,   88,   87,  341,  926,    2,  372,  719,
131935 /*   440 */   698,  369,  950,  317,   49,   49,  940,  941,  719,  177,
131936 /*   450 */    72,   93,   94,   84,  823,  823,  835,  838,  827,  827,
131937 /*   460 */    91,   91,   92,   92,   92,   92,  322,   90,   90,   90,
131938 /*   470 */    90,   89,   89,   88,   88,   88,   87,  341,  317,  415,
131939 /*   480 */   405,  824,  824,  836,  839,   75,   93,   82,   84,  823,
131940 /*   490 */   823,  835,  838,  827,  827,   91,   91,   92,   92,   92,
131941 /*   500 */    92,  430,   90,   90,   90,   90,   89,   89,   88,   88,
131942 /*   510 */    88,   87,  341,  317,  340,  340,  340,  658,  659,  660,
131943 /*   520 */   333,  288,   94,   84,  823,  823,  835,  838,  827,  827,
131944 /*   530 */    91,   91,   92,   92,   92,   92,  437,   90,   90,   90,
131945 /*   540 */    90,   89,   89,   88,   88,   88,   87,  341,  317,  882,
131946 /*   550 */   882,  375,  828,   66,  330,  409,   49,   49,   84,  823,
131947 /*   560 */   823,  835,  838,  827,  827,   91,   91,   92,   92,   92,
131948 /*   570 */    92,  351,   90,   90,   90,   90,   89,   89,   88,   88,
131949 /*   580 */    88,   87,  341,   80,  432,  742,    3, 1180,  351,  350,
131950 /*   590 */   741,  334,  796,  939,  939,  761,   80,  432,  278,    3,
131951 /*   600 */   204,  161,  279,  393,  274,  392,  191,  362,  437,  277,
131952 /*   610 */   745,   77,   78,  272,  800,  254,  355,  243,   79,  342,
131953 /*   620 */   342,   86,   83,  169,   77,   78,  234,  399,   49,   49,
131954 /*   630 */   435,   79,  342,  342,  437,  940,  941,  186,  442,  655,
131955 /*   640 */   390,  387,  386,  435,  235,  213,  108,  421,  761,  351,
131956 /*   650 */   437,  385,  167,  732,   10,   10,  124,  124,  671,  814,
131957 /*   660 */   421,  439,  438,  415,  414,  802,  362,  168,  327,  124,
131958 /*   670 */    49,   49,  814,  219,  439,  438,  800,  186,  802,  326,
131959 /*   680 */   390,  387,  386,  437, 1248, 1248,   23,  939,  939,   80,
131960 /*   690 */   432,  385,    3,  761,  416,  876,  807,  807,  807,  809,
131961 /*   700 */    19,  290,  149,   49,   49,  415,  396,  260,  910,  807,
131962 /*   710 */   807,  807,  809,   19,  312,  237,  145,   77,   78,  746,
131963 /*   720 */   168,  702,  437,  149,   79,  342,  342,  114,  358,  940,
131964 /*   730 */   941,  302,  223,  397,  345,  313,  435,  260,  415,  417,
131965 /*   740 */   858,  374,   31,   31,   80,  432,  761,    3,  348,   92,
131966 /*   750 */    92,   92,   92,  421,   90,   90,   90,   90,   89,   89,
131967 /*   760 */    88,   88,   88,   87,  341,  814,  114,  439,  438,  796,
131968 /*   770 */   367,  802,   77,   78,  701,  796,  124, 1187,  220,   79,
131969 /*   780 */   342,  342,  124,  747,  734,  939,  939,  775,  404,  939,
131970 /*   790 */   939,  435,  254,  360,  253,  402,  895,  346,  254,  360,
131971 /*   800 */   253,  774,  807,  807,  807,  809,   19,  800,  421,   90,
131972 /*   810 */    90,   90,   90,   89,   89,   88,   88,   88,   87,  341,
131973 /*   820 */   814,  114,  439,  438,  939,  939,  802,  940,  941,  114,
131974 /*   830 */   437,  940,  941,   86,   83,  169,  192,  166,  309,  979,
131975 /*   840 */    70,  432,  700,    3,  382,  870,  238,   86,   83,  169,
131976 /*   850 */    10,   10,  361,  406,  763,  190,  222,  807,  807,  807,
131977 /*   860 */   809,   19,  870,  872,  329,   24,  940,  941,   77,   78,
131978 /*   870 */   359,  437,  335,  260,  218,   79,  342,  342,  437,  307,
131979 /*   880 */   306,  305,  207,  303,  339,  338,  668,  435,  339,  338,
131980 /*   890 */   407,   10,   10,  762,  216,  216,  939,  939,   49,   49,
131981 /*   900 */   437,  260,   97,  241,  421,  225,  402,  189,  188,  187,
131982 /*   910 */   309,  918,  980,  149,  221,  898,  814,  868,  439,  438,
131983 /*   920 */    10,   10,  802,  870,  915,  316,  898,  163,  162,  171,
131984 /*   930 */   249,  240,  322,  410,  412,  687,  687,  272,  940,  941,
131985 /*   940 */   239,  965,  901,  437,  226,  403,  226,  437,  963,  367,
131986 /*   950 */   964,  173,  248,  807,  807,  807,  809,   19,  174,  367,
131987 /*   960 */   899,  124,  172,   48,   48,    9,    9,   35,   35,  966,
131988 /*   970 */   966,  899,  363,  966,  966,  814,  900,  808,  725,  939,
131989 /*   980 */   939,  802,  895,  318,  980,  324,  125,  900,  726,  420,
131990 /*   990 */    92,   92,   92,   92,   85,   90,   90,   90,   90,   89,
131991 /*  1000 */    89,   88,   88,   88,   87,  341,  216,  216,  437,  946,
131992 /*  1010 */   349,  292,  807,  807,  807,  114,  291,  693,  402,  705,
131993 /*  1020 */   890,  940,  941,  437,  245,  889,  247,  437,   36,   36,
131994 /*  1030 */   437,  353,  391,  437,  260,  252,  260,  437,  361,  437,
131995 /*  1040 */   706,  437,  370,   12,   12,  224,  437,   27,   27,  437,
131996 /*  1050 */    37,   37,  437,   38,   38,  752,  368,   39,   39,   28,
131997 /*  1060 */    28,   29,   29,  215,  166,  331,   40,   40,  437,   41,
131998 /*  1070 */    41,  437,   42,   42,  437,  866,  246,  731,  437,  879,
131999 /*  1080 */   437,  256,  437,  878,  437,  267,  437,  261,   11,   11,
132000 /*  1090 */   437,   43,   43,  437,   99,   99,  437,  373,   44,   44,
132001 /*  1100 */    45,   45,   32,   32,   46,   46,   47,   47,  437,  426,
132002 /*  1110 */    33,   33,  776,  116,  116,  437,  117,  117,  437,  124,
132003 /*  1120 */   437,  777,  437,  260,  437,  957,  437,  352,  118,  118,
132004 /*  1130 */   437,  195,  437,  111,  437,   53,   53,  264,   34,   34,
132005 /*  1140 */   100,  100,   50,   50,  101,  101,  102,  102,  437,  260,
132006 /*  1150 */    98,   98,  115,  115,  113,  113,  437,  262,  437,  265,
132007 /*  1160 */   437,  943,  958,  437,  727,  437,  681,  437,  106,  106,
132008 /*  1170 */    68,  437,  893,  730,  437,  365,  105,  105,  103,  103,
132009 /*  1180 */   104,  104,  217,   52,   52,   54,   54,   51,   51,  694,
132010 /*  1190 */   259,   26,   26,  266,   30,   30,  677,  323,  433,  323,
132011 /*  1200 */   674,  423,  427,  943,  958,  114,  114,  431,  681,  865,
132012 /*  1210 */  1277,  233,  366,  714,  112,   20,  154,  704,  703,  810,
132013 /*  1220 */   914,   55,  159,  311,  798,  255,  383,  194,   68,  200,
132014 /*  1230 */    21,  694,  268,  114,  114,  114,  270,  711,  712,   68,
132015 /*  1240 */   114,  739,  770,  715,   71,  194,  861,  875,  875,  200,
132016 /*  1250 */   696,  865,  874,  874,  679,  699,  273,  110,  229,  419,
132017 /*  1260 */   768,  810,  799,  378,  748,  759,  418,  210,  294,  281,
132018 /*  1270 */   295,  806,  283,  682,  676,  665,  664,  666,  933,  151,
132019 /*  1280 */   285,    7, 1267,  308,  251,  790,  354,  244,  892,  364,
132020 /*  1290 */   287,  422,  300,  164,  160,  936,  974,  127,  197,  137,
132021 /*  1300 */   909,  907,  971,  388,  276,  863,  862,   56,  698,  325,
132022 /*  1310 */   148,   59,  122,   66,  356,  381,  357,  176,  152,   62,
132023 /*  1320 */   371,  130,  877,  181,  377,  760,  211,  182,  132,  133,
132024 /*  1330 */   134,  135,  258,  146,  140,  795,  787,  263,  183,  379,
132025 /*  1340 */   667,  394,  184,  332,  894,  314,  718,  717,  857,  716,
132026 /*  1350 */   696,  315,  709,  690,   65,  196,    6,  408,  289,  708,
132027 /*  1360 */   275,  689,  688,  948,  756,  757,  280,  282,  425,  755,
132028 /*  1370 */   284,  336,   73,   67,  754,  429,  411,   96,  286,  413,
132029 /*  1380 */   205,  934,  673,   22,  209,  440,  119,  120,  109,  206,
132030 /*  1390 */   208,  441,  662,  661,  656,  843,  654,  343,  158,  236,
132031 /*  1400 */   170,  347,  107,  227,  121,  738,  873,  298,  296,  297,
132032 /*  1410 */   299,  871,  794,  128,  129,  728,  230,  131,  175,  250,
132033 /*  1420 */   888,  136,  138,  231,  232,  139,   60,   61,  891,  178,
132034 /*  1430 */   179,  887,    8,   13,  180,  257,  880,  968,  194,  141,
132035 /*  1440 */   142,  376,  153,  670,  380,  185,  143,  277,   63,  384,
132036 /*  1450 */    14,  707,  271,   15,  389,   64,  319,  320,  126,  228,
132037 /*  1460 */   813,  812,  841,  736,  123,   16,  401,  740,    4,  769,
132038 /*  1470 */   165,  212,  214,  193,  144,  764,   71,   68,   17,   18,
132039 /*  1480 */   856,  842,  840,  897,  845,  896,  199,  198,  923,  155,
132040 /*  1490 */   424,  929,  924,  156,  201,  202,  428,  844,  157,  203,
132041 /*  1500 */   811,  680,   81, 1269, 1268,  301,  304,
132042};
132043static const YYCODETYPE yy_lookahead[] = {
132044 /*     0 */    19,   95,   53,   97,   22,   24,   24,  101,   27,   28,
132045 /*    10 */    29,   30,   31,   32,   33,   34,   35,   36,   37,   38,
132046 /*    20 */    39,   40,   41,  152,   43,   44,   45,   46,   47,   48,
132047 /*    30 */    49,   50,   51,   52,   53,   19,   55,   55,  132,  133,
132048 /*    40 */   134,    1,    2,   27,   28,   29,   30,   31,   32,   33,
132049 /*    50 */    34,   35,   36,   37,   38,   39,   40,   41,  187,   43,
132050 /*    60 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
132051 /*    70 */    47,   48,   49,   50,   51,   52,   53,   61,   97,   97,
132052 /*    80 */    19,   49,   50,   51,   52,   53,   70,   26,   27,   28,
132053 /*    90 */    29,   30,   31,   32,   33,   34,   35,   36,   37,   38,
132054 /*   100 */    39,   40,   41,  152,   43,   44,   45,   46,   47,   48,
132055 /*   110 */    49,   50,   51,   52,   53,  144,  145,  146,  147,   19,
132056 /*   120 */   137,   22,  139,  172,  173,   52,   53,   27,   28,   29,
132057 /*   130 */    30,   31,   32,   33,   34,   35,   36,   37,   38,   39,
132058 /*   140 */    40,   41,   81,   43,   44,   45,   46,   47,   48,   49,
132059 /*   150 */    50,   51,   52,   53,   55,   56,   19,  152,  207,  208,
132060 /*   160 */   115,   24,  117,  118,   27,   28,   29,   30,   31,   32,
132061 /*   170 */    33,   34,   35,   36,   37,   38,   39,   40,   41,   79,
132062 /*   180 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
132063 /*   190 */    53,   19,    0,    1,    2,   23,   97,   98,  193,   27,
132064 /*   200 */    28,   29,   30,   31,   32,   33,   34,   35,   36,   37,
132065 /*   210 */    38,   39,   40,   41,  152,   43,   44,   45,   46,   47,
132066 /*   220 */    48,   49,   50,   51,   52,   53,   19,   22,   23,  163,
132067 /*   230 */    23,   26,  190,  191,   27,   28,   29,   30,   31,   32,
132068 /*   240 */    33,   34,   35,   36,   37,   38,   39,   40,   41,  187,
132069 /*   250 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
132070 /*   260 */    53,   19,  196,   22,   23,   23,   49,   26,   92,   27,
132071 /*   270 */    28,   29,   30,   31,   32,   33,   34,   35,   36,   37,
132072 /*   280 */    38,   39,   40,   41,  172,   43,   44,   45,   46,   47,
132073 /*   290 */    48,   49,   50,   51,   52,   53,   19,  221,  222,  223,
132074 /*   300 */    23,   96,  119,  120,   27,   28,   29,   30,   31,   32,
132075 /*   310 */    33,   34,   35,   36,   37,   38,   39,   40,   41,  172,
132076 /*   320 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
132077 /*   330 */    53,   19,  152,  116,  221,  222,  223,   96,  121,   27,
132078 /*   340 */    28,   29,   30,   31,   32,   33,   34,   35,   36,   37,
132079 /*   350 */    38,   39,   40,   41,  241,   43,   44,   45,   46,   47,
132080 /*   360 */    48,   49,   50,   51,   52,   53,   19,  157,  168,  169,
132081 /*   370 */   170,   22,  190,  191,   27,   28,   29,   30,   31,   32,
132082 /*   380 */    33,   34,   35,   36,   37,   38,   39,   40,   41,   30,
132083 /*   390 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
132084 /*   400 */    53,   19,  172,  152,   55,   56,   24,  247,  248,   27,
132085 /*   410 */    28,   29,   30,   31,   32,   33,   34,   35,   36,   37,
132086 /*   420 */    38,   39,   40,   41,  152,   43,   44,   45,   46,   47,
132087 /*   430 */    48,   49,   50,   51,   52,   53,  146,  147,  228,  179,
132088 /*   440 */   180,  231,  185,   19,  172,  173,   97,   98,  188,   26,
132089 /*   450 */   138,   27,   28,   29,   30,   31,   32,   33,   34,   35,
132090 /*   460 */    36,   37,   38,   39,   40,   41,  107,   43,   44,   45,
132091 /*   470 */    46,   47,   48,   49,   50,   51,   52,   53,   19,  207,
132092 /*   480 */   208,   30,   31,   32,   33,  138,   27,   28,   29,   30,
132093 /*   490 */    31,   32,   33,   34,   35,   36,   37,   38,   39,   40,
132094 /*   500 */    41,  250,   43,   44,   45,   46,   47,   48,   49,   50,
132095 /*   510 */    51,   52,   53,   19,  168,  169,  170,    7,    8,    9,
132096 /*   520 */    19,  152,   28,   29,   30,   31,   32,   33,   34,   35,
132097 /*   530 */    36,   37,   38,   39,   40,   41,  152,   43,   44,   45,
132098 /*   540 */    46,   47,   48,   49,   50,   51,   52,   53,   19,  108,
132099 /*   550 */   109,  110,  101,  130,   53,  152,  172,  173,   29,   30,
132100 /*   560 */    31,   32,   33,   34,   35,   36,   37,   38,   39,   40,
132101 /*   570 */    41,  152,   43,   44,   45,   46,   47,   48,   49,   50,
132102 /*   580 */    51,   52,   53,   19,   20,  116,   22,   23,  169,  170,
132103 /*   590 */   121,  207,   85,   55,   56,   26,   19,   20,  101,   22,
132104 /*   600 */    99,  100,  101,  102,  103,  104,  105,  152,  152,  112,
132105 /*   610 */   210,   47,   48,  112,  152,  108,  109,  110,   54,   55,
132106 /*   620 */    56,  221,  222,  223,   47,   48,  119,  120,  172,  173,
132107 /*   630 */    66,   54,   55,   56,  152,   97,   98,   99,  148,  149,
132108 /*   640 */   102,  103,  104,   66,  154,   23,  156,   83,   26,  230,
132109 /*   650 */   152,  113,  152,  163,  172,  173,   92,   92,   21,   95,
132110 /*   660 */    83,   97,   98,  207,  208,  101,  152,   98,  186,   92,
132111 /*   670 */   172,  173,   95,  218,   97,   98,  152,   99,  101,  217,
132112 /*   680 */   102,  103,  104,  152,  119,  120,  196,   55,   56,   19,
132113 /*   690 */    20,  113,   22,  124,  163,   11,  132,  133,  134,  135,
132114 /*   700 */   136,  152,  152,  172,  173,  207,  208,  152,  152,  132,
132115 /*   710 */   133,  134,  135,  136,  164,  152,   84,   47,   48,   49,
132116 /*   720 */    98,  181,  152,  152,   54,   55,   56,  196,   91,   97,
132117 /*   730 */    98,  160,  218,  163,  244,  164,   66,  152,  207,  208,
132118 /*   740 */   103,  217,  172,  173,   19,   20,  124,   22,  193,   38,
132119 /*   750 */    39,   40,   41,   83,   43,   44,   45,   46,   47,   48,
132120 /*   760 */    49,   50,   51,   52,   53,   95,  196,   97,   98,   85,
132121 /*   770 */   152,  101,   47,   48,  181,   85,   92,  140,  193,   54,
132122 /*   780 */    55,   56,   92,   49,  195,   55,   56,  175,  163,   55,
132123 /*   790 */    56,   66,  108,  109,  110,  206,  163,  242,  108,  109,
132124 /*   800 */   110,  175,  132,  133,  134,  135,  136,  152,   83,   43,
132125 /*   810 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
132126 /*   820 */    95,  196,   97,   98,   55,   56,  101,   97,   98,  196,
132127 /*   830 */   152,   97,   98,  221,  222,  223,  211,  212,   22,   23,
132128 /*   840 */    19,   20,  181,   22,   19,  152,  152,  221,  222,  223,
132129 /*   850 */   172,  173,  219,   19,  124,   30,  238,  132,  133,  134,
132130 /*   860 */   135,  136,  169,  170,  186,  232,   97,   98,   47,   48,
132131 /*   870 */   237,  152,  217,  152,    5,   54,   55,   56,  152,   10,
132132 /*   880 */    11,   12,   13,   14,   47,   48,   17,   66,   47,   48,
132133 /*   890 */    56,  172,  173,  124,  194,  195,   55,   56,  172,  173,
132134 /*   900 */   152,  152,   22,  152,   83,  186,  206,  108,  109,  110,
132135 /*   910 */    22,   23,   96,  152,  193,   12,   95,  152,   97,   98,
132136 /*   920 */   172,  173,  101,  230,  152,  164,   12,   47,   48,   60,
132137 /*   930 */   152,   62,  107,  207,  186,   55,   56,  112,   97,   98,
132138 /*   940 */    71,  100,  193,  152,  183,  152,  185,  152,  107,  152,
132139 /*   950 */   109,   82,   16,  132,  133,  134,  135,  136,   89,  152,
132140 /*   960 */    57,   92,   93,  172,  173,  172,  173,  172,  173,  132,
132141 /*   970 */   133,   57,  152,  132,  133,   95,   73,   97,   75,   55,
132142 /*   980 */    56,  101,  163,  114,   96,  245,  246,   73,   85,   75,
132143 /*   990 */    38,   39,   40,   41,   42,   43,   44,   45,   46,   47,
132144 /*  1000 */    48,   49,   50,   51,   52,   53,  194,  195,  152,  171,
132145 /*  1010 */   141,  152,  132,  133,  134,  196,  225,  179,  206,   65,
132146 /*  1020 */   152,   97,   98,  152,   88,  152,   90,  152,  172,  173,
132147 /*  1030 */   152,  219,   78,  152,  152,  238,  152,  152,  219,  152,
132148 /*  1040 */    86,  152,  152,  172,  173,  238,  152,  172,  173,  152,
132149 /*  1050 */   172,  173,  152,  172,  173,  213,  237,  172,  173,  172,
132150 /*  1060 */   173,  172,  173,  211,  212,  111,  172,  173,  152,  172,
132151 /*  1070 */   173,  152,  172,  173,  152,  193,  140,  193,  152,   59,
132152 /*  1080 */   152,  152,  152,   63,  152,   16,  152,  152,  172,  173,
132153 /*  1090 */   152,  172,  173,  152,  172,  173,  152,   77,  172,  173,
132154 /*  1100 */   172,  173,  172,  173,  172,  173,  172,  173,  152,  250,
132155 /*  1110 */   172,  173,   61,  172,  173,  152,  172,  173,  152,   92,
132156 /*  1120 */   152,   70,  152,  152,  152,   26,  152,  100,  172,  173,
132157 /*  1130 */   152,   24,  152,   22,  152,  172,  173,  152,  172,  173,
132158 /*  1140 */   172,  173,  172,  173,  172,  173,  172,  173,  152,  152,
132159 /*  1150 */   172,  173,  172,  173,  172,  173,  152,   88,  152,   90,
132160 /*  1160 */   152,   55,   55,  152,  193,  152,   55,  152,  172,  173,
132161 /*  1170 */    26,  152,  163,  163,  152,   19,  172,  173,  172,  173,
132162 /*  1180 */   172,  173,   22,  172,  173,  172,  173,  172,  173,   55,
132163 /*  1190 */   193,  172,  173,  152,  172,  173,  166,  167,  166,  167,
132164 /*  1200 */   163,  163,  163,   97,   97,  196,  196,  163,   97,   55,
132165 /*  1210 */    23,  199,   56,   26,   22,   22,   24,  100,  101,   55,
132166 /*  1220 */    23,  209,  123,   26,   23,   23,   23,   26,   26,   26,
132167 /*  1230 */    37,   97,  152,  196,  196,  196,   23,    7,    8,   26,
132168 /*  1240 */   196,   23,   23,  152,   26,   26,   23,  132,  133,   26,
132169 /*  1250 */   106,   97,  132,  133,   23,  152,  152,   26,  210,  191,
132170 /*  1260 */   152,   97,  152,  234,  152,  152,  152,  233,  152,  210,
132171 /*  1270 */   152,  152,  210,  152,  152,  152,  152,  152,  152,  197,
132172 /*  1280 */   210,  198,  122,  150,  239,  201,  214,  214,  201,  239,
132173 /*  1290 */   214,  227,  200,  184,  198,  155,   67,  243,  122,   22,
132174 /*  1300 */   159,  159,   69,  176,  175,  175,  175,  240,  180,  159,
132175 /*  1310 */   220,  240,   27,  130,   18,   18,  159,  158,  220,  137,
132176 /*  1320 */   159,  189,  236,  158,   74,  159,  159,  158,  192,  192,
132177 /*  1330 */   192,  192,  235,   22,  189,  189,  201,  159,  158,  177,
132178 /*  1340 */   159,  107,  158,   76,  201,  177,  174,  174,  201,  174,
132179 /*  1350 */   106,  177,  182,  174,  107,  159,   22,  125,  159,  182,
132180 /*  1360 */   174,  176,  174,  174,  216,  216,  215,  215,  177,  216,
132181 /*  1370 */   215,   53,  137,  128,  216,  177,  127,  129,  215,  126,
132182 /*  1380 */    25,   13,  162,   26,    6,  161,  165,  165,  178,  153,
132183 /*  1390 */   153,  151,  151,  151,  151,  224,    4,    3,   22,  142,
132184 /*  1400 */    15,   94,   16,  178,  165,  205,   23,  202,  204,  203,
132185 /*  1410 */   201,   23,  120,  131,  111,   20,  226,  123,  125,   16,
132186 /*  1420 */     1,  123,  131,  229,  229,  111,   37,   37,   56,   64,
132187 /*  1430 */   122,    1,    5,   22,  107,  140,   80,   87,   26,   80,
132188 /*  1440 */   107,   72,   24,   20,   19,  105,   22,  112,   22,   79,
132189 /*  1450 */    22,   58,   23,   22,   79,   22,  249,  249,  246,   79,
132190 /*  1460 */    23,   23,   23,  116,   68,   22,   26,   23,   22,   56,
132191 /*  1470 */   122,   23,   23,   64,   22,  124,   26,   26,   64,   64,
132192 /*  1480 */    23,   23,   23,   23,   11,   23,   22,   26,   23,   22,
132193 /*  1490 */    24,    1,   23,   22,   26,  122,   24,   23,   22,  122,
132194 /*  1500 */    23,   23,   22,  122,  122,   23,   15,
132195};
132196#define YY_SHIFT_USE_DFLT (-95)
132197#define YY_SHIFT_COUNT (442)
132198#define YY_SHIFT_MIN   (-94)
132199#define YY_SHIFT_MAX   (1491)
132200static const short yy_shift_ofst[] = {
132201 /*     0 */    40,  564,  869,  577,  725,  725,  725,  725,  690,  -19,
132202 /*    10 */    16,   16,  100,  725,  725,  725,  725,  725,  725,  725,
132203 /*    20 */   841,  841,  538,  507,  684,  565,   61,  137,  172,  207,
132204 /*    30 */   242,  277,  312,  347,  382,  424,  424,  424,  424,  424,
132205 /*    40 */   424,  424,  424,  424,  424,  424,  424,  424,  424,  424,
132206 /*    50 */   459,  424,  494,  529,  529,  670,  725,  725,  725,  725,
132207 /*    60 */   725,  725,  725,  725,  725,  725,  725,  725,  725,  725,
132208 /*    70 */   725,  725,  725,  725,  725,  725,  725,  725,  725,  725,
132209 /*    80 */   725,  725,  725,  725,  821,  725,  725,  725,  725,  725,
132210 /*    90 */   725,  725,  725,  725,  725,  725,  725,  725,  952,  711,
132211 /*   100 */   711,  711,  711,  711,  766,   23,   32,  924,  637,  825,
132212 /*   110 */   837,  837,  924,   73,  183,  -51,  -95,  -95,  -95,  501,
132213 /*   120 */   501,  501,  903,  903,  632,  205,  241,  924,  924,  924,
132214 /*   130 */   924,  924,  924,  924,  924,  924,  924,  924,  924,  924,
132215 /*   140 */   924,  924,  924,  924,  924,  924,  924,  192, 1027, 1106,
132216 /*   150 */  1106,  183,  176,  176,  176,  176,  176,  176,  -95,  -95,
132217 /*   160 */   -95,  880,  -94,  -94,  578,  734,   99,  730,  769,  349,
132218 /*   170 */   924,  924,  924,  924,  924,  924,  924,  924,  924,  924,
132219 /*   180 */   924,  924,  924,  924,  924,  924,  924,  954,  954,  954,
132220 /*   190 */   924,  924,  622,  924,  924,  924,  -18,  924,  924,  914,
132221 /*   200 */   924,  924,  924,  924,  924,  924,  924,  924,  924,  924,
132222 /*   210 */   441, 1020, 1107, 1107, 1107,  569,   45,  217,  510,  423,
132223 /*   220 */   834,  834, 1156,  423, 1156, 1144, 1187,  359, 1051,  834,
132224 /*   230 */   -17, 1051, 1051, 1099,  469, 1192, 1229, 1176, 1176, 1233,
132225 /*   240 */  1233, 1176, 1277, 1285, 1183, 1296, 1296, 1296, 1296, 1176,
132226 /*   250 */  1297, 1183, 1277, 1285, 1285, 1183, 1176, 1297, 1182, 1250,
132227 /*   260 */  1176, 1176, 1297, 1311, 1176, 1297, 1176, 1297, 1311, 1234,
132228 /*   270 */  1234, 1234, 1267, 1311, 1234, 1244, 1234, 1267, 1234, 1234,
132229 /*   280 */  1232, 1247, 1232, 1247, 1232, 1247, 1232, 1247, 1176, 1334,
132230 /*   290 */  1176, 1235, 1311, 1318, 1318, 1311, 1248, 1253, 1245, 1249,
132231 /*   300 */  1183, 1355, 1357, 1368, 1368, 1378, 1378, 1378, 1378,  -95,
132232 /*   310 */   -95,  -95,  -95,  -95,  -95,  -95,  -95,  451,  936,  816,
132233 /*   320 */   888, 1069,  799, 1111, 1197, 1193, 1201, 1202, 1203, 1213,
132234 /*   330 */  1134, 1117, 1230,  497, 1218, 1219, 1154, 1223, 1115, 1120,
132235 /*   340 */  1231, 1164, 1160, 1392, 1394, 1376, 1257, 1385, 1307, 1386,
132236 /*   350 */  1383, 1388, 1292, 1282, 1303, 1294, 1395, 1293, 1403, 1419,
132237 /*   360 */  1298, 1291, 1389, 1390, 1314, 1372, 1365, 1308, 1430, 1427,
132238 /*   370 */  1411, 1327, 1295, 1356, 1412, 1359, 1350, 1369, 1333, 1418,
132239 /*   380 */  1423, 1425, 1335, 1340, 1424, 1370, 1426, 1428, 1429, 1431,
132240 /*   390 */  1375, 1393, 1433, 1380, 1396, 1437, 1438, 1439, 1347, 1443,
132241 /*   400 */  1444, 1446, 1440, 1348, 1448, 1449, 1413, 1409, 1452, 1351,
132242 /*   410 */  1450, 1414, 1451, 1415, 1457, 1450, 1458, 1459, 1460, 1461,
132243 /*   420 */  1462, 1464, 1473, 1465, 1467, 1466, 1468, 1469, 1471, 1472,
132244 /*   430 */  1468, 1474, 1476, 1477, 1478, 1480, 1373, 1377, 1381, 1382,
132245 /*   440 */  1482, 1491, 1490,
132246};
132247#define YY_REDUCE_USE_DFLT (-130)
132248#define YY_REDUCE_COUNT (316)
132249#define YY_REDUCE_MIN   (-129)
132250#define YY_REDUCE_MAX   (1243)
132251static const short yy_reduce_ofst[] = {
132252 /*     0 */   -29,  531,  490,  570,  -49,  272,  456,  498,  633,  400,
132253 /*    10 */   612,  626,  113,  482,  678,  719,  384,  726,  748,  791,
132254 /*    20 */   419,  693,  761,  812,  819,  625,   76,   76,   76,   76,
132255 /*    30 */    76,   76,   76,   76,   76,   76,   76,   76,   76,   76,
132256 /*    40 */    76,   76,   76,   76,   76,   76,   76,   76,   76,   76,
132257 /*    50 */    76,   76,   76,   76,   76,  793,  795,  856,  871,  875,
132258 /*    60 */   878,  881,  885,  887,  889,  894,  897,  900,  916,  919,
132259 /*    70 */   922,  926,  928,  930,  932,  934,  938,  941,  944,  956,
132260 /*    80 */   963,  966,  968,  970,  972,  974,  978,  980,  982,  996,
132261 /*    90 */  1004, 1006, 1008, 1011, 1013, 1015, 1019, 1022,   76,   76,
132262 /*   100 */    76,   76,   76,   76,   76,   76,   76,  555,  210,  260,
132263 /*   110 */   200,  346,  571,   76,  700,   76,   76,   76,   76,  838,
132264 /*   120 */   838,  838,   42,  182,  251,  160,  160,  550,    5,  455,
132265 /*   130 */   585,  721,  749,  882,  884,  971,  618,  462,  797,  514,
132266 /*   140 */   807,  524,  997, -129,  655,  859,   62,  290,   66, 1030,
132267 /*   150 */  1032,  589, 1009, 1010, 1037, 1038, 1039, 1044,  740,  852,
132268 /*   160 */  1012,  112,  147,  230,  257,  180,  369,  403,  500,  549,
132269 /*   170 */   556,  563,  694,  751,  765,  772,  778,  820,  868,  873,
132270 /*   180 */   890,  929,  935,  985, 1041, 1080, 1091,  540,  593,  661,
132271 /*   190 */  1103, 1104,  842, 1108, 1110, 1112, 1048, 1113, 1114, 1068,
132272 /*   200 */  1116, 1118, 1119,  180, 1121, 1122, 1123, 1124, 1125, 1126,
132273 /*   210 */  1029, 1034, 1059, 1062, 1070,  842, 1082, 1083, 1133, 1084,
132274 /*   220 */  1072, 1073, 1045, 1087, 1050, 1127, 1109, 1128, 1129, 1076,
132275 /*   230 */  1064, 1130, 1131, 1092, 1096, 1140, 1054, 1141, 1142, 1067,
132276 /*   240 */  1071, 1150, 1090, 1132, 1135, 1136, 1137, 1138, 1139, 1157,
132277 /*   250 */  1159, 1143, 1098, 1145, 1146, 1147, 1161, 1165, 1086, 1097,
132278 /*   260 */  1166, 1167, 1169, 1162, 1178, 1180, 1181, 1184, 1168, 1172,
132279 /*   270 */  1173, 1175, 1170, 1174, 1179, 1185, 1186, 1177, 1188, 1189,
132280 /*   280 */  1148, 1151, 1149, 1152, 1153, 1155, 1158, 1163, 1196, 1171,
132281 /*   290 */  1199, 1190, 1191, 1194, 1195, 1198, 1200, 1204, 1206, 1205,
132282 /*   300 */  1209, 1220, 1224, 1236, 1237, 1240, 1241, 1242, 1243, 1207,
132283 /*   310 */  1208, 1212, 1221, 1222, 1210, 1225, 1239,
132284};
132285static const YYACTIONTYPE yy_default[] = {
132286 /*     0 */  1258, 1248, 1248, 1248, 1180, 1180, 1180, 1180, 1248, 1077,
132287 /*    10 */  1106, 1106, 1232, 1309, 1309, 1309, 1309, 1309, 1309, 1179,
132288 /*    20 */  1309, 1309, 1309, 1309, 1248, 1081, 1112, 1309, 1309, 1309,
132289 /*    30 */  1309, 1309, 1309, 1309, 1309, 1231, 1233, 1120, 1119, 1214,
132290 /*    40 */  1093, 1117, 1110, 1114, 1181, 1175, 1176, 1174, 1178, 1182,
132291 /*    50 */  1309, 1113, 1144, 1159, 1143, 1309, 1309, 1309, 1309, 1309,
132292 /*    60 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132293 /*    70 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132294 /*    80 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132295 /*    90 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1153, 1158,
132296 /*   100 */  1165, 1157, 1154, 1146, 1145, 1147, 1148, 1309, 1000, 1048,
132297 /*   110 */  1309, 1309, 1309, 1149, 1309, 1150, 1162, 1161, 1160, 1239,
132298 /*   120 */  1266, 1265, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132299 /*   130 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132300 /*   140 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1258, 1248, 1006,
132301 /*   150 */  1006, 1309, 1248, 1248, 1248, 1248, 1248, 1248, 1244, 1081,
132302 /*   160 */  1072, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132303 /*   170 */  1309, 1236, 1234, 1309, 1195, 1309, 1309, 1309, 1309, 1309,
132304 /*   180 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132305 /*   190 */  1309, 1309, 1309, 1309, 1309, 1309, 1077, 1309, 1309, 1309,
132306 /*   200 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1260,
132307 /*   210 */  1309, 1209, 1077, 1077, 1077, 1079, 1061, 1071,  985, 1116,
132308 /*   220 */  1095, 1095, 1298, 1116, 1298, 1023, 1280, 1020, 1106, 1095,
132309 /*   230 */  1177, 1106, 1106, 1078, 1071, 1309, 1301, 1086, 1086, 1300,
132310 /*   240 */  1300, 1086, 1125, 1051, 1116, 1057, 1057, 1057, 1057, 1086,
132311 /*   250 */   997, 1116, 1125, 1051, 1051, 1116, 1086,  997, 1213, 1295,
132312 /*   260 */  1086, 1086,  997, 1188, 1086,  997, 1086,  997, 1188, 1049,
132313 /*   270 */  1049, 1049, 1038, 1188, 1049, 1023, 1049, 1038, 1049, 1049,
132314 /*   280 */  1099, 1094, 1099, 1094, 1099, 1094, 1099, 1094, 1086, 1183,
132315 /*   290 */  1086, 1309, 1188, 1192, 1192, 1188, 1111, 1100, 1109, 1107,
132316 /*   300 */  1116, 1003, 1041, 1263, 1263, 1259, 1259, 1259, 1259, 1306,
132317 /*   310 */  1306, 1244, 1275, 1275, 1025, 1025, 1275, 1309, 1309, 1309,
132318 /*   320 */  1309, 1309, 1309, 1270, 1309, 1197, 1309, 1309, 1309, 1309,
132319 /*   330 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132320 /*   340 */  1309, 1309, 1131, 1309,  981, 1241, 1309, 1309, 1240, 1309,
132321 /*   350 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132322 /*   360 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1297, 1309, 1309,
132323 /*   370 */  1309, 1309, 1309, 1309, 1212, 1211, 1309, 1309, 1309, 1309,
132324 /*   380 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132325 /*   390 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1063, 1309,
132326 /*   400 */  1309, 1309, 1284, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132327 /*   410 */  1108, 1309, 1101, 1309, 1309, 1288, 1309, 1309, 1309, 1309,
132328 /*   420 */  1309, 1309, 1309, 1309, 1309, 1309, 1250, 1309, 1309, 1309,
132329 /*   430 */  1249, 1309, 1309, 1309, 1309, 1309, 1133, 1309, 1132, 1136,
132330 /*   440 */  1309,  991, 1309,
132331};
132332/********** End of lemon-generated parsing tables *****************************/
132333
132334/* The next table maps tokens (terminal symbols) into fallback tokens.
132335** If a construct like the following:
132336**
132337**      %fallback ID X Y Z.
132338**
132339** appears in the grammar, then ID becomes a fallback token for X, Y,
132340** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
132341** but it does not parse, the type of the token is changed to ID and
132342** the parse is retried before an error is thrown.
132343**
132344** This feature can be used, for example, to cause some keywords in a language
132345** to revert to identifiers if they keyword does not apply in the context where
132346** it appears.
132347*/
132348#ifdef YYFALLBACK
132349static const YYCODETYPE yyFallback[] = {
132350    0,  /*          $ => nothing */
132351    0,  /*       SEMI => nothing */
132352   55,  /*    EXPLAIN => ID */
132353   55,  /*      QUERY => ID */
132354   55,  /*       PLAN => ID */
132355   55,  /*      BEGIN => ID */
132356    0,  /* TRANSACTION => nothing */
132357   55,  /*   DEFERRED => ID */
132358   55,  /*  IMMEDIATE => ID */
132359   55,  /*  EXCLUSIVE => ID */
132360    0,  /*     COMMIT => nothing */
132361   55,  /*        END => ID */
132362   55,  /*   ROLLBACK => ID */
132363   55,  /*  SAVEPOINT => ID */
132364   55,  /*    RELEASE => ID */
132365    0,  /*         TO => nothing */
132366    0,  /*      TABLE => nothing */
132367    0,  /*     CREATE => nothing */
132368   55,  /*         IF => ID */
132369    0,  /*        NOT => nothing */
132370    0,  /*     EXISTS => nothing */
132371   55,  /*       TEMP => ID */
132372    0,  /*         LP => nothing */
132373    0,  /*         RP => nothing */
132374    0,  /*         AS => nothing */
132375   55,  /*    WITHOUT => ID */
132376    0,  /*      COMMA => nothing */
132377    0,  /*         OR => nothing */
132378    0,  /*        AND => nothing */
132379    0,  /*         IS => nothing */
132380   55,  /*      MATCH => ID */
132381   55,  /*    LIKE_KW => ID */
132382    0,  /*    BETWEEN => nothing */
132383    0,  /*         IN => nothing */
132384    0,  /*     ISNULL => nothing */
132385    0,  /*    NOTNULL => nothing */
132386    0,  /*         NE => nothing */
132387    0,  /*         EQ => nothing */
132388    0,  /*         GT => nothing */
132389    0,  /*         LE => nothing */
132390    0,  /*         LT => nothing */
132391    0,  /*         GE => nothing */
132392    0,  /*     ESCAPE => nothing */
132393    0,  /*     BITAND => nothing */
132394    0,  /*      BITOR => nothing */
132395    0,  /*     LSHIFT => nothing */
132396    0,  /*     RSHIFT => nothing */
132397    0,  /*       PLUS => nothing */
132398    0,  /*      MINUS => nothing */
132399    0,  /*       STAR => nothing */
132400    0,  /*      SLASH => nothing */
132401    0,  /*        REM => nothing */
132402    0,  /*     CONCAT => nothing */
132403    0,  /*    COLLATE => nothing */
132404    0,  /*     BITNOT => nothing */
132405    0,  /*         ID => nothing */
132406    0,  /*    INDEXED => nothing */
132407   55,  /*      ABORT => ID */
132408   55,  /*     ACTION => ID */
132409   55,  /*      AFTER => ID */
132410   55,  /*    ANALYZE => ID */
132411   55,  /*        ASC => ID */
132412   55,  /*     ATTACH => ID */
132413   55,  /*     BEFORE => ID */
132414   55,  /*         BY => ID */
132415   55,  /*    CASCADE => ID */
132416   55,  /*       CAST => ID */
132417   55,  /*   COLUMNKW => ID */
132418   55,  /*   CONFLICT => ID */
132419   55,  /*   DATABASE => ID */
132420   55,  /*       DESC => ID */
132421   55,  /*     DETACH => ID */
132422   55,  /*       EACH => ID */
132423   55,  /*       FAIL => ID */
132424   55,  /*        FOR => ID */
132425   55,  /*     IGNORE => ID */
132426   55,  /*  INITIALLY => ID */
132427   55,  /*    INSTEAD => ID */
132428   55,  /*         NO => ID */
132429   55,  /*        KEY => ID */
132430   55,  /*         OF => ID */
132431   55,  /*     OFFSET => ID */
132432   55,  /*     PRAGMA => ID */
132433   55,  /*      RAISE => ID */
132434   55,  /*  RECURSIVE => ID */
132435   55,  /*    REPLACE => ID */
132436   55,  /*   RESTRICT => ID */
132437   55,  /*        ROW => ID */
132438   55,  /*    TRIGGER => ID */
132439   55,  /*     VACUUM => ID */
132440   55,  /*       VIEW => ID */
132441   55,  /*    VIRTUAL => ID */
132442   55,  /*       WITH => ID */
132443   55,  /*    REINDEX => ID */
132444   55,  /*     RENAME => ID */
132445   55,  /*   CTIME_KW => ID */
132446};
132447#endif /* YYFALLBACK */
132448
132449/* The following structure represents a single element of the
132450** parser's stack.  Information stored includes:
132451**
132452**   +  The state number for the parser at this level of the stack.
132453**
132454**   +  The value of the token stored at this level of the stack.
132455**      (In other words, the "major" token.)
132456**
132457**   +  The semantic value stored at this level of the stack.  This is
132458**      the information used by the action routines in the grammar.
132459**      It is sometimes called the "minor" token.
132460**
132461** After the "shift" half of a SHIFTREDUCE action, the stateno field
132462** actually contains the reduce action for the second half of the
132463** SHIFTREDUCE.
132464*/
132465struct yyStackEntry {
132466  YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
132467  YYCODETYPE major;      /* The major token value.  This is the code
132468                         ** number for the token at this stack level */
132469  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
132470                         ** is the value of the token  */
132471};
132472typedef struct yyStackEntry yyStackEntry;
132473
132474/* The state of the parser is completely contained in an instance of
132475** the following structure */
132476struct yyParser {
132477  yyStackEntry *yytos;          /* Pointer to top element of the stack */
132478#ifdef YYTRACKMAXSTACKDEPTH
132479  int yyhwm;                    /* High-water mark of the stack */
132480#endif
132481#ifndef YYNOERRORRECOVERY
132482  int yyerrcnt;                 /* Shifts left before out of the error */
132483#endif
132484  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
132485#if YYSTACKDEPTH<=0
132486  int yystksz;                  /* Current side of the stack */
132487  yyStackEntry *yystack;        /* The parser's stack */
132488  yyStackEntry yystk0;          /* First stack entry */
132489#else
132490  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
132491#endif
132492};
132493typedef struct yyParser yyParser;
132494
132495#ifndef NDEBUG
132496/* #include <stdio.h> */
132497static FILE *yyTraceFILE = 0;
132498static char *yyTracePrompt = 0;
132499#endif /* NDEBUG */
132500
132501#ifndef NDEBUG
132502/*
132503** Turn parser tracing on by giving a stream to which to write the trace
132504** and a prompt to preface each trace message.  Tracing is turned off
132505** by making either argument NULL
132506**
132507** Inputs:
132508** <ul>
132509** <li> A FILE* to which trace output should be written.
132510**      If NULL, then tracing is turned off.
132511** <li> A prefix string written at the beginning of every
132512**      line of trace output.  If NULL, then tracing is
132513**      turned off.
132514** </ul>
132515**
132516** Outputs:
132517** None.
132518*/
132519SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
132520  yyTraceFILE = TraceFILE;
132521  yyTracePrompt = zTracePrompt;
132522  if( yyTraceFILE==0 ) yyTracePrompt = 0;
132523  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
132524}
132525#endif /* NDEBUG */
132526
132527#ifndef NDEBUG
132528/* For tracing shifts, the names of all terminals and nonterminals
132529** are required.  The following table supplies these names */
132530static const char *const yyTokenName[] = {
132531  "$",             "SEMI",          "EXPLAIN",       "QUERY",
132532  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
132533  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
132534  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
132535  "TABLE",         "CREATE",        "IF",            "NOT",
132536  "EXISTS",        "TEMP",          "LP",            "RP",
132537  "AS",            "WITHOUT",       "COMMA",         "OR",
132538  "AND",           "IS",            "MATCH",         "LIKE_KW",
132539  "BETWEEN",       "IN",            "ISNULL",        "NOTNULL",
132540  "NE",            "EQ",            "GT",            "LE",
132541  "LT",            "GE",            "ESCAPE",        "BITAND",
132542  "BITOR",         "LSHIFT",        "RSHIFT",        "PLUS",
132543  "MINUS",         "STAR",          "SLASH",         "REM",
132544  "CONCAT",        "COLLATE",       "BITNOT",        "ID",
132545  "INDEXED",       "ABORT",         "ACTION",        "AFTER",
132546  "ANALYZE",       "ASC",           "ATTACH",        "BEFORE",
132547  "BY",            "CASCADE",       "CAST",          "COLUMNKW",
132548  "CONFLICT",      "DATABASE",      "DESC",          "DETACH",
132549  "EACH",          "FAIL",          "FOR",           "IGNORE",
132550  "INITIALLY",     "INSTEAD",       "NO",            "KEY",
132551  "OF",            "OFFSET",        "PRAGMA",        "RAISE",
132552  "RECURSIVE",     "REPLACE",       "RESTRICT",      "ROW",
132553  "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
132554  "WITH",          "REINDEX",       "RENAME",        "CTIME_KW",
132555  "ANY",           "STRING",        "JOIN_KW",       "CONSTRAINT",
132556  "DEFAULT",       "NULL",          "PRIMARY",       "UNIQUE",
132557  "CHECK",         "REFERENCES",    "AUTOINCR",      "ON",
132558  "INSERT",        "DELETE",        "UPDATE",        "SET",
132559  "DEFERRABLE",    "FOREIGN",       "DROP",          "UNION",
132560  "ALL",           "EXCEPT",        "INTERSECT",     "SELECT",
132561  "VALUES",        "DISTINCT",      "DOT",           "FROM",
132562  "JOIN",          "USING",         "ORDER",         "GROUP",
132563  "HAVING",        "LIMIT",         "WHERE",         "INTO",
132564  "INTEGER",       "FLOAT",         "BLOB",          "VARIABLE",
132565  "CASE",          "WHEN",          "THEN",          "ELSE",
132566  "INDEX",         "ALTER",         "ADD",           "error",
132567  "input",         "cmdlist",       "ecmd",          "explain",
132568  "cmdx",          "cmd",           "transtype",     "trans_opt",
132569  "nm",            "savepoint_opt",  "create_table",  "create_table_args",
132570  "createkw",      "temp",          "ifnotexists",   "dbnm",
132571  "columnlist",    "conslist_opt",  "table_options",  "select",
132572  "columnname",    "carglist",      "typetoken",     "typename",
132573  "signed",        "plus_num",      "minus_num",     "ccons",
132574  "term",          "expr",          "onconf",        "sortorder",
132575  "autoinc",       "eidlist_opt",   "refargs",       "defer_subclause",
132576  "refarg",        "refact",        "init_deferred_pred_opt",  "conslist",
132577  "tconscomma",    "tcons",         "sortlist",      "eidlist",
132578  "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
132579  "ifexists",      "fullname",      "selectnowith",  "oneselect",
132580  "with",          "multiselect_op",  "distinct",      "selcollist",
132581  "from",          "where_opt",     "groupby_opt",   "having_opt",
132582  "orderby_opt",   "limit_opt",     "values",        "nexprlist",
132583  "exprlist",      "sclp",          "as",            "seltablist",
132584  "stl_prefix",    "joinop",        "indexed_opt",   "on_opt",
132585  "using_opt",     "idlist",        "setlist",       "insert_cmd",
132586  "idlist_opt",    "likeop",        "between_op",    "in_op",
132587  "paren_exprlist",  "case_operand",  "case_exprlist",  "case_else",
132588  "uniqueflag",    "collate",       "nmnum",         "trigger_decl",
132589  "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
132590  "when_clause",   "trigger_cmd",   "trnm",          "tridxby",
132591  "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
132592  "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
132593  "lp",            "anylist",       "wqlist",
132594};
132595#endif /* NDEBUG */
132596
132597#ifndef NDEBUG
132598/* For tracing reduce actions, the names of all rules are required.
132599*/
132600static const char *const yyRuleName[] = {
132601 /*   0 */ "explain ::= EXPLAIN",
132602 /*   1 */ "explain ::= EXPLAIN QUERY PLAN",
132603 /*   2 */ "cmdx ::= cmd",
132604 /*   3 */ "cmd ::= BEGIN transtype trans_opt",
132605 /*   4 */ "transtype ::=",
132606 /*   5 */ "transtype ::= DEFERRED",
132607 /*   6 */ "transtype ::= IMMEDIATE",
132608 /*   7 */ "transtype ::= EXCLUSIVE",
132609 /*   8 */ "cmd ::= COMMIT trans_opt",
132610 /*   9 */ "cmd ::= END trans_opt",
132611 /*  10 */ "cmd ::= ROLLBACK trans_opt",
132612 /*  11 */ "cmd ::= SAVEPOINT nm",
132613 /*  12 */ "cmd ::= RELEASE savepoint_opt nm",
132614 /*  13 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
132615 /*  14 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
132616 /*  15 */ "createkw ::= CREATE",
132617 /*  16 */ "ifnotexists ::=",
132618 /*  17 */ "ifnotexists ::= IF NOT EXISTS",
132619 /*  18 */ "temp ::= TEMP",
132620 /*  19 */ "temp ::=",
132621 /*  20 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
132622 /*  21 */ "create_table_args ::= AS select",
132623 /*  22 */ "table_options ::=",
132624 /*  23 */ "table_options ::= WITHOUT nm",
132625 /*  24 */ "columnname ::= nm typetoken",
132626 /*  25 */ "typetoken ::=",
132627 /*  26 */ "typetoken ::= typename LP signed RP",
132628 /*  27 */ "typetoken ::= typename LP signed COMMA signed RP",
132629 /*  28 */ "typename ::= typename ID|STRING",
132630 /*  29 */ "ccons ::= CONSTRAINT nm",
132631 /*  30 */ "ccons ::= DEFAULT term",
132632 /*  31 */ "ccons ::= DEFAULT LP expr RP",
132633 /*  32 */ "ccons ::= DEFAULT PLUS term",
132634 /*  33 */ "ccons ::= DEFAULT MINUS term",
132635 /*  34 */ "ccons ::= DEFAULT ID|INDEXED",
132636 /*  35 */ "ccons ::= NOT NULL onconf",
132637 /*  36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
132638 /*  37 */ "ccons ::= UNIQUE onconf",
132639 /*  38 */ "ccons ::= CHECK LP expr RP",
132640 /*  39 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
132641 /*  40 */ "ccons ::= defer_subclause",
132642 /*  41 */ "ccons ::= COLLATE ID|STRING",
132643 /*  42 */ "autoinc ::=",
132644 /*  43 */ "autoinc ::= AUTOINCR",
132645 /*  44 */ "refargs ::=",
132646 /*  45 */ "refargs ::= refargs refarg",
132647 /*  46 */ "refarg ::= MATCH nm",
132648 /*  47 */ "refarg ::= ON INSERT refact",
132649 /*  48 */ "refarg ::= ON DELETE refact",
132650 /*  49 */ "refarg ::= ON UPDATE refact",
132651 /*  50 */ "refact ::= SET NULL",
132652 /*  51 */ "refact ::= SET DEFAULT",
132653 /*  52 */ "refact ::= CASCADE",
132654 /*  53 */ "refact ::= RESTRICT",
132655 /*  54 */ "refact ::= NO ACTION",
132656 /*  55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
132657 /*  56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
132658 /*  57 */ "init_deferred_pred_opt ::=",
132659 /*  58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
132660 /*  59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
132661 /*  60 */ "conslist_opt ::=",
132662 /*  61 */ "tconscomma ::= COMMA",
132663 /*  62 */ "tcons ::= CONSTRAINT nm",
132664 /*  63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
132665 /*  64 */ "tcons ::= UNIQUE LP sortlist RP onconf",
132666 /*  65 */ "tcons ::= CHECK LP expr RP onconf",
132667 /*  66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
132668 /*  67 */ "defer_subclause_opt ::=",
132669 /*  68 */ "onconf ::=",
132670 /*  69 */ "onconf ::= ON CONFLICT resolvetype",
132671 /*  70 */ "orconf ::=",
132672 /*  71 */ "orconf ::= OR resolvetype",
132673 /*  72 */ "resolvetype ::= IGNORE",
132674 /*  73 */ "resolvetype ::= REPLACE",
132675 /*  74 */ "cmd ::= DROP TABLE ifexists fullname",
132676 /*  75 */ "ifexists ::= IF EXISTS",
132677 /*  76 */ "ifexists ::=",
132678 /*  77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
132679 /*  78 */ "cmd ::= DROP VIEW ifexists fullname",
132680 /*  79 */ "cmd ::= select",
132681 /*  80 */ "select ::= with selectnowith",
132682 /*  81 */ "selectnowith ::= selectnowith multiselect_op oneselect",
132683 /*  82 */ "multiselect_op ::= UNION",
132684 /*  83 */ "multiselect_op ::= UNION ALL",
132685 /*  84 */ "multiselect_op ::= EXCEPT|INTERSECT",
132686 /*  85 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
132687 /*  86 */ "values ::= VALUES LP nexprlist RP",
132688 /*  87 */ "values ::= values COMMA LP exprlist RP",
132689 /*  88 */ "distinct ::= DISTINCT",
132690 /*  89 */ "distinct ::= ALL",
132691 /*  90 */ "distinct ::=",
132692 /*  91 */ "sclp ::=",
132693 /*  92 */ "selcollist ::= sclp expr as",
132694 /*  93 */ "selcollist ::= sclp STAR",
132695 /*  94 */ "selcollist ::= sclp nm DOT STAR",
132696 /*  95 */ "as ::= AS nm",
132697 /*  96 */ "as ::=",
132698 /*  97 */ "from ::=",
132699 /*  98 */ "from ::= FROM seltablist",
132700 /*  99 */ "stl_prefix ::= seltablist joinop",
132701 /* 100 */ "stl_prefix ::=",
132702 /* 101 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
132703 /* 102 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
132704 /* 103 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
132705 /* 104 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
132706 /* 105 */ "dbnm ::=",
132707 /* 106 */ "dbnm ::= DOT nm",
132708 /* 107 */ "fullname ::= nm dbnm",
132709 /* 108 */ "joinop ::= COMMA|JOIN",
132710 /* 109 */ "joinop ::= JOIN_KW JOIN",
132711 /* 110 */ "joinop ::= JOIN_KW nm JOIN",
132712 /* 111 */ "joinop ::= JOIN_KW nm nm JOIN",
132713 /* 112 */ "on_opt ::= ON expr",
132714 /* 113 */ "on_opt ::=",
132715 /* 114 */ "indexed_opt ::=",
132716 /* 115 */ "indexed_opt ::= INDEXED BY nm",
132717 /* 116 */ "indexed_opt ::= NOT INDEXED",
132718 /* 117 */ "using_opt ::= USING LP idlist RP",
132719 /* 118 */ "using_opt ::=",
132720 /* 119 */ "orderby_opt ::=",
132721 /* 120 */ "orderby_opt ::= ORDER BY sortlist",
132722 /* 121 */ "sortlist ::= sortlist COMMA expr sortorder",
132723 /* 122 */ "sortlist ::= expr sortorder",
132724 /* 123 */ "sortorder ::= ASC",
132725 /* 124 */ "sortorder ::= DESC",
132726 /* 125 */ "sortorder ::=",
132727 /* 126 */ "groupby_opt ::=",
132728 /* 127 */ "groupby_opt ::= GROUP BY nexprlist",
132729 /* 128 */ "having_opt ::=",
132730 /* 129 */ "having_opt ::= HAVING expr",
132731 /* 130 */ "limit_opt ::=",
132732 /* 131 */ "limit_opt ::= LIMIT expr",
132733 /* 132 */ "limit_opt ::= LIMIT expr OFFSET expr",
132734 /* 133 */ "limit_opt ::= LIMIT expr COMMA expr",
132735 /* 134 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
132736 /* 135 */ "where_opt ::=",
132737 /* 136 */ "where_opt ::= WHERE expr",
132738 /* 137 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
132739 /* 138 */ "setlist ::= setlist COMMA nm EQ expr",
132740 /* 139 */ "setlist ::= nm EQ expr",
132741 /* 140 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
132742 /* 141 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
132743 /* 142 */ "insert_cmd ::= INSERT orconf",
132744 /* 143 */ "insert_cmd ::= REPLACE",
132745 /* 144 */ "idlist_opt ::=",
132746 /* 145 */ "idlist_opt ::= LP idlist RP",
132747 /* 146 */ "idlist ::= idlist COMMA nm",
132748 /* 147 */ "idlist ::= nm",
132749 /* 148 */ "expr ::= LP expr RP",
132750 /* 149 */ "term ::= NULL",
132751 /* 150 */ "expr ::= ID|INDEXED",
132752 /* 151 */ "expr ::= JOIN_KW",
132753 /* 152 */ "expr ::= nm DOT nm",
132754 /* 153 */ "expr ::= nm DOT nm DOT nm",
132755 /* 154 */ "term ::= INTEGER|FLOAT|BLOB",
132756 /* 155 */ "term ::= STRING",
132757 /* 156 */ "expr ::= VARIABLE",
132758 /* 157 */ "expr ::= expr COLLATE ID|STRING",
132759 /* 158 */ "expr ::= CAST LP expr AS typetoken RP",
132760 /* 159 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
132761 /* 160 */ "expr ::= ID|INDEXED LP STAR RP",
132762 /* 161 */ "term ::= CTIME_KW",
132763 /* 162 */ "expr ::= expr AND expr",
132764 /* 163 */ "expr ::= expr OR expr",
132765 /* 164 */ "expr ::= expr LT|GT|GE|LE expr",
132766 /* 165 */ "expr ::= expr EQ|NE expr",
132767 /* 166 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
132768 /* 167 */ "expr ::= expr PLUS|MINUS expr",
132769 /* 168 */ "expr ::= expr STAR|SLASH|REM expr",
132770 /* 169 */ "expr ::= expr CONCAT expr",
132771 /* 170 */ "likeop ::= LIKE_KW|MATCH",
132772 /* 171 */ "likeop ::= NOT LIKE_KW|MATCH",
132773 /* 172 */ "expr ::= expr likeop expr",
132774 /* 173 */ "expr ::= expr likeop expr ESCAPE expr",
132775 /* 174 */ "expr ::= expr ISNULL|NOTNULL",
132776 /* 175 */ "expr ::= expr NOT NULL",
132777 /* 176 */ "expr ::= expr IS expr",
132778 /* 177 */ "expr ::= expr IS NOT expr",
132779 /* 178 */ "expr ::= NOT expr",
132780 /* 179 */ "expr ::= BITNOT expr",
132781 /* 180 */ "expr ::= MINUS expr",
132782 /* 181 */ "expr ::= PLUS expr",
132783 /* 182 */ "between_op ::= BETWEEN",
132784 /* 183 */ "between_op ::= NOT BETWEEN",
132785 /* 184 */ "expr ::= expr between_op expr AND expr",
132786 /* 185 */ "in_op ::= IN",
132787 /* 186 */ "in_op ::= NOT IN",
132788 /* 187 */ "expr ::= expr in_op LP exprlist RP",
132789 /* 188 */ "expr ::= LP select RP",
132790 /* 189 */ "expr ::= expr in_op LP select RP",
132791 /* 190 */ "expr ::= expr in_op nm dbnm paren_exprlist",
132792 /* 191 */ "expr ::= EXISTS LP select RP",
132793 /* 192 */ "expr ::= CASE case_operand case_exprlist case_else END",
132794 /* 193 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
132795 /* 194 */ "case_exprlist ::= WHEN expr THEN expr",
132796 /* 195 */ "case_else ::= ELSE expr",
132797 /* 196 */ "case_else ::=",
132798 /* 197 */ "case_operand ::= expr",
132799 /* 198 */ "case_operand ::=",
132800 /* 199 */ "exprlist ::=",
132801 /* 200 */ "nexprlist ::= nexprlist COMMA expr",
132802 /* 201 */ "nexprlist ::= expr",
132803 /* 202 */ "paren_exprlist ::=",
132804 /* 203 */ "paren_exprlist ::= LP exprlist RP",
132805 /* 204 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
132806 /* 205 */ "uniqueflag ::= UNIQUE",
132807 /* 206 */ "uniqueflag ::=",
132808 /* 207 */ "eidlist_opt ::=",
132809 /* 208 */ "eidlist_opt ::= LP eidlist RP",
132810 /* 209 */ "eidlist ::= eidlist COMMA nm collate sortorder",
132811 /* 210 */ "eidlist ::= nm collate sortorder",
132812 /* 211 */ "collate ::=",
132813 /* 212 */ "collate ::= COLLATE ID|STRING",
132814 /* 213 */ "cmd ::= DROP INDEX ifexists fullname",
132815 /* 214 */ "cmd ::= VACUUM",
132816 /* 215 */ "cmd ::= VACUUM nm",
132817 /* 216 */ "cmd ::= PRAGMA nm dbnm",
132818 /* 217 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
132819 /* 218 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
132820 /* 219 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
132821 /* 220 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
132822 /* 221 */ "plus_num ::= PLUS INTEGER|FLOAT",
132823 /* 222 */ "minus_num ::= MINUS INTEGER|FLOAT",
132824 /* 223 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
132825 /* 224 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
132826 /* 225 */ "trigger_time ::= BEFORE",
132827 /* 226 */ "trigger_time ::= AFTER",
132828 /* 227 */ "trigger_time ::= INSTEAD OF",
132829 /* 228 */ "trigger_time ::=",
132830 /* 229 */ "trigger_event ::= DELETE|INSERT",
132831 /* 230 */ "trigger_event ::= UPDATE",
132832 /* 231 */ "trigger_event ::= UPDATE OF idlist",
132833 /* 232 */ "when_clause ::=",
132834 /* 233 */ "when_clause ::= WHEN expr",
132835 /* 234 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
132836 /* 235 */ "trigger_cmd_list ::= trigger_cmd SEMI",
132837 /* 236 */ "trnm ::= nm DOT nm",
132838 /* 237 */ "tridxby ::= INDEXED BY nm",
132839 /* 238 */ "tridxby ::= NOT INDEXED",
132840 /* 239 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
132841 /* 240 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
132842 /* 241 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
132843 /* 242 */ "trigger_cmd ::= select",
132844 /* 243 */ "expr ::= RAISE LP IGNORE RP",
132845 /* 244 */ "expr ::= RAISE LP raisetype COMMA nm RP",
132846 /* 245 */ "raisetype ::= ROLLBACK",
132847 /* 246 */ "raisetype ::= ABORT",
132848 /* 247 */ "raisetype ::= FAIL",
132849 /* 248 */ "cmd ::= DROP TRIGGER ifexists fullname",
132850 /* 249 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
132851 /* 250 */ "cmd ::= DETACH database_kw_opt expr",
132852 /* 251 */ "key_opt ::=",
132853 /* 252 */ "key_opt ::= KEY expr",
132854 /* 253 */ "cmd ::= REINDEX",
132855 /* 254 */ "cmd ::= REINDEX nm dbnm",
132856 /* 255 */ "cmd ::= ANALYZE",
132857 /* 256 */ "cmd ::= ANALYZE nm dbnm",
132858 /* 257 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
132859 /* 258 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
132860 /* 259 */ "add_column_fullname ::= fullname",
132861 /* 260 */ "cmd ::= create_vtab",
132862 /* 261 */ "cmd ::= create_vtab LP vtabarglist RP",
132863 /* 262 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
132864 /* 263 */ "vtabarg ::=",
132865 /* 264 */ "vtabargtoken ::= ANY",
132866 /* 265 */ "vtabargtoken ::= lp anylist RP",
132867 /* 266 */ "lp ::= LP",
132868 /* 267 */ "with ::=",
132869 /* 268 */ "with ::= WITH wqlist",
132870 /* 269 */ "with ::= WITH RECURSIVE wqlist",
132871 /* 270 */ "wqlist ::= nm eidlist_opt AS LP select RP",
132872 /* 271 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
132873 /* 272 */ "input ::= cmdlist",
132874 /* 273 */ "cmdlist ::= cmdlist ecmd",
132875 /* 274 */ "cmdlist ::= ecmd",
132876 /* 275 */ "ecmd ::= SEMI",
132877 /* 276 */ "ecmd ::= explain cmdx SEMI",
132878 /* 277 */ "explain ::=",
132879 /* 278 */ "trans_opt ::=",
132880 /* 279 */ "trans_opt ::= TRANSACTION",
132881 /* 280 */ "trans_opt ::= TRANSACTION nm",
132882 /* 281 */ "savepoint_opt ::= SAVEPOINT",
132883 /* 282 */ "savepoint_opt ::=",
132884 /* 283 */ "cmd ::= create_table create_table_args",
132885 /* 284 */ "columnlist ::= columnlist COMMA columnname carglist",
132886 /* 285 */ "columnlist ::= columnname carglist",
132887 /* 286 */ "nm ::= ID|INDEXED",
132888 /* 287 */ "nm ::= STRING",
132889 /* 288 */ "nm ::= JOIN_KW",
132890 /* 289 */ "typetoken ::= typename",
132891 /* 290 */ "typename ::= ID|STRING",
132892 /* 291 */ "signed ::= plus_num",
132893 /* 292 */ "signed ::= minus_num",
132894 /* 293 */ "carglist ::= carglist ccons",
132895 /* 294 */ "carglist ::=",
132896 /* 295 */ "ccons ::= NULL onconf",
132897 /* 296 */ "conslist_opt ::= COMMA conslist",
132898 /* 297 */ "conslist ::= conslist tconscomma tcons",
132899 /* 298 */ "conslist ::= tcons",
132900 /* 299 */ "tconscomma ::=",
132901 /* 300 */ "defer_subclause_opt ::= defer_subclause",
132902 /* 301 */ "resolvetype ::= raisetype",
132903 /* 302 */ "selectnowith ::= oneselect",
132904 /* 303 */ "oneselect ::= values",
132905 /* 304 */ "sclp ::= selcollist COMMA",
132906 /* 305 */ "as ::= ID|STRING",
132907 /* 306 */ "expr ::= term",
132908 /* 307 */ "exprlist ::= nexprlist",
132909 /* 308 */ "nmnum ::= plus_num",
132910 /* 309 */ "nmnum ::= nm",
132911 /* 310 */ "nmnum ::= ON",
132912 /* 311 */ "nmnum ::= DELETE",
132913 /* 312 */ "nmnum ::= DEFAULT",
132914 /* 313 */ "plus_num ::= INTEGER|FLOAT",
132915 /* 314 */ "foreach_clause ::=",
132916 /* 315 */ "foreach_clause ::= FOR EACH ROW",
132917 /* 316 */ "trnm ::= nm",
132918 /* 317 */ "tridxby ::=",
132919 /* 318 */ "database_kw_opt ::= DATABASE",
132920 /* 319 */ "database_kw_opt ::=",
132921 /* 320 */ "kwcolumn_opt ::=",
132922 /* 321 */ "kwcolumn_opt ::= COLUMNKW",
132923 /* 322 */ "vtabarglist ::= vtabarg",
132924 /* 323 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
132925 /* 324 */ "vtabarg ::= vtabarg vtabargtoken",
132926 /* 325 */ "anylist ::=",
132927 /* 326 */ "anylist ::= anylist LP anylist RP",
132928 /* 327 */ "anylist ::= anylist ANY",
132929};
132930#endif /* NDEBUG */
132931
132932
132933#if YYSTACKDEPTH<=0
132934/*
132935** Try to increase the size of the parser stack.  Return the number
132936** of errors.  Return 0 on success.
132937*/
132938static int yyGrowStack(yyParser *p){
132939  int newSize;
132940  int idx;
132941  yyStackEntry *pNew;
132942
132943  newSize = p->yystksz*2 + 100;
132944  idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
132945  if( p->yystack==&p->yystk0 ){
132946    pNew = malloc(newSize*sizeof(pNew[0]));
132947    if( pNew ) pNew[0] = p->yystk0;
132948  }else{
132949    pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
132950  }
132951  if( pNew ){
132952    p->yystack = pNew;
132953    p->yytos = &p->yystack[idx];
132954#ifndef NDEBUG
132955    if( yyTraceFILE ){
132956      fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
132957              yyTracePrompt, p->yystksz, newSize);
132958    }
132959#endif
132960    p->yystksz = newSize;
132961  }
132962  return pNew==0;
132963}
132964#endif
132965
132966/* Datatype of the argument to the memory allocated passed as the
132967** second argument to sqlite3ParserAlloc() below.  This can be changed by
132968** putting an appropriate #define in the %include section of the input
132969** grammar.
132970*/
132971#ifndef YYMALLOCARGTYPE
132972# define YYMALLOCARGTYPE size_t
132973#endif
132974
132975/*
132976** This function allocates a new parser.
132977** The only argument is a pointer to a function which works like
132978** malloc.
132979**
132980** Inputs:
132981** A pointer to the function used to allocate memory.
132982**
132983** Outputs:
132984** A pointer to a parser.  This pointer is used in subsequent calls
132985** to sqlite3Parser and sqlite3ParserFree.
132986*/
132987SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){
132988  yyParser *pParser;
132989  pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
132990  if( pParser ){
132991#ifdef YYTRACKMAXSTACKDEPTH
132992    pParser->yyhwm = 0;
132993#endif
132994#if YYSTACKDEPTH<=0
132995    pParser->yytos = NULL;
132996    pParser->yystack = NULL;
132997    pParser->yystksz = 0;
132998    if( yyGrowStack(pParser) ){
132999      pParser->yystack = &pParser->yystk0;
133000      pParser->yystksz = 1;
133001    }
133002#endif
133003#ifndef YYNOERRORRECOVERY
133004    pParser->yyerrcnt = -1;
133005#endif
133006    pParser->yytos = pParser->yystack;
133007    pParser->yystack[0].stateno = 0;
133008    pParser->yystack[0].major = 0;
133009  }
133010  return pParser;
133011}
133012
133013/* The following function deletes the "minor type" or semantic value
133014** associated with a symbol.  The symbol can be either a terminal
133015** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
133016** a pointer to the value to be deleted.  The code used to do the
133017** deletions is derived from the %destructor and/or %token_destructor
133018** directives of the input grammar.
133019*/
133020static void yy_destructor(
133021  yyParser *yypParser,    /* The parser */
133022  YYCODETYPE yymajor,     /* Type code for object to destroy */
133023  YYMINORTYPE *yypminor   /* The object to be destroyed */
133024){
133025  sqlite3ParserARG_FETCH;
133026  switch( yymajor ){
133027    /* Here is inserted the actions which take place when a
133028    ** terminal or non-terminal is destroyed.  This can happen
133029    ** when the symbol is popped from the stack during a
133030    ** reduce or during error processing or when a parser is
133031    ** being destroyed before it is finished parsing.
133032    **
133033    ** Note: during a reduce, the only symbols destroyed are those
133034    ** which appear on the RHS of the rule, but which are *not* used
133035    ** inside the C code.
133036    */
133037/********* Begin destructor definitions ***************************************/
133038    case 163: /* select */
133039    case 194: /* selectnowith */
133040    case 195: /* oneselect */
133041    case 206: /* values */
133042{
133043sqlite3SelectDelete(pParse->db, (yypminor->yy243));
133044}
133045      break;
133046    case 172: /* term */
133047    case 173: /* expr */
133048{
133049sqlite3ExprDelete(pParse->db, (yypminor->yy190).pExpr);
133050}
133051      break;
133052    case 177: /* eidlist_opt */
133053    case 186: /* sortlist */
133054    case 187: /* eidlist */
133055    case 199: /* selcollist */
133056    case 202: /* groupby_opt */
133057    case 204: /* orderby_opt */
133058    case 207: /* nexprlist */
133059    case 208: /* exprlist */
133060    case 209: /* sclp */
133061    case 218: /* setlist */
133062    case 224: /* paren_exprlist */
133063    case 226: /* case_exprlist */
133064{
133065sqlite3ExprListDelete(pParse->db, (yypminor->yy148));
133066}
133067      break;
133068    case 193: /* fullname */
133069    case 200: /* from */
133070    case 211: /* seltablist */
133071    case 212: /* stl_prefix */
133072{
133073sqlite3SrcListDelete(pParse->db, (yypminor->yy185));
133074}
133075      break;
133076    case 196: /* with */
133077    case 250: /* wqlist */
133078{
133079sqlite3WithDelete(pParse->db, (yypminor->yy285));
133080}
133081      break;
133082    case 201: /* where_opt */
133083    case 203: /* having_opt */
133084    case 215: /* on_opt */
133085    case 225: /* case_operand */
133086    case 227: /* case_else */
133087    case 236: /* when_clause */
133088    case 241: /* key_opt */
133089{
133090sqlite3ExprDelete(pParse->db, (yypminor->yy72));
133091}
133092      break;
133093    case 216: /* using_opt */
133094    case 217: /* idlist */
133095    case 220: /* idlist_opt */
133096{
133097sqlite3IdListDelete(pParse->db, (yypminor->yy254));
133098}
133099      break;
133100    case 232: /* trigger_cmd_list */
133101    case 237: /* trigger_cmd */
133102{
133103sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145));
133104}
133105      break;
133106    case 234: /* trigger_event */
133107{
133108sqlite3IdListDelete(pParse->db, (yypminor->yy332).b);
133109}
133110      break;
133111/********* End destructor definitions *****************************************/
133112    default:  break;   /* If no destructor action specified: do nothing */
133113  }
133114}
133115
133116/*
133117** Pop the parser's stack once.
133118**
133119** If there is a destructor routine associated with the token which
133120** is popped from the stack, then call it.
133121*/
133122static void yy_pop_parser_stack(yyParser *pParser){
133123  yyStackEntry *yytos;
133124  assert( pParser->yytos!=0 );
133125  assert( pParser->yytos > pParser->yystack );
133126  yytos = pParser->yytos--;
133127#ifndef NDEBUG
133128  if( yyTraceFILE ){
133129    fprintf(yyTraceFILE,"%sPopping %s\n",
133130      yyTracePrompt,
133131      yyTokenName[yytos->major]);
133132  }
133133#endif
133134  yy_destructor(pParser, yytos->major, &yytos->minor);
133135}
133136
133137/*
133138** Deallocate and destroy a parser.  Destructors are called for
133139** all stack elements before shutting the parser down.
133140**
133141** If the YYPARSEFREENEVERNULL macro exists (for example because it
133142** is defined in a %include section of the input grammar) then it is
133143** assumed that the input pointer is never NULL.
133144*/
133145SQLITE_PRIVATE void sqlite3ParserFree(
133146  void *p,                    /* The parser to be deleted */
133147  void (*freeProc)(void*)     /* Function used to reclaim memory */
133148){
133149  yyParser *pParser = (yyParser*)p;
133150#ifndef YYPARSEFREENEVERNULL
133151  if( pParser==0 ) return;
133152#endif
133153  while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
133154#if YYSTACKDEPTH<=0
133155  if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
133156#endif
133157  (*freeProc)((void*)pParser);
133158}
133159
133160/*
133161** Return the peak depth of the stack for a parser.
133162*/
133163#ifdef YYTRACKMAXSTACKDEPTH
133164SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
133165  yyParser *pParser = (yyParser*)p;
133166  return pParser->yyhwm;
133167}
133168#endif
133169
133170/*
133171** Find the appropriate action for a parser given the terminal
133172** look-ahead token iLookAhead.
133173*/
133174static unsigned int yy_find_shift_action(
133175  yyParser *pParser,        /* The parser */
133176  YYCODETYPE iLookAhead     /* The look-ahead token */
133177){
133178  int i;
133179  int stateno = pParser->yytos->stateno;
133180
133181  if( stateno>=YY_MIN_REDUCE ) return stateno;
133182  assert( stateno <= YY_SHIFT_COUNT );
133183  do{
133184    i = yy_shift_ofst[stateno];
133185    if( i==YY_SHIFT_USE_DFLT ) return yy_default[stateno];
133186    assert( iLookAhead!=YYNOCODE );
133187    i += iLookAhead;
133188    if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
133189      if( iLookAhead>0 ){
133190#ifdef YYFALLBACK
133191        YYCODETYPE iFallback;            /* Fallback token */
133192        if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
133193               && (iFallback = yyFallback[iLookAhead])!=0 ){
133194#ifndef NDEBUG
133195          if( yyTraceFILE ){
133196            fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
133197               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
133198          }
133199#endif
133200          assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
133201          iLookAhead = iFallback;
133202          continue;
133203        }
133204#endif
133205#ifdef YYWILDCARD
133206        {
133207          int j = i - iLookAhead + YYWILDCARD;
133208          if(
133209#if YY_SHIFT_MIN+YYWILDCARD<0
133210            j>=0 &&
133211#endif
133212#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
133213            j<YY_ACTTAB_COUNT &&
133214#endif
133215            yy_lookahead[j]==YYWILDCARD
133216          ){
133217#ifndef NDEBUG
133218            if( yyTraceFILE ){
133219              fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
133220                 yyTracePrompt, yyTokenName[iLookAhead],
133221                 yyTokenName[YYWILDCARD]);
133222            }
133223#endif /* NDEBUG */
133224            return yy_action[j];
133225          }
133226        }
133227#endif /* YYWILDCARD */
133228      }
133229      return yy_default[stateno];
133230    }else{
133231      return yy_action[i];
133232    }
133233  }while(1);
133234}
133235
133236/*
133237** Find the appropriate action for a parser given the non-terminal
133238** look-ahead token iLookAhead.
133239*/
133240static int yy_find_reduce_action(
133241  int stateno,              /* Current state number */
133242  YYCODETYPE iLookAhead     /* The look-ahead token */
133243){
133244  int i;
133245#ifdef YYERRORSYMBOL
133246  if( stateno>YY_REDUCE_COUNT ){
133247    return yy_default[stateno];
133248  }
133249#else
133250  assert( stateno<=YY_REDUCE_COUNT );
133251#endif
133252  i = yy_reduce_ofst[stateno];
133253  assert( i!=YY_REDUCE_USE_DFLT );
133254  assert( iLookAhead!=YYNOCODE );
133255  i += iLookAhead;
133256#ifdef YYERRORSYMBOL
133257  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
133258    return yy_default[stateno];
133259  }
133260#else
133261  assert( i>=0 && i<YY_ACTTAB_COUNT );
133262  assert( yy_lookahead[i]==iLookAhead );
133263#endif
133264  return yy_action[i];
133265}
133266
133267/*
133268** The following routine is called if the stack overflows.
133269*/
133270static void yyStackOverflow(yyParser *yypParser){
133271   sqlite3ParserARG_FETCH;
133272   yypParser->yytos--;
133273#ifndef NDEBUG
133274   if( yyTraceFILE ){
133275     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
133276   }
133277#endif
133278   while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
133279   /* Here code is inserted which will execute if the parser
133280   ** stack every overflows */
133281/******** Begin %stack_overflow code ******************************************/
133282
133283  sqlite3ErrorMsg(pParse, "parser stack overflow");
133284/******** End %stack_overflow code ********************************************/
133285   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
133286}
133287
133288/*
133289** Print tracing information for a SHIFT action
133290*/
133291#ifndef NDEBUG
133292static void yyTraceShift(yyParser *yypParser, int yyNewState){
133293  if( yyTraceFILE ){
133294    if( yyNewState<YYNSTATE ){
133295      fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n",
133296         yyTracePrompt,yyTokenName[yypParser->yytos->major],
133297         yyNewState);
133298    }else{
133299      fprintf(yyTraceFILE,"%sShift '%s'\n",
133300         yyTracePrompt,yyTokenName[yypParser->yytos->major]);
133301    }
133302  }
133303}
133304#else
133305# define yyTraceShift(X,Y)
133306#endif
133307
133308/*
133309** Perform a shift action.
133310*/
133311static void yy_shift(
133312  yyParser *yypParser,          /* The parser to be shifted */
133313  int yyNewState,               /* The new state to shift in */
133314  int yyMajor,                  /* The major token to shift in */
133315  sqlite3ParserTOKENTYPE yyMinor        /* The minor token to shift in */
133316){
133317  yyStackEntry *yytos;
133318  yypParser->yytos++;
133319#ifdef YYTRACKMAXSTACKDEPTH
133320  if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
133321    yypParser->yyhwm++;
133322    assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
133323  }
133324#endif
133325#if YYSTACKDEPTH>0
133326  if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH] ){
133327    yyStackOverflow(yypParser);
133328    return;
133329  }
133330#else
133331  if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
133332    if( yyGrowStack(yypParser) ){
133333      yyStackOverflow(yypParser);
133334      return;
133335    }
133336  }
133337#endif
133338  if( yyNewState > YY_MAX_SHIFT ){
133339    yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
133340  }
133341  yytos = yypParser->yytos;
133342  yytos->stateno = (YYACTIONTYPE)yyNewState;
133343  yytos->major = (YYCODETYPE)yyMajor;
133344  yytos->minor.yy0 = yyMinor;
133345  yyTraceShift(yypParser, yyNewState);
133346}
133347
133348/* The following table contains information about every rule that
133349** is used during the reduce.
133350*/
133351static const struct {
133352  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
133353  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
133354} yyRuleInfo[] = {
133355  { 147, 1 },
133356  { 147, 3 },
133357  { 148, 1 },
133358  { 149, 3 },
133359  { 150, 0 },
133360  { 150, 1 },
133361  { 150, 1 },
133362  { 150, 1 },
133363  { 149, 2 },
133364  { 149, 2 },
133365  { 149, 2 },
133366  { 149, 2 },
133367  { 149, 3 },
133368  { 149, 5 },
133369  { 154, 6 },
133370  { 156, 1 },
133371  { 158, 0 },
133372  { 158, 3 },
133373  { 157, 1 },
133374  { 157, 0 },
133375  { 155, 5 },
133376  { 155, 2 },
133377  { 162, 0 },
133378  { 162, 2 },
133379  { 164, 2 },
133380  { 166, 0 },
133381  { 166, 4 },
133382  { 166, 6 },
133383  { 167, 2 },
133384  { 171, 2 },
133385  { 171, 2 },
133386  { 171, 4 },
133387  { 171, 3 },
133388  { 171, 3 },
133389  { 171, 2 },
133390  { 171, 3 },
133391  { 171, 5 },
133392  { 171, 2 },
133393  { 171, 4 },
133394  { 171, 4 },
133395  { 171, 1 },
133396  { 171, 2 },
133397  { 176, 0 },
133398  { 176, 1 },
133399  { 178, 0 },
133400  { 178, 2 },
133401  { 180, 2 },
133402  { 180, 3 },
133403  { 180, 3 },
133404  { 180, 3 },
133405  { 181, 2 },
133406  { 181, 2 },
133407  { 181, 1 },
133408  { 181, 1 },
133409  { 181, 2 },
133410  { 179, 3 },
133411  { 179, 2 },
133412  { 182, 0 },
133413  { 182, 2 },
133414  { 182, 2 },
133415  { 161, 0 },
133416  { 184, 1 },
133417  { 185, 2 },
133418  { 185, 7 },
133419  { 185, 5 },
133420  { 185, 5 },
133421  { 185, 10 },
133422  { 188, 0 },
133423  { 174, 0 },
133424  { 174, 3 },
133425  { 189, 0 },
133426  { 189, 2 },
133427  { 190, 1 },
133428  { 190, 1 },
133429  { 149, 4 },
133430  { 192, 2 },
133431  { 192, 0 },
133432  { 149, 9 },
133433  { 149, 4 },
133434  { 149, 1 },
133435  { 163, 2 },
133436  { 194, 3 },
133437  { 197, 1 },
133438  { 197, 2 },
133439  { 197, 1 },
133440  { 195, 9 },
133441  { 206, 4 },
133442  { 206, 5 },
133443  { 198, 1 },
133444  { 198, 1 },
133445  { 198, 0 },
133446  { 209, 0 },
133447  { 199, 3 },
133448  { 199, 2 },
133449  { 199, 4 },
133450  { 210, 2 },
133451  { 210, 0 },
133452  { 200, 0 },
133453  { 200, 2 },
133454  { 212, 2 },
133455  { 212, 0 },
133456  { 211, 7 },
133457  { 211, 9 },
133458  { 211, 7 },
133459  { 211, 7 },
133460  { 159, 0 },
133461  { 159, 2 },
133462  { 193, 2 },
133463  { 213, 1 },
133464  { 213, 2 },
133465  { 213, 3 },
133466  { 213, 4 },
133467  { 215, 2 },
133468  { 215, 0 },
133469  { 214, 0 },
133470  { 214, 3 },
133471  { 214, 2 },
133472  { 216, 4 },
133473  { 216, 0 },
133474  { 204, 0 },
133475  { 204, 3 },
133476  { 186, 4 },
133477  { 186, 2 },
133478  { 175, 1 },
133479  { 175, 1 },
133480  { 175, 0 },
133481  { 202, 0 },
133482  { 202, 3 },
133483  { 203, 0 },
133484  { 203, 2 },
133485  { 205, 0 },
133486  { 205, 2 },
133487  { 205, 4 },
133488  { 205, 4 },
133489  { 149, 6 },
133490  { 201, 0 },
133491  { 201, 2 },
133492  { 149, 8 },
133493  { 218, 5 },
133494  { 218, 3 },
133495  { 149, 6 },
133496  { 149, 7 },
133497  { 219, 2 },
133498  { 219, 1 },
133499  { 220, 0 },
133500  { 220, 3 },
133501  { 217, 3 },
133502  { 217, 1 },
133503  { 173, 3 },
133504  { 172, 1 },
133505  { 173, 1 },
133506  { 173, 1 },
133507  { 173, 3 },
133508  { 173, 5 },
133509  { 172, 1 },
133510  { 172, 1 },
133511  { 173, 1 },
133512  { 173, 3 },
133513  { 173, 6 },
133514  { 173, 5 },
133515  { 173, 4 },
133516  { 172, 1 },
133517  { 173, 3 },
133518  { 173, 3 },
133519  { 173, 3 },
133520  { 173, 3 },
133521  { 173, 3 },
133522  { 173, 3 },
133523  { 173, 3 },
133524  { 173, 3 },
133525  { 221, 1 },
133526  { 221, 2 },
133527  { 173, 3 },
133528  { 173, 5 },
133529  { 173, 2 },
133530  { 173, 3 },
133531  { 173, 3 },
133532  { 173, 4 },
133533  { 173, 2 },
133534  { 173, 2 },
133535  { 173, 2 },
133536  { 173, 2 },
133537  { 222, 1 },
133538  { 222, 2 },
133539  { 173, 5 },
133540  { 223, 1 },
133541  { 223, 2 },
133542  { 173, 5 },
133543  { 173, 3 },
133544  { 173, 5 },
133545  { 173, 5 },
133546  { 173, 4 },
133547  { 173, 5 },
133548  { 226, 5 },
133549  { 226, 4 },
133550  { 227, 2 },
133551  { 227, 0 },
133552  { 225, 1 },
133553  { 225, 0 },
133554  { 208, 0 },
133555  { 207, 3 },
133556  { 207, 1 },
133557  { 224, 0 },
133558  { 224, 3 },
133559  { 149, 12 },
133560  { 228, 1 },
133561  { 228, 0 },
133562  { 177, 0 },
133563  { 177, 3 },
133564  { 187, 5 },
133565  { 187, 3 },
133566  { 229, 0 },
133567  { 229, 2 },
133568  { 149, 4 },
133569  { 149, 1 },
133570  { 149, 2 },
133571  { 149, 3 },
133572  { 149, 5 },
133573  { 149, 6 },
133574  { 149, 5 },
133575  { 149, 6 },
133576  { 169, 2 },
133577  { 170, 2 },
133578  { 149, 5 },
133579  { 231, 11 },
133580  { 233, 1 },
133581  { 233, 1 },
133582  { 233, 2 },
133583  { 233, 0 },
133584  { 234, 1 },
133585  { 234, 1 },
133586  { 234, 3 },
133587  { 236, 0 },
133588  { 236, 2 },
133589  { 232, 3 },
133590  { 232, 2 },
133591  { 238, 3 },
133592  { 239, 3 },
133593  { 239, 2 },
133594  { 237, 7 },
133595  { 237, 5 },
133596  { 237, 5 },
133597  { 237, 1 },
133598  { 173, 4 },
133599  { 173, 6 },
133600  { 191, 1 },
133601  { 191, 1 },
133602  { 191, 1 },
133603  { 149, 4 },
133604  { 149, 6 },
133605  { 149, 3 },
133606  { 241, 0 },
133607  { 241, 2 },
133608  { 149, 1 },
133609  { 149, 3 },
133610  { 149, 1 },
133611  { 149, 3 },
133612  { 149, 6 },
133613  { 149, 7 },
133614  { 242, 1 },
133615  { 149, 1 },
133616  { 149, 4 },
133617  { 244, 8 },
133618  { 246, 0 },
133619  { 247, 1 },
133620  { 247, 3 },
133621  { 248, 1 },
133622  { 196, 0 },
133623  { 196, 2 },
133624  { 196, 3 },
133625  { 250, 6 },
133626  { 250, 8 },
133627  { 144, 1 },
133628  { 145, 2 },
133629  { 145, 1 },
133630  { 146, 1 },
133631  { 146, 3 },
133632  { 147, 0 },
133633  { 151, 0 },
133634  { 151, 1 },
133635  { 151, 2 },
133636  { 153, 1 },
133637  { 153, 0 },
133638  { 149, 2 },
133639  { 160, 4 },
133640  { 160, 2 },
133641  { 152, 1 },
133642  { 152, 1 },
133643  { 152, 1 },
133644  { 166, 1 },
133645  { 167, 1 },
133646  { 168, 1 },
133647  { 168, 1 },
133648  { 165, 2 },
133649  { 165, 0 },
133650  { 171, 2 },
133651  { 161, 2 },
133652  { 183, 3 },
133653  { 183, 1 },
133654  { 184, 0 },
133655  { 188, 1 },
133656  { 190, 1 },
133657  { 194, 1 },
133658  { 195, 1 },
133659  { 209, 2 },
133660  { 210, 1 },
133661  { 173, 1 },
133662  { 208, 1 },
133663  { 230, 1 },
133664  { 230, 1 },
133665  { 230, 1 },
133666  { 230, 1 },
133667  { 230, 1 },
133668  { 169, 1 },
133669  { 235, 0 },
133670  { 235, 3 },
133671  { 238, 1 },
133672  { 239, 0 },
133673  { 240, 1 },
133674  { 240, 0 },
133675  { 243, 0 },
133676  { 243, 1 },
133677  { 245, 1 },
133678  { 245, 3 },
133679  { 246, 2 },
133680  { 249, 0 },
133681  { 249, 4 },
133682  { 249, 2 },
133683};
133684
133685static void yy_accept(yyParser*);  /* Forward Declaration */
133686
133687/*
133688** Perform a reduce action and the shift that must immediately
133689** follow the reduce.
133690*/
133691static void yy_reduce(
133692  yyParser *yypParser,         /* The parser */
133693  unsigned int yyruleno        /* Number of the rule by which to reduce */
133694){
133695  int yygoto;                     /* The next state */
133696  int yyact;                      /* The next action */
133697  yyStackEntry *yymsp;            /* The top of the parser's stack */
133698  int yysize;                     /* Amount to pop the stack */
133699  sqlite3ParserARG_FETCH;
133700  yymsp = yypParser->yytos;
133701#ifndef NDEBUG
133702  if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
133703    yysize = yyRuleInfo[yyruleno].nrhs;
133704    fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt,
133705      yyRuleName[yyruleno], yymsp[-yysize].stateno);
133706  }
133707#endif /* NDEBUG */
133708
133709  /* Check that the stack is large enough to grow by a single entry
133710  ** if the RHS of the rule is empty.  This ensures that there is room
133711  ** enough on the stack to push the LHS value */
133712  if( yyRuleInfo[yyruleno].nrhs==0 ){
133713#ifdef YYTRACKMAXSTACKDEPTH
133714    if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
133715      yypParser->yyhwm++;
133716      assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
133717    }
133718#endif
133719#if YYSTACKDEPTH>0
133720    if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH-1] ){
133721      yyStackOverflow(yypParser);
133722      return;
133723    }
133724#else
133725    if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
133726      if( yyGrowStack(yypParser) ){
133727        yyStackOverflow(yypParser);
133728        return;
133729      }
133730      yymsp = yypParser->yytos;
133731    }
133732#endif
133733  }
133734
133735  switch( yyruleno ){
133736  /* Beginning here are the reduction cases.  A typical example
133737  ** follows:
133738  **   case 0:
133739  **  #line <lineno> <grammarfile>
133740  **     { ... }           // User supplied code
133741  **  #line <lineno> <thisfile>
133742  **     break;
133743  */
133744/********** Begin reduce actions **********************************************/
133745        YYMINORTYPE yylhsminor;
133746      case 0: /* explain ::= EXPLAIN */
133747{ pParse->explain = 1; }
133748        break;
133749      case 1: /* explain ::= EXPLAIN QUERY PLAN */
133750{ pParse->explain = 2; }
133751        break;
133752      case 2: /* cmdx ::= cmd */
133753{ sqlite3FinishCoding(pParse); }
133754        break;
133755      case 3: /* cmd ::= BEGIN transtype trans_opt */
133756{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy194);}
133757        break;
133758      case 4: /* transtype ::= */
133759{yymsp[1].minor.yy194 = TK_DEFERRED;}
133760        break;
133761      case 5: /* transtype ::= DEFERRED */
133762      case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
133763      case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
133764{yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/}
133765        break;
133766      case 8: /* cmd ::= COMMIT trans_opt */
133767      case 9: /* cmd ::= END trans_opt */ yytestcase(yyruleno==9);
133768{sqlite3CommitTransaction(pParse);}
133769        break;
133770      case 10: /* cmd ::= ROLLBACK trans_opt */
133771{sqlite3RollbackTransaction(pParse);}
133772        break;
133773      case 11: /* cmd ::= SAVEPOINT nm */
133774{
133775  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
133776}
133777        break;
133778      case 12: /* cmd ::= RELEASE savepoint_opt nm */
133779{
133780  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
133781}
133782        break;
133783      case 13: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
133784{
133785  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
133786}
133787        break;
133788      case 14: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
133789{
133790   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy194,0,0,yymsp[-2].minor.yy194);
133791}
133792        break;
133793      case 15: /* createkw ::= CREATE */
133794{disableLookaside(pParse);}
133795        break;
133796      case 16: /* ifnotexists ::= */
133797      case 19: /* temp ::= */ yytestcase(yyruleno==19);
133798      case 22: /* table_options ::= */ yytestcase(yyruleno==22);
133799      case 42: /* autoinc ::= */ yytestcase(yyruleno==42);
133800      case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57);
133801      case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67);
133802      case 76: /* ifexists ::= */ yytestcase(yyruleno==76);
133803      case 90: /* distinct ::= */ yytestcase(yyruleno==90);
133804      case 211: /* collate ::= */ yytestcase(yyruleno==211);
133805{yymsp[1].minor.yy194 = 0;}
133806        break;
133807      case 17: /* ifnotexists ::= IF NOT EXISTS */
133808{yymsp[-2].minor.yy194 = 1;}
133809        break;
133810      case 18: /* temp ::= TEMP */
133811      case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43);
133812{yymsp[0].minor.yy194 = 1;}
133813        break;
133814      case 20: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
133815{
133816  sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy194,0);
133817}
133818        break;
133819      case 21: /* create_table_args ::= AS select */
133820{
133821  sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy243);
133822  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
133823}
133824        break;
133825      case 23: /* table_options ::= WITHOUT nm */
133826{
133827  if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
133828    yymsp[-1].minor.yy194 = TF_WithoutRowid | TF_NoVisibleRowid;
133829  }else{
133830    yymsp[-1].minor.yy194 = 0;
133831    sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
133832  }
133833}
133834        break;
133835      case 24: /* columnname ::= nm typetoken */
133836{sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
133837        break;
133838      case 25: /* typetoken ::= */
133839      case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60);
133840      case 96: /* as ::= */ yytestcase(yyruleno==96);
133841{yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
133842        break;
133843      case 26: /* typetoken ::= typename LP signed RP */
133844{
133845  yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
133846}
133847        break;
133848      case 27: /* typetoken ::= typename LP signed COMMA signed RP */
133849{
133850  yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
133851}
133852        break;
133853      case 28: /* typename ::= typename ID|STRING */
133854{yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
133855        break;
133856      case 29: /* ccons ::= CONSTRAINT nm */
133857      case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62);
133858{pParse->constraintName = yymsp[0].minor.yy0;}
133859        break;
133860      case 30: /* ccons ::= DEFAULT term */
133861      case 32: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==32);
133862{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy190);}
133863        break;
133864      case 31: /* ccons ::= DEFAULT LP expr RP */
133865{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy190);}
133866        break;
133867      case 33: /* ccons ::= DEFAULT MINUS term */
133868{
133869  ExprSpan v;
133870  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy190.pExpr, 0, 0);
133871  v.zStart = yymsp[-1].minor.yy0.z;
133872  v.zEnd = yymsp[0].minor.yy190.zEnd;
133873  sqlite3AddDefaultValue(pParse,&v);
133874}
133875        break;
133876      case 34: /* ccons ::= DEFAULT ID|INDEXED */
133877{
133878  ExprSpan v;
133879  spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0);
133880  sqlite3AddDefaultValue(pParse,&v);
133881}
133882        break;
133883      case 35: /* ccons ::= NOT NULL onconf */
133884{sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);}
133885        break;
133886      case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
133887{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);}
133888        break;
133889      case 37: /* ccons ::= UNIQUE onconf */
133890{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0,
133891                                   SQLITE_IDXTYPE_UNIQUE);}
133892        break;
133893      case 38: /* ccons ::= CHECK LP expr RP */
133894{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy190.pExpr);}
133895        break;
133896      case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */
133897{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);}
133898        break;
133899      case 40: /* ccons ::= defer_subclause */
133900{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);}
133901        break;
133902      case 41: /* ccons ::= COLLATE ID|STRING */
133903{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
133904        break;
133905      case 44: /* refargs ::= */
133906{ yymsp[1].minor.yy194 = OE_None*0x0101; /* EV: R-19803-45884 */}
133907        break;
133908      case 45: /* refargs ::= refargs refarg */
133909{ yymsp[-1].minor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; }
133910        break;
133911      case 46: /* refarg ::= MATCH nm */
133912{ yymsp[-1].minor.yy497.value = 0;     yymsp[-1].minor.yy497.mask = 0x000000; }
133913        break;
133914      case 47: /* refarg ::= ON INSERT refact */
133915{ yymsp[-2].minor.yy497.value = 0;     yymsp[-2].minor.yy497.mask = 0x000000; }
133916        break;
133917      case 48: /* refarg ::= ON DELETE refact */
133918{ yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194;     yymsp[-2].minor.yy497.mask = 0x0000ff; }
133919        break;
133920      case 49: /* refarg ::= ON UPDATE refact */
133921{ yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194<<8;  yymsp[-2].minor.yy497.mask = 0x00ff00; }
133922        break;
133923      case 50: /* refact ::= SET NULL */
133924{ yymsp[-1].minor.yy194 = OE_SetNull;  /* EV: R-33326-45252 */}
133925        break;
133926      case 51: /* refact ::= SET DEFAULT */
133927{ yymsp[-1].minor.yy194 = OE_SetDflt;  /* EV: R-33326-45252 */}
133928        break;
133929      case 52: /* refact ::= CASCADE */
133930{ yymsp[0].minor.yy194 = OE_Cascade;  /* EV: R-33326-45252 */}
133931        break;
133932      case 53: /* refact ::= RESTRICT */
133933{ yymsp[0].minor.yy194 = OE_Restrict; /* EV: R-33326-45252 */}
133934        break;
133935      case 54: /* refact ::= NO ACTION */
133936{ yymsp[-1].minor.yy194 = OE_None;     /* EV: R-33326-45252 */}
133937        break;
133938      case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
133939{yymsp[-2].minor.yy194 = 0;}
133940        break;
133941      case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
133942      case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71);
133943      case 142: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==142);
133944{yymsp[-1].minor.yy194 = yymsp[0].minor.yy194;}
133945        break;
133946      case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
133947      case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75);
133948      case 183: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==183);
133949      case 186: /* in_op ::= NOT IN */ yytestcase(yyruleno==186);
133950      case 212: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==212);
133951{yymsp[-1].minor.yy194 = 1;}
133952        break;
133953      case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
133954{yymsp[-1].minor.yy194 = 0;}
133955        break;
133956      case 61: /* tconscomma ::= COMMA */
133957{pParse->constraintName.n = 0;}
133958        break;
133959      case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
133960{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);}
133961        break;
133962      case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */
133963{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0,
133964                                       SQLITE_IDXTYPE_UNIQUE);}
133965        break;
133966      case 65: /* tcons ::= CHECK LP expr RP onconf */
133967{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy190.pExpr);}
133968        break;
133969      case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
133970{
133971    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194);
133972    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194);
133973}
133974        break;
133975      case 68: /* onconf ::= */
133976      case 70: /* orconf ::= */ yytestcase(yyruleno==70);
133977{yymsp[1].minor.yy194 = OE_Default;}
133978        break;
133979      case 69: /* onconf ::= ON CONFLICT resolvetype */
133980{yymsp[-2].minor.yy194 = yymsp[0].minor.yy194;}
133981        break;
133982      case 72: /* resolvetype ::= IGNORE */
133983{yymsp[0].minor.yy194 = OE_Ignore;}
133984        break;
133985      case 73: /* resolvetype ::= REPLACE */
133986      case 143: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==143);
133987{yymsp[0].minor.yy194 = OE_Replace;}
133988        break;
133989      case 74: /* cmd ::= DROP TABLE ifexists fullname */
133990{
133991  sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194);
133992}
133993        break;
133994      case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
133995{
133996  sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[0].minor.yy243, yymsp[-7].minor.yy194, yymsp[-5].minor.yy194);
133997}
133998        break;
133999      case 78: /* cmd ::= DROP VIEW ifexists fullname */
134000{
134001  sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194);
134002}
134003        break;
134004      case 79: /* cmd ::= select */
134005{
134006  SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
134007  sqlite3Select(pParse, yymsp[0].minor.yy243, &dest);
134008  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
134009}
134010        break;
134011      case 80: /* select ::= with selectnowith */
134012{
134013  Select *p = yymsp[0].minor.yy243;
134014  if( p ){
134015    p->pWith = yymsp[-1].minor.yy285;
134016    parserDoubleLinkSelect(pParse, p);
134017  }else{
134018    sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy285);
134019  }
134020  yymsp[-1].minor.yy243 = p; /*A-overwrites-W*/
134021}
134022        break;
134023      case 81: /* selectnowith ::= selectnowith multiselect_op oneselect */
134024{
134025  Select *pRhs = yymsp[0].minor.yy243;
134026  Select *pLhs = yymsp[-2].minor.yy243;
134027  if( pRhs && pRhs->pPrior ){
134028    SrcList *pFrom;
134029    Token x;
134030    x.n = 0;
134031    parserDoubleLinkSelect(pParse, pRhs);
134032    pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
134033    pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
134034  }
134035  if( pRhs ){
134036    pRhs->op = (u8)yymsp[-1].minor.yy194;
134037    pRhs->pPrior = pLhs;
134038    if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
134039    pRhs->selFlags &= ~SF_MultiValue;
134040    if( yymsp[-1].minor.yy194!=TK_ALL ) pParse->hasCompound = 1;
134041  }else{
134042    sqlite3SelectDelete(pParse->db, pLhs);
134043  }
134044  yymsp[-2].minor.yy243 = pRhs;
134045}
134046        break;
134047      case 82: /* multiselect_op ::= UNION */
134048      case 84: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==84);
134049{yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-OP*/}
134050        break;
134051      case 83: /* multiselect_op ::= UNION ALL */
134052{yymsp[-1].minor.yy194 = TK_ALL;}
134053        break;
134054      case 85: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
134055{
134056#if SELECTTRACE_ENABLED
134057  Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/
134058#endif
134059  yymsp[-8].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy148,yymsp[-5].minor.yy185,yymsp[-4].minor.yy72,yymsp[-3].minor.yy148,yymsp[-2].minor.yy72,yymsp[-1].minor.yy148,yymsp[-7].minor.yy194,yymsp[0].minor.yy354.pLimit,yymsp[0].minor.yy354.pOffset);
134060#if SELECTTRACE_ENABLED
134061  /* Populate the Select.zSelName[] string that is used to help with
134062  ** query planner debugging, to differentiate between multiple Select
134063  ** objects in a complex query.
134064  **
134065  ** If the SELECT keyword is immediately followed by a C-style comment
134066  ** then extract the first few alphanumeric characters from within that
134067  ** comment to be the zSelName value.  Otherwise, the label is #N where
134068  ** is an integer that is incremented with each SELECT statement seen.
134069  */
134070  if( yymsp[-8].minor.yy243!=0 ){
134071    const char *z = s.z+6;
134072    int i;
134073    sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "#%d",
134074                     ++pParse->nSelect);
134075    while( z[0]==' ' ) z++;
134076    if( z[0]=='/' && z[1]=='*' ){
134077      z += 2;
134078      while( z[0]==' ' ) z++;
134079      for(i=0; sqlite3Isalnum(z[i]); i++){}
134080      sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "%.*s", i, z);
134081    }
134082  }
134083#endif /* SELECTRACE_ENABLED */
134084}
134085        break;
134086      case 86: /* values ::= VALUES LP nexprlist RP */
134087{
134088  yymsp[-3].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values,0,0);
134089}
134090        break;
134091      case 87: /* values ::= values COMMA LP exprlist RP */
134092{
134093  Select *pRight, *pLeft = yymsp[-4].minor.yy243;
134094  pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
134095  if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
134096  if( pRight ){
134097    pRight->op = TK_ALL;
134098    pRight->pPrior = pLeft;
134099    yymsp[-4].minor.yy243 = pRight;
134100  }else{
134101    yymsp[-4].minor.yy243 = pLeft;
134102  }
134103}
134104        break;
134105      case 88: /* distinct ::= DISTINCT */
134106{yymsp[0].minor.yy194 = SF_Distinct;}
134107        break;
134108      case 89: /* distinct ::= ALL */
134109{yymsp[0].minor.yy194 = SF_All;}
134110        break;
134111      case 91: /* sclp ::= */
134112      case 119: /* orderby_opt ::= */ yytestcase(yyruleno==119);
134113      case 126: /* groupby_opt ::= */ yytestcase(yyruleno==126);
134114      case 199: /* exprlist ::= */ yytestcase(yyruleno==199);
134115      case 202: /* paren_exprlist ::= */ yytestcase(yyruleno==202);
134116      case 207: /* eidlist_opt ::= */ yytestcase(yyruleno==207);
134117{yymsp[1].minor.yy148 = 0;}
134118        break;
134119      case 92: /* selcollist ::= sclp expr as */
134120{
134121   yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy148, yymsp[-1].minor.yy190.pExpr);
134122   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy148, &yymsp[0].minor.yy0, 1);
134123   sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy148,&yymsp[-1].minor.yy190);
134124}
134125        break;
134126      case 93: /* selcollist ::= sclp STAR */
134127{
134128  Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
134129  yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p);
134130}
134131        break;
134132      case 94: /* selcollist ::= sclp nm DOT STAR */
134133{
134134  Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0, &yymsp[0].minor.yy0);
134135  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
134136  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
134137  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot);
134138}
134139        break;
134140      case 95: /* as ::= AS nm */
134141      case 106: /* dbnm ::= DOT nm */ yytestcase(yyruleno==106);
134142      case 221: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==221);
134143      case 222: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==222);
134144{yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
134145        break;
134146      case 97: /* from ::= */
134147{yymsp[1].minor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy185));}
134148        break;
134149      case 98: /* from ::= FROM seltablist */
134150{
134151  yymsp[-1].minor.yy185 = yymsp[0].minor.yy185;
134152  sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy185);
134153}
134154        break;
134155      case 99: /* stl_prefix ::= seltablist joinop */
134156{
134157   if( ALWAYS(yymsp[-1].minor.yy185 && yymsp[-1].minor.yy185->nSrc>0) ) yymsp[-1].minor.yy185->a[yymsp[-1].minor.yy185->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy194;
134158}
134159        break;
134160      case 100: /* stl_prefix ::= */
134161{yymsp[1].minor.yy185 = 0;}
134162        break;
134163      case 101: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
134164{
134165  yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
134166  sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy185, &yymsp[-2].minor.yy0);
134167}
134168        break;
134169      case 102: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
134170{
134171  yymsp[-8].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy185,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
134172  sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy185, yymsp[-4].minor.yy148);
134173}
134174        break;
134175      case 103: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
134176{
134177    yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy243,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
134178  }
134179        break;
134180      case 104: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
134181{
134182    if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){
134183      yymsp[-6].minor.yy185 = yymsp[-4].minor.yy185;
134184    }else if( yymsp[-4].minor.yy185->nSrc==1 ){
134185      yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
134186      if( yymsp[-6].minor.yy185 ){
134187        struct SrcList_item *pNew = &yymsp[-6].minor.yy185->a[yymsp[-6].minor.yy185->nSrc-1];
134188        struct SrcList_item *pOld = yymsp[-4].minor.yy185->a;
134189        pNew->zName = pOld->zName;
134190        pNew->zDatabase = pOld->zDatabase;
134191        pNew->pSelect = pOld->pSelect;
134192        pOld->zName = pOld->zDatabase = 0;
134193        pOld->pSelect = 0;
134194      }
134195      sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy185);
134196    }else{
134197      Select *pSubquery;
134198      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185);
134199      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,SF_NestedFrom,0,0);
134200      yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
134201    }
134202  }
134203        break;
134204      case 105: /* dbnm ::= */
134205      case 114: /* indexed_opt ::= */ yytestcase(yyruleno==114);
134206{yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
134207        break;
134208      case 107: /* fullname ::= nm dbnm */
134209{yymsp[-1].minor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
134210        break;
134211      case 108: /* joinop ::= COMMA|JOIN */
134212{ yymsp[0].minor.yy194 = JT_INNER; }
134213        break;
134214      case 109: /* joinop ::= JOIN_KW JOIN */
134215{yymsp[-1].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0);  /*X-overwrites-A*/}
134216        break;
134217      case 110: /* joinop ::= JOIN_KW nm JOIN */
134218{yymsp[-2].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
134219        break;
134220      case 111: /* joinop ::= JOIN_KW nm nm JOIN */
134221{yymsp[-3].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
134222        break;
134223      case 112: /* on_opt ::= ON expr */
134224      case 129: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==129);
134225      case 136: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==136);
134226      case 195: /* case_else ::= ELSE expr */ yytestcase(yyruleno==195);
134227{yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr;}
134228        break;
134229      case 113: /* on_opt ::= */
134230      case 128: /* having_opt ::= */ yytestcase(yyruleno==128);
134231      case 135: /* where_opt ::= */ yytestcase(yyruleno==135);
134232      case 196: /* case_else ::= */ yytestcase(yyruleno==196);
134233      case 198: /* case_operand ::= */ yytestcase(yyruleno==198);
134234{yymsp[1].minor.yy72 = 0;}
134235        break;
134236      case 115: /* indexed_opt ::= INDEXED BY nm */
134237{yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
134238        break;
134239      case 116: /* indexed_opt ::= NOT INDEXED */
134240{yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
134241        break;
134242      case 117: /* using_opt ::= USING LP idlist RP */
134243{yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;}
134244        break;
134245      case 118: /* using_opt ::= */
134246      case 144: /* idlist_opt ::= */ yytestcase(yyruleno==144);
134247{yymsp[1].minor.yy254 = 0;}
134248        break;
134249      case 120: /* orderby_opt ::= ORDER BY sortlist */
134250      case 127: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==127);
134251{yymsp[-2].minor.yy148 = yymsp[0].minor.yy148;}
134252        break;
134253      case 121: /* sortlist ::= sortlist COMMA expr sortorder */
134254{
134255  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy190.pExpr);
134256  sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy148,yymsp[0].minor.yy194);
134257}
134258        break;
134259      case 122: /* sortlist ::= expr sortorder */
134260{
134261  yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy190.pExpr); /*A-overwrites-Y*/
134262  sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy148,yymsp[0].minor.yy194);
134263}
134264        break;
134265      case 123: /* sortorder ::= ASC */
134266{yymsp[0].minor.yy194 = SQLITE_SO_ASC;}
134267        break;
134268      case 124: /* sortorder ::= DESC */
134269{yymsp[0].minor.yy194 = SQLITE_SO_DESC;}
134270        break;
134271      case 125: /* sortorder ::= */
134272{yymsp[1].minor.yy194 = SQLITE_SO_UNDEFINED;}
134273        break;
134274      case 130: /* limit_opt ::= */
134275{yymsp[1].minor.yy354.pLimit = 0; yymsp[1].minor.yy354.pOffset = 0;}
134276        break;
134277      case 131: /* limit_opt ::= LIMIT expr */
134278{yymsp[-1].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr; yymsp[-1].minor.yy354.pOffset = 0;}
134279        break;
134280      case 132: /* limit_opt ::= LIMIT expr OFFSET expr */
134281{yymsp[-3].minor.yy354.pLimit = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pOffset = yymsp[0].minor.yy190.pExpr;}
134282        break;
134283      case 133: /* limit_opt ::= LIMIT expr COMMA expr */
134284{yymsp[-3].minor.yy354.pOffset = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr;}
134285        break;
134286      case 134: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
134287{
134288  sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
134289  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0);
134290  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72);
134291}
134292        break;
134293      case 137: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
134294{
134295  sqlite3WithPush(pParse, yymsp[-7].minor.yy285, 1);
134296  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0);
134297  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list");
134298  sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194);
134299}
134300        break;
134301      case 138: /* setlist ::= setlist COMMA nm EQ expr */
134302{
134303  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
134304  sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, 1);
134305}
134306        break;
134307      case 139: /* setlist ::= nm EQ expr */
134308{
134309  yylhsminor.yy148 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy190.pExpr);
134310  sqlite3ExprListSetName(pParse, yylhsminor.yy148, &yymsp[-2].minor.yy0, 1);
134311}
134312  yymsp[-2].minor.yy148 = yylhsminor.yy148;
134313        break;
134314      case 140: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
134315{
134316  sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
134317  sqlite3Insert(pParse, yymsp[-2].minor.yy185, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194);
134318}
134319        break;
134320      case 141: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
134321{
134322  sqlite3WithPush(pParse, yymsp[-6].minor.yy285, 1);
134323  sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194);
134324}
134325        break;
134326      case 145: /* idlist_opt ::= LP idlist RP */
134327{yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;}
134328        break;
134329      case 146: /* idlist ::= idlist COMMA nm */
134330{yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);}
134331        break;
134332      case 147: /* idlist ::= nm */
134333{yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
134334        break;
134335      case 148: /* expr ::= LP expr RP */
134336{spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/  yymsp[-2].minor.yy190.pExpr = yymsp[-1].minor.yy190.pExpr;}
134337        break;
134338      case 149: /* term ::= NULL */
134339      case 154: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==154);
134340      case 155: /* term ::= STRING */ yytestcase(yyruleno==155);
134341{spanExpr(&yymsp[0].minor.yy190,pParse,yymsp[0].major,yymsp[0].minor.yy0);/*A-overwrites-X*/}
134342        break;
134343      case 150: /* expr ::= ID|INDEXED */
134344      case 151: /* expr ::= JOIN_KW */ yytestcase(yyruleno==151);
134345{spanExpr(&yymsp[0].minor.yy190,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
134346        break;
134347      case 152: /* expr ::= nm DOT nm */
134348{
134349  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
134350  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
134351  spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
134352  yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
134353}
134354        break;
134355      case 153: /* expr ::= nm DOT nm DOT nm */
134356{
134357  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
134358  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
134359  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
134360  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
134361  spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
134362  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
134363}
134364        break;
134365      case 156: /* expr ::= VARIABLE */
134366{
134367  if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
134368    spanExpr(&yymsp[0].minor.yy190, pParse, TK_VARIABLE, yymsp[0].minor.yy0);
134369    sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy190.pExpr);
134370  }else{
134371    /* When doing a nested parse, one can include terms in an expression
134372    ** that look like this:   #1 #2 ...  These terms refer to registers
134373    ** in the virtual machine.  #N is the N-th register. */
134374    Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
134375    assert( t.n>=2 );
134376    spanSet(&yymsp[0].minor.yy190, &t, &t);
134377    if( pParse->nested==0 ){
134378      sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
134379      yymsp[0].minor.yy190.pExpr = 0;
134380    }else{
134381      yymsp[0].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &t);
134382      if( yymsp[0].minor.yy190.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy190.pExpr->iTable);
134383    }
134384  }
134385}
134386        break;
134387      case 157: /* expr ::= expr COLLATE ID|STRING */
134388{
134389  yymsp[-2].minor.yy190.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy190.pExpr, &yymsp[0].minor.yy0, 1);
134390  yymsp[-2].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
134391}
134392        break;
134393      case 158: /* expr ::= CAST LP expr AS typetoken RP */
134394{
134395  spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
134396  yymsp[-5].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy190.pExpr, 0, &yymsp[-1].minor.yy0);
134397}
134398        break;
134399      case 159: /* expr ::= ID|INDEXED LP distinct exprlist RP */
134400{
134401  if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
134402    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
134403  }
134404  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0);
134405  spanSet(&yylhsminor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
134406  if( yymsp[-2].minor.yy194==SF_Distinct && yylhsminor.yy190.pExpr ){
134407    yylhsminor.yy190.pExpr->flags |= EP_Distinct;
134408  }
134409}
134410  yymsp[-4].minor.yy190 = yylhsminor.yy190;
134411        break;
134412      case 160: /* expr ::= ID|INDEXED LP STAR RP */
134413{
134414  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
134415  spanSet(&yylhsminor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
134416}
134417  yymsp[-3].minor.yy190 = yylhsminor.yy190;
134418        break;
134419      case 161: /* term ::= CTIME_KW */
134420{
134421  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
134422  spanSet(&yylhsminor.yy190, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
134423}
134424  yymsp[0].minor.yy190 = yylhsminor.yy190;
134425        break;
134426      case 162: /* expr ::= expr AND expr */
134427      case 163: /* expr ::= expr OR expr */ yytestcase(yyruleno==163);
134428      case 164: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==164);
134429      case 165: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==165);
134430      case 166: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==166);
134431      case 167: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==167);
134432      case 168: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==168);
134433      case 169: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==169);
134434{spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);}
134435        break;
134436      case 170: /* likeop ::= LIKE_KW|MATCH */
134437{yymsp[0].minor.yy392.eOperator = yymsp[0].minor.yy0; yymsp[0].minor.yy392.bNot = 0;/*A-overwrites-X*/}
134438        break;
134439      case 171: /* likeop ::= NOT LIKE_KW|MATCH */
134440{yymsp[-1].minor.yy392.eOperator = yymsp[0].minor.yy0; yymsp[-1].minor.yy392.bNot = 1;}
134441        break;
134442      case 172: /* expr ::= expr likeop expr */
134443{
134444  ExprList *pList;
134445  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy190.pExpr);
134446  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy190.pExpr);
134447  yymsp[-2].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy392.eOperator);
134448  exprNot(pParse, yymsp[-1].minor.yy392.bNot, &yymsp[-2].minor.yy190);
134449  yymsp[-2].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
134450  if( yymsp[-2].minor.yy190.pExpr ) yymsp[-2].minor.yy190.pExpr->flags |= EP_InfixFunc;
134451}
134452        break;
134453      case 173: /* expr ::= expr likeop expr ESCAPE expr */
134454{
134455  ExprList *pList;
134456  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
134457  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy190.pExpr);
134458  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
134459  yymsp[-4].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy392.eOperator);
134460  exprNot(pParse, yymsp[-3].minor.yy392.bNot, &yymsp[-4].minor.yy190);
134461  yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
134462  if( yymsp[-4].minor.yy190.pExpr ) yymsp[-4].minor.yy190.pExpr->flags |= EP_InfixFunc;
134463}
134464        break;
134465      case 174: /* expr ::= expr ISNULL|NOTNULL */
134466{spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy190,&yymsp[0].minor.yy0);}
134467        break;
134468      case 175: /* expr ::= expr NOT NULL */
134469{spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy0);}
134470        break;
134471      case 176: /* expr ::= expr IS expr */
134472{
134473  spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);
134474  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-2].minor.yy190.pExpr, TK_ISNULL);
134475}
134476        break;
134477      case 177: /* expr ::= expr IS NOT expr */
134478{
134479  spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy190,&yymsp[0].minor.yy190);
134480  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, TK_NOTNULL);
134481}
134482        break;
134483      case 178: /* expr ::= NOT expr */
134484      case 179: /* expr ::= BITNOT expr */ yytestcase(yyruleno==179);
134485{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,yymsp[-1].major,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
134486        break;
134487      case 180: /* expr ::= MINUS expr */
134488{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UMINUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
134489        break;
134490      case 181: /* expr ::= PLUS expr */
134491{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UPLUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
134492        break;
134493      case 182: /* between_op ::= BETWEEN */
134494      case 185: /* in_op ::= IN */ yytestcase(yyruleno==185);
134495{yymsp[0].minor.yy194 = 0;}
134496        break;
134497      case 184: /* expr ::= expr between_op expr AND expr */
134498{
134499  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
134500  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
134501  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy190.pExpr, 0, 0);
134502  if( yymsp[-4].minor.yy190.pExpr ){
134503    yymsp[-4].minor.yy190.pExpr->x.pList = pList;
134504  }else{
134505    sqlite3ExprListDelete(pParse->db, pList);
134506  }
134507  exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
134508  yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
134509}
134510        break;
134511      case 187: /* expr ::= expr in_op LP exprlist RP */
134512{
134513    if( yymsp[-1].minor.yy148==0 ){
134514      /* Expressions of the form
134515      **
134516      **      expr1 IN ()
134517      **      expr1 NOT IN ()
134518      **
134519      ** simplify to constants 0 (false) and 1 (true), respectively,
134520      ** regardless of the value of expr1.
134521      */
134522      sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy190.pExpr);
134523      yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy194]);
134524    }else if( yymsp[-1].minor.yy148->nExpr==1 ){
134525      /* Expressions of the form:
134526      **
134527      **      expr1 IN (?1)
134528      **      expr1 NOT IN (?2)
134529      **
134530      ** with exactly one value on the RHS can be simplified to something
134531      ** like this:
134532      **
134533      **      expr1 == ?1
134534      **      expr1 <> ?2
134535      **
134536      ** But, the RHS of the == or <> is marked with the EP_Generic flag
134537      ** so that it may not contribute to the computation of comparison
134538      ** affinity or the collating sequence to use for comparison.  Otherwise,
134539      ** the semantics would be subtly different from IN or NOT IN.
134540      */
134541      Expr *pRHS = yymsp[-1].minor.yy148->a[0].pExpr;
134542      yymsp[-1].minor.yy148->a[0].pExpr = 0;
134543      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
134544      /* pRHS cannot be NULL because a malloc error would have been detected
134545      ** before now and control would have never reached this point */
134546      if( ALWAYS(pRHS) ){
134547        pRHS->flags &= ~EP_Collate;
134548        pRHS->flags |= EP_Generic;
134549      }
134550      yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy194 ? TK_NE : TK_EQ, yymsp[-4].minor.yy190.pExpr, pRHS, 0);
134551    }else{
134552      yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0);
134553      if( yymsp[-4].minor.yy190.pExpr ){
134554        yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy148;
134555        sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
134556      }else{
134557        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
134558      }
134559      exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
134560    }
134561    yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
134562  }
134563        break;
134564      case 188: /* expr ::= LP select RP */
134565{
134566    spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
134567    yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
134568    sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy190.pExpr, yymsp[-1].minor.yy243);
134569  }
134570        break;
134571      case 189: /* expr ::= expr in_op LP select RP */
134572{
134573    yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0);
134574    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, yymsp[-1].minor.yy243);
134575    exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
134576    yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
134577  }
134578        break;
134579      case 190: /* expr ::= expr in_op nm dbnm paren_exprlist */
134580{
134581    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
134582    Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
134583    if( yymsp[0].minor.yy148 )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy148);
134584    yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0);
134585    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, pSelect);
134586    exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
134587    yymsp[-4].minor.yy190.zEnd = yymsp[-1].minor.yy0.z ? &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n] : &yymsp[-2].minor.yy0.z[yymsp[-2].minor.yy0.n];
134588  }
134589        break;
134590      case 191: /* expr ::= EXISTS LP select RP */
134591{
134592    Expr *p;
134593    spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
134594    p = yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
134595    sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy243);
134596  }
134597        break;
134598      case 192: /* expr ::= CASE case_operand case_exprlist case_else END */
134599{
134600  spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-C*/
134601  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, 0, 0);
134602  if( yymsp[-4].minor.yy190.pExpr ){
134603    yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy72 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[-1].minor.yy72) : yymsp[-2].minor.yy148;
134604    sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
134605  }else{
134606    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148);
134607    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy72);
134608  }
134609}
134610        break;
134611      case 193: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
134612{
134613  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy190.pExpr);
134614  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
134615}
134616        break;
134617      case 194: /* case_exprlist ::= WHEN expr THEN expr */
134618{
134619  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
134620  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, yymsp[0].minor.yy190.pExpr);
134621}
134622        break;
134623      case 197: /* case_operand ::= expr */
134624{yymsp[0].minor.yy72 = yymsp[0].minor.yy190.pExpr; /*A-overwrites-X*/}
134625        break;
134626      case 200: /* nexprlist ::= nexprlist COMMA expr */
134627{yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy190.pExpr);}
134628        break;
134629      case 201: /* nexprlist ::= expr */
134630{yymsp[0].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy190.pExpr); /*A-overwrites-Y*/}
134631        break;
134632      case 203: /* paren_exprlist ::= LP exprlist RP */
134633      case 208: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==208);
134634{yymsp[-2].minor.yy148 = yymsp[-1].minor.yy148;}
134635        break;
134636      case 204: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
134637{
134638  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
134639                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy148, yymsp[-10].minor.yy194,
134640                      &yymsp[-11].minor.yy0, yymsp[0].minor.yy72, SQLITE_SO_ASC, yymsp[-8].minor.yy194, SQLITE_IDXTYPE_APPDEF);
134641}
134642        break;
134643      case 205: /* uniqueflag ::= UNIQUE */
134644      case 246: /* raisetype ::= ABORT */ yytestcase(yyruleno==246);
134645{yymsp[0].minor.yy194 = OE_Abort;}
134646        break;
134647      case 206: /* uniqueflag ::= */
134648{yymsp[1].minor.yy194 = OE_None;}
134649        break;
134650      case 209: /* eidlist ::= eidlist COMMA nm collate sortorder */
134651{
134652  yymsp[-4].minor.yy148 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194);
134653}
134654        break;
134655      case 210: /* eidlist ::= nm collate sortorder */
134656{
134657  yymsp[-2].minor.yy148 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); /*A-overwrites-Y*/
134658}
134659        break;
134660      case 213: /* cmd ::= DROP INDEX ifexists fullname */
134661{sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);}
134662        break;
134663      case 214: /* cmd ::= VACUUM */
134664      case 215: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==215);
134665{sqlite3Vacuum(pParse);}
134666        break;
134667      case 216: /* cmd ::= PRAGMA nm dbnm */
134668{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
134669        break;
134670      case 217: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
134671{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
134672        break;
134673      case 218: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
134674{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
134675        break;
134676      case 219: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
134677{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
134678        break;
134679      case 220: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
134680{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
134681        break;
134682      case 223: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
134683{
134684  Token all;
134685  all.z = yymsp[-3].minor.yy0.z;
134686  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
134687  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy145, &all);
134688}
134689        break;
134690      case 224: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
134691{
134692  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy194, yymsp[-4].minor.yy332.a, yymsp[-4].minor.yy332.b, yymsp[-2].minor.yy185, yymsp[0].minor.yy72, yymsp[-10].minor.yy194, yymsp[-8].minor.yy194);
134693  yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
134694}
134695        break;
134696      case 225: /* trigger_time ::= BEFORE */
134697{ yymsp[0].minor.yy194 = TK_BEFORE; }
134698        break;
134699      case 226: /* trigger_time ::= AFTER */
134700{ yymsp[0].minor.yy194 = TK_AFTER;  }
134701        break;
134702      case 227: /* trigger_time ::= INSTEAD OF */
134703{ yymsp[-1].minor.yy194 = TK_INSTEAD;}
134704        break;
134705      case 228: /* trigger_time ::= */
134706{ yymsp[1].minor.yy194 = TK_BEFORE; }
134707        break;
134708      case 229: /* trigger_event ::= DELETE|INSERT */
134709      case 230: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==230);
134710{yymsp[0].minor.yy332.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy332.b = 0;}
134711        break;
134712      case 231: /* trigger_event ::= UPDATE OF idlist */
134713{yymsp[-2].minor.yy332.a = TK_UPDATE; yymsp[-2].minor.yy332.b = yymsp[0].minor.yy254;}
134714        break;
134715      case 232: /* when_clause ::= */
134716      case 251: /* key_opt ::= */ yytestcase(yyruleno==251);
134717{ yymsp[1].minor.yy72 = 0; }
134718        break;
134719      case 233: /* when_clause ::= WHEN expr */
134720      case 252: /* key_opt ::= KEY expr */ yytestcase(yyruleno==252);
134721{ yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr; }
134722        break;
134723      case 234: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
134724{
134725  assert( yymsp[-2].minor.yy145!=0 );
134726  yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145;
134727  yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145;
134728}
134729        break;
134730      case 235: /* trigger_cmd_list ::= trigger_cmd SEMI */
134731{
134732  assert( yymsp[-1].minor.yy145!=0 );
134733  yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145;
134734}
134735        break;
134736      case 236: /* trnm ::= nm DOT nm */
134737{
134738  yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
134739  sqlite3ErrorMsg(pParse,
134740        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
134741        "statements within triggers");
134742}
134743        break;
134744      case 237: /* tridxby ::= INDEXED BY nm */
134745{
134746  sqlite3ErrorMsg(pParse,
134747        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
134748        "within triggers");
134749}
134750        break;
134751      case 238: /* tridxby ::= NOT INDEXED */
134752{
134753  sqlite3ErrorMsg(pParse,
134754        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
134755        "within triggers");
134756}
134757        break;
134758      case 239: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
134759{yymsp[-6].minor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-5].minor.yy194);}
134760        break;
134761      case 240: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
134762{yymsp[-4].minor.yy145 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy254, yymsp[0].minor.yy243, yymsp[-4].minor.yy194);/*A-overwrites-R*/}
134763        break;
134764      case 241: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
134765{yymsp[-4].minor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy72);}
134766        break;
134767      case 242: /* trigger_cmd ::= select */
134768{yymsp[0].minor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); /*A-overwrites-X*/}
134769        break;
134770      case 243: /* expr ::= RAISE LP IGNORE RP */
134771{
134772  spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-X*/
134773  yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
134774  if( yymsp[-3].minor.yy190.pExpr ){
134775    yymsp[-3].minor.yy190.pExpr->affinity = OE_Ignore;
134776  }
134777}
134778        break;
134779      case 244: /* expr ::= RAISE LP raisetype COMMA nm RP */
134780{
134781  spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-X*/
134782  yymsp[-5].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
134783  if( yymsp[-5].minor.yy190.pExpr ) {
134784    yymsp[-5].minor.yy190.pExpr->affinity = (char)yymsp[-3].minor.yy194;
134785  }
134786}
134787        break;
134788      case 245: /* raisetype ::= ROLLBACK */
134789{yymsp[0].minor.yy194 = OE_Rollback;}
134790        break;
134791      case 247: /* raisetype ::= FAIL */
134792{yymsp[0].minor.yy194 = OE_Fail;}
134793        break;
134794      case 248: /* cmd ::= DROP TRIGGER ifexists fullname */
134795{
134796  sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194);
134797}
134798        break;
134799      case 249: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
134800{
134801  sqlite3Attach(pParse, yymsp[-3].minor.yy190.pExpr, yymsp[-1].minor.yy190.pExpr, yymsp[0].minor.yy72);
134802}
134803        break;
134804      case 250: /* cmd ::= DETACH database_kw_opt expr */
134805{
134806  sqlite3Detach(pParse, yymsp[0].minor.yy190.pExpr);
134807}
134808        break;
134809      case 253: /* cmd ::= REINDEX */
134810{sqlite3Reindex(pParse, 0, 0);}
134811        break;
134812      case 254: /* cmd ::= REINDEX nm dbnm */
134813{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
134814        break;
134815      case 255: /* cmd ::= ANALYZE */
134816{sqlite3Analyze(pParse, 0, 0);}
134817        break;
134818      case 256: /* cmd ::= ANALYZE nm dbnm */
134819{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
134820        break;
134821      case 257: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
134822{
134823  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0);
134824}
134825        break;
134826      case 258: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
134827{
134828  yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
134829  sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
134830}
134831        break;
134832      case 259: /* add_column_fullname ::= fullname */
134833{
134834  disableLookaside(pParse);
134835  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185);
134836}
134837        break;
134838      case 260: /* cmd ::= create_vtab */
134839{sqlite3VtabFinishParse(pParse,0);}
134840        break;
134841      case 261: /* cmd ::= create_vtab LP vtabarglist RP */
134842{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
134843        break;
134844      case 262: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
134845{
134846    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy194);
134847}
134848        break;
134849      case 263: /* vtabarg ::= */
134850{sqlite3VtabArgInit(pParse);}
134851        break;
134852      case 264: /* vtabargtoken ::= ANY */
134853      case 265: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==265);
134854      case 266: /* lp ::= LP */ yytestcase(yyruleno==266);
134855{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
134856        break;
134857      case 267: /* with ::= */
134858{yymsp[1].minor.yy285 = 0;}
134859        break;
134860      case 268: /* with ::= WITH wqlist */
134861{ yymsp[-1].minor.yy285 = yymsp[0].minor.yy285; }
134862        break;
134863      case 269: /* with ::= WITH RECURSIVE wqlist */
134864{ yymsp[-2].minor.yy285 = yymsp[0].minor.yy285; }
134865        break;
134866      case 270: /* wqlist ::= nm eidlist_opt AS LP select RP */
134867{
134868  yymsp[-5].minor.yy285 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); /*A-overwrites-X*/
134869}
134870        break;
134871      case 271: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
134872{
134873  yymsp[-7].minor.yy285 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy285, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243);
134874}
134875        break;
134876      default:
134877      /* (272) input ::= cmdlist */ yytestcase(yyruleno==272);
134878      /* (273) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==273);
134879      /* (274) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=274);
134880      /* (275) ecmd ::= SEMI */ yytestcase(yyruleno==275);
134881      /* (276) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==276);
134882      /* (277) explain ::= */ yytestcase(yyruleno==277);
134883      /* (278) trans_opt ::= */ yytestcase(yyruleno==278);
134884      /* (279) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==279);
134885      /* (280) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==280);
134886      /* (281) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==281);
134887      /* (282) savepoint_opt ::= */ yytestcase(yyruleno==282);
134888      /* (283) cmd ::= create_table create_table_args */ yytestcase(yyruleno==283);
134889      /* (284) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==284);
134890      /* (285) columnlist ::= columnname carglist */ yytestcase(yyruleno==285);
134891      /* (286) nm ::= ID|INDEXED */ yytestcase(yyruleno==286);
134892      /* (287) nm ::= STRING */ yytestcase(yyruleno==287);
134893      /* (288) nm ::= JOIN_KW */ yytestcase(yyruleno==288);
134894      /* (289) typetoken ::= typename */ yytestcase(yyruleno==289);
134895      /* (290) typename ::= ID|STRING */ yytestcase(yyruleno==290);
134896      /* (291) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=291);
134897      /* (292) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=292);
134898      /* (293) carglist ::= carglist ccons */ yytestcase(yyruleno==293);
134899      /* (294) carglist ::= */ yytestcase(yyruleno==294);
134900      /* (295) ccons ::= NULL onconf */ yytestcase(yyruleno==295);
134901      /* (296) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==296);
134902      /* (297) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==297);
134903      /* (298) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=298);
134904      /* (299) tconscomma ::= */ yytestcase(yyruleno==299);
134905      /* (300) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=300);
134906      /* (301) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=301);
134907      /* (302) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=302);
134908      /* (303) oneselect ::= values */ yytestcase(yyruleno==303);
134909      /* (304) sclp ::= selcollist COMMA */ yytestcase(yyruleno==304);
134910      /* (305) as ::= ID|STRING */ yytestcase(yyruleno==305);
134911      /* (306) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=306);
134912      /* (307) exprlist ::= nexprlist */ yytestcase(yyruleno==307);
134913      /* (308) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=308);
134914      /* (309) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=309);
134915      /* (310) nmnum ::= ON */ yytestcase(yyruleno==310);
134916      /* (311) nmnum ::= DELETE */ yytestcase(yyruleno==311);
134917      /* (312) nmnum ::= DEFAULT */ yytestcase(yyruleno==312);
134918      /* (313) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==313);
134919      /* (314) foreach_clause ::= */ yytestcase(yyruleno==314);
134920      /* (315) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==315);
134921      /* (316) trnm ::= nm */ yytestcase(yyruleno==316);
134922      /* (317) tridxby ::= */ yytestcase(yyruleno==317);
134923      /* (318) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==318);
134924      /* (319) database_kw_opt ::= */ yytestcase(yyruleno==319);
134925      /* (320) kwcolumn_opt ::= */ yytestcase(yyruleno==320);
134926      /* (321) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==321);
134927      /* (322) vtabarglist ::= vtabarg */ yytestcase(yyruleno==322);
134928      /* (323) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==323);
134929      /* (324) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==324);
134930      /* (325) anylist ::= */ yytestcase(yyruleno==325);
134931      /* (326) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==326);
134932      /* (327) anylist ::= anylist ANY */ yytestcase(yyruleno==327);
134933        break;
134934/********** End reduce actions ************************************************/
134935  };
134936  assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
134937  yygoto = yyRuleInfo[yyruleno].lhs;
134938  yysize = yyRuleInfo[yyruleno].nrhs;
134939  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
134940  if( yyact <= YY_MAX_SHIFTREDUCE ){
134941    if( yyact>YY_MAX_SHIFT ){
134942      yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
134943    }
134944    yymsp -= yysize-1;
134945    yypParser->yytos = yymsp;
134946    yymsp->stateno = (YYACTIONTYPE)yyact;
134947    yymsp->major = (YYCODETYPE)yygoto;
134948    yyTraceShift(yypParser, yyact);
134949  }else{
134950    assert( yyact == YY_ACCEPT_ACTION );
134951    yypParser->yytos -= yysize;
134952    yy_accept(yypParser);
134953  }
134954}
134955
134956/*
134957** The following code executes when the parse fails
134958*/
134959#ifndef YYNOERRORRECOVERY
134960static void yy_parse_failed(
134961  yyParser *yypParser           /* The parser */
134962){
134963  sqlite3ParserARG_FETCH;
134964#ifndef NDEBUG
134965  if( yyTraceFILE ){
134966    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
134967  }
134968#endif
134969  while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
134970  /* Here code is inserted which will be executed whenever the
134971  ** parser fails */
134972/************ Begin %parse_failure code ***************************************/
134973/************ End %parse_failure code *****************************************/
134974  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
134975}
134976#endif /* YYNOERRORRECOVERY */
134977
134978/*
134979** The following code executes when a syntax error first occurs.
134980*/
134981static void yy_syntax_error(
134982  yyParser *yypParser,           /* The parser */
134983  int yymajor,                   /* The major type of the error token */
134984  sqlite3ParserTOKENTYPE yyminor         /* The minor type of the error token */
134985){
134986  sqlite3ParserARG_FETCH;
134987#define TOKEN yyminor
134988/************ Begin %syntax_error code ****************************************/
134989
134990  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
134991  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
134992  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
134993/************ End %syntax_error code ******************************************/
134994  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
134995}
134996
134997/*
134998** The following is executed when the parser accepts
134999*/
135000static void yy_accept(
135001  yyParser *yypParser           /* The parser */
135002){
135003  sqlite3ParserARG_FETCH;
135004#ifndef NDEBUG
135005  if( yyTraceFILE ){
135006    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
135007  }
135008#endif
135009#ifndef YYNOERRORRECOVERY
135010  yypParser->yyerrcnt = -1;
135011#endif
135012  assert( yypParser->yytos==yypParser->yystack );
135013  /* Here code is inserted which will be executed whenever the
135014  ** parser accepts */
135015/*********** Begin %parse_accept code *****************************************/
135016/*********** End %parse_accept code *******************************************/
135017  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
135018}
135019
135020/* The main parser program.
135021** The first argument is a pointer to a structure obtained from
135022** "sqlite3ParserAlloc" which describes the current state of the parser.
135023** The second argument is the major token number.  The third is
135024** the minor token.  The fourth optional argument is whatever the
135025** user wants (and specified in the grammar) and is available for
135026** use by the action routines.
135027**
135028** Inputs:
135029** <ul>
135030** <li> A pointer to the parser (an opaque structure.)
135031** <li> The major token number.
135032** <li> The minor token number.
135033** <li> An option argument of a grammar-specified type.
135034** </ul>
135035**
135036** Outputs:
135037** None.
135038*/
135039SQLITE_PRIVATE void sqlite3Parser(
135040  void *yyp,                   /* The parser */
135041  int yymajor,                 /* The major token code number */
135042  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
135043  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
135044){
135045  YYMINORTYPE yyminorunion;
135046  unsigned int yyact;   /* The parser action. */
135047#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
135048  int yyendofinput;     /* True if we are at the end of input */
135049#endif
135050#ifdef YYERRORSYMBOL
135051  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
135052#endif
135053  yyParser *yypParser;  /* The parser */
135054
135055  yypParser = (yyParser*)yyp;
135056  assert( yypParser->yytos!=0 );
135057#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
135058  yyendofinput = (yymajor==0);
135059#endif
135060  sqlite3ParserARG_STORE;
135061
135062#ifndef NDEBUG
135063  if( yyTraceFILE ){
135064    fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]);
135065  }
135066#endif
135067
135068  do{
135069    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
135070    if( yyact <= YY_MAX_SHIFTREDUCE ){
135071      yy_shift(yypParser,yyact,yymajor,yyminor);
135072#ifndef YYNOERRORRECOVERY
135073      yypParser->yyerrcnt--;
135074#endif
135075      yymajor = YYNOCODE;
135076    }else if( yyact <= YY_MAX_REDUCE ){
135077      yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
135078    }else{
135079      assert( yyact == YY_ERROR_ACTION );
135080      yyminorunion.yy0 = yyminor;
135081#ifdef YYERRORSYMBOL
135082      int yymx;
135083#endif
135084#ifndef NDEBUG
135085      if( yyTraceFILE ){
135086        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
135087      }
135088#endif
135089#ifdef YYERRORSYMBOL
135090      /* A syntax error has occurred.
135091      ** The response to an error depends upon whether or not the
135092      ** grammar defines an error token "ERROR".
135093      **
135094      ** This is what we do if the grammar does define ERROR:
135095      **
135096      **  * Call the %syntax_error function.
135097      **
135098      **  * Begin popping the stack until we enter a state where
135099      **    it is legal to shift the error symbol, then shift
135100      **    the error symbol.
135101      **
135102      **  * Set the error count to three.
135103      **
135104      **  * Begin accepting and shifting new tokens.  No new error
135105      **    processing will occur until three tokens have been
135106      **    shifted successfully.
135107      **
135108      */
135109      if( yypParser->yyerrcnt<0 ){
135110        yy_syntax_error(yypParser,yymajor,yyminor);
135111      }
135112      yymx = yypParser->yytos->major;
135113      if( yymx==YYERRORSYMBOL || yyerrorhit ){
135114#ifndef NDEBUG
135115        if( yyTraceFILE ){
135116          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
135117             yyTracePrompt,yyTokenName[yymajor]);
135118        }
135119#endif
135120        yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
135121        yymajor = YYNOCODE;
135122      }else{
135123        while( yypParser->yytos >= &yypParser->yystack
135124            && yymx != YYERRORSYMBOL
135125            && (yyact = yy_find_reduce_action(
135126                        yypParser->yytos->stateno,
135127                        YYERRORSYMBOL)) >= YY_MIN_REDUCE
135128        ){
135129          yy_pop_parser_stack(yypParser);
135130        }
135131        if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
135132          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
135133          yy_parse_failed(yypParser);
135134#ifndef YYNOERRORRECOVERY
135135          yypParser->yyerrcnt = -1;
135136#endif
135137          yymajor = YYNOCODE;
135138        }else if( yymx!=YYERRORSYMBOL ){
135139          yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
135140        }
135141      }
135142      yypParser->yyerrcnt = 3;
135143      yyerrorhit = 1;
135144#elif defined(YYNOERRORRECOVERY)
135145      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
135146      ** do any kind of error recovery.  Instead, simply invoke the syntax
135147      ** error routine and continue going as if nothing had happened.
135148      **
135149      ** Applications can set this macro (for example inside %include) if
135150      ** they intend to abandon the parse upon the first syntax error seen.
135151      */
135152      yy_syntax_error(yypParser,yymajor, yyminor);
135153      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
135154      yymajor = YYNOCODE;
135155
135156#else  /* YYERRORSYMBOL is not defined */
135157      /* This is what we do if the grammar does not define ERROR:
135158      **
135159      **  * Report an error message, and throw away the input token.
135160      **
135161      **  * If the input token is $, then fail the parse.
135162      **
135163      ** As before, subsequent error messages are suppressed until
135164      ** three input tokens have been successfully shifted.
135165      */
135166      if( yypParser->yyerrcnt<=0 ){
135167        yy_syntax_error(yypParser,yymajor, yyminor);
135168      }
135169      yypParser->yyerrcnt = 3;
135170      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
135171      if( yyendofinput ){
135172        yy_parse_failed(yypParser);
135173#ifndef YYNOERRORRECOVERY
135174        yypParser->yyerrcnt = -1;
135175#endif
135176      }
135177      yymajor = YYNOCODE;
135178#endif
135179    }
135180  }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack );
135181#ifndef NDEBUG
135182  if( yyTraceFILE ){
135183    yyStackEntry *i;
135184    char cDiv = '[';
135185    fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
135186    for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
135187      fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
135188      cDiv = ' ';
135189    }
135190    fprintf(yyTraceFILE,"]\n");
135191  }
135192#endif
135193  return;
135194}
135195
135196/************** End of parse.c ***********************************************/
135197/************** Begin file tokenize.c ****************************************/
135198/*
135199** 2001 September 15
135200**
135201** The author disclaims copyright to this source code.  In place of
135202** a legal notice, here is a blessing:
135203**
135204**    May you do good and not evil.
135205**    May you find forgiveness for yourself and forgive others.
135206**    May you share freely, never taking more than you give.
135207**
135208*************************************************************************
135209** An tokenizer for SQL
135210**
135211** This file contains C code that splits an SQL input string up into
135212** individual tokens and sends those tokens one-by-one over to the
135213** parser for analysis.
135214*/
135215/* #include "sqliteInt.h" */
135216/* #include <stdlib.h> */
135217
135218/* Character classes for tokenizing
135219**
135220** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
135221** using a lookup table, whereas a switch() directly on c uses a binary search.
135222** The lookup table is much faster.  To maximize speed, and to ensure that
135223** a lookup table is used, all of the classes need to be small integers and
135224** all of them need to be used within the switch.
135225*/
135226#define CC_X          0    /* The letter 'x', or start of BLOB literal */
135227#define CC_KYWD       1    /* Alphabetics or '_'.  Usable in a keyword */
135228#define CC_ID         2    /* unicode characters usable in IDs */
135229#define CC_DIGIT      3    /* Digits */
135230#define CC_DOLLAR     4    /* '$' */
135231#define CC_VARALPHA   5    /* '@', '#', ':'.  Alphabetic SQL variables */
135232#define CC_VARNUM     6    /* '?'.  Numeric SQL variables */
135233#define CC_SPACE      7    /* Space characters */
135234#define CC_QUOTE      8    /* '"', '\'', or '`'.  String literals, quoted ids */
135235#define CC_QUOTE2     9    /* '['.   [...] style quoted ids */
135236#define CC_PIPE      10    /* '|'.   Bitwise OR or concatenate */
135237#define CC_MINUS     11    /* '-'.  Minus or SQL-style comment */
135238#define CC_LT        12    /* '<'.  Part of < or <= or <> */
135239#define CC_GT        13    /* '>'.  Part of > or >= */
135240#define CC_EQ        14    /* '='.  Part of = or == */
135241#define CC_BANG      15    /* '!'.  Part of != */
135242#define CC_SLASH     16    /* '/'.  / or c-style comment */
135243#define CC_LP        17    /* '(' */
135244#define CC_RP        18    /* ')' */
135245#define CC_SEMI      19    /* ';' */
135246#define CC_PLUS      20    /* '+' */
135247#define CC_STAR      21    /* '*' */
135248#define CC_PERCENT   22    /* '%' */
135249#define CC_COMMA     23    /* ',' */
135250#define CC_AND       24    /* '&' */
135251#define CC_TILDA     25    /* '~' */
135252#define CC_DOT       26    /* '.' */
135253#define CC_ILLEGAL   27    /* Illegal character */
135254
135255static const unsigned char aiClass[] = {
135256#ifdef SQLITE_ASCII
135257/*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
135258/* 0x */   27, 27, 27, 27, 27, 27, 27, 27, 27,  7,  7, 27,  7,  7, 27, 27,
135259/* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
135260/* 2x */    7, 15,  8,  5,  4, 22, 24,  8, 17, 18, 21, 20, 23, 11, 26, 16,
135261/* 3x */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  5, 19, 12, 14, 13,  6,
135262/* 4x */    5,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
135263/* 5x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  9, 27, 27, 27,  1,
135264/* 6x */    8,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
135265/* 7x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1, 27, 10, 27, 25, 27,
135266/* 8x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135267/* 9x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135268/* Ax */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135269/* Bx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135270/* Cx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135271/* Dx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135272/* Ex */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135273/* Fx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2
135274#endif
135275#ifdef SQLITE_EBCDIC
135276/*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
135277/* 0x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27,  7,  7, 27, 27,
135278/* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
135279/* 2x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
135280/* 3x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
135281/* 4x */    7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 12, 17, 20, 10,
135282/* 5x */   24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15,  4, 21, 18, 19, 27,
135283/* 6x */   11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22,  1, 13,  7,
135284/* 7x */   27, 27, 27, 27, 27, 27, 27, 27, 27,  8,  5,  5,  5,  8, 14,  8,
135285/* 8x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
135286/* 9x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
135287/* 9x */   25,  1,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,
135288/* Bx */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  9, 27, 27, 27, 27, 27,
135289/* Cx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
135290/* Dx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
135291/* Ex */   27, 27,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,
135292/* Fx */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3, 27, 27, 27, 27, 27, 27,
135293#endif
135294};
135295
135296/*
135297** The charMap() macro maps alphabetic characters (only) into their
135298** lower-case ASCII equivalent.  On ASCII machines, this is just
135299** an upper-to-lower case map.  On EBCDIC machines we also need
135300** to adjust the encoding.  The mapping is only valid for alphabetics
135301** which are the only characters for which this feature is used.
135302**
135303** Used by keywordhash.h
135304*/
135305#ifdef SQLITE_ASCII
135306# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
135307#endif
135308#ifdef SQLITE_EBCDIC
135309# define charMap(X) ebcdicToAscii[(unsigned char)X]
135310const unsigned char ebcdicToAscii[] = {
135311/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
135312   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
135313   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
135314   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
135315   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
135316   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
135317   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
135318   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
135319   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
135320   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
135321   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
135322   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
135323   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
135324   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
135325   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
135326   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
135327   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
135328};
135329#endif
135330
135331/*
135332** The sqlite3KeywordCode function looks up an identifier to determine if
135333** it is a keyword.  If it is a keyword, the token code of that keyword is
135334** returned.  If the input is not a keyword, TK_ID is returned.
135335**
135336** The implementation of this routine was generated by a program,
135337** mkkeywordhash.c, located in the tool subdirectory of the distribution.
135338** The output of the mkkeywordhash.c program is written into a file
135339** named keywordhash.h and then included into this source file by
135340** the #include below.
135341*/
135342/************** Include keywordhash.h in the middle of tokenize.c ************/
135343/************** Begin file keywordhash.h *************************************/
135344/***** This file contains automatically generated code ******
135345**
135346** The code in this file has been automatically generated by
135347**
135348**   sqlite/tool/mkkeywordhash.c
135349**
135350** The code in this file implements a function that determines whether
135351** or not a given identifier is really an SQL keyword.  The same thing
135352** might be implemented more directly using a hand-written hash table.
135353** But by using this automatically generated code, the size of the code
135354** is substantially reduced.  This is important for embedded applications
135355** on platforms with limited memory.
135356*/
135357/* Hash score: 182 */
135358static int keywordCode(const char *z, int n, int *pType){
135359  /* zText[] encodes 834 bytes of keywords in 554 bytes */
135360  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
135361  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
135362  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
135363  /*   UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE         */
135364  /*   BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH     */
135365  /*   IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN     */
135366  /*   WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT         */
135367  /*   CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL        */
135368  /*   FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING        */
135369  /*   VACUUMVIEWINITIALLY                                                */
135370  static const char zText[553] = {
135371    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
135372    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
135373    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
135374    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
135375    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
135376    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
135377    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
135378    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
135379    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
135380    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
135381    'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
135382    'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
135383    'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
135384    'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
135385    'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
135386    'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
135387    'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
135388    'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
135389    'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
135390    'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
135391    'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
135392    'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
135393    'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
135394    'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
135395    'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
135396    'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
135397    'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
135398    'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
135399    'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
135400    'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
135401    'V','I','E','W','I','N','I','T','I','A','L','L','Y',
135402  };
135403  static const unsigned char aHash[127] = {
135404      76, 105, 117,  74,   0,  45,   0,   0,  82,   0,  77,   0,   0,
135405      42,  12,  78,  15,   0, 116,  85,  54, 112,   0,  19,   0,   0,
135406     121,   0, 119, 115,   0,  22,  93,   0,   9,   0,   0,  70,  71,
135407       0,  69,   6,   0,  48,  90, 102,   0, 118, 101,   0,   0,  44,
135408       0, 103,  24,   0,  17,   0, 122,  53,  23,   0,   5, 110,  25,
135409      96,   0,   0, 124, 106,  60, 123,  57,  28,  55,   0,  91,   0,
135410     100,  26,   0,  99,   0,   0,   0,  95,  92,  97,  88, 109,  14,
135411      39, 108,   0,  81,   0,  18,  89, 111,  32,   0, 120,  80, 113,
135412      62,  46,  84,   0,   0,  94,  40,  59, 114,   0,  36,   0,   0,
135413      29,   0,  86,  63,  64,   0,  20,  61,   0,  56,
135414  };
135415  static const unsigned char aNext[124] = {
135416       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
135417       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
135418       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
135419       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,   0,   0,  50,
135420       0,  43,   3,  47,   0,   0,   0,   0,  30,   0,  58,   0,  38,
135421       0,   0,   0,   1,  66,   0,   0,  67,   0,  41,   0,   0,   0,
135422       0,   0,   0,  49,  65,   0,   0,   0,   0,  31,  52,  16,  34,
135423      10,   0,   0,   0,   0,   0,   0,   0,  11,  72,  79,   0,   8,
135424       0, 104,  98,   0, 107,   0,  87,   0,  75,  51,   0,  27,  37,
135425      73,  83,   0,  35,  68,   0,   0,
135426  };
135427  static const unsigned char aLen[124] = {
135428       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
135429       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
135430      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
135431       4,   6,   2,   3,   9,   4,   2,   6,   5,   7,   4,   5,   7,
135432       6,   6,   5,   6,   5,   5,   9,   7,   7,   3,   2,   4,   4,
135433       7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,   5,   4,
135434       7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
135435      13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
135436       2,   4,   4,   4,   4,   4,   2,   2,   6,   5,   8,   5,   8,
135437       3,   5,   5,   6,   4,   9,   3,
135438  };
135439  static const unsigned short int aOffset[124] = {
135440       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
135441      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
135442      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
135443     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
135444     199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
135445     250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
135446     320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
135447     387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
135448     460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
135449     521, 524, 529, 534, 540, 544, 549,
135450  };
135451  static const unsigned char aCode[124] = {
135452    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
135453    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
135454    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
135455    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
135456    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
135457    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
135458    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
135459    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
135460    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
135461    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,
135462    TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_GROUP,
135463    TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RECURSIVE,  TK_BETWEEN,
135464    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,
135465    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,
135466    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,
135467    TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,
135468    TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,
135469    TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    TK_AND,
135470    TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,
135471    TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,
135472    TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,
135473    TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,
135474    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      TK_RESTRICT,
135475    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_UNION,      TK_USING,
135476    TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  TK_ALL,
135477  };
135478  int i, j;
135479  const char *zKW;
135480  if( n>=2 ){
135481    i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
135482    for(i=((int)aHash[i])-1; i>=0; i=((int)aNext[i])-1){
135483      if( aLen[i]!=n ) continue;
135484      j = 0;
135485      zKW = &zText[aOffset[i]];
135486#ifdef SQLITE_ASCII
135487      while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
135488#endif
135489#ifdef SQLITE_EBCDIC
135490      while( j<n && toupper(z[j])==zKW[j] ){ j++; }
135491#endif
135492      if( j<n ) continue;
135493      testcase( i==0 ); /* REINDEX */
135494      testcase( i==1 ); /* INDEXED */
135495      testcase( i==2 ); /* INDEX */
135496      testcase( i==3 ); /* DESC */
135497      testcase( i==4 ); /* ESCAPE */
135498      testcase( i==5 ); /* EACH */
135499      testcase( i==6 ); /* CHECK */
135500      testcase( i==7 ); /* KEY */
135501      testcase( i==8 ); /* BEFORE */
135502      testcase( i==9 ); /* FOREIGN */
135503      testcase( i==10 ); /* FOR */
135504      testcase( i==11 ); /* IGNORE */
135505      testcase( i==12 ); /* REGEXP */
135506      testcase( i==13 ); /* EXPLAIN */
135507      testcase( i==14 ); /* INSTEAD */
135508      testcase( i==15 ); /* ADD */
135509      testcase( i==16 ); /* DATABASE */
135510      testcase( i==17 ); /* AS */
135511      testcase( i==18 ); /* SELECT */
135512      testcase( i==19 ); /* TABLE */
135513      testcase( i==20 ); /* LEFT */
135514      testcase( i==21 ); /* THEN */
135515      testcase( i==22 ); /* END */
135516      testcase( i==23 ); /* DEFERRABLE */
135517      testcase( i==24 ); /* ELSE */
135518      testcase( i==25 ); /* EXCEPT */
135519      testcase( i==26 ); /* TRANSACTION */
135520      testcase( i==27 ); /* ACTION */
135521      testcase( i==28 ); /* ON */
135522      testcase( i==29 ); /* NATURAL */
135523      testcase( i==30 ); /* ALTER */
135524      testcase( i==31 ); /* RAISE */
135525      testcase( i==32 ); /* EXCLUSIVE */
135526      testcase( i==33 ); /* EXISTS */
135527      testcase( i==34 ); /* SAVEPOINT */
135528      testcase( i==35 ); /* INTERSECT */
135529      testcase( i==36 ); /* TRIGGER */
135530      testcase( i==37 ); /* REFERENCES */
135531      testcase( i==38 ); /* CONSTRAINT */
135532      testcase( i==39 ); /* INTO */
135533      testcase( i==40 ); /* OFFSET */
135534      testcase( i==41 ); /* OF */
135535      testcase( i==42 ); /* SET */
135536      testcase( i==43 ); /* TEMPORARY */
135537      testcase( i==44 ); /* TEMP */
135538      testcase( i==45 ); /* OR */
135539      testcase( i==46 ); /* UNIQUE */
135540      testcase( i==47 ); /* QUERY */
135541      testcase( i==48 ); /* WITHOUT */
135542      testcase( i==49 ); /* WITH */
135543      testcase( i==50 ); /* OUTER */
135544      testcase( i==51 ); /* RELEASE */
135545      testcase( i==52 ); /* ATTACH */
135546      testcase( i==53 ); /* HAVING */
135547      testcase( i==54 ); /* GROUP */
135548      testcase( i==55 ); /* UPDATE */
135549      testcase( i==56 ); /* BEGIN */
135550      testcase( i==57 ); /* INNER */
135551      testcase( i==58 ); /* RECURSIVE */
135552      testcase( i==59 ); /* BETWEEN */
135553      testcase( i==60 ); /* NOTNULL */
135554      testcase( i==61 ); /* NOT */
135555      testcase( i==62 ); /* NO */
135556      testcase( i==63 ); /* NULL */
135557      testcase( i==64 ); /* LIKE */
135558      testcase( i==65 ); /* CASCADE */
135559      testcase( i==66 ); /* ASC */
135560      testcase( i==67 ); /* DELETE */
135561      testcase( i==68 ); /* CASE */
135562      testcase( i==69 ); /* COLLATE */
135563      testcase( i==70 ); /* CREATE */
135564      testcase( i==71 ); /* CURRENT_DATE */
135565      testcase( i==72 ); /* DETACH */
135566      testcase( i==73 ); /* IMMEDIATE */
135567      testcase( i==74 ); /* JOIN */
135568      testcase( i==75 ); /* INSERT */
135569      testcase( i==76 ); /* MATCH */
135570      testcase( i==77 ); /* PLAN */
135571      testcase( i==78 ); /* ANALYZE */
135572      testcase( i==79 ); /* PRAGMA */
135573      testcase( i==80 ); /* ABORT */
135574      testcase( i==81 ); /* VALUES */
135575      testcase( i==82 ); /* VIRTUAL */
135576      testcase( i==83 ); /* LIMIT */
135577      testcase( i==84 ); /* WHEN */
135578      testcase( i==85 ); /* WHERE */
135579      testcase( i==86 ); /* RENAME */
135580      testcase( i==87 ); /* AFTER */
135581      testcase( i==88 ); /* REPLACE */
135582      testcase( i==89 ); /* AND */
135583      testcase( i==90 ); /* DEFAULT */
135584      testcase( i==91 ); /* AUTOINCREMENT */
135585      testcase( i==92 ); /* TO */
135586      testcase( i==93 ); /* IN */
135587      testcase( i==94 ); /* CAST */
135588      testcase( i==95 ); /* COLUMN */
135589      testcase( i==96 ); /* COMMIT */
135590      testcase( i==97 ); /* CONFLICT */
135591      testcase( i==98 ); /* CROSS */
135592      testcase( i==99 ); /* CURRENT_TIMESTAMP */
135593      testcase( i==100 ); /* CURRENT_TIME */
135594      testcase( i==101 ); /* PRIMARY */
135595      testcase( i==102 ); /* DEFERRED */
135596      testcase( i==103 ); /* DISTINCT */
135597      testcase( i==104 ); /* IS */
135598      testcase( i==105 ); /* DROP */
135599      testcase( i==106 ); /* FAIL */
135600      testcase( i==107 ); /* FROM */
135601      testcase( i==108 ); /* FULL */
135602      testcase( i==109 ); /* GLOB */
135603      testcase( i==110 ); /* BY */
135604      testcase( i==111 ); /* IF */
135605      testcase( i==112 ); /* ISNULL */
135606      testcase( i==113 ); /* ORDER */
135607      testcase( i==114 ); /* RESTRICT */
135608      testcase( i==115 ); /* RIGHT */
135609      testcase( i==116 ); /* ROLLBACK */
135610      testcase( i==117 ); /* ROW */
135611      testcase( i==118 ); /* UNION */
135612      testcase( i==119 ); /* USING */
135613      testcase( i==120 ); /* VACUUM */
135614      testcase( i==121 ); /* VIEW */
135615      testcase( i==122 ); /* INITIALLY */
135616      testcase( i==123 ); /* ALL */
135617      *pType = aCode[i];
135618      break;
135619    }
135620  }
135621  return n;
135622}
135623SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
135624  int id = TK_ID;
135625  keywordCode((char*)z, n, &id);
135626  return id;
135627}
135628#define SQLITE_N_KEYWORD 124
135629
135630/************** End of keywordhash.h *****************************************/
135631/************** Continuing where we left off in tokenize.c *******************/
135632
135633
135634/*
135635** If X is a character that can be used in an identifier then
135636** IdChar(X) will be true.  Otherwise it is false.
135637**
135638** For ASCII, any character with the high-order bit set is
135639** allowed in an identifier.  For 7-bit characters,
135640** sqlite3IsIdChar[X] must be 1.
135641**
135642** For EBCDIC, the rules are more complex but have the same
135643** end result.
135644**
135645** Ticket #1066.  the SQL standard does not allow '$' in the
135646** middle of identifiers.  But many SQL implementations do.
135647** SQLite will allow '$' in identifiers for compatibility.
135648** But the feature is undocumented.
135649*/
135650#ifdef SQLITE_ASCII
135651#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
135652#endif
135653#ifdef SQLITE_EBCDIC
135654SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
135655/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
135656    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
135657    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
135658    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
135659    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
135660    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
135661    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
135662    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
135663    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
135664    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
135665    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
135666    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
135667    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
135668};
135669#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
135670#endif
135671
135672/* Make the IdChar function accessible from ctime.c */
135673#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
135674SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
135675#endif
135676
135677
135678/*
135679** Return the length (in bytes) of the token that begins at z[0].
135680** Store the token type in *tokenType before returning.
135681*/
135682SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
135683  int i, c;
135684  switch( aiClass[*z] ){  /* Switch on the character-class of the first byte
135685                          ** of the token. See the comment on the CC_ defines
135686                          ** above. */
135687    case CC_SPACE: {
135688      testcase( z[0]==' ' );
135689      testcase( z[0]=='\t' );
135690      testcase( z[0]=='\n' );
135691      testcase( z[0]=='\f' );
135692      testcase( z[0]=='\r' );
135693      for(i=1; sqlite3Isspace(z[i]); i++){}
135694      *tokenType = TK_SPACE;
135695      return i;
135696    }
135697    case CC_MINUS: {
135698      if( z[1]=='-' ){
135699        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
135700        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
135701        return i;
135702      }
135703      *tokenType = TK_MINUS;
135704      return 1;
135705    }
135706    case CC_LP: {
135707      *tokenType = TK_LP;
135708      return 1;
135709    }
135710    case CC_RP: {
135711      *tokenType = TK_RP;
135712      return 1;
135713    }
135714    case CC_SEMI: {
135715      *tokenType = TK_SEMI;
135716      return 1;
135717    }
135718    case CC_PLUS: {
135719      *tokenType = TK_PLUS;
135720      return 1;
135721    }
135722    case CC_STAR: {
135723      *tokenType = TK_STAR;
135724      return 1;
135725    }
135726    case CC_SLASH: {
135727      if( z[1]!='*' || z[2]==0 ){
135728        *tokenType = TK_SLASH;
135729        return 1;
135730      }
135731      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
135732      if( c ) i++;
135733      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
135734      return i;
135735    }
135736    case CC_PERCENT: {
135737      *tokenType = TK_REM;
135738      return 1;
135739    }
135740    case CC_EQ: {
135741      *tokenType = TK_EQ;
135742      return 1 + (z[1]=='=');
135743    }
135744    case CC_LT: {
135745      if( (c=z[1])=='=' ){
135746        *tokenType = TK_LE;
135747        return 2;
135748      }else if( c=='>' ){
135749        *tokenType = TK_NE;
135750        return 2;
135751      }else if( c=='<' ){
135752        *tokenType = TK_LSHIFT;
135753        return 2;
135754      }else{
135755        *tokenType = TK_LT;
135756        return 1;
135757      }
135758    }
135759    case CC_GT: {
135760      if( (c=z[1])=='=' ){
135761        *tokenType = TK_GE;
135762        return 2;
135763      }else if( c=='>' ){
135764        *tokenType = TK_RSHIFT;
135765        return 2;
135766      }else{
135767        *tokenType = TK_GT;
135768        return 1;
135769      }
135770    }
135771    case CC_BANG: {
135772      if( z[1]!='=' ){
135773        *tokenType = TK_ILLEGAL;
135774        return 1;
135775      }else{
135776        *tokenType = TK_NE;
135777        return 2;
135778      }
135779    }
135780    case CC_PIPE: {
135781      if( z[1]!='|' ){
135782        *tokenType = TK_BITOR;
135783        return 1;
135784      }else{
135785        *tokenType = TK_CONCAT;
135786        return 2;
135787      }
135788    }
135789    case CC_COMMA: {
135790      *tokenType = TK_COMMA;
135791      return 1;
135792    }
135793    case CC_AND: {
135794      *tokenType = TK_BITAND;
135795      return 1;
135796    }
135797    case CC_TILDA: {
135798      *tokenType = TK_BITNOT;
135799      return 1;
135800    }
135801    case CC_QUOTE: {
135802      int delim = z[0];
135803      testcase( delim=='`' );
135804      testcase( delim=='\'' );
135805      testcase( delim=='"' );
135806      for(i=1; (c=z[i])!=0; i++){
135807        if( c==delim ){
135808          if( z[i+1]==delim ){
135809            i++;
135810          }else{
135811            break;
135812          }
135813        }
135814      }
135815      if( c=='\'' ){
135816        *tokenType = TK_STRING;
135817        return i+1;
135818      }else if( c!=0 ){
135819        *tokenType = TK_ID;
135820        return i+1;
135821      }else{
135822        *tokenType = TK_ILLEGAL;
135823        return i;
135824      }
135825    }
135826    case CC_DOT: {
135827#ifndef SQLITE_OMIT_FLOATING_POINT
135828      if( !sqlite3Isdigit(z[1]) )
135829#endif
135830      {
135831        *tokenType = TK_DOT;
135832        return 1;
135833      }
135834      /* If the next character is a digit, this is a floating point
135835      ** number that begins with ".".  Fall thru into the next case */
135836    }
135837    case CC_DIGIT: {
135838      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
135839      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
135840      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
135841      testcase( z[0]=='9' );
135842      *tokenType = TK_INTEGER;
135843#ifndef SQLITE_OMIT_HEX_INTEGER
135844      if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
135845        for(i=3; sqlite3Isxdigit(z[i]); i++){}
135846        return i;
135847      }
135848#endif
135849      for(i=0; sqlite3Isdigit(z[i]); i++){}
135850#ifndef SQLITE_OMIT_FLOATING_POINT
135851      if( z[i]=='.' ){
135852        i++;
135853        while( sqlite3Isdigit(z[i]) ){ i++; }
135854        *tokenType = TK_FLOAT;
135855      }
135856      if( (z[i]=='e' || z[i]=='E') &&
135857           ( sqlite3Isdigit(z[i+1])
135858            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
135859           )
135860      ){
135861        i += 2;
135862        while( sqlite3Isdigit(z[i]) ){ i++; }
135863        *tokenType = TK_FLOAT;
135864      }
135865#endif
135866      while( IdChar(z[i]) ){
135867        *tokenType = TK_ILLEGAL;
135868        i++;
135869      }
135870      return i;
135871    }
135872    case CC_QUOTE2: {
135873      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
135874      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
135875      return i;
135876    }
135877    case CC_VARNUM: {
135878      *tokenType = TK_VARIABLE;
135879      for(i=1; sqlite3Isdigit(z[i]); i++){}
135880      return i;
135881    }
135882    case CC_DOLLAR:
135883    case CC_VARALPHA: {
135884      int n = 0;
135885      testcase( z[0]=='$' );  testcase( z[0]=='@' );
135886      testcase( z[0]==':' );  testcase( z[0]=='#' );
135887      *tokenType = TK_VARIABLE;
135888      for(i=1; (c=z[i])!=0; i++){
135889        if( IdChar(c) ){
135890          n++;
135891#ifndef SQLITE_OMIT_TCL_VARIABLE
135892        }else if( c=='(' && n>0 ){
135893          do{
135894            i++;
135895          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
135896          if( c==')' ){
135897            i++;
135898          }else{
135899            *tokenType = TK_ILLEGAL;
135900          }
135901          break;
135902        }else if( c==':' && z[i+1]==':' ){
135903          i++;
135904#endif
135905        }else{
135906          break;
135907        }
135908      }
135909      if( n==0 ) *tokenType = TK_ILLEGAL;
135910      return i;
135911    }
135912    case CC_KYWD: {
135913      for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
135914      if( IdChar(z[i]) ){
135915        /* This token started out using characters that can appear in keywords,
135916        ** but z[i] is a character not allowed within keywords, so this must
135917        ** be an identifier instead */
135918        i++;
135919        break;
135920      }
135921      *tokenType = TK_ID;
135922      return keywordCode((char*)z, i, tokenType);
135923    }
135924    case CC_X: {
135925#ifndef SQLITE_OMIT_BLOB_LITERAL
135926      testcase( z[0]=='x' ); testcase( z[0]=='X' );
135927      if( z[1]=='\'' ){
135928        *tokenType = TK_BLOB;
135929        for(i=2; sqlite3Isxdigit(z[i]); i++){}
135930        if( z[i]!='\'' || i%2 ){
135931          *tokenType = TK_ILLEGAL;
135932          while( z[i] && z[i]!='\'' ){ i++; }
135933        }
135934        if( z[i] ) i++;
135935        return i;
135936      }
135937#endif
135938      /* If it is not a BLOB literal, then it must be an ID, since no
135939      ** SQL keywords start with the letter 'x'.  Fall through */
135940    }
135941    case CC_ID: {
135942      i = 1;
135943      break;
135944    }
135945    default: {
135946      *tokenType = TK_ILLEGAL;
135947      return 1;
135948    }
135949  }
135950  while( IdChar(z[i]) ){ i++; }
135951  *tokenType = TK_ID;
135952  return i;
135953}
135954
135955/*
135956** Run the parser on the given SQL string.  The parser structure is
135957** passed in.  An SQLITE_ status code is returned.  If an error occurs
135958** then an and attempt is made to write an error message into
135959** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
135960** error message.
135961*/
135962SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
135963  int nErr = 0;                   /* Number of errors encountered */
135964  int i;                          /* Loop counter */
135965  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
135966  int tokenType;                  /* type of the next token */
135967  int lastTokenParsed = -1;       /* type of the previous token */
135968  sqlite3 *db = pParse->db;       /* The database connection */
135969  int mxSqlLen;                   /* Max length of an SQL string */
135970
135971  assert( zSql!=0 );
135972  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
135973  if( db->nVdbeActive==0 ){
135974    db->u1.isInterrupted = 0;
135975  }
135976  pParse->rc = SQLITE_OK;
135977  pParse->zTail = zSql;
135978  i = 0;
135979  assert( pzErrMsg!=0 );
135980  /* sqlite3ParserTrace(stdout, "parser: "); */
135981  pEngine = sqlite3ParserAlloc(sqlite3Malloc);
135982  if( pEngine==0 ){
135983    sqlite3OomFault(db);
135984    return SQLITE_NOMEM_BKPT;
135985  }
135986  assert( pParse->pNewTable==0 );
135987  assert( pParse->pNewTrigger==0 );
135988  assert( pParse->nVar==0 );
135989  assert( pParse->nzVar==0 );
135990  assert( pParse->azVar==0 );
135991  while( zSql[i]!=0 ){
135992    assert( i>=0 );
135993    pParse->sLastToken.z = &zSql[i];
135994    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
135995    i += pParse->sLastToken.n;
135996    if( i>mxSqlLen ){
135997      pParse->rc = SQLITE_TOOBIG;
135998      break;
135999    }
136000    if( tokenType>=TK_SPACE ){
136001      assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
136002      if( db->u1.isInterrupted ){
136003        pParse->rc = SQLITE_INTERRUPT;
136004        break;
136005      }
136006      if( tokenType==TK_ILLEGAL ){
136007        sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"",
136008                        &pParse->sLastToken);
136009        break;
136010      }
136011    }else{
136012      sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
136013      lastTokenParsed = tokenType;
136014      if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
136015    }
136016  }
136017  assert( nErr==0 );
136018  pParse->zTail = &zSql[i];
136019  if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
136020    assert( zSql[i]==0 );
136021    if( lastTokenParsed!=TK_SEMI ){
136022      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
136023    }
136024    if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
136025      sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
136026    }
136027  }
136028#ifdef YYTRACKMAXSTACKDEPTH
136029  sqlite3_mutex_enter(sqlite3MallocMutex());
136030  sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
136031      sqlite3ParserStackPeak(pEngine)
136032  );
136033  sqlite3_mutex_leave(sqlite3MallocMutex());
136034#endif /* YYDEBUG */
136035  sqlite3ParserFree(pEngine, sqlite3_free);
136036  if( db->mallocFailed ){
136037    pParse->rc = SQLITE_NOMEM_BKPT;
136038  }
136039  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
136040    pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
136041  }
136042  assert( pzErrMsg!=0 );
136043  if( pParse->zErrMsg ){
136044    *pzErrMsg = pParse->zErrMsg;
136045    sqlite3_log(pParse->rc, "%s", *pzErrMsg);
136046    pParse->zErrMsg = 0;
136047    nErr++;
136048  }
136049  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
136050    sqlite3VdbeDelete(pParse->pVdbe);
136051    pParse->pVdbe = 0;
136052  }
136053#ifndef SQLITE_OMIT_SHARED_CACHE
136054  if( pParse->nested==0 ){
136055    sqlite3DbFree(db, pParse->aTableLock);
136056    pParse->aTableLock = 0;
136057    pParse->nTableLock = 0;
136058  }
136059#endif
136060#ifndef SQLITE_OMIT_VIRTUALTABLE
136061  sqlite3_free(pParse->apVtabLock);
136062#endif
136063
136064  if( !IN_DECLARE_VTAB ){
136065    /* If the pParse->declareVtab flag is set, do not delete any table
136066    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
136067    ** will take responsibility for freeing the Table structure.
136068    */
136069    sqlite3DeleteTable(db, pParse->pNewTable);
136070  }
136071
136072  if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
136073  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
136074  for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
136075  sqlite3DbFree(db, pParse->azVar);
136076  while( pParse->pAinc ){
136077    AutoincInfo *p = pParse->pAinc;
136078    pParse->pAinc = p->pNext;
136079    sqlite3DbFree(db, p);
136080  }
136081  while( pParse->pZombieTab ){
136082    Table *p = pParse->pZombieTab;
136083    pParse->pZombieTab = p->pNextZombie;
136084    sqlite3DeleteTable(db, p);
136085  }
136086  assert( nErr==0 || pParse->rc!=SQLITE_OK );
136087  return nErr;
136088}
136089
136090/************** End of tokenize.c ********************************************/
136091/************** Begin file complete.c ****************************************/
136092/*
136093** 2001 September 15
136094**
136095** The author disclaims copyright to this source code.  In place of
136096** a legal notice, here is a blessing:
136097**
136098**    May you do good and not evil.
136099**    May you find forgiveness for yourself and forgive others.
136100**    May you share freely, never taking more than you give.
136101**
136102*************************************************************************
136103** An tokenizer for SQL
136104**
136105** This file contains C code that implements the sqlite3_complete() API.
136106** This code used to be part of the tokenizer.c source file.  But by
136107** separating it out, the code will be automatically omitted from
136108** static links that do not use it.
136109*/
136110/* #include "sqliteInt.h" */
136111#ifndef SQLITE_OMIT_COMPLETE
136112
136113/*
136114** This is defined in tokenize.c.  We just have to import the definition.
136115*/
136116#ifndef SQLITE_AMALGAMATION
136117#ifdef SQLITE_ASCII
136118#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
136119#endif
136120#ifdef SQLITE_EBCDIC
136121SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
136122#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
136123#endif
136124#endif /* SQLITE_AMALGAMATION */
136125
136126
136127/*
136128** Token types used by the sqlite3_complete() routine.  See the header
136129** comments on that procedure for additional information.
136130*/
136131#define tkSEMI    0
136132#define tkWS      1
136133#define tkOTHER   2
136134#ifndef SQLITE_OMIT_TRIGGER
136135#define tkEXPLAIN 3
136136#define tkCREATE  4
136137#define tkTEMP    5
136138#define tkTRIGGER 6
136139#define tkEND     7
136140#endif
136141
136142/*
136143** Return TRUE if the given SQL string ends in a semicolon.
136144**
136145** Special handling is require for CREATE TRIGGER statements.
136146** Whenever the CREATE TRIGGER keywords are seen, the statement
136147** must end with ";END;".
136148**
136149** This implementation uses a state machine with 8 states:
136150**
136151**   (0) INVALID   We have not yet seen a non-whitespace character.
136152**
136153**   (1) START     At the beginning or end of an SQL statement.  This routine
136154**                 returns 1 if it ends in the START state and 0 if it ends
136155**                 in any other state.
136156**
136157**   (2) NORMAL    We are in the middle of statement which ends with a single
136158**                 semicolon.
136159**
136160**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
136161**                 a statement.
136162**
136163**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
136164**                 statement, possibly preceded by EXPLAIN and/or followed by
136165**                 TEMP or TEMPORARY
136166**
136167**   (5) TRIGGER   We are in the middle of a trigger definition that must be
136168**                 ended by a semicolon, the keyword END, and another semicolon.
136169**
136170**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
136171**                 the end of a trigger definition.
136172**
136173**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
136174**                 of a trigger definition.
136175**
136176** Transitions between states above are determined by tokens extracted
136177** from the input.  The following tokens are significant:
136178**
136179**   (0) tkSEMI      A semicolon.
136180**   (1) tkWS        Whitespace.
136181**   (2) tkOTHER     Any other SQL token.
136182**   (3) tkEXPLAIN   The "explain" keyword.
136183**   (4) tkCREATE    The "create" keyword.
136184**   (5) tkTEMP      The "temp" or "temporary" keyword.
136185**   (6) tkTRIGGER   The "trigger" keyword.
136186**   (7) tkEND       The "end" keyword.
136187**
136188** Whitespace never causes a state transition and is always ignored.
136189** This means that a SQL string of all whitespace is invalid.
136190**
136191** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
136192** to recognize the end of a trigger can be omitted.  All we have to do
136193** is look for a semicolon that is not part of an string or comment.
136194*/
136195SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *zSql){
136196  u8 state = 0;   /* Current state, using numbers defined in header comment */
136197  u8 token;       /* Value of the next token */
136198
136199#ifndef SQLITE_OMIT_TRIGGER
136200  /* A complex statement machine used to detect the end of a CREATE TRIGGER
136201  ** statement.  This is the normal case.
136202  */
136203  static const u8 trans[8][8] = {
136204                     /* Token:                                                */
136205     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
136206     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
136207     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
136208     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
136209     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
136210     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
136211     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
136212     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
136213     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
136214  };
136215#else
136216  /* If triggers are not supported by this compile then the statement machine
136217  ** used to detect the end of a statement is much simpler
136218  */
136219  static const u8 trans[3][3] = {
136220                     /* Token:           */
136221     /* State:       **  SEMI  WS  OTHER */
136222     /* 0 INVALID: */ {    1,  0,     2, },
136223     /* 1   START: */ {    1,  1,     2, },
136224     /* 2  NORMAL: */ {    1,  2,     2, },
136225  };
136226#endif /* SQLITE_OMIT_TRIGGER */
136227
136228#ifdef SQLITE_ENABLE_API_ARMOR
136229  if( zSql==0 ){
136230    (void)SQLITE_MISUSE_BKPT;
136231    return 0;
136232  }
136233#endif
136234
136235  while( *zSql ){
136236    switch( *zSql ){
136237      case ';': {  /* A semicolon */
136238        token = tkSEMI;
136239        break;
136240      }
136241      case ' ':
136242      case '\r':
136243      case '\t':
136244      case '\n':
136245      case '\f': {  /* White space is ignored */
136246        token = tkWS;
136247        break;
136248      }
136249      case '/': {   /* C-style comments */
136250        if( zSql[1]!='*' ){
136251          token = tkOTHER;
136252          break;
136253        }
136254        zSql += 2;
136255        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
136256        if( zSql[0]==0 ) return 0;
136257        zSql++;
136258        token = tkWS;
136259        break;
136260      }
136261      case '-': {   /* SQL-style comments from "--" to end of line */
136262        if( zSql[1]!='-' ){
136263          token = tkOTHER;
136264          break;
136265        }
136266        while( *zSql && *zSql!='\n' ){ zSql++; }
136267        if( *zSql==0 ) return state==1;
136268        token = tkWS;
136269        break;
136270      }
136271      case '[': {   /* Microsoft-style identifiers in [...] */
136272        zSql++;
136273        while( *zSql && *zSql!=']' ){ zSql++; }
136274        if( *zSql==0 ) return 0;
136275        token = tkOTHER;
136276        break;
136277      }
136278      case '`':     /* Grave-accent quoted symbols used by MySQL */
136279      case '"':     /* single- and double-quoted strings */
136280      case '\'': {
136281        int c = *zSql;
136282        zSql++;
136283        while( *zSql && *zSql!=c ){ zSql++; }
136284        if( *zSql==0 ) return 0;
136285        token = tkOTHER;
136286        break;
136287      }
136288      default: {
136289#ifdef SQLITE_EBCDIC
136290        unsigned char c;
136291#endif
136292        if( IdChar((u8)*zSql) ){
136293          /* Keywords and unquoted identifiers */
136294          int nId;
136295          for(nId=1; IdChar(zSql[nId]); nId++){}
136296#ifdef SQLITE_OMIT_TRIGGER
136297          token = tkOTHER;
136298#else
136299          switch( *zSql ){
136300            case 'c': case 'C': {
136301              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
136302                token = tkCREATE;
136303              }else{
136304                token = tkOTHER;
136305              }
136306              break;
136307            }
136308            case 't': case 'T': {
136309              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
136310                token = tkTRIGGER;
136311              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
136312                token = tkTEMP;
136313              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
136314                token = tkTEMP;
136315              }else{
136316                token = tkOTHER;
136317              }
136318              break;
136319            }
136320            case 'e':  case 'E': {
136321              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
136322                token = tkEND;
136323              }else
136324#ifndef SQLITE_OMIT_EXPLAIN
136325              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
136326                token = tkEXPLAIN;
136327              }else
136328#endif
136329              {
136330                token = tkOTHER;
136331              }
136332              break;
136333            }
136334            default: {
136335              token = tkOTHER;
136336              break;
136337            }
136338          }
136339#endif /* SQLITE_OMIT_TRIGGER */
136340          zSql += nId-1;
136341        }else{
136342          /* Operators and special symbols */
136343          token = tkOTHER;
136344        }
136345        break;
136346      }
136347    }
136348    state = trans[state][token];
136349    zSql++;
136350  }
136351  return state==1;
136352}
136353
136354#ifndef SQLITE_OMIT_UTF16
136355/*
136356** This routine is the same as the sqlite3_complete() routine described
136357** above, except that the parameter is required to be UTF-16 encoded, not
136358** UTF-8.
136359*/
136360SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *zSql){
136361  sqlite3_value *pVal;
136362  char const *zSql8;
136363  int rc;
136364
136365#ifndef SQLITE_OMIT_AUTOINIT
136366  rc = sqlite3_initialize();
136367  if( rc ) return rc;
136368#endif
136369  pVal = sqlite3ValueNew(0);
136370  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
136371  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
136372  if( zSql8 ){
136373    rc = sqlite3_complete(zSql8);
136374  }else{
136375    rc = SQLITE_NOMEM_BKPT;
136376  }
136377  sqlite3ValueFree(pVal);
136378  return rc & 0xff;
136379}
136380#endif /* SQLITE_OMIT_UTF16 */
136381#endif /* SQLITE_OMIT_COMPLETE */
136382
136383/************** End of complete.c ********************************************/
136384/************** Begin file main.c ********************************************/
136385/*
136386** 2001 September 15
136387**
136388** The author disclaims copyright to this source code.  In place of
136389** a legal notice, here is a blessing:
136390**
136391**    May you do good and not evil.
136392**    May you find forgiveness for yourself and forgive others.
136393**    May you share freely, never taking more than you give.
136394**
136395*************************************************************************
136396** Main file for the SQLite library.  The routines in this file
136397** implement the programmer interface to the library.  Routines in
136398** other files are for internal use by SQLite and should not be
136399** accessed by users of the library.
136400*/
136401/* #include "sqliteInt.h" */
136402
136403#ifdef SQLITE_ENABLE_FTS3
136404/************** Include fts3.h in the middle of main.c ***********************/
136405/************** Begin file fts3.h ********************************************/
136406/*
136407** 2006 Oct 10
136408**
136409** The author disclaims copyright to this source code.  In place of
136410** a legal notice, here is a blessing:
136411**
136412**    May you do good and not evil.
136413**    May you find forgiveness for yourself and forgive others.
136414**    May you share freely, never taking more than you give.
136415**
136416******************************************************************************
136417**
136418** This header file is used by programs that want to link against the
136419** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
136420*/
136421/* #include "sqlite3.h" */
136422
136423#if 0
136424extern "C" {
136425#endif  /* __cplusplus */
136426
136427SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
136428
136429#if 0
136430}  /* extern "C" */
136431#endif  /* __cplusplus */
136432
136433/************** End of fts3.h ************************************************/
136434/************** Continuing where we left off in main.c ***********************/
136435#endif
136436#ifdef SQLITE_ENABLE_RTREE
136437/************** Include rtree.h in the middle of main.c **********************/
136438/************** Begin file rtree.h *******************************************/
136439/*
136440** 2008 May 26
136441**
136442** The author disclaims copyright to this source code.  In place of
136443** a legal notice, here is a blessing:
136444**
136445**    May you do good and not evil.
136446**    May you find forgiveness for yourself and forgive others.
136447**    May you share freely, never taking more than you give.
136448**
136449******************************************************************************
136450**
136451** This header file is used by programs that want to link against the
136452** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
136453*/
136454/* #include "sqlite3.h" */
136455
136456#if 0
136457extern "C" {
136458#endif  /* __cplusplus */
136459
136460SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
136461
136462#if 0
136463}  /* extern "C" */
136464#endif  /* __cplusplus */
136465
136466/************** End of rtree.h ***********************************************/
136467/************** Continuing where we left off in main.c ***********************/
136468#endif
136469#ifdef SQLITE_ENABLE_ICU
136470/************** Include sqliteicu.h in the middle of main.c ******************/
136471/************** Begin file sqliteicu.h ***************************************/
136472/*
136473** 2008 May 26
136474**
136475** The author disclaims copyright to this source code.  In place of
136476** a legal notice, here is a blessing:
136477**
136478**    May you do good and not evil.
136479**    May you find forgiveness for yourself and forgive others.
136480**    May you share freely, never taking more than you give.
136481**
136482******************************************************************************
136483**
136484** This header file is used by programs that want to link against the
136485** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
136486*/
136487/* #include "sqlite3.h" */
136488
136489#if 0
136490extern "C" {
136491#endif  /* __cplusplus */
136492
136493SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
136494
136495#if 0
136496}  /* extern "C" */
136497#endif  /* __cplusplus */
136498
136499
136500/************** End of sqliteicu.h *******************************************/
136501/************** Continuing where we left off in main.c ***********************/
136502#endif
136503#ifdef SQLITE_ENABLE_JSON1
136504SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
136505#endif
136506#ifdef SQLITE_ENABLE_FTS5
136507SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
136508#endif
136509
136510#ifndef SQLITE_AMALGAMATION
136511/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
136512** contains the text of SQLITE_VERSION macro.
136513*/
136514SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
136515#endif
136516
136517/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
136518** a pointer to the to the sqlite3_version[] string constant.
136519*/
136520SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void){ return sqlite3_version; }
136521
136522/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
136523** pointer to a string constant whose value is the same as the
136524** SQLITE_SOURCE_ID C preprocessor macro.
136525*/
136526SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
136527
136528/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
136529** returns an integer equal to SQLITE_VERSION_NUMBER.
136530*/
136531SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
136532
136533/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
136534** zero if and only if SQLite was compiled with mutexing code omitted due to
136535** the SQLITE_THREADSAFE compile-time option being set to 0.
136536*/
136537SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
136538
136539/*
136540** When compiling the test fixture or with debugging enabled (on Win32),
136541** this variable being set to non-zero will cause OSTRACE macros to emit
136542** extra diagnostic information.
136543*/
136544#ifdef SQLITE_HAVE_OS_TRACE
136545# ifndef SQLITE_DEBUG_OS_TRACE
136546#   define SQLITE_DEBUG_OS_TRACE 0
136547# endif
136548  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
136549#endif
136550
136551#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
136552/*
136553** If the following function pointer is not NULL and if
136554** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
136555** I/O active are written using this function.  These messages
136556** are intended for debugging activity only.
136557*/
136558SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
136559#endif
136560
136561/*
136562** If the following global variable points to a string which is the
136563** name of a directory, then that directory will be used to store
136564** temporary files.
136565**
136566** See also the "PRAGMA temp_store_directory" SQL command.
136567*/
136568SQLITE_API char *sqlite3_temp_directory = 0;
136569
136570/*
136571** If the following global variable points to a string which is the
136572** name of a directory, then that directory will be used to store
136573** all database files specified with a relative pathname.
136574**
136575** See also the "PRAGMA data_store_directory" SQL command.
136576*/
136577SQLITE_API char *sqlite3_data_directory = 0;
136578
136579/*
136580** Initialize SQLite.
136581**
136582** This routine must be called to initialize the memory allocation,
136583** VFS, and mutex subsystems prior to doing any serious work with
136584** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
136585** this routine will be called automatically by key routines such as
136586** sqlite3_open().
136587**
136588** This routine is a no-op except on its very first call for the process,
136589** or for the first call after a call to sqlite3_shutdown.
136590**
136591** The first thread to call this routine runs the initialization to
136592** completion.  If subsequent threads call this routine before the first
136593** thread has finished the initialization process, then the subsequent
136594** threads must block until the first thread finishes with the initialization.
136595**
136596** The first thread might call this routine recursively.  Recursive
136597** calls to this routine should not block, of course.  Otherwise the
136598** initialization process would never complete.
136599**
136600** Let X be the first thread to enter this routine.  Let Y be some other
136601** thread.  Then while the initial invocation of this routine by X is
136602** incomplete, it is required that:
136603**
136604**    *  Calls to this routine from Y must block until the outer-most
136605**       call by X completes.
136606**
136607**    *  Recursive calls to this routine from thread X return immediately
136608**       without blocking.
136609*/
136610SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void){
136611  MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
136612  int rc;                                      /* Result code */
136613#ifdef SQLITE_EXTRA_INIT
136614  int bRunExtraInit = 0;                       /* Extra initialization needed */
136615#endif
136616
136617#ifdef SQLITE_OMIT_WSD
136618  rc = sqlite3_wsd_init(4096, 24);
136619  if( rc!=SQLITE_OK ){
136620    return rc;
136621  }
136622#endif
136623
136624  /* If the following assert() fails on some obscure processor/compiler
136625  ** combination, the work-around is to set the correct pointer
136626  ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
136627  assert( SQLITE_PTRSIZE==sizeof(char*) );
136628
136629  /* If SQLite is already completely initialized, then this call
136630  ** to sqlite3_initialize() should be a no-op.  But the initialization
136631  ** must be complete.  So isInit must not be set until the very end
136632  ** of this routine.
136633  */
136634  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
136635
136636  /* Make sure the mutex subsystem is initialized.  If unable to
136637  ** initialize the mutex subsystem, return early with the error.
136638  ** If the system is so sick that we are unable to allocate a mutex,
136639  ** there is not much SQLite is going to be able to do.
136640  **
136641  ** The mutex subsystem must take care of serializing its own
136642  ** initialization.
136643  */
136644  rc = sqlite3MutexInit();
136645  if( rc ) return rc;
136646
136647  /* Initialize the malloc() system and the recursive pInitMutex mutex.
136648  ** This operation is protected by the STATIC_MASTER mutex.  Note that
136649  ** MutexAlloc() is called for a static mutex prior to initializing the
136650  ** malloc subsystem - this implies that the allocation of a static
136651  ** mutex must not require support from the malloc subsystem.
136652  */
136653  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
136654  sqlite3_mutex_enter(pMaster);
136655  sqlite3GlobalConfig.isMutexInit = 1;
136656  if( !sqlite3GlobalConfig.isMallocInit ){
136657    rc = sqlite3MallocInit();
136658  }
136659  if( rc==SQLITE_OK ){
136660    sqlite3GlobalConfig.isMallocInit = 1;
136661    if( !sqlite3GlobalConfig.pInitMutex ){
136662      sqlite3GlobalConfig.pInitMutex =
136663           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
136664      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
136665        rc = SQLITE_NOMEM_BKPT;
136666      }
136667    }
136668  }
136669  if( rc==SQLITE_OK ){
136670    sqlite3GlobalConfig.nRefInitMutex++;
136671  }
136672  sqlite3_mutex_leave(pMaster);
136673
136674  /* If rc is not SQLITE_OK at this point, then either the malloc
136675  ** subsystem could not be initialized or the system failed to allocate
136676  ** the pInitMutex mutex. Return an error in either case.  */
136677  if( rc!=SQLITE_OK ){
136678    return rc;
136679  }
136680
136681  /* Do the rest of the initialization under the recursive mutex so
136682  ** that we will be able to handle recursive calls into
136683  ** sqlite3_initialize().  The recursive calls normally come through
136684  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
136685  ** recursive calls might also be possible.
136686  **
136687  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
136688  ** to the xInit method, so the xInit method need not be threadsafe.
136689  **
136690  ** The following mutex is what serializes access to the appdef pcache xInit
136691  ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
136692  ** call to sqlite3PcacheInitialize().
136693  */
136694  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
136695  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
136696    sqlite3GlobalConfig.inProgress = 1;
136697#ifdef SQLITE_ENABLE_SQLLOG
136698    {
136699      extern void sqlite3_init_sqllog(void);
136700      sqlite3_init_sqllog();
136701    }
136702#endif
136703    memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
136704    sqlite3RegisterBuiltinFunctions();
136705    if( sqlite3GlobalConfig.isPCacheInit==0 ){
136706      rc = sqlite3PcacheInitialize();
136707    }
136708    if( rc==SQLITE_OK ){
136709      sqlite3GlobalConfig.isPCacheInit = 1;
136710      rc = sqlite3OsInit();
136711    }
136712    if( rc==SQLITE_OK ){
136713      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
136714          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
136715      sqlite3GlobalConfig.isInit = 1;
136716#ifdef SQLITE_EXTRA_INIT
136717      bRunExtraInit = 1;
136718#endif
136719    }
136720    sqlite3GlobalConfig.inProgress = 0;
136721  }
136722  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
136723
136724  /* Go back under the static mutex and clean up the recursive
136725  ** mutex to prevent a resource leak.
136726  */
136727  sqlite3_mutex_enter(pMaster);
136728  sqlite3GlobalConfig.nRefInitMutex--;
136729  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
136730    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
136731    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
136732    sqlite3GlobalConfig.pInitMutex = 0;
136733  }
136734  sqlite3_mutex_leave(pMaster);
136735
136736  /* The following is just a sanity check to make sure SQLite has
136737  ** been compiled correctly.  It is important to run this code, but
136738  ** we don't want to run it too often and soak up CPU cycles for no
136739  ** reason.  So we run it once during initialization.
136740  */
136741#ifndef NDEBUG
136742#ifndef SQLITE_OMIT_FLOATING_POINT
136743  /* This section of code's only "output" is via assert() statements. */
136744  if ( rc==SQLITE_OK ){
136745    u64 x = (((u64)1)<<63)-1;
136746    double y;
136747    assert(sizeof(x)==8);
136748    assert(sizeof(x)==sizeof(y));
136749    memcpy(&y, &x, 8);
136750    assert( sqlite3IsNaN(y) );
136751  }
136752#endif
136753#endif
136754
136755  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
136756  ** compile-time option.
136757  */
136758#ifdef SQLITE_EXTRA_INIT
136759  if( bRunExtraInit ){
136760    int SQLITE_EXTRA_INIT(const char*);
136761    rc = SQLITE_EXTRA_INIT(0);
136762  }
136763#endif
136764
136765  return rc;
136766}
136767
136768/*
136769** Undo the effects of sqlite3_initialize().  Must not be called while
136770** there are outstanding database connections or memory allocations or
136771** while any part of SQLite is otherwise in use in any thread.  This
136772** routine is not threadsafe.  But it is safe to invoke this routine
136773** on when SQLite is already shut down.  If SQLite is already shut down
136774** when this routine is invoked, then this routine is a harmless no-op.
136775*/
136776SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void){
136777#ifdef SQLITE_OMIT_WSD
136778  int rc = sqlite3_wsd_init(4096, 24);
136779  if( rc!=SQLITE_OK ){
136780    return rc;
136781  }
136782#endif
136783
136784  if( sqlite3GlobalConfig.isInit ){
136785#ifdef SQLITE_EXTRA_SHUTDOWN
136786    void SQLITE_EXTRA_SHUTDOWN(void);
136787    SQLITE_EXTRA_SHUTDOWN();
136788#endif
136789    sqlite3_os_end();
136790    sqlite3_reset_auto_extension();
136791    sqlite3GlobalConfig.isInit = 0;
136792  }
136793  if( sqlite3GlobalConfig.isPCacheInit ){
136794    sqlite3PcacheShutdown();
136795    sqlite3GlobalConfig.isPCacheInit = 0;
136796  }
136797  if( sqlite3GlobalConfig.isMallocInit ){
136798    sqlite3MallocEnd();
136799    sqlite3GlobalConfig.isMallocInit = 0;
136800
136801#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
136802    /* The heap subsystem has now been shutdown and these values are supposed
136803    ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
136804    ** which would rely on that heap subsystem; therefore, make sure these
136805    ** values cannot refer to heap memory that was just invalidated when the
136806    ** heap subsystem was shutdown.  This is only done if the current call to
136807    ** this function resulted in the heap subsystem actually being shutdown.
136808    */
136809    sqlite3_data_directory = 0;
136810    sqlite3_temp_directory = 0;
136811#endif
136812  }
136813  if( sqlite3GlobalConfig.isMutexInit ){
136814    sqlite3MutexEnd();
136815    sqlite3GlobalConfig.isMutexInit = 0;
136816  }
136817
136818  return SQLITE_OK;
136819}
136820
136821/*
136822** This API allows applications to modify the global configuration of
136823** the SQLite library at run-time.
136824**
136825** This routine should only be called when there are no outstanding
136826** database connections or memory allocations.  This routine is not
136827** threadsafe.  Failure to heed these warnings can lead to unpredictable
136828** behavior.
136829*/
136830SQLITE_API int SQLITE_CDECL sqlite3_config(int op, ...){
136831  va_list ap;
136832  int rc = SQLITE_OK;
136833
136834  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
136835  ** the SQLite library is in use. */
136836  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
136837
136838  va_start(ap, op);
136839  switch( op ){
136840
136841    /* Mutex configuration options are only available in a threadsafe
136842    ** compile.
136843    */
136844#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
136845    case SQLITE_CONFIG_SINGLETHREAD: {
136846      /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
136847      ** Single-thread. */
136848      sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */
136849      sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
136850      break;
136851    }
136852#endif
136853#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
136854    case SQLITE_CONFIG_MULTITHREAD: {
136855      /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
136856      ** Multi-thread. */
136857      sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
136858      sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
136859      break;
136860    }
136861#endif
136862#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
136863    case SQLITE_CONFIG_SERIALIZED: {
136864      /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
136865      ** Serialized. */
136866      sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
136867      sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */
136868      break;
136869    }
136870#endif
136871#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
136872    case SQLITE_CONFIG_MUTEX: {
136873      /* Specify an alternative mutex implementation */
136874      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
136875      break;
136876    }
136877#endif
136878#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
136879    case SQLITE_CONFIG_GETMUTEX: {
136880      /* Retrieve the current mutex implementation */
136881      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
136882      break;
136883    }
136884#endif
136885
136886    case SQLITE_CONFIG_MALLOC: {
136887      /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
136888      ** single argument which is a pointer to an instance of the
136889      ** sqlite3_mem_methods structure. The argument specifies alternative
136890      ** low-level memory allocation routines to be used in place of the memory
136891      ** allocation routines built into SQLite. */
136892      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
136893      break;
136894    }
136895    case SQLITE_CONFIG_GETMALLOC: {
136896      /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
136897      ** single argument which is a pointer to an instance of the
136898      ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
136899      ** filled with the currently defined memory allocation routines. */
136900      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
136901      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
136902      break;
136903    }
136904    case SQLITE_CONFIG_MEMSTATUS: {
136905      /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
136906      ** single argument of type int, interpreted as a boolean, which enables
136907      ** or disables the collection of memory allocation statistics. */
136908      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
136909      break;
136910    }
136911    case SQLITE_CONFIG_SCRATCH: {
136912      /* EVIDENCE-OF: R-08404-60887 There are three arguments to
136913      ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
136914      ** which the scratch allocations will be drawn, the size of each scratch
136915      ** allocation (sz), and the maximum number of scratch allocations (N). */
136916      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
136917      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
136918      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
136919      break;
136920    }
136921    case SQLITE_CONFIG_PAGECACHE: {
136922      /* EVIDENCE-OF: R-18761-36601 There are three arguments to
136923      ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
136924      ** the size of each page cache line (sz), and the number of cache lines
136925      ** (N). */
136926      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
136927      sqlite3GlobalConfig.szPage = va_arg(ap, int);
136928      sqlite3GlobalConfig.nPage = va_arg(ap, int);
136929      break;
136930    }
136931    case SQLITE_CONFIG_PCACHE_HDRSZ: {
136932      /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
136933      ** a single parameter which is a pointer to an integer and writes into
136934      ** that integer the number of extra bytes per page required for each page
136935      ** in SQLITE_CONFIG_PAGECACHE. */
136936      *va_arg(ap, int*) =
136937          sqlite3HeaderSizeBtree() +
136938          sqlite3HeaderSizePcache() +
136939          sqlite3HeaderSizePcache1();
136940      break;
136941    }
136942
136943    case SQLITE_CONFIG_PCACHE: {
136944      /* no-op */
136945      break;
136946    }
136947    case SQLITE_CONFIG_GETPCACHE: {
136948      /* now an error */
136949      rc = SQLITE_ERROR;
136950      break;
136951    }
136952
136953    case SQLITE_CONFIG_PCACHE2: {
136954      /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
136955      ** single argument which is a pointer to an sqlite3_pcache_methods2
136956      ** object. This object specifies the interface to a custom page cache
136957      ** implementation. */
136958      sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
136959      break;
136960    }
136961    case SQLITE_CONFIG_GETPCACHE2: {
136962      /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
136963      ** single argument which is a pointer to an sqlite3_pcache_methods2
136964      ** object. SQLite copies of the current page cache implementation into
136965      ** that object. */
136966      if( sqlite3GlobalConfig.pcache2.xInit==0 ){
136967        sqlite3PCacheSetDefault();
136968      }
136969      *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
136970      break;
136971    }
136972
136973/* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
136974** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
136975** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
136976#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
136977    case SQLITE_CONFIG_HEAP: {
136978      /* EVIDENCE-OF: R-19854-42126 There are three arguments to
136979      ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
136980      ** number of bytes in the memory buffer, and the minimum allocation size.
136981      */
136982      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
136983      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
136984      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
136985
136986      if( sqlite3GlobalConfig.mnReq<1 ){
136987        sqlite3GlobalConfig.mnReq = 1;
136988      }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
136989        /* cap min request size at 2^12 */
136990        sqlite3GlobalConfig.mnReq = (1<<12);
136991      }
136992
136993      if( sqlite3GlobalConfig.pHeap==0 ){
136994        /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
136995        ** is NULL, then SQLite reverts to using its default memory allocator
136996        ** (the system malloc() implementation), undoing any prior invocation of
136997        ** SQLITE_CONFIG_MALLOC.
136998        **
136999        ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
137000        ** revert to its default implementation when sqlite3_initialize() is run
137001        */
137002        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
137003      }else{
137004        /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
137005        ** alternative memory allocator is engaged to handle all of SQLites
137006        ** memory allocation needs. */
137007#ifdef SQLITE_ENABLE_MEMSYS3
137008        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
137009#endif
137010#ifdef SQLITE_ENABLE_MEMSYS5
137011        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
137012#endif
137013      }
137014      break;
137015    }
137016#endif
137017
137018    case SQLITE_CONFIG_LOOKASIDE: {
137019      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
137020      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
137021      break;
137022    }
137023
137024    /* Record a pointer to the logger function and its first argument.
137025    ** The default is NULL.  Logging is disabled if the function pointer is
137026    ** NULL.
137027    */
137028    case SQLITE_CONFIG_LOG: {
137029      /* MSVC is picky about pulling func ptrs from va lists.
137030      ** http://support.microsoft.com/kb/47961
137031      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
137032      */
137033      typedef void(*LOGFUNC_t)(void*,int,const char*);
137034      sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
137035      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
137036      break;
137037    }
137038
137039    /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
137040    ** can be changed at start-time using the
137041    ** sqlite3_config(SQLITE_CONFIG_URI,1) or
137042    ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
137043    */
137044    case SQLITE_CONFIG_URI: {
137045      /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
137046      ** argument of type int. If non-zero, then URI handling is globally
137047      ** enabled. If the parameter is zero, then URI handling is globally
137048      ** disabled. */
137049      sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
137050      break;
137051    }
137052
137053    case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
137054      /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
137055      ** option takes a single integer argument which is interpreted as a
137056      ** boolean in order to enable or disable the use of covering indices for
137057      ** full table scans in the query optimizer. */
137058      sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
137059      break;
137060    }
137061
137062#ifdef SQLITE_ENABLE_SQLLOG
137063    case SQLITE_CONFIG_SQLLOG: {
137064      typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
137065      sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
137066      sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
137067      break;
137068    }
137069#endif
137070
137071    case SQLITE_CONFIG_MMAP_SIZE: {
137072      /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
137073      ** integer (sqlite3_int64) values that are the default mmap size limit
137074      ** (the default setting for PRAGMA mmap_size) and the maximum allowed
137075      ** mmap size limit. */
137076      sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
137077      sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
137078      /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
137079      ** negative, then that argument is changed to its compile-time default.
137080      **
137081      ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
137082      ** silently truncated if necessary so that it does not exceed the
137083      ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
137084      ** compile-time option.
137085      */
137086      if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
137087        mxMmap = SQLITE_MAX_MMAP_SIZE;
137088      }
137089      if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
137090      if( szMmap>mxMmap) szMmap = mxMmap;
137091      sqlite3GlobalConfig.mxMmap = mxMmap;
137092      sqlite3GlobalConfig.szMmap = szMmap;
137093      break;
137094    }
137095
137096#if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
137097    case SQLITE_CONFIG_WIN32_HEAPSIZE: {
137098      /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
137099      ** unsigned integer value that specifies the maximum size of the created
137100      ** heap. */
137101      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
137102      break;
137103    }
137104#endif
137105
137106    case SQLITE_CONFIG_PMASZ: {
137107      sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
137108      break;
137109    }
137110
137111    case SQLITE_CONFIG_STMTJRNL_SPILL: {
137112      sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
137113      break;
137114    }
137115
137116    default: {
137117      rc = SQLITE_ERROR;
137118      break;
137119    }
137120  }
137121  va_end(ap);
137122  return rc;
137123}
137124
137125/*
137126** Set up the lookaside buffers for a database connection.
137127** Return SQLITE_OK on success.
137128** If lookaside is already active, return SQLITE_BUSY.
137129**
137130** The sz parameter is the number of bytes in each lookaside slot.
137131** The cnt parameter is the number of slots.  If pStart is NULL the
137132** space for the lookaside memory is obtained from sqlite3_malloc().
137133** If pStart is not NULL then it is sz*cnt bytes of memory to use for
137134** the lookaside memory.
137135*/
137136static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
137137#ifndef SQLITE_OMIT_LOOKASIDE
137138  void *pStart;
137139  if( db->lookaside.nOut ){
137140    return SQLITE_BUSY;
137141  }
137142  /* Free any existing lookaside buffer for this handle before
137143  ** allocating a new one so we don't have to have space for
137144  ** both at the same time.
137145  */
137146  if( db->lookaside.bMalloced ){
137147    sqlite3_free(db->lookaside.pStart);
137148  }
137149  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
137150  ** than a pointer to be useful.
137151  */
137152  sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
137153  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
137154  if( cnt<0 ) cnt = 0;
137155  if( sz==0 || cnt==0 ){
137156    sz = 0;
137157    pStart = 0;
137158  }else if( pBuf==0 ){
137159    sqlite3BeginBenignMalloc();
137160    pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
137161    sqlite3EndBenignMalloc();
137162    if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
137163  }else{
137164    pStart = pBuf;
137165  }
137166  db->lookaside.pStart = pStart;
137167  db->lookaside.pFree = 0;
137168  db->lookaside.sz = (u16)sz;
137169  if( pStart ){
137170    int i;
137171    LookasideSlot *p;
137172    assert( sz > (int)sizeof(LookasideSlot*) );
137173    p = (LookasideSlot*)pStart;
137174    for(i=cnt-1; i>=0; i--){
137175      p->pNext = db->lookaside.pFree;
137176      db->lookaside.pFree = p;
137177      p = (LookasideSlot*)&((u8*)p)[sz];
137178    }
137179    db->lookaside.pEnd = p;
137180    db->lookaside.bDisable = 0;
137181    db->lookaside.bMalloced = pBuf==0 ?1:0;
137182  }else{
137183    db->lookaside.pStart = db;
137184    db->lookaside.pEnd = db;
137185    db->lookaside.bDisable = 1;
137186    db->lookaside.bMalloced = 0;
137187  }
137188#endif /* SQLITE_OMIT_LOOKASIDE */
137189  return SQLITE_OK;
137190}
137191
137192/*
137193** Return the mutex associated with a database connection.
137194*/
137195SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3 *db){
137196#ifdef SQLITE_ENABLE_API_ARMOR
137197  if( !sqlite3SafetyCheckOk(db) ){
137198    (void)SQLITE_MISUSE_BKPT;
137199    return 0;
137200  }
137201#endif
137202  return db->mutex;
137203}
137204
137205/*
137206** Free up as much memory as we can from the given database
137207** connection.
137208*/
137209SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3 *db){
137210  int i;
137211
137212#ifdef SQLITE_ENABLE_API_ARMOR
137213  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
137214#endif
137215  sqlite3_mutex_enter(db->mutex);
137216  sqlite3BtreeEnterAll(db);
137217  for(i=0; i<db->nDb; i++){
137218    Btree *pBt = db->aDb[i].pBt;
137219    if( pBt ){
137220      Pager *pPager = sqlite3BtreePager(pBt);
137221      sqlite3PagerShrink(pPager);
137222    }
137223  }
137224  sqlite3BtreeLeaveAll(db);
137225  sqlite3_mutex_leave(db->mutex);
137226  return SQLITE_OK;
137227}
137228
137229/*
137230** Flush any dirty pages in the pager-cache for any attached database
137231** to disk.
137232*/
137233SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3 *db){
137234  int i;
137235  int rc = SQLITE_OK;
137236  int bSeenBusy = 0;
137237
137238#ifdef SQLITE_ENABLE_API_ARMOR
137239  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
137240#endif
137241  sqlite3_mutex_enter(db->mutex);
137242  sqlite3BtreeEnterAll(db);
137243  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
137244    Btree *pBt = db->aDb[i].pBt;
137245    if( pBt && sqlite3BtreeIsInTrans(pBt) ){
137246      Pager *pPager = sqlite3BtreePager(pBt);
137247      rc = sqlite3PagerFlush(pPager);
137248      if( rc==SQLITE_BUSY ){
137249        bSeenBusy = 1;
137250        rc = SQLITE_OK;
137251      }
137252    }
137253  }
137254  sqlite3BtreeLeaveAll(db);
137255  sqlite3_mutex_leave(db->mutex);
137256  return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
137257}
137258
137259/*
137260** Configuration settings for an individual database connection
137261*/
137262SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3 *db, int op, ...){
137263  va_list ap;
137264  int rc;
137265  va_start(ap, op);
137266  switch( op ){
137267    case SQLITE_DBCONFIG_LOOKASIDE: {
137268      void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
137269      int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
137270      int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
137271      rc = setupLookaside(db, pBuf, sz, cnt);
137272      break;
137273    }
137274    default: {
137275      static const struct {
137276        int op;      /* The opcode */
137277        u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
137278      } aFlagOp[] = {
137279        { SQLITE_DBCONFIG_ENABLE_FKEY,           SQLITE_ForeignKeys    },
137280        { SQLITE_DBCONFIG_ENABLE_TRIGGER,        SQLITE_EnableTrigger  },
137281        { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer  },
137282        { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension  },
137283      };
137284      unsigned int i;
137285      rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
137286      for(i=0; i<ArraySize(aFlagOp); i++){
137287        if( aFlagOp[i].op==op ){
137288          int onoff = va_arg(ap, int);
137289          int *pRes = va_arg(ap, int*);
137290          int oldFlags = db->flags;
137291          if( onoff>0 ){
137292            db->flags |= aFlagOp[i].mask;
137293          }else if( onoff==0 ){
137294            db->flags &= ~aFlagOp[i].mask;
137295          }
137296          if( oldFlags!=db->flags ){
137297            sqlite3ExpirePreparedStatements(db);
137298          }
137299          if( pRes ){
137300            *pRes = (db->flags & aFlagOp[i].mask)!=0;
137301          }
137302          rc = SQLITE_OK;
137303          break;
137304        }
137305      }
137306      break;
137307    }
137308  }
137309  va_end(ap);
137310  return rc;
137311}
137312
137313
137314/*
137315** Return true if the buffer z[0..n-1] contains all spaces.
137316*/
137317static int allSpaces(const char *z, int n){
137318  while( n>0 && z[n-1]==' ' ){ n--; }
137319  return n==0;
137320}
137321
137322/*
137323** This is the default collating function named "BINARY" which is always
137324** available.
137325**
137326** If the padFlag argument is not NULL then space padding at the end
137327** of strings is ignored.  This implements the RTRIM collation.
137328*/
137329static int binCollFunc(
137330  void *padFlag,
137331  int nKey1, const void *pKey1,
137332  int nKey2, const void *pKey2
137333){
137334  int rc, n;
137335  n = nKey1<nKey2 ? nKey1 : nKey2;
137336  /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
137337  ** strings byte by byte using the memcmp() function from the standard C
137338  ** library. */
137339  rc = memcmp(pKey1, pKey2, n);
137340  if( rc==0 ){
137341    if( padFlag
137342     && allSpaces(((char*)pKey1)+n, nKey1-n)
137343     && allSpaces(((char*)pKey2)+n, nKey2-n)
137344    ){
137345      /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
137346      ** spaces at the end of either string do not change the result. In other
137347      ** words, strings will compare equal to one another as long as they
137348      ** differ only in the number of spaces at the end.
137349      */
137350    }else{
137351      rc = nKey1 - nKey2;
137352    }
137353  }
137354  return rc;
137355}
137356
137357/*
137358** Another built-in collating sequence: NOCASE.
137359**
137360** This collating sequence is intended to be used for "case independent
137361** comparison". SQLite's knowledge of upper and lower case equivalents
137362** extends only to the 26 characters used in the English language.
137363**
137364** At the moment there is only a UTF-8 implementation.
137365*/
137366static int nocaseCollatingFunc(
137367  void *NotUsed,
137368  int nKey1, const void *pKey1,
137369  int nKey2, const void *pKey2
137370){
137371  int r = sqlite3StrNICmp(
137372      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
137373  UNUSED_PARAMETER(NotUsed);
137374  if( 0==r ){
137375    r = nKey1-nKey2;
137376  }
137377  return r;
137378}
137379
137380/*
137381** Return the ROWID of the most recent insert
137382*/
137383SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3 *db){
137384#ifdef SQLITE_ENABLE_API_ARMOR
137385  if( !sqlite3SafetyCheckOk(db) ){
137386    (void)SQLITE_MISUSE_BKPT;
137387    return 0;
137388  }
137389#endif
137390  return db->lastRowid;
137391}
137392
137393/*
137394** Return the number of changes in the most recent call to sqlite3_exec().
137395*/
137396SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3 *db){
137397#ifdef SQLITE_ENABLE_API_ARMOR
137398  if( !sqlite3SafetyCheckOk(db) ){
137399    (void)SQLITE_MISUSE_BKPT;
137400    return 0;
137401  }
137402#endif
137403  return db->nChange;
137404}
137405
137406/*
137407** Return the number of changes since the database handle was opened.
137408*/
137409SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3 *db){
137410#ifdef SQLITE_ENABLE_API_ARMOR
137411  if( !sqlite3SafetyCheckOk(db) ){
137412    (void)SQLITE_MISUSE_BKPT;
137413    return 0;
137414  }
137415#endif
137416  return db->nTotalChange;
137417}
137418
137419/*
137420** Close all open savepoints. This function only manipulates fields of the
137421** database handle object, it does not close any savepoints that may be open
137422** at the b-tree/pager level.
137423*/
137424SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
137425  while( db->pSavepoint ){
137426    Savepoint *pTmp = db->pSavepoint;
137427    db->pSavepoint = pTmp->pNext;
137428    sqlite3DbFree(db, pTmp);
137429  }
137430  db->nSavepoint = 0;
137431  db->nStatement = 0;
137432  db->isTransactionSavepoint = 0;
137433}
137434
137435/*
137436** Invoke the destructor function associated with FuncDef p, if any. Except,
137437** if this is not the last copy of the function, do not invoke it. Multiple
137438** copies of a single function are created when create_function() is called
137439** with SQLITE_ANY as the encoding.
137440*/
137441static void functionDestroy(sqlite3 *db, FuncDef *p){
137442  FuncDestructor *pDestructor = p->u.pDestructor;
137443  if( pDestructor ){
137444    pDestructor->nRef--;
137445    if( pDestructor->nRef==0 ){
137446      pDestructor->xDestroy(pDestructor->pUserData);
137447      sqlite3DbFree(db, pDestructor);
137448    }
137449  }
137450}
137451
137452/*
137453** Disconnect all sqlite3_vtab objects that belong to database connection
137454** db. This is called when db is being closed.
137455*/
137456static void disconnectAllVtab(sqlite3 *db){
137457#ifndef SQLITE_OMIT_VIRTUALTABLE
137458  int i;
137459  HashElem *p;
137460  sqlite3BtreeEnterAll(db);
137461  for(i=0; i<db->nDb; i++){
137462    Schema *pSchema = db->aDb[i].pSchema;
137463    if( db->aDb[i].pSchema ){
137464      for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
137465        Table *pTab = (Table *)sqliteHashData(p);
137466        if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
137467      }
137468    }
137469  }
137470  for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
137471    Module *pMod = (Module *)sqliteHashData(p);
137472    if( pMod->pEpoTab ){
137473      sqlite3VtabDisconnect(db, pMod->pEpoTab);
137474    }
137475  }
137476  sqlite3VtabUnlockList(db);
137477  sqlite3BtreeLeaveAll(db);
137478#else
137479  UNUSED_PARAMETER(db);
137480#endif
137481}
137482
137483/*
137484** Return TRUE if database connection db has unfinalized prepared
137485** statements or unfinished sqlite3_backup objects.
137486*/
137487static int connectionIsBusy(sqlite3 *db){
137488  int j;
137489  assert( sqlite3_mutex_held(db->mutex) );
137490  if( db->pVdbe ) return 1;
137491  for(j=0; j<db->nDb; j++){
137492    Btree *pBt = db->aDb[j].pBt;
137493    if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
137494  }
137495  return 0;
137496}
137497
137498/*
137499** Close an existing SQLite database
137500*/
137501static int sqlite3Close(sqlite3 *db, int forceZombie){
137502  if( !db ){
137503    /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
137504    ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
137505    return SQLITE_OK;
137506  }
137507  if( !sqlite3SafetyCheckSickOrOk(db) ){
137508    return SQLITE_MISUSE_BKPT;
137509  }
137510  sqlite3_mutex_enter(db->mutex);
137511  if( db->mTrace & SQLITE_TRACE_CLOSE ){
137512    db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
137513  }
137514
137515  /* Force xDisconnect calls on all virtual tables */
137516  disconnectAllVtab(db);
137517
137518  /* If a transaction is open, the disconnectAllVtab() call above
137519  ** will not have called the xDisconnect() method on any virtual
137520  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
137521  ** call will do so. We need to do this before the check for active
137522  ** SQL statements below, as the v-table implementation may be storing
137523  ** some prepared statements internally.
137524  */
137525  sqlite3VtabRollback(db);
137526
137527  /* Legacy behavior (sqlite3_close() behavior) is to return
137528  ** SQLITE_BUSY if the connection can not be closed immediately.
137529  */
137530  if( !forceZombie && connectionIsBusy(db) ){
137531    sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
137532       "statements or unfinished backups");
137533    sqlite3_mutex_leave(db->mutex);
137534    return SQLITE_BUSY;
137535  }
137536
137537#ifdef SQLITE_ENABLE_SQLLOG
137538  if( sqlite3GlobalConfig.xSqllog ){
137539    /* Closing the handle. Fourth parameter is passed the value 2. */
137540    sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
137541  }
137542#endif
137543
137544  /* Convert the connection into a zombie and then close it.
137545  */
137546  db->magic = SQLITE_MAGIC_ZOMBIE;
137547  sqlite3LeaveMutexAndCloseZombie(db);
137548  return SQLITE_OK;
137549}
137550
137551/*
137552** Two variations on the public interface for closing a database
137553** connection. The sqlite3_close() version returns SQLITE_BUSY and
137554** leaves the connection option if there are unfinalized prepared
137555** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
137556** version forces the connection to become a zombie if there are
137557** unclosed resources, and arranges for deallocation when the last
137558** prepare statement or sqlite3_backup closes.
137559*/
137560SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
137561SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
137562
137563
137564/*
137565** Close the mutex on database connection db.
137566**
137567** Furthermore, if database connection db is a zombie (meaning that there
137568** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
137569** every sqlite3_stmt has now been finalized and every sqlite3_backup has
137570** finished, then free all resources.
137571*/
137572SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
137573  HashElem *i;                    /* Hash table iterator */
137574  int j;
137575
137576  /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
137577  ** or if the connection has not yet been closed by sqlite3_close_v2(),
137578  ** then just leave the mutex and return.
137579  */
137580  if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
137581    sqlite3_mutex_leave(db->mutex);
137582    return;
137583  }
137584
137585  /* If we reach this point, it means that the database connection has
137586  ** closed all sqlite3_stmt and sqlite3_backup objects and has been
137587  ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
137588  ** go ahead and free all resources.
137589  */
137590
137591  /* If a transaction is open, roll it back. This also ensures that if
137592  ** any database schemas have been modified by an uncommitted transaction
137593  ** they are reset. And that the required b-tree mutex is held to make
137594  ** the pager rollback and schema reset an atomic operation. */
137595  sqlite3RollbackAll(db, SQLITE_OK);
137596
137597  /* Free any outstanding Savepoint structures. */
137598  sqlite3CloseSavepoints(db);
137599
137600  /* Close all database connections */
137601  for(j=0; j<db->nDb; j++){
137602    struct Db *pDb = &db->aDb[j];
137603    if( pDb->pBt ){
137604      sqlite3BtreeClose(pDb->pBt);
137605      pDb->pBt = 0;
137606      if( j!=1 ){
137607        pDb->pSchema = 0;
137608      }
137609    }
137610  }
137611  /* Clear the TEMP schema separately and last */
137612  if( db->aDb[1].pSchema ){
137613    sqlite3SchemaClear(db->aDb[1].pSchema);
137614  }
137615  sqlite3VtabUnlockList(db);
137616
137617  /* Free up the array of auxiliary databases */
137618  sqlite3CollapseDatabaseArray(db);
137619  assert( db->nDb<=2 );
137620  assert( db->aDb==db->aDbStatic );
137621
137622  /* Tell the code in notify.c that the connection no longer holds any
137623  ** locks and does not require any further unlock-notify callbacks.
137624  */
137625  sqlite3ConnectionClosed(db);
137626
137627  for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
137628    FuncDef *pNext, *p;
137629    p = sqliteHashData(i);
137630    do{
137631      functionDestroy(db, p);
137632      pNext = p->pNext;
137633      sqlite3DbFree(db, p);
137634      p = pNext;
137635    }while( p );
137636  }
137637  sqlite3HashClear(&db->aFunc);
137638  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
137639    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
137640    /* Invoke any destructors registered for collation sequence user data. */
137641    for(j=0; j<3; j++){
137642      if( pColl[j].xDel ){
137643        pColl[j].xDel(pColl[j].pUser);
137644      }
137645    }
137646    sqlite3DbFree(db, pColl);
137647  }
137648  sqlite3HashClear(&db->aCollSeq);
137649#ifndef SQLITE_OMIT_VIRTUALTABLE
137650  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
137651    Module *pMod = (Module *)sqliteHashData(i);
137652    if( pMod->xDestroy ){
137653      pMod->xDestroy(pMod->pAux);
137654    }
137655    sqlite3VtabEponymousTableClear(db, pMod);
137656    sqlite3DbFree(db, pMod);
137657  }
137658  sqlite3HashClear(&db->aModule);
137659#endif
137660
137661  sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
137662  sqlite3ValueFree(db->pErr);
137663  sqlite3CloseExtensions(db);
137664#if SQLITE_USER_AUTHENTICATION
137665  sqlite3_free(db->auth.zAuthUser);
137666  sqlite3_free(db->auth.zAuthPW);
137667#endif
137668
137669  db->magic = SQLITE_MAGIC_ERROR;
137670
137671  /* The temp-database schema is allocated differently from the other schema
137672  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
137673  ** So it needs to be freed here. Todo: Why not roll the temp schema into
137674  ** the same sqliteMalloc() as the one that allocates the database
137675  ** structure?
137676  */
137677  sqlite3DbFree(db, db->aDb[1].pSchema);
137678  sqlite3_mutex_leave(db->mutex);
137679  db->magic = SQLITE_MAGIC_CLOSED;
137680  sqlite3_mutex_free(db->mutex);
137681  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
137682  if( db->lookaside.bMalloced ){
137683    sqlite3_free(db->lookaside.pStart);
137684  }
137685  sqlite3_free(db);
137686}
137687
137688/*
137689** Rollback all database files.  If tripCode is not SQLITE_OK, then
137690** any write cursors are invalidated ("tripped" - as in "tripping a circuit
137691** breaker") and made to return tripCode if there are any further
137692** attempts to use that cursor.  Read cursors remain open and valid
137693** but are "saved" in case the table pages are moved around.
137694*/
137695SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
137696  int i;
137697  int inTrans = 0;
137698  int schemaChange;
137699  assert( sqlite3_mutex_held(db->mutex) );
137700  sqlite3BeginBenignMalloc();
137701
137702  /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
137703  ** This is important in case the transaction being rolled back has
137704  ** modified the database schema. If the b-tree mutexes are not taken
137705  ** here, then another shared-cache connection might sneak in between
137706  ** the database rollback and schema reset, which can cause false
137707  ** corruption reports in some cases.  */
137708  sqlite3BtreeEnterAll(db);
137709  schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
137710
137711  for(i=0; i<db->nDb; i++){
137712    Btree *p = db->aDb[i].pBt;
137713    if( p ){
137714      if( sqlite3BtreeIsInTrans(p) ){
137715        inTrans = 1;
137716      }
137717      sqlite3BtreeRollback(p, tripCode, !schemaChange);
137718    }
137719  }
137720  sqlite3VtabRollback(db);
137721  sqlite3EndBenignMalloc();
137722
137723  if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
137724    sqlite3ExpirePreparedStatements(db);
137725    sqlite3ResetAllSchemasOfConnection(db);
137726  }
137727  sqlite3BtreeLeaveAll(db);
137728
137729  /* Any deferred constraint violations have now been resolved. */
137730  db->nDeferredCons = 0;
137731  db->nDeferredImmCons = 0;
137732  db->flags &= ~SQLITE_DeferFKs;
137733
137734  /* If one has been configured, invoke the rollback-hook callback */
137735  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
137736    db->xRollbackCallback(db->pRollbackArg);
137737  }
137738}
137739
137740/*
137741** Return a static string containing the name corresponding to the error code
137742** specified in the argument.
137743*/
137744#if defined(SQLITE_NEED_ERR_NAME)
137745SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
137746  const char *zName = 0;
137747  int i, origRc = rc;
137748  for(i=0; i<2 && zName==0; i++, rc &= 0xff){
137749    switch( rc ){
137750      case SQLITE_OK:                 zName = "SQLITE_OK";                break;
137751      case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
137752      case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
137753      case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
137754      case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
137755      case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
137756      case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
137757      case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
137758      case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
137759      case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
137760      case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
137761      case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
137762      case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
137763      case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
137764      case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
137765      case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
137766      case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
137767      case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
137768      case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
137769      case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
137770      case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
137771      case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
137772      case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
137773      case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
137774      case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
137775      case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
137776      case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
137777      case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
137778      case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
137779      case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
137780      case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
137781      case SQLITE_IOERR_CHECKRESERVEDLOCK:
137782                                zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
137783      case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
137784      case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
137785      case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
137786      case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
137787      case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
137788      case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
137789      case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
137790      case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
137791      case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
137792      case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
137793      case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
137794      case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
137795      case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
137796      case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
137797      case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
137798      case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
137799      case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
137800      case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
137801      case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
137802      case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
137803      case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
137804      case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
137805      case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
137806      case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
137807      case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
137808      case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
137809      case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
137810      case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
137811      case SQLITE_CONSTRAINT_FOREIGNKEY:
137812                                zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
137813      case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
137814      case SQLITE_CONSTRAINT_PRIMARYKEY:
137815                                zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
137816      case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
137817      case SQLITE_CONSTRAINT_COMMITHOOK:
137818                                zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
137819      case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
137820      case SQLITE_CONSTRAINT_FUNCTION:
137821                                zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
137822      case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
137823      case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
137824      case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
137825      case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
137826      case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
137827      case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
137828      case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
137829      case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
137830      case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
137831      case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
137832      case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
137833      case SQLITE_NOTICE_RECOVER_ROLLBACK:
137834                                zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
137835      case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
137836      case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
137837      case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
137838    }
137839  }
137840  if( zName==0 ){
137841    static char zBuf[50];
137842    sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
137843    zName = zBuf;
137844  }
137845  return zName;
137846}
137847#endif
137848
137849/*
137850** Return a static string that describes the kind of error specified in the
137851** argument.
137852*/
137853SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
137854  static const char* const aMsg[] = {
137855    /* SQLITE_OK          */ "not an error",
137856    /* SQLITE_ERROR       */ "SQL logic error or missing database",
137857    /* SQLITE_INTERNAL    */ 0,
137858    /* SQLITE_PERM        */ "access permission denied",
137859    /* SQLITE_ABORT       */ "callback requested query abort",
137860    /* SQLITE_BUSY        */ "database is locked",
137861    /* SQLITE_LOCKED      */ "database table is locked",
137862    /* SQLITE_NOMEM       */ "out of memory",
137863    /* SQLITE_READONLY    */ "attempt to write a readonly database",
137864    /* SQLITE_INTERRUPT   */ "interrupted",
137865    /* SQLITE_IOERR       */ "disk I/O error",
137866    /* SQLITE_CORRUPT     */ "database disk image is malformed",
137867    /* SQLITE_NOTFOUND    */ "unknown operation",
137868    /* SQLITE_FULL        */ "database or disk is full",
137869    /* SQLITE_CANTOPEN    */ "unable to open database file",
137870    /* SQLITE_PROTOCOL    */ "locking protocol",
137871    /* SQLITE_EMPTY       */ "table contains no data",
137872    /* SQLITE_SCHEMA      */ "database schema has changed",
137873    /* SQLITE_TOOBIG      */ "string or blob too big",
137874    /* SQLITE_CONSTRAINT  */ "constraint failed",
137875    /* SQLITE_MISMATCH    */ "datatype mismatch",
137876    /* SQLITE_MISUSE      */ "library routine called out of sequence",
137877    /* SQLITE_NOLFS       */ "large file support is disabled",
137878    /* SQLITE_AUTH        */ "authorization denied",
137879    /* SQLITE_FORMAT      */ "auxiliary database format error",
137880    /* SQLITE_RANGE       */ "bind or column index out of range",
137881    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
137882  };
137883  const char *zErr = "unknown error";
137884  switch( rc ){
137885    case SQLITE_ABORT_ROLLBACK: {
137886      zErr = "abort due to ROLLBACK";
137887      break;
137888    }
137889    default: {
137890      rc &= 0xff;
137891      if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
137892        zErr = aMsg[rc];
137893      }
137894      break;
137895    }
137896  }
137897  return zErr;
137898}
137899
137900/*
137901** This routine implements a busy callback that sleeps and tries
137902** again until a timeout value is reached.  The timeout value is
137903** an integer number of milliseconds passed in as the first
137904** argument.
137905*/
137906static int sqliteDefaultBusyCallback(
137907 void *ptr,               /* Database connection */
137908 int count                /* Number of times table has been busy */
137909){
137910#if SQLITE_OS_WIN || HAVE_USLEEP
137911  static const u8 delays[] =
137912     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
137913  static const u8 totals[] =
137914     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
137915# define NDELAY ArraySize(delays)
137916  sqlite3 *db = (sqlite3 *)ptr;
137917  int timeout = db->busyTimeout;
137918  int delay, prior;
137919
137920  assert( count>=0 );
137921  if( count < NDELAY ){
137922    delay = delays[count];
137923    prior = totals[count];
137924  }else{
137925    delay = delays[NDELAY-1];
137926    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
137927  }
137928  if( prior + delay > timeout ){
137929    delay = timeout - prior;
137930    if( delay<=0 ) return 0;
137931  }
137932  sqlite3OsSleep(db->pVfs, delay*1000);
137933  return 1;
137934#else
137935  sqlite3 *db = (sqlite3 *)ptr;
137936  int timeout = ((sqlite3 *)ptr)->busyTimeout;
137937  if( (count+1)*1000 > timeout ){
137938    return 0;
137939  }
137940  sqlite3OsSleep(db->pVfs, 1000000);
137941  return 1;
137942#endif
137943}
137944
137945/*
137946** Invoke the given busy handler.
137947**
137948** This routine is called when an operation failed with a lock.
137949** If this routine returns non-zero, the lock is retried.  If it
137950** returns 0, the operation aborts with an SQLITE_BUSY error.
137951*/
137952SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
137953  int rc;
137954  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
137955  rc = p->xFunc(p->pArg, p->nBusy);
137956  if( rc==0 ){
137957    p->nBusy = -1;
137958  }else{
137959    p->nBusy++;
137960  }
137961  return rc;
137962}
137963
137964/*
137965** This routine sets the busy callback for an Sqlite database to the
137966** given callback function with the given argument.
137967*/
137968SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(
137969  sqlite3 *db,
137970  int (*xBusy)(void*,int),
137971  void *pArg
137972){
137973#ifdef SQLITE_ENABLE_API_ARMOR
137974  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
137975#endif
137976  sqlite3_mutex_enter(db->mutex);
137977  db->busyHandler.xFunc = xBusy;
137978  db->busyHandler.pArg = pArg;
137979  db->busyHandler.nBusy = 0;
137980  db->busyTimeout = 0;
137981  sqlite3_mutex_leave(db->mutex);
137982  return SQLITE_OK;
137983}
137984
137985#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
137986/*
137987** This routine sets the progress callback for an Sqlite database to the
137988** given callback function with the given argument. The progress callback will
137989** be invoked every nOps opcodes.
137990*/
137991SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(
137992  sqlite3 *db,
137993  int nOps,
137994  int (*xProgress)(void*),
137995  void *pArg
137996){
137997#ifdef SQLITE_ENABLE_API_ARMOR
137998  if( !sqlite3SafetyCheckOk(db) ){
137999    (void)SQLITE_MISUSE_BKPT;
138000    return;
138001  }
138002#endif
138003  sqlite3_mutex_enter(db->mutex);
138004  if( nOps>0 ){
138005    db->xProgress = xProgress;
138006    db->nProgressOps = (unsigned)nOps;
138007    db->pProgressArg = pArg;
138008  }else{
138009    db->xProgress = 0;
138010    db->nProgressOps = 0;
138011    db->pProgressArg = 0;
138012  }
138013  sqlite3_mutex_leave(db->mutex);
138014}
138015#endif
138016
138017
138018/*
138019** This routine installs a default busy handler that waits for the
138020** specified number of milliseconds before returning 0.
138021*/
138022SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3 *db, int ms){
138023#ifdef SQLITE_ENABLE_API_ARMOR
138024  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
138025#endif
138026  if( ms>0 ){
138027    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
138028    db->busyTimeout = ms;
138029  }else{
138030    sqlite3_busy_handler(db, 0, 0);
138031  }
138032  return SQLITE_OK;
138033}
138034
138035/*
138036** Cause any pending operation to stop at its earliest opportunity.
138037*/
138038SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3 *db){
138039#ifdef SQLITE_ENABLE_API_ARMOR
138040  if( !sqlite3SafetyCheckOk(db) ){
138041    (void)SQLITE_MISUSE_BKPT;
138042    return;
138043  }
138044#endif
138045  db->u1.isInterrupted = 1;
138046}
138047
138048
138049/*
138050** This function is exactly the same as sqlite3_create_function(), except
138051** that it is designed to be called by internal code. The difference is
138052** that if a malloc() fails in sqlite3_create_function(), an error code
138053** is returned and the mallocFailed flag cleared.
138054*/
138055SQLITE_PRIVATE int sqlite3CreateFunc(
138056  sqlite3 *db,
138057  const char *zFunctionName,
138058  int nArg,
138059  int enc,
138060  void *pUserData,
138061  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
138062  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
138063  void (*xFinal)(sqlite3_context*),
138064  FuncDestructor *pDestructor
138065){
138066  FuncDef *p;
138067  int nName;
138068  int extraFlags;
138069
138070  assert( sqlite3_mutex_held(db->mutex) );
138071  if( zFunctionName==0 ||
138072      (xSFunc && (xFinal || xStep)) ||
138073      (!xSFunc && (xFinal && !xStep)) ||
138074      (!xSFunc && (!xFinal && xStep)) ||
138075      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
138076      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
138077    return SQLITE_MISUSE_BKPT;
138078  }
138079
138080  assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
138081  extraFlags = enc &  SQLITE_DETERMINISTIC;
138082  enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
138083
138084#ifndef SQLITE_OMIT_UTF16
138085  /* If SQLITE_UTF16 is specified as the encoding type, transform this
138086  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
138087  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
138088  **
138089  ** If SQLITE_ANY is specified, add three versions of the function
138090  ** to the hash table.
138091  */
138092  if( enc==SQLITE_UTF16 ){
138093    enc = SQLITE_UTF16NATIVE;
138094  }else if( enc==SQLITE_ANY ){
138095    int rc;
138096    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
138097         pUserData, xSFunc, xStep, xFinal, pDestructor);
138098    if( rc==SQLITE_OK ){
138099      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
138100          pUserData, xSFunc, xStep, xFinal, pDestructor);
138101    }
138102    if( rc!=SQLITE_OK ){
138103      return rc;
138104    }
138105    enc = SQLITE_UTF16BE;
138106  }
138107#else
138108  enc = SQLITE_UTF8;
138109#endif
138110
138111  /* Check if an existing function is being overridden or deleted. If so,
138112  ** and there are active VMs, then return SQLITE_BUSY. If a function
138113  ** is being overridden/deleted but there are no active VMs, allow the
138114  ** operation to continue but invalidate all precompiled statements.
138115  */
138116  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
138117  if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
138118    if( db->nVdbeActive ){
138119      sqlite3ErrorWithMsg(db, SQLITE_BUSY,
138120        "unable to delete/modify user-function due to active statements");
138121      assert( !db->mallocFailed );
138122      return SQLITE_BUSY;
138123    }else{
138124      sqlite3ExpirePreparedStatements(db);
138125    }
138126  }
138127
138128  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
138129  assert(p || db->mallocFailed);
138130  if( !p ){
138131    return SQLITE_NOMEM_BKPT;
138132  }
138133
138134  /* If an older version of the function with a configured destructor is
138135  ** being replaced invoke the destructor function here. */
138136  functionDestroy(db, p);
138137
138138  if( pDestructor ){
138139    pDestructor->nRef++;
138140  }
138141  p->u.pDestructor = pDestructor;
138142  p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
138143  testcase( p->funcFlags & SQLITE_DETERMINISTIC );
138144  p->xSFunc = xSFunc ? xSFunc : xStep;
138145  p->xFinalize = xFinal;
138146  p->pUserData = pUserData;
138147  p->nArg = (u16)nArg;
138148  return SQLITE_OK;
138149}
138150
138151/*
138152** Create new user functions.
138153*/
138154SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
138155  sqlite3 *db,
138156  const char *zFunc,
138157  int nArg,
138158  int enc,
138159  void *p,
138160  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
138161  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
138162  void (*xFinal)(sqlite3_context*)
138163){
138164  return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
138165                                    xFinal, 0);
138166}
138167
138168SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
138169  sqlite3 *db,
138170  const char *zFunc,
138171  int nArg,
138172  int enc,
138173  void *p,
138174  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
138175  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
138176  void (*xFinal)(sqlite3_context*),
138177  void (*xDestroy)(void *)
138178){
138179  int rc = SQLITE_ERROR;
138180  FuncDestructor *pArg = 0;
138181
138182#ifdef SQLITE_ENABLE_API_ARMOR
138183  if( !sqlite3SafetyCheckOk(db) ){
138184    return SQLITE_MISUSE_BKPT;
138185  }
138186#endif
138187  sqlite3_mutex_enter(db->mutex);
138188  if( xDestroy ){
138189    pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
138190    if( !pArg ){
138191      xDestroy(p);
138192      goto out;
138193    }
138194    pArg->xDestroy = xDestroy;
138195    pArg->pUserData = p;
138196  }
138197  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
138198  if( pArg && pArg->nRef==0 ){
138199    assert( rc!=SQLITE_OK );
138200    xDestroy(p);
138201    sqlite3DbFree(db, pArg);
138202  }
138203
138204 out:
138205  rc = sqlite3ApiExit(db, rc);
138206  sqlite3_mutex_leave(db->mutex);
138207  return rc;
138208}
138209
138210#ifndef SQLITE_OMIT_UTF16
138211SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
138212  sqlite3 *db,
138213  const void *zFunctionName,
138214  int nArg,
138215  int eTextRep,
138216  void *p,
138217  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
138218  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
138219  void (*xFinal)(sqlite3_context*)
138220){
138221  int rc;
138222  char *zFunc8;
138223
138224#ifdef SQLITE_ENABLE_API_ARMOR
138225  if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
138226#endif
138227  sqlite3_mutex_enter(db->mutex);
138228  assert( !db->mallocFailed );
138229  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
138230  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
138231  sqlite3DbFree(db, zFunc8);
138232  rc = sqlite3ApiExit(db, rc);
138233  sqlite3_mutex_leave(db->mutex);
138234  return rc;
138235}
138236#endif
138237
138238
138239/*
138240** Declare that a function has been overloaded by a virtual table.
138241**
138242** If the function already exists as a regular global function, then
138243** this routine is a no-op.  If the function does not exist, then create
138244** a new one that always throws a run-time error.
138245**
138246** When virtual tables intend to provide an overloaded function, they
138247** should call this routine to make sure the global function exists.
138248** A global function must exist in order for name resolution to work
138249** properly.
138250*/
138251SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(
138252  sqlite3 *db,
138253  const char *zName,
138254  int nArg
138255){
138256  int rc = SQLITE_OK;
138257
138258#ifdef SQLITE_ENABLE_API_ARMOR
138259  if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
138260    return SQLITE_MISUSE_BKPT;
138261  }
138262#endif
138263  sqlite3_mutex_enter(db->mutex);
138264  if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
138265    rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
138266                           0, sqlite3InvalidFunction, 0, 0, 0);
138267  }
138268  rc = sqlite3ApiExit(db, rc);
138269  sqlite3_mutex_leave(db->mutex);
138270  return rc;
138271}
138272
138273#ifndef SQLITE_OMIT_TRACE
138274/*
138275** Register a trace function.  The pArg from the previously registered trace
138276** is returned.
138277**
138278** A NULL trace function means that no tracing is executes.  A non-NULL
138279** trace is a pointer to a function that is invoked at the start of each
138280** SQL statement.
138281*/
138282#ifndef SQLITE_OMIT_DEPRECATED
138283SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
138284  void *pOld;
138285
138286#ifdef SQLITE_ENABLE_API_ARMOR
138287  if( !sqlite3SafetyCheckOk(db) ){
138288    (void)SQLITE_MISUSE_BKPT;
138289    return 0;
138290  }
138291#endif
138292  sqlite3_mutex_enter(db->mutex);
138293  pOld = db->pTraceArg;
138294  db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
138295  db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
138296  db->pTraceArg = pArg;
138297  sqlite3_mutex_leave(db->mutex);
138298  return pOld;
138299}
138300#endif /* SQLITE_OMIT_DEPRECATED */
138301
138302/* Register a trace callback using the version-2 interface.
138303*/
138304SQLITE_API int SQLITE_STDCALL sqlite3_trace_v2(
138305  sqlite3 *db,                               /* Trace this connection */
138306  unsigned mTrace,                           /* Mask of events to be traced */
138307  int(*xTrace)(unsigned,void*,void*,void*),  /* Callback to invoke */
138308  void *pArg                                 /* Context */
138309){
138310#ifdef SQLITE_ENABLE_API_ARMOR
138311  if( !sqlite3SafetyCheckOk(db) ){
138312    return SQLITE_MISUSE_BKPT;
138313  }
138314#endif
138315  sqlite3_mutex_enter(db->mutex);
138316  db->mTrace = mTrace;
138317  db->xTrace = xTrace;
138318  db->pTraceArg = pArg;
138319  sqlite3_mutex_leave(db->mutex);
138320  return SQLITE_OK;
138321}
138322
138323#ifndef SQLITE_OMIT_DEPRECATED
138324/*
138325** Register a profile function.  The pArg from the previously registered
138326** profile function is returned.
138327**
138328** A NULL profile function means that no profiling is executes.  A non-NULL
138329** profile is a pointer to a function that is invoked at the conclusion of
138330** each SQL statement that is run.
138331*/
138332SQLITE_API void *SQLITE_STDCALL sqlite3_profile(
138333  sqlite3 *db,
138334  void (*xProfile)(void*,const char*,sqlite_uint64),
138335  void *pArg
138336){
138337  void *pOld;
138338
138339#ifdef SQLITE_ENABLE_API_ARMOR
138340  if( !sqlite3SafetyCheckOk(db) ){
138341    (void)SQLITE_MISUSE_BKPT;
138342    return 0;
138343  }
138344#endif
138345  sqlite3_mutex_enter(db->mutex);
138346  pOld = db->pProfileArg;
138347  db->xProfile = xProfile;
138348  db->pProfileArg = pArg;
138349  sqlite3_mutex_leave(db->mutex);
138350  return pOld;
138351}
138352#endif /* SQLITE_OMIT_DEPRECATED */
138353#endif /* SQLITE_OMIT_TRACE */
138354
138355/*
138356** Register a function to be invoked when a transaction commits.
138357** If the invoked function returns non-zero, then the commit becomes a
138358** rollback.
138359*/
138360SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(
138361  sqlite3 *db,              /* Attach the hook to this database */
138362  int (*xCallback)(void*),  /* Function to invoke on each commit */
138363  void *pArg                /* Argument to the function */
138364){
138365  void *pOld;
138366
138367#ifdef SQLITE_ENABLE_API_ARMOR
138368  if( !sqlite3SafetyCheckOk(db) ){
138369    (void)SQLITE_MISUSE_BKPT;
138370    return 0;
138371  }
138372#endif
138373  sqlite3_mutex_enter(db->mutex);
138374  pOld = db->pCommitArg;
138375  db->xCommitCallback = xCallback;
138376  db->pCommitArg = pArg;
138377  sqlite3_mutex_leave(db->mutex);
138378  return pOld;
138379}
138380
138381/*
138382** Register a callback to be invoked each time a row is updated,
138383** inserted or deleted using this database connection.
138384*/
138385SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
138386  sqlite3 *db,              /* Attach the hook to this database */
138387  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
138388  void *pArg                /* Argument to the function */
138389){
138390  void *pRet;
138391
138392#ifdef SQLITE_ENABLE_API_ARMOR
138393  if( !sqlite3SafetyCheckOk(db) ){
138394    (void)SQLITE_MISUSE_BKPT;
138395    return 0;
138396  }
138397#endif
138398  sqlite3_mutex_enter(db->mutex);
138399  pRet = db->pUpdateArg;
138400  db->xUpdateCallback = xCallback;
138401  db->pUpdateArg = pArg;
138402  sqlite3_mutex_leave(db->mutex);
138403  return pRet;
138404}
138405
138406/*
138407** Register a callback to be invoked each time a transaction is rolled
138408** back by this database connection.
138409*/
138410SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(
138411  sqlite3 *db,              /* Attach the hook to this database */
138412  void (*xCallback)(void*), /* Callback function */
138413  void *pArg                /* Argument to the function */
138414){
138415  void *pRet;
138416
138417#ifdef SQLITE_ENABLE_API_ARMOR
138418  if( !sqlite3SafetyCheckOk(db) ){
138419    (void)SQLITE_MISUSE_BKPT;
138420    return 0;
138421  }
138422#endif
138423  sqlite3_mutex_enter(db->mutex);
138424  pRet = db->pRollbackArg;
138425  db->xRollbackCallback = xCallback;
138426  db->pRollbackArg = pArg;
138427  sqlite3_mutex_leave(db->mutex);
138428  return pRet;
138429}
138430
138431#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
138432/*
138433** Register a callback to be invoked each time a row is updated,
138434** inserted or deleted using this database connection.
138435*/
138436SQLITE_API void *SQLITE_STDCALL sqlite3_preupdate_hook(
138437  sqlite3 *db,              /* Attach the hook to this database */
138438  void(*xCallback)(         /* Callback function */
138439    void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
138440  void *pArg                /* First callback argument */
138441){
138442  void *pRet;
138443  sqlite3_mutex_enter(db->mutex);
138444  pRet = db->pPreUpdateArg;
138445  db->xPreUpdateCallback = xCallback;
138446  db->pPreUpdateArg = pArg;
138447  sqlite3_mutex_leave(db->mutex);
138448  return pRet;
138449}
138450#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
138451
138452#ifndef SQLITE_OMIT_WAL
138453/*
138454** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
138455** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
138456** is greater than sqlite3.pWalArg cast to an integer (the value configured by
138457** wal_autocheckpoint()).
138458*/
138459SQLITE_PRIVATE int sqlite3WalDefaultHook(
138460  void *pClientData,     /* Argument */
138461  sqlite3 *db,           /* Connection */
138462  const char *zDb,       /* Database */
138463  int nFrame             /* Size of WAL */
138464){
138465  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
138466    sqlite3BeginBenignMalloc();
138467    sqlite3_wal_checkpoint(db, zDb);
138468    sqlite3EndBenignMalloc();
138469  }
138470  return SQLITE_OK;
138471}
138472#endif /* SQLITE_OMIT_WAL */
138473
138474/*
138475** Configure an sqlite3_wal_hook() callback to automatically checkpoint
138476** a database after committing a transaction if there are nFrame or
138477** more frames in the log file. Passing zero or a negative value as the
138478** nFrame parameter disables automatic checkpoints entirely.
138479**
138480** The callback registered by this function replaces any existing callback
138481** registered using sqlite3_wal_hook(). Likewise, registering a callback
138482** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
138483** configured by this function.
138484*/
138485SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
138486#ifdef SQLITE_OMIT_WAL
138487  UNUSED_PARAMETER(db);
138488  UNUSED_PARAMETER(nFrame);
138489#else
138490#ifdef SQLITE_ENABLE_API_ARMOR
138491  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
138492#endif
138493  if( nFrame>0 ){
138494    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
138495  }else{
138496    sqlite3_wal_hook(db, 0, 0);
138497  }
138498#endif
138499  return SQLITE_OK;
138500}
138501
138502/*
138503** Register a callback to be invoked each time a transaction is written
138504** into the write-ahead-log by this database connection.
138505*/
138506SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
138507  sqlite3 *db,                    /* Attach the hook to this db handle */
138508  int(*xCallback)(void *, sqlite3*, const char*, int),
138509  void *pArg                      /* First argument passed to xCallback() */
138510){
138511#ifndef SQLITE_OMIT_WAL
138512  void *pRet;
138513#ifdef SQLITE_ENABLE_API_ARMOR
138514  if( !sqlite3SafetyCheckOk(db) ){
138515    (void)SQLITE_MISUSE_BKPT;
138516    return 0;
138517  }
138518#endif
138519  sqlite3_mutex_enter(db->mutex);
138520  pRet = db->pWalArg;
138521  db->xWalCallback = xCallback;
138522  db->pWalArg = pArg;
138523  sqlite3_mutex_leave(db->mutex);
138524  return pRet;
138525#else
138526  return 0;
138527#endif
138528}
138529
138530/*
138531** Checkpoint database zDb.
138532*/
138533SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
138534  sqlite3 *db,                    /* Database handle */
138535  const char *zDb,                /* Name of attached database (or NULL) */
138536  int eMode,                      /* SQLITE_CHECKPOINT_* value */
138537  int *pnLog,                     /* OUT: Size of WAL log in frames */
138538  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
138539){
138540#ifdef SQLITE_OMIT_WAL
138541  return SQLITE_OK;
138542#else
138543  int rc;                         /* Return code */
138544  int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
138545
138546#ifdef SQLITE_ENABLE_API_ARMOR
138547  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
138548#endif
138549
138550  /* Initialize the output variables to -1 in case an error occurs. */
138551  if( pnLog ) *pnLog = -1;
138552  if( pnCkpt ) *pnCkpt = -1;
138553
138554  assert( SQLITE_CHECKPOINT_PASSIVE==0 );
138555  assert( SQLITE_CHECKPOINT_FULL==1 );
138556  assert( SQLITE_CHECKPOINT_RESTART==2 );
138557  assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
138558  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
138559    /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
138560    ** mode: */
138561    return SQLITE_MISUSE;
138562  }
138563
138564  sqlite3_mutex_enter(db->mutex);
138565  if( zDb && zDb[0] ){
138566    iDb = sqlite3FindDbName(db, zDb);
138567  }
138568  if( iDb<0 ){
138569    rc = SQLITE_ERROR;
138570    sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
138571  }else{
138572    db->busyHandler.nBusy = 0;
138573    rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
138574    sqlite3Error(db, rc);
138575  }
138576  rc = sqlite3ApiExit(db, rc);
138577  sqlite3_mutex_leave(db->mutex);
138578  return rc;
138579#endif
138580}
138581
138582
138583/*
138584** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
138585** to contains a zero-length string, all attached databases are
138586** checkpointed.
138587*/
138588SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
138589  /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
138590  ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
138591  return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
138592}
138593
138594#ifndef SQLITE_OMIT_WAL
138595/*
138596** Run a checkpoint on database iDb. This is a no-op if database iDb is
138597** not currently open in WAL mode.
138598**
138599** If a transaction is open on the database being checkpointed, this
138600** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
138601** an error occurs while running the checkpoint, an SQLite error code is
138602** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
138603**
138604** The mutex on database handle db should be held by the caller. The mutex
138605** associated with the specific b-tree being checkpointed is taken by
138606** this function while the checkpoint is running.
138607**
138608** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
138609** checkpointed. If an error is encountered it is returned immediately -
138610** no attempt is made to checkpoint any remaining databases.
138611**
138612** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
138613*/
138614SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
138615  int rc = SQLITE_OK;             /* Return code */
138616  int i;                          /* Used to iterate through attached dbs */
138617  int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
138618
138619  assert( sqlite3_mutex_held(db->mutex) );
138620  assert( !pnLog || *pnLog==-1 );
138621  assert( !pnCkpt || *pnCkpt==-1 );
138622
138623  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
138624    if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
138625      rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
138626      pnLog = 0;
138627      pnCkpt = 0;
138628      if( rc==SQLITE_BUSY ){
138629        bBusy = 1;
138630        rc = SQLITE_OK;
138631      }
138632    }
138633  }
138634
138635  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
138636}
138637#endif /* SQLITE_OMIT_WAL */
138638
138639/*
138640** This function returns true if main-memory should be used instead of
138641** a temporary file for transient pager files and statement journals.
138642** The value returned depends on the value of db->temp_store (runtime
138643** parameter) and the compile time value of SQLITE_TEMP_STORE. The
138644** following table describes the relationship between these two values
138645** and this functions return value.
138646**
138647**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
138648**   -----------------     --------------     ------------------------------
138649**   0                     any                file      (return 0)
138650**   1                     1                  file      (return 0)
138651**   1                     2                  memory    (return 1)
138652**   1                     0                  file      (return 0)
138653**   2                     1                  file      (return 0)
138654**   2                     2                  memory    (return 1)
138655**   2                     0                  memory    (return 1)
138656**   3                     any                memory    (return 1)
138657*/
138658SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
138659#if SQLITE_TEMP_STORE==1
138660  return ( db->temp_store==2 );
138661#endif
138662#if SQLITE_TEMP_STORE==2
138663  return ( db->temp_store!=1 );
138664#endif
138665#if SQLITE_TEMP_STORE==3
138666  UNUSED_PARAMETER(db);
138667  return 1;
138668#endif
138669#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
138670  UNUSED_PARAMETER(db);
138671  return 0;
138672#endif
138673}
138674
138675/*
138676** Return UTF-8 encoded English language explanation of the most recent
138677** error.
138678*/
138679SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3 *db){
138680  const char *z;
138681  if( !db ){
138682    return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
138683  }
138684  if( !sqlite3SafetyCheckSickOrOk(db) ){
138685    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
138686  }
138687  sqlite3_mutex_enter(db->mutex);
138688  if( db->mallocFailed ){
138689    z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
138690  }else{
138691    testcase( db->pErr==0 );
138692    z = (char*)sqlite3_value_text(db->pErr);
138693    assert( !db->mallocFailed );
138694    if( z==0 ){
138695      z = sqlite3ErrStr(db->errCode);
138696    }
138697  }
138698  sqlite3_mutex_leave(db->mutex);
138699  return z;
138700}
138701
138702#ifndef SQLITE_OMIT_UTF16
138703/*
138704** Return UTF-16 encoded English language explanation of the most recent
138705** error.
138706*/
138707SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3 *db){
138708  static const u16 outOfMem[] = {
138709    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
138710  };
138711  static const u16 misuse[] = {
138712    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
138713    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
138714    'c', 'a', 'l', 'l', 'e', 'd', ' ',
138715    'o', 'u', 't', ' ',
138716    'o', 'f', ' ',
138717    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
138718  };
138719
138720  const void *z;
138721  if( !db ){
138722    return (void *)outOfMem;
138723  }
138724  if( !sqlite3SafetyCheckSickOrOk(db) ){
138725    return (void *)misuse;
138726  }
138727  sqlite3_mutex_enter(db->mutex);
138728  if( db->mallocFailed ){
138729    z = (void *)outOfMem;
138730  }else{
138731    z = sqlite3_value_text16(db->pErr);
138732    if( z==0 ){
138733      sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
138734      z = sqlite3_value_text16(db->pErr);
138735    }
138736    /* A malloc() may have failed within the call to sqlite3_value_text16()
138737    ** above. If this is the case, then the db->mallocFailed flag needs to
138738    ** be cleared before returning. Do this directly, instead of via
138739    ** sqlite3ApiExit(), to avoid setting the database handle error message.
138740    */
138741    sqlite3OomClear(db);
138742  }
138743  sqlite3_mutex_leave(db->mutex);
138744  return z;
138745}
138746#endif /* SQLITE_OMIT_UTF16 */
138747
138748/*
138749** Return the most recent error code generated by an SQLite routine. If NULL is
138750** passed to this function, we assume a malloc() failed during sqlite3_open().
138751*/
138752SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db){
138753  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
138754    return SQLITE_MISUSE_BKPT;
138755  }
138756  if( !db || db->mallocFailed ){
138757    return SQLITE_NOMEM_BKPT;
138758  }
138759  return db->errCode & db->errMask;
138760}
138761SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db){
138762  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
138763    return SQLITE_MISUSE_BKPT;
138764  }
138765  if( !db || db->mallocFailed ){
138766    return SQLITE_NOMEM_BKPT;
138767  }
138768  return db->errCode;
138769}
138770SQLITE_API int SQLITE_STDCALL sqlite3_system_errno(sqlite3 *db){
138771  return db ? db->iSysErrno : 0;
138772}
138773
138774/*
138775** Return a string that describes the kind of error specified in the
138776** argument.  For now, this simply calls the internal sqlite3ErrStr()
138777** function.
138778*/
138779SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int rc){
138780  return sqlite3ErrStr(rc);
138781}
138782
138783/*
138784** Create a new collating function for database "db".  The name is zName
138785** and the encoding is enc.
138786*/
138787static int createCollation(
138788  sqlite3* db,
138789  const char *zName,
138790  u8 enc,
138791  void* pCtx,
138792  int(*xCompare)(void*,int,const void*,int,const void*),
138793  void(*xDel)(void*)
138794){
138795  CollSeq *pColl;
138796  int enc2;
138797
138798  assert( sqlite3_mutex_held(db->mutex) );
138799
138800  /* If SQLITE_UTF16 is specified as the encoding type, transform this
138801  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
138802  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
138803  */
138804  enc2 = enc;
138805  testcase( enc2==SQLITE_UTF16 );
138806  testcase( enc2==SQLITE_UTF16_ALIGNED );
138807  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
138808    enc2 = SQLITE_UTF16NATIVE;
138809  }
138810  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
138811    return SQLITE_MISUSE_BKPT;
138812  }
138813
138814  /* Check if this call is removing or replacing an existing collation
138815  ** sequence. If so, and there are active VMs, return busy. If there
138816  ** are no active VMs, invalidate any pre-compiled statements.
138817  */
138818  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
138819  if( pColl && pColl->xCmp ){
138820    if( db->nVdbeActive ){
138821      sqlite3ErrorWithMsg(db, SQLITE_BUSY,
138822        "unable to delete/modify collation sequence due to active statements");
138823      return SQLITE_BUSY;
138824    }
138825    sqlite3ExpirePreparedStatements(db);
138826
138827    /* If collation sequence pColl was created directly by a call to
138828    ** sqlite3_create_collation, and not generated by synthCollSeq(),
138829    ** then any copies made by synthCollSeq() need to be invalidated.
138830    ** Also, collation destructor - CollSeq.xDel() - function may need
138831    ** to be called.
138832    */
138833    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
138834      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
138835      int j;
138836      for(j=0; j<3; j++){
138837        CollSeq *p = &aColl[j];
138838        if( p->enc==pColl->enc ){
138839          if( p->xDel ){
138840            p->xDel(p->pUser);
138841          }
138842          p->xCmp = 0;
138843        }
138844      }
138845    }
138846  }
138847
138848  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
138849  if( pColl==0 ) return SQLITE_NOMEM_BKPT;
138850  pColl->xCmp = xCompare;
138851  pColl->pUser = pCtx;
138852  pColl->xDel = xDel;
138853  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
138854  sqlite3Error(db, SQLITE_OK);
138855  return SQLITE_OK;
138856}
138857
138858
138859/*
138860** This array defines hard upper bounds on limit values.  The
138861** initializer must be kept in sync with the SQLITE_LIMIT_*
138862** #defines in sqlite3.h.
138863*/
138864static const int aHardLimit[] = {
138865  SQLITE_MAX_LENGTH,
138866  SQLITE_MAX_SQL_LENGTH,
138867  SQLITE_MAX_COLUMN,
138868  SQLITE_MAX_EXPR_DEPTH,
138869  SQLITE_MAX_COMPOUND_SELECT,
138870  SQLITE_MAX_VDBE_OP,
138871  SQLITE_MAX_FUNCTION_ARG,
138872  SQLITE_MAX_ATTACHED,
138873  SQLITE_MAX_LIKE_PATTERN_LENGTH,
138874  SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
138875  SQLITE_MAX_TRIGGER_DEPTH,
138876  SQLITE_MAX_WORKER_THREADS,
138877};
138878
138879/*
138880** Make sure the hard limits are set to reasonable values
138881*/
138882#if SQLITE_MAX_LENGTH<100
138883# error SQLITE_MAX_LENGTH must be at least 100
138884#endif
138885#if SQLITE_MAX_SQL_LENGTH<100
138886# error SQLITE_MAX_SQL_LENGTH must be at least 100
138887#endif
138888#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
138889# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
138890#endif
138891#if SQLITE_MAX_COMPOUND_SELECT<2
138892# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
138893#endif
138894#if SQLITE_MAX_VDBE_OP<40
138895# error SQLITE_MAX_VDBE_OP must be at least 40
138896#endif
138897#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
138898# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
138899#endif
138900#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
138901# error SQLITE_MAX_ATTACHED must be between 0 and 125
138902#endif
138903#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
138904# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
138905#endif
138906#if SQLITE_MAX_COLUMN>32767
138907# error SQLITE_MAX_COLUMN must not exceed 32767
138908#endif
138909#if SQLITE_MAX_TRIGGER_DEPTH<1
138910# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
138911#endif
138912#if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
138913# error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
138914#endif
138915
138916
138917/*
138918** Change the value of a limit.  Report the old value.
138919** If an invalid limit index is supplied, report -1.
138920** Make no changes but still report the old value if the
138921** new limit is negative.
138922**
138923** A new lower limit does not shrink existing constructs.
138924** It merely prevents new constructs that exceed the limit
138925** from forming.
138926*/
138927SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
138928  int oldLimit;
138929
138930#ifdef SQLITE_ENABLE_API_ARMOR
138931  if( !sqlite3SafetyCheckOk(db) ){
138932    (void)SQLITE_MISUSE_BKPT;
138933    return -1;
138934  }
138935#endif
138936
138937  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
138938  ** there is a hard upper bound set at compile-time by a C preprocessor
138939  ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
138940  ** "_MAX_".)
138941  */
138942  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
138943  assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
138944  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
138945  assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
138946  assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
138947  assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
138948  assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
138949  assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
138950  assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
138951                                               SQLITE_MAX_LIKE_PATTERN_LENGTH );
138952  assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
138953  assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
138954  assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
138955  assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
138956
138957
138958  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
138959    return -1;
138960  }
138961  oldLimit = db->aLimit[limitId];
138962  if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
138963    if( newLimit>aHardLimit[limitId] ){
138964      newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
138965    }
138966    db->aLimit[limitId] = newLimit;
138967  }
138968  return oldLimit;                     /* IMP: R-53341-35419 */
138969}
138970
138971/*
138972** This function is used to parse both URIs and non-URI filenames passed by the
138973** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
138974** URIs specified as part of ATTACH statements.
138975**
138976** The first argument to this function is the name of the VFS to use (or
138977** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
138978** query parameter. The second argument contains the URI (or non-URI filename)
138979** itself. When this function is called the *pFlags variable should contain
138980** the default flags to open the database handle with. The value stored in
138981** *pFlags may be updated before returning if the URI filename contains
138982** "cache=xxx" or "mode=xxx" query parameters.
138983**
138984** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
138985** the VFS that should be used to open the database file. *pzFile is set to
138986** point to a buffer containing the name of the file to open. It is the
138987** responsibility of the caller to eventually call sqlite3_free() to release
138988** this buffer.
138989**
138990** If an error occurs, then an SQLite error code is returned and *pzErrMsg
138991** may be set to point to a buffer containing an English language error
138992** message. It is the responsibility of the caller to eventually release
138993** this buffer by calling sqlite3_free().
138994*/
138995SQLITE_PRIVATE int sqlite3ParseUri(
138996  const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
138997  const char *zUri,               /* Nul-terminated URI to parse */
138998  unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
138999  sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
139000  char **pzFile,                  /* OUT: Filename component of URI */
139001  char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
139002){
139003  int rc = SQLITE_OK;
139004  unsigned int flags = *pFlags;
139005  const char *zVfs = zDefaultVfs;
139006  char *zFile;
139007  char c;
139008  int nUri = sqlite3Strlen30(zUri);
139009
139010  assert( *pzErrMsg==0 );
139011
139012  if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
139013            || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
139014   && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
139015  ){
139016    char *zOpt;
139017    int eState;                   /* Parser state when parsing URI */
139018    int iIn;                      /* Input character index */
139019    int iOut = 0;                 /* Output character index */
139020    u64 nByte = nUri+2;           /* Bytes of space to allocate */
139021
139022    /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
139023    ** method that there may be extra parameters following the file-name.  */
139024    flags |= SQLITE_OPEN_URI;
139025
139026    for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
139027    zFile = sqlite3_malloc64(nByte);
139028    if( !zFile ) return SQLITE_NOMEM_BKPT;
139029
139030    iIn = 5;
139031#ifdef SQLITE_ALLOW_URI_AUTHORITY
139032    if( strncmp(zUri+5, "///", 3)==0 ){
139033      iIn = 7;
139034      /* The following condition causes URIs with five leading / characters
139035      ** like file://///host/path to be converted into UNCs like //host/path.
139036      ** The correct URI for that UNC has only two or four leading / characters
139037      ** file://host/path or file:////host/path.  But 5 leading slashes is a
139038      ** common error, we are told, so we handle it as a special case. */
139039      if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
139040    }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
139041      iIn = 16;
139042    }
139043#else
139044    /* Discard the scheme and authority segments of the URI. */
139045    if( zUri[5]=='/' && zUri[6]=='/' ){
139046      iIn = 7;
139047      while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
139048      if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
139049        *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
139050            iIn-7, &zUri[7]);
139051        rc = SQLITE_ERROR;
139052        goto parse_uri_out;
139053      }
139054    }
139055#endif
139056
139057    /* Copy the filename and any query parameters into the zFile buffer.
139058    ** Decode %HH escape codes along the way.
139059    **
139060    ** Within this loop, variable eState may be set to 0, 1 or 2, depending
139061    ** on the parsing context. As follows:
139062    **
139063    **   0: Parsing file-name.
139064    **   1: Parsing name section of a name=value query parameter.
139065    **   2: Parsing value section of a name=value query parameter.
139066    */
139067    eState = 0;
139068    while( (c = zUri[iIn])!=0 && c!='#' ){
139069      iIn++;
139070      if( c=='%'
139071       && sqlite3Isxdigit(zUri[iIn])
139072       && sqlite3Isxdigit(zUri[iIn+1])
139073      ){
139074        int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
139075        octet += sqlite3HexToInt(zUri[iIn++]);
139076
139077        assert( octet>=0 && octet<256 );
139078        if( octet==0 ){
139079          /* This branch is taken when "%00" appears within the URI. In this
139080          ** case we ignore all text in the remainder of the path, name or
139081          ** value currently being parsed. So ignore the current character
139082          ** and skip to the next "?", "=" or "&", as appropriate. */
139083          while( (c = zUri[iIn])!=0 && c!='#'
139084              && (eState!=0 || c!='?')
139085              && (eState!=1 || (c!='=' && c!='&'))
139086              && (eState!=2 || c!='&')
139087          ){
139088            iIn++;
139089          }
139090          continue;
139091        }
139092        c = octet;
139093      }else if( eState==1 && (c=='&' || c=='=') ){
139094        if( zFile[iOut-1]==0 ){
139095          /* An empty option name. Ignore this option altogether. */
139096          while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
139097          continue;
139098        }
139099        if( c=='&' ){
139100          zFile[iOut++] = '\0';
139101        }else{
139102          eState = 2;
139103        }
139104        c = 0;
139105      }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
139106        c = 0;
139107        eState = 1;
139108      }
139109      zFile[iOut++] = c;
139110    }
139111    if( eState==1 ) zFile[iOut++] = '\0';
139112    zFile[iOut++] = '\0';
139113    zFile[iOut++] = '\0';
139114
139115    /* Check if there were any options specified that should be interpreted
139116    ** here. Options that are interpreted here include "vfs" and those that
139117    ** correspond to flags that may be passed to the sqlite3_open_v2()
139118    ** method. */
139119    zOpt = &zFile[sqlite3Strlen30(zFile)+1];
139120    while( zOpt[0] ){
139121      int nOpt = sqlite3Strlen30(zOpt);
139122      char *zVal = &zOpt[nOpt+1];
139123      int nVal = sqlite3Strlen30(zVal);
139124
139125      if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
139126        zVfs = zVal;
139127      }else{
139128        struct OpenMode {
139129          const char *z;
139130          int mode;
139131        } *aMode = 0;
139132        char *zModeType = 0;
139133        int mask = 0;
139134        int limit = 0;
139135
139136        if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
139137          static struct OpenMode aCacheMode[] = {
139138            { "shared",  SQLITE_OPEN_SHAREDCACHE },
139139            { "private", SQLITE_OPEN_PRIVATECACHE },
139140            { 0, 0 }
139141          };
139142
139143          mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
139144          aMode = aCacheMode;
139145          limit = mask;
139146          zModeType = "cache";
139147        }
139148        if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
139149          static struct OpenMode aOpenMode[] = {
139150            { "ro",  SQLITE_OPEN_READONLY },
139151            { "rw",  SQLITE_OPEN_READWRITE },
139152            { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
139153            { "memory", SQLITE_OPEN_MEMORY },
139154            { 0, 0 }
139155          };
139156
139157          mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
139158                   | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
139159          aMode = aOpenMode;
139160          limit = mask & flags;
139161          zModeType = "access";
139162        }
139163
139164        if( aMode ){
139165          int i;
139166          int mode = 0;
139167          for(i=0; aMode[i].z; i++){
139168            const char *z = aMode[i].z;
139169            if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
139170              mode = aMode[i].mode;
139171              break;
139172            }
139173          }
139174          if( mode==0 ){
139175            *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
139176            rc = SQLITE_ERROR;
139177            goto parse_uri_out;
139178          }
139179          if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
139180            *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
139181                                        zModeType, zVal);
139182            rc = SQLITE_PERM;
139183            goto parse_uri_out;
139184          }
139185          flags = (flags & ~mask) | mode;
139186        }
139187      }
139188
139189      zOpt = &zVal[nVal+1];
139190    }
139191
139192  }else{
139193    zFile = sqlite3_malloc64(nUri+2);
139194    if( !zFile ) return SQLITE_NOMEM_BKPT;
139195    memcpy(zFile, zUri, nUri);
139196    zFile[nUri] = '\0';
139197    zFile[nUri+1] = '\0';
139198    flags &= ~SQLITE_OPEN_URI;
139199  }
139200
139201  *ppVfs = sqlite3_vfs_find(zVfs);
139202  if( *ppVfs==0 ){
139203    *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
139204    rc = SQLITE_ERROR;
139205  }
139206 parse_uri_out:
139207  if( rc!=SQLITE_OK ){
139208    sqlite3_free(zFile);
139209    zFile = 0;
139210  }
139211  *pFlags = flags;
139212  *pzFile = zFile;
139213  return rc;
139214}
139215
139216
139217/*
139218** This routine does the work of opening a database on behalf of
139219** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
139220** is UTF-8 encoded.
139221*/
139222static int openDatabase(
139223  const char *zFilename, /* Database filename UTF-8 encoded */
139224  sqlite3 **ppDb,        /* OUT: Returned database handle */
139225  unsigned int flags,    /* Operational flags */
139226  const char *zVfs       /* Name of the VFS to use */
139227){
139228  sqlite3 *db;                    /* Store allocated handle here */
139229  int rc;                         /* Return code */
139230  int isThreadsafe;               /* True for threadsafe connections */
139231  char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
139232  char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
139233
139234#ifdef SQLITE_ENABLE_API_ARMOR
139235  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
139236#endif
139237  *ppDb = 0;
139238#ifndef SQLITE_OMIT_AUTOINIT
139239  rc = sqlite3_initialize();
139240  if( rc ) return rc;
139241#endif
139242
139243  /* Only allow sensible combinations of bits in the flags argument.
139244  ** Throw an error if any non-sense combination is used.  If we
139245  ** do not block illegal combinations here, it could trigger
139246  ** assert() statements in deeper layers.  Sensible combinations
139247  ** are:
139248  **
139249  **  1:  SQLITE_OPEN_READONLY
139250  **  2:  SQLITE_OPEN_READWRITE
139251  **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
139252  */
139253  assert( SQLITE_OPEN_READONLY  == 0x01 );
139254  assert( SQLITE_OPEN_READWRITE == 0x02 );
139255  assert( SQLITE_OPEN_CREATE    == 0x04 );
139256  testcase( (1<<(flags&7))==0x02 ); /* READONLY */
139257  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
139258  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
139259  if( ((1<<(flags&7)) & 0x46)==0 ){
139260    return SQLITE_MISUSE_BKPT;  /* IMP: R-65497-44594 */
139261  }
139262
139263  if( sqlite3GlobalConfig.bCoreMutex==0 ){
139264    isThreadsafe = 0;
139265  }else if( flags & SQLITE_OPEN_NOMUTEX ){
139266    isThreadsafe = 0;
139267  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
139268    isThreadsafe = 1;
139269  }else{
139270    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
139271  }
139272  if( flags & SQLITE_OPEN_PRIVATECACHE ){
139273    flags &= ~SQLITE_OPEN_SHAREDCACHE;
139274  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
139275    flags |= SQLITE_OPEN_SHAREDCACHE;
139276  }
139277
139278  /* Remove harmful bits from the flags parameter
139279  **
139280  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
139281  ** dealt with in the previous code block.  Besides these, the only
139282  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
139283  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
139284  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
139285  ** off all other flags.
139286  */
139287  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
139288               SQLITE_OPEN_EXCLUSIVE |
139289               SQLITE_OPEN_MAIN_DB |
139290               SQLITE_OPEN_TEMP_DB |
139291               SQLITE_OPEN_TRANSIENT_DB |
139292               SQLITE_OPEN_MAIN_JOURNAL |
139293               SQLITE_OPEN_TEMP_JOURNAL |
139294               SQLITE_OPEN_SUBJOURNAL |
139295               SQLITE_OPEN_MASTER_JOURNAL |
139296               SQLITE_OPEN_NOMUTEX |
139297               SQLITE_OPEN_FULLMUTEX |
139298               SQLITE_OPEN_WAL
139299             );
139300
139301  /* Allocate the sqlite data structure */
139302  db = sqlite3MallocZero( sizeof(sqlite3) );
139303  if( db==0 ) goto opendb_out;
139304  if( isThreadsafe ){
139305    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
139306    if( db->mutex==0 ){
139307      sqlite3_free(db);
139308      db = 0;
139309      goto opendb_out;
139310    }
139311  }
139312  sqlite3_mutex_enter(db->mutex);
139313  db->errMask = 0xff;
139314  db->nDb = 2;
139315  db->magic = SQLITE_MAGIC_BUSY;
139316  db->aDb = db->aDbStatic;
139317
139318  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
139319  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
139320  db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
139321  db->autoCommit = 1;
139322  db->nextAutovac = -1;
139323  db->szMmap = sqlite3GlobalConfig.szMmap;
139324  db->nextPagesize = 0;
139325  db->nMaxSorterMmap = 0x7FFFFFFF;
139326  db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
139327#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
139328                 | SQLITE_AutoIndex
139329#endif
139330#if SQLITE_DEFAULT_CKPTFULLFSYNC
139331                 | SQLITE_CkptFullFSync
139332#endif
139333#if SQLITE_DEFAULT_FILE_FORMAT<4
139334                 | SQLITE_LegacyFileFmt
139335#endif
139336#ifdef SQLITE_ENABLE_LOAD_EXTENSION
139337                 | SQLITE_LoadExtension
139338#endif
139339#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
139340                 | SQLITE_RecTriggers
139341#endif
139342#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
139343                 | SQLITE_ForeignKeys
139344#endif
139345#if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
139346                 | SQLITE_ReverseOrder
139347#endif
139348#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
139349                 | SQLITE_CellSizeCk
139350#endif
139351#if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
139352                 | SQLITE_Fts3Tokenizer
139353#endif
139354      ;
139355  sqlite3HashInit(&db->aCollSeq);
139356#ifndef SQLITE_OMIT_VIRTUALTABLE
139357  sqlite3HashInit(&db->aModule);
139358#endif
139359
139360  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
139361  ** and UTF-16, so add a version for each to avoid any unnecessary
139362  ** conversions. The only error that can occur here is a malloc() failure.
139363  **
139364  ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
139365  ** functions:
139366  */
139367  createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
139368  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
139369  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
139370  createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
139371  createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
139372  if( db->mallocFailed ){
139373    goto opendb_out;
139374  }
139375  /* EVIDENCE-OF: R-08308-17224 The default collating function for all
139376  ** strings is BINARY.
139377  */
139378  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
139379  assert( db->pDfltColl!=0 );
139380
139381  /* Parse the filename/URI argument. */
139382  db->openFlags = flags;
139383  rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
139384  if( rc!=SQLITE_OK ){
139385    if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
139386    sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
139387    sqlite3_free(zErrMsg);
139388    goto opendb_out;
139389  }
139390
139391  /* Open the backend database driver */
139392  rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
139393                        flags | SQLITE_OPEN_MAIN_DB);
139394  if( rc!=SQLITE_OK ){
139395    if( rc==SQLITE_IOERR_NOMEM ){
139396      rc = SQLITE_NOMEM_BKPT;
139397    }
139398    sqlite3Error(db, rc);
139399    goto opendb_out;
139400  }
139401  sqlite3BtreeEnter(db->aDb[0].pBt);
139402  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
139403  if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
139404  sqlite3BtreeLeave(db->aDb[0].pBt);
139405  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
139406
139407  /* The default safety_level for the main database is FULL; for the temp
139408  ** database it is OFF. This matches the pager layer defaults.
139409  */
139410  db->aDb[0].zName = "main";
139411  db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
139412  db->aDb[1].zName = "temp";
139413  db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
139414
139415  db->magic = SQLITE_MAGIC_OPEN;
139416  if( db->mallocFailed ){
139417    goto opendb_out;
139418  }
139419
139420  /* Register all built-in functions, but do not attempt to read the
139421  ** database schema yet. This is delayed until the first time the database
139422  ** is accessed.
139423  */
139424  sqlite3Error(db, SQLITE_OK);
139425  sqlite3RegisterPerConnectionBuiltinFunctions(db);
139426
139427  /* Load automatic extensions - extensions that have been registered
139428  ** using the sqlite3_automatic_extension() API.
139429  */
139430  rc = sqlite3_errcode(db);
139431  if( rc==SQLITE_OK ){
139432    sqlite3AutoLoadExtensions(db);
139433    rc = sqlite3_errcode(db);
139434    if( rc!=SQLITE_OK ){
139435      goto opendb_out;
139436    }
139437  }
139438
139439#ifdef SQLITE_ENABLE_FTS1
139440  if( !db->mallocFailed ){
139441    extern int sqlite3Fts1Init(sqlite3*);
139442    rc = sqlite3Fts1Init(db);
139443  }
139444#endif
139445
139446#ifdef SQLITE_ENABLE_FTS2
139447  if( !db->mallocFailed && rc==SQLITE_OK ){
139448    extern int sqlite3Fts2Init(sqlite3*);
139449    rc = sqlite3Fts2Init(db);
139450  }
139451#endif
139452
139453#ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
139454  if( !db->mallocFailed && rc==SQLITE_OK ){
139455    rc = sqlite3Fts3Init(db);
139456  }
139457#endif
139458
139459#ifdef SQLITE_ENABLE_FTS5
139460  if( !db->mallocFailed && rc==SQLITE_OK ){
139461    rc = sqlite3Fts5Init(db);
139462  }
139463#endif
139464
139465#ifdef SQLITE_ENABLE_ICU
139466  if( !db->mallocFailed && rc==SQLITE_OK ){
139467    rc = sqlite3IcuInit(db);
139468  }
139469#endif
139470
139471#ifdef SQLITE_ENABLE_RTREE
139472  if( !db->mallocFailed && rc==SQLITE_OK){
139473    rc = sqlite3RtreeInit(db);
139474  }
139475#endif
139476
139477#ifdef SQLITE_ENABLE_DBSTAT_VTAB
139478  if( !db->mallocFailed && rc==SQLITE_OK){
139479    rc = sqlite3DbstatRegister(db);
139480  }
139481#endif
139482
139483#ifdef SQLITE_ENABLE_JSON1
139484  if( !db->mallocFailed && rc==SQLITE_OK){
139485    rc = sqlite3Json1Init(db);
139486  }
139487#endif
139488
139489  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
139490  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
139491  ** mode.  Doing nothing at all also makes NORMAL the default.
139492  */
139493#ifdef SQLITE_DEFAULT_LOCKING_MODE
139494  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
139495  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
139496                          SQLITE_DEFAULT_LOCKING_MODE);
139497#endif
139498
139499  if( rc ) sqlite3Error(db, rc);
139500
139501  /* Enable the lookaside-malloc subsystem */
139502  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
139503                        sqlite3GlobalConfig.nLookaside);
139504
139505  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
139506
139507opendb_out:
139508  if( db ){
139509    assert( db->mutex!=0 || isThreadsafe==0
139510           || sqlite3GlobalConfig.bFullMutex==0 );
139511    sqlite3_mutex_leave(db->mutex);
139512  }
139513  rc = sqlite3_errcode(db);
139514  assert( db!=0 || rc==SQLITE_NOMEM );
139515  if( rc==SQLITE_NOMEM ){
139516    sqlite3_close(db);
139517    db = 0;
139518  }else if( rc!=SQLITE_OK ){
139519    db->magic = SQLITE_MAGIC_SICK;
139520  }
139521  *ppDb = db;
139522#ifdef SQLITE_ENABLE_SQLLOG
139523  if( sqlite3GlobalConfig.xSqllog ){
139524    /* Opening a db handle. Fourth parameter is passed 0. */
139525    void *pArg = sqlite3GlobalConfig.pSqllogArg;
139526    sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
139527  }
139528#endif
139529#if defined(SQLITE_HAS_CODEC)
139530  if( rc==SQLITE_OK ){
139531    const char *zHexKey = sqlite3_uri_parameter(zOpen, "hexkey");
139532    if( zHexKey && zHexKey[0] ){
139533      u8 iByte;
139534      int i;
139535      char zKey[40];
139536      for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zHexKey[i]); i++){
139537        iByte = (iByte<<4) + sqlite3HexToInt(zHexKey[i]);
139538        if( (i&1)!=0 ) zKey[i/2] = iByte;
139539      }
139540      sqlite3_key_v2(db, 0, zKey, i/2);
139541    }
139542  }
139543#endif
139544  sqlite3_free(zOpen);
139545  return rc & 0xff;
139546}
139547
139548/*
139549** Open a new database handle.
139550*/
139551SQLITE_API int SQLITE_STDCALL sqlite3_open(
139552  const char *zFilename,
139553  sqlite3 **ppDb
139554){
139555  return openDatabase(zFilename, ppDb,
139556                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
139557}
139558SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
139559  const char *filename,   /* Database filename (UTF-8) */
139560  sqlite3 **ppDb,         /* OUT: SQLite db handle */
139561  int flags,              /* Flags */
139562  const char *zVfs        /* Name of VFS module to use */
139563){
139564  return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
139565}
139566
139567#ifndef SQLITE_OMIT_UTF16
139568/*
139569** Open a new database handle.
139570*/
139571SQLITE_API int SQLITE_STDCALL sqlite3_open16(
139572  const void *zFilename,
139573  sqlite3 **ppDb
139574){
139575  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
139576  sqlite3_value *pVal;
139577  int rc;
139578
139579#ifdef SQLITE_ENABLE_API_ARMOR
139580  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
139581#endif
139582  *ppDb = 0;
139583#ifndef SQLITE_OMIT_AUTOINIT
139584  rc = sqlite3_initialize();
139585  if( rc ) return rc;
139586#endif
139587  if( zFilename==0 ) zFilename = "\000\000";
139588  pVal = sqlite3ValueNew(0);
139589  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
139590  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
139591  if( zFilename8 ){
139592    rc = openDatabase(zFilename8, ppDb,
139593                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
139594    assert( *ppDb || rc==SQLITE_NOMEM );
139595    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
139596      SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
139597    }
139598  }else{
139599    rc = SQLITE_NOMEM_BKPT;
139600  }
139601  sqlite3ValueFree(pVal);
139602
139603  return rc & 0xff;
139604}
139605#endif /* SQLITE_OMIT_UTF16 */
139606
139607/*
139608** Register a new collation sequence with the database handle db.
139609*/
139610SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
139611  sqlite3* db,
139612  const char *zName,
139613  int enc,
139614  void* pCtx,
139615  int(*xCompare)(void*,int,const void*,int,const void*)
139616){
139617  return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
139618}
139619
139620/*
139621** Register a new collation sequence with the database handle db.
139622*/
139623SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
139624  sqlite3* db,
139625  const char *zName,
139626  int enc,
139627  void* pCtx,
139628  int(*xCompare)(void*,int,const void*,int,const void*),
139629  void(*xDel)(void*)
139630){
139631  int rc;
139632
139633#ifdef SQLITE_ENABLE_API_ARMOR
139634  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
139635#endif
139636  sqlite3_mutex_enter(db->mutex);
139637  assert( !db->mallocFailed );
139638  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
139639  rc = sqlite3ApiExit(db, rc);
139640  sqlite3_mutex_leave(db->mutex);
139641  return rc;
139642}
139643
139644#ifndef SQLITE_OMIT_UTF16
139645/*
139646** Register a new collation sequence with the database handle db.
139647*/
139648SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
139649  sqlite3* db,
139650  const void *zName,
139651  int enc,
139652  void* pCtx,
139653  int(*xCompare)(void*,int,const void*,int,const void*)
139654){
139655  int rc = SQLITE_OK;
139656  char *zName8;
139657
139658#ifdef SQLITE_ENABLE_API_ARMOR
139659  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
139660#endif
139661  sqlite3_mutex_enter(db->mutex);
139662  assert( !db->mallocFailed );
139663  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
139664  if( zName8 ){
139665    rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
139666    sqlite3DbFree(db, zName8);
139667  }
139668  rc = sqlite3ApiExit(db, rc);
139669  sqlite3_mutex_leave(db->mutex);
139670  return rc;
139671}
139672#endif /* SQLITE_OMIT_UTF16 */
139673
139674/*
139675** Register a collation sequence factory callback with the database handle
139676** db. Replace any previously installed collation sequence factory.
139677*/
139678SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
139679  sqlite3 *db,
139680  void *pCollNeededArg,
139681  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
139682){
139683#ifdef SQLITE_ENABLE_API_ARMOR
139684  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139685#endif
139686  sqlite3_mutex_enter(db->mutex);
139687  db->xCollNeeded = xCollNeeded;
139688  db->xCollNeeded16 = 0;
139689  db->pCollNeededArg = pCollNeededArg;
139690  sqlite3_mutex_leave(db->mutex);
139691  return SQLITE_OK;
139692}
139693
139694#ifndef SQLITE_OMIT_UTF16
139695/*
139696** Register a collation sequence factory callback with the database handle
139697** db. Replace any previously installed collation sequence factory.
139698*/
139699SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
139700  sqlite3 *db,
139701  void *pCollNeededArg,
139702  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
139703){
139704#ifdef SQLITE_ENABLE_API_ARMOR
139705  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139706#endif
139707  sqlite3_mutex_enter(db->mutex);
139708  db->xCollNeeded = 0;
139709  db->xCollNeeded16 = xCollNeeded16;
139710  db->pCollNeededArg = pCollNeededArg;
139711  sqlite3_mutex_leave(db->mutex);
139712  return SQLITE_OK;
139713}
139714#endif /* SQLITE_OMIT_UTF16 */
139715
139716#ifndef SQLITE_OMIT_DEPRECATED
139717/*
139718** This function is now an anachronism. It used to be used to recover from a
139719** malloc() failure, but SQLite now does this automatically.
139720*/
139721SQLITE_API int SQLITE_STDCALL sqlite3_global_recover(void){
139722  return SQLITE_OK;
139723}
139724#endif
139725
139726/*
139727** Test to see whether or not the database connection is in autocommit
139728** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
139729** by default.  Autocommit is disabled by a BEGIN statement and reenabled
139730** by the next COMMIT or ROLLBACK.
139731*/
139732SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3 *db){
139733#ifdef SQLITE_ENABLE_API_ARMOR
139734  if( !sqlite3SafetyCheckOk(db) ){
139735    (void)SQLITE_MISUSE_BKPT;
139736    return 0;
139737  }
139738#endif
139739  return db->autoCommit;
139740}
139741
139742/*
139743** The following routines are substitutes for constants SQLITE_CORRUPT,
139744** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
139745** constants.  They serve two purposes:
139746**
139747**   1.  Serve as a convenient place to set a breakpoint in a debugger
139748**       to detect when version error conditions occurs.
139749**
139750**   2.  Invoke sqlite3_log() to provide the source code location where
139751**       a low-level error is first detected.
139752*/
139753static int reportError(int iErr, int lineno, const char *zType){
139754  sqlite3_log(iErr, "%s at line %d of [%.10s]",
139755              zType, lineno, 20+sqlite3_sourceid());
139756  return iErr;
139757}
139758SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
139759  testcase( sqlite3GlobalConfig.xLog!=0 );
139760  return reportError(SQLITE_CORRUPT, lineno, "database corruption");
139761}
139762SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
139763  testcase( sqlite3GlobalConfig.xLog!=0 );
139764  return reportError(SQLITE_MISUSE, lineno, "misuse");
139765}
139766SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
139767  testcase( sqlite3GlobalConfig.xLog!=0 );
139768  return reportError(SQLITE_CANTOPEN, lineno, "cannot open file");
139769}
139770#ifdef SQLITE_DEBUG
139771SQLITE_PRIVATE int sqlite3NomemError(int lineno){
139772  testcase( sqlite3GlobalConfig.xLog!=0 );
139773  return reportError(SQLITE_NOMEM, lineno, "OOM");
139774}
139775SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
139776  testcase( sqlite3GlobalConfig.xLog!=0 );
139777  return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
139778}
139779#endif
139780
139781#ifndef SQLITE_OMIT_DEPRECATED
139782/*
139783** This is a convenience routine that makes sure that all thread-specific
139784** data for this thread has been deallocated.
139785**
139786** SQLite no longer uses thread-specific data so this routine is now a
139787** no-op.  It is retained for historical compatibility.
139788*/
139789SQLITE_API void SQLITE_STDCALL sqlite3_thread_cleanup(void){
139790}
139791#endif
139792
139793/*
139794** Return meta information about a specific column of a database table.
139795** See comment in sqlite3.h (sqlite.h.in) for details.
139796*/
139797SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
139798  sqlite3 *db,                /* Connection handle */
139799  const char *zDbName,        /* Database name or NULL */
139800  const char *zTableName,     /* Table name */
139801  const char *zColumnName,    /* Column name */
139802  char const **pzDataType,    /* OUTPUT: Declared data type */
139803  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
139804  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
139805  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
139806  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
139807){
139808  int rc;
139809  char *zErrMsg = 0;
139810  Table *pTab = 0;
139811  Column *pCol = 0;
139812  int iCol = 0;
139813  char const *zDataType = 0;
139814  char const *zCollSeq = 0;
139815  int notnull = 0;
139816  int primarykey = 0;
139817  int autoinc = 0;
139818
139819
139820#ifdef SQLITE_ENABLE_API_ARMOR
139821  if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
139822    return SQLITE_MISUSE_BKPT;
139823  }
139824#endif
139825
139826  /* Ensure the database schema has been loaded */
139827  sqlite3_mutex_enter(db->mutex);
139828  sqlite3BtreeEnterAll(db);
139829  rc = sqlite3Init(db, &zErrMsg);
139830  if( SQLITE_OK!=rc ){
139831    goto error_out;
139832  }
139833
139834  /* Locate the table in question */
139835  pTab = sqlite3FindTable(db, zTableName, zDbName);
139836  if( !pTab || pTab->pSelect ){
139837    pTab = 0;
139838    goto error_out;
139839  }
139840
139841  /* Find the column for which info is requested */
139842  if( zColumnName==0 ){
139843    /* Query for existance of table only */
139844  }else{
139845    for(iCol=0; iCol<pTab->nCol; iCol++){
139846      pCol = &pTab->aCol[iCol];
139847      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
139848        break;
139849      }
139850    }
139851    if( iCol==pTab->nCol ){
139852      if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
139853        iCol = pTab->iPKey;
139854        pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
139855      }else{
139856        pTab = 0;
139857        goto error_out;
139858      }
139859    }
139860  }
139861
139862  /* The following block stores the meta information that will be returned
139863  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
139864  ** and autoinc. At this point there are two possibilities:
139865  **
139866  **     1. The specified column name was rowid", "oid" or "_rowid_"
139867  **        and there is no explicitly declared IPK column.
139868  **
139869  **     2. The table is not a view and the column name identified an
139870  **        explicitly declared column. Copy meta information from *pCol.
139871  */
139872  if( pCol ){
139873    zDataType = sqlite3ColumnType(pCol,0);
139874    zCollSeq = pCol->zColl;
139875    notnull = pCol->notNull!=0;
139876    primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
139877    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
139878  }else{
139879    zDataType = "INTEGER";
139880    primarykey = 1;
139881  }
139882  if( !zCollSeq ){
139883    zCollSeq = sqlite3StrBINARY;
139884  }
139885
139886error_out:
139887  sqlite3BtreeLeaveAll(db);
139888
139889  /* Whether the function call succeeded or failed, set the output parameters
139890  ** to whatever their local counterparts contain. If an error did occur,
139891  ** this has the effect of zeroing all output parameters.
139892  */
139893  if( pzDataType ) *pzDataType = zDataType;
139894  if( pzCollSeq ) *pzCollSeq = zCollSeq;
139895  if( pNotNull ) *pNotNull = notnull;
139896  if( pPrimaryKey ) *pPrimaryKey = primarykey;
139897  if( pAutoinc ) *pAutoinc = autoinc;
139898
139899  if( SQLITE_OK==rc && !pTab ){
139900    sqlite3DbFree(db, zErrMsg);
139901    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
139902        zColumnName);
139903    rc = SQLITE_ERROR;
139904  }
139905  sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
139906  sqlite3DbFree(db, zErrMsg);
139907  rc = sqlite3ApiExit(db, rc);
139908  sqlite3_mutex_leave(db->mutex);
139909  return rc;
139910}
139911
139912/*
139913** Sleep for a little while.  Return the amount of time slept.
139914*/
139915SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int ms){
139916  sqlite3_vfs *pVfs;
139917  int rc;
139918  pVfs = sqlite3_vfs_find(0);
139919  if( pVfs==0 ) return 0;
139920
139921  /* This function works in milliseconds, but the underlying OsSleep()
139922  ** API uses microseconds. Hence the 1000's.
139923  */
139924  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
139925  return rc;
139926}
139927
139928/*
139929** Enable or disable the extended result codes.
139930*/
139931SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3 *db, int onoff){
139932#ifdef SQLITE_ENABLE_API_ARMOR
139933  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139934#endif
139935  sqlite3_mutex_enter(db->mutex);
139936  db->errMask = onoff ? 0xffffffff : 0xff;
139937  sqlite3_mutex_leave(db->mutex);
139938  return SQLITE_OK;
139939}
139940
139941/*
139942** Invoke the xFileControl method on a particular database.
139943*/
139944SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
139945  int rc = SQLITE_ERROR;
139946  Btree *pBtree;
139947
139948#ifdef SQLITE_ENABLE_API_ARMOR
139949  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139950#endif
139951  sqlite3_mutex_enter(db->mutex);
139952  pBtree = sqlite3DbNameToBtree(db, zDbName);
139953  if( pBtree ){
139954    Pager *pPager;
139955    sqlite3_file *fd;
139956    sqlite3BtreeEnter(pBtree);
139957    pPager = sqlite3BtreePager(pBtree);
139958    assert( pPager!=0 );
139959    fd = sqlite3PagerFile(pPager);
139960    assert( fd!=0 );
139961    if( op==SQLITE_FCNTL_FILE_POINTER ){
139962      *(sqlite3_file**)pArg = fd;
139963      rc = SQLITE_OK;
139964    }else if( op==SQLITE_FCNTL_VFS_POINTER ){
139965      *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
139966      rc = SQLITE_OK;
139967    }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
139968      *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
139969      rc = SQLITE_OK;
139970    }else if( fd->pMethods ){
139971      rc = sqlite3OsFileControl(fd, op, pArg);
139972    }else{
139973      rc = SQLITE_NOTFOUND;
139974    }
139975    sqlite3BtreeLeave(pBtree);
139976  }
139977  sqlite3_mutex_leave(db->mutex);
139978  return rc;
139979}
139980
139981/*
139982** Interface to the testing logic.
139983*/
139984SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...){
139985  int rc = 0;
139986#ifdef SQLITE_OMIT_BUILTIN_TEST
139987  UNUSED_PARAMETER(op);
139988#else
139989  va_list ap;
139990  va_start(ap, op);
139991  switch( op ){
139992
139993    /*
139994    ** Save the current state of the PRNG.
139995    */
139996    case SQLITE_TESTCTRL_PRNG_SAVE: {
139997      sqlite3PrngSaveState();
139998      break;
139999    }
140000
140001    /*
140002    ** Restore the state of the PRNG to the last state saved using
140003    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
140004    ** this verb acts like PRNG_RESET.
140005    */
140006    case SQLITE_TESTCTRL_PRNG_RESTORE: {
140007      sqlite3PrngRestoreState();
140008      break;
140009    }
140010
140011    /*
140012    ** Reset the PRNG back to its uninitialized state.  The next call
140013    ** to sqlite3_randomness() will reseed the PRNG using a single call
140014    ** to the xRandomness method of the default VFS.
140015    */
140016    case SQLITE_TESTCTRL_PRNG_RESET: {
140017      sqlite3_randomness(0,0);
140018      break;
140019    }
140020
140021    /*
140022    **  sqlite3_test_control(BITVEC_TEST, size, program)
140023    **
140024    ** Run a test against a Bitvec object of size.  The program argument
140025    ** is an array of integers that defines the test.  Return -1 on a
140026    ** memory allocation error, 0 on success, or non-zero for an error.
140027    ** See the sqlite3BitvecBuiltinTest() for additional information.
140028    */
140029    case SQLITE_TESTCTRL_BITVEC_TEST: {
140030      int sz = va_arg(ap, int);
140031      int *aProg = va_arg(ap, int*);
140032      rc = sqlite3BitvecBuiltinTest(sz, aProg);
140033      break;
140034    }
140035
140036    /*
140037    **  sqlite3_test_control(FAULT_INSTALL, xCallback)
140038    **
140039    ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
140040    ** if xCallback is not NULL.
140041    **
140042    ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
140043    ** is called immediately after installing the new callback and the return
140044    ** value from sqlite3FaultSim(0) becomes the return from
140045    ** sqlite3_test_control().
140046    */
140047    case SQLITE_TESTCTRL_FAULT_INSTALL: {
140048      /* MSVC is picky about pulling func ptrs from va lists.
140049      ** http://support.microsoft.com/kb/47961
140050      ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
140051      */
140052      typedef int(*TESTCALLBACKFUNC_t)(int);
140053      sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
140054      rc = sqlite3FaultSim(0);
140055      break;
140056    }
140057
140058    /*
140059    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
140060    **
140061    ** Register hooks to call to indicate which malloc() failures
140062    ** are benign.
140063    */
140064    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
140065      typedef void (*void_function)(void);
140066      void_function xBenignBegin;
140067      void_function xBenignEnd;
140068      xBenignBegin = va_arg(ap, void_function);
140069      xBenignEnd = va_arg(ap, void_function);
140070      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
140071      break;
140072    }
140073
140074    /*
140075    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
140076    **
140077    ** Set the PENDING byte to the value in the argument, if X>0.
140078    ** Make no changes if X==0.  Return the value of the pending byte
140079    ** as it existing before this routine was called.
140080    **
140081    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
140082    ** an incompatible database file format.  Changing the PENDING byte
140083    ** while any database connection is open results in undefined and
140084    ** deleterious behavior.
140085    */
140086    case SQLITE_TESTCTRL_PENDING_BYTE: {
140087      rc = PENDING_BYTE;
140088#ifndef SQLITE_OMIT_WSD
140089      {
140090        unsigned int newVal = va_arg(ap, unsigned int);
140091        if( newVal ) sqlite3PendingByte = newVal;
140092      }
140093#endif
140094      break;
140095    }
140096
140097    /*
140098    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
140099    **
140100    ** This action provides a run-time test to see whether or not
140101    ** assert() was enabled at compile-time.  If X is true and assert()
140102    ** is enabled, then the return value is true.  If X is true and
140103    ** assert() is disabled, then the return value is zero.  If X is
140104    ** false and assert() is enabled, then the assertion fires and the
140105    ** process aborts.  If X is false and assert() is disabled, then the
140106    ** return value is zero.
140107    */
140108    case SQLITE_TESTCTRL_ASSERT: {
140109      volatile int x = 0;
140110      assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
140111      rc = x;
140112      break;
140113    }
140114
140115
140116    /*
140117    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
140118    **
140119    ** This action provides a run-time test to see how the ALWAYS and
140120    ** NEVER macros were defined at compile-time.
140121    **
140122    ** The return value is ALWAYS(X).
140123    **
140124    ** The recommended test is X==2.  If the return value is 2, that means
140125    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
140126    ** default setting.  If the return value is 1, then ALWAYS() is either
140127    ** hard-coded to true or else it asserts if its argument is false.
140128    ** The first behavior (hard-coded to true) is the case if
140129    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
140130    ** behavior (assert if the argument to ALWAYS() is false) is the case if
140131    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
140132    **
140133    ** The run-time test procedure might look something like this:
140134    **
140135    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
140136    **      // ALWAYS() and NEVER() are no-op pass-through macros
140137    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
140138    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
140139    **    }else{
140140    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
140141    **    }
140142    */
140143    case SQLITE_TESTCTRL_ALWAYS: {
140144      int x = va_arg(ap,int);
140145      rc = ALWAYS(x);
140146      break;
140147    }
140148
140149    /*
140150    **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
140151    **
140152    ** The integer returned reveals the byte-order of the computer on which
140153    ** SQLite is running:
140154    **
140155    **       1     big-endian,    determined at run-time
140156    **      10     little-endian, determined at run-time
140157    **  432101     big-endian,    determined at compile-time
140158    **  123410     little-endian, determined at compile-time
140159    */
140160    case SQLITE_TESTCTRL_BYTEORDER: {
140161      rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
140162      break;
140163    }
140164
140165    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
140166    **
140167    ** Set the nReserve size to N for the main database on the database
140168    ** connection db.
140169    */
140170    case SQLITE_TESTCTRL_RESERVE: {
140171      sqlite3 *db = va_arg(ap, sqlite3*);
140172      int x = va_arg(ap,int);
140173      sqlite3_mutex_enter(db->mutex);
140174      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
140175      sqlite3_mutex_leave(db->mutex);
140176      break;
140177    }
140178
140179    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
140180    **
140181    ** Enable or disable various optimizations for testing purposes.  The
140182    ** argument N is a bitmask of optimizations to be disabled.  For normal
140183    ** operation N should be 0.  The idea is that a test program (like the
140184    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
140185    ** with various optimizations disabled to verify that the same answer
140186    ** is obtained in every case.
140187    */
140188    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
140189      sqlite3 *db = va_arg(ap, sqlite3*);
140190      db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
140191      break;
140192    }
140193
140194#ifdef SQLITE_N_KEYWORD
140195    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
140196    **
140197    ** If zWord is a keyword recognized by the parser, then return the
140198    ** number of keywords.  Or if zWord is not a keyword, return 0.
140199    **
140200    ** This test feature is only available in the amalgamation since
140201    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
140202    ** is built using separate source files.
140203    */
140204    case SQLITE_TESTCTRL_ISKEYWORD: {
140205      const char *zWord = va_arg(ap, const char*);
140206      int n = sqlite3Strlen30(zWord);
140207      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
140208      break;
140209    }
140210#endif
140211
140212    /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
140213    **
140214    ** Pass pFree into sqlite3ScratchFree().
140215    ** If sz>0 then allocate a scratch buffer into pNew.
140216    */
140217    case SQLITE_TESTCTRL_SCRATCHMALLOC: {
140218      void *pFree, **ppNew;
140219      int sz;
140220      sz = va_arg(ap, int);
140221      ppNew = va_arg(ap, void**);
140222      pFree = va_arg(ap, void*);
140223      if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
140224      sqlite3ScratchFree(pFree);
140225      break;
140226    }
140227
140228    /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
140229    **
140230    ** If parameter onoff is non-zero, configure the wrappers so that all
140231    ** subsequent calls to localtime() and variants fail. If onoff is zero,
140232    ** undo this setting.
140233    */
140234    case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
140235      sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
140236      break;
140237    }
140238
140239    /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
140240    **
140241    ** Set or clear a flag that indicates that the database file is always well-
140242    ** formed and never corrupt.  This flag is clear by default, indicating that
140243    ** database files might have arbitrary corruption.  Setting the flag during
140244    ** testing causes certain assert() statements in the code to be activated
140245    ** that demonstrat invariants on well-formed database files.
140246    */
140247    case SQLITE_TESTCTRL_NEVER_CORRUPT: {
140248      sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
140249      break;
140250    }
140251
140252
140253    /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
140254    **
140255    ** Set the VDBE coverage callback function to xCallback with context
140256    ** pointer ptr.
140257    */
140258    case SQLITE_TESTCTRL_VDBE_COVERAGE: {
140259#ifdef SQLITE_VDBE_COVERAGE
140260      typedef void (*branch_callback)(void*,int,u8,u8);
140261      sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
140262      sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
140263#endif
140264      break;
140265    }
140266
140267    /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
140268    case SQLITE_TESTCTRL_SORTER_MMAP: {
140269      sqlite3 *db = va_arg(ap, sqlite3*);
140270      db->nMaxSorterMmap = va_arg(ap, int);
140271      break;
140272    }
140273
140274    /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
140275    **
140276    ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
140277    ** not.
140278    */
140279    case SQLITE_TESTCTRL_ISINIT: {
140280      if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
140281      break;
140282    }
140283
140284    /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
140285    **
140286    ** This test control is used to create imposter tables.  "db" is a pointer
140287    ** to the database connection.  dbName is the database name (ex: "main" or
140288    ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
140289    ** or off.  "tnum" is the root page of the b-tree to which the imposter
140290    ** table should connect.
140291    **
140292    ** Enable imposter mode only when the schema has already been parsed.  Then
140293    ** run a single CREATE TABLE statement to construct the imposter table in
140294    ** the parsed schema.  Then turn imposter mode back off again.
140295    **
140296    ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
140297    ** the schema to be reparsed the next time it is needed.  This has the
140298    ** effect of erasing all imposter tables.
140299    */
140300    case SQLITE_TESTCTRL_IMPOSTER: {
140301      sqlite3 *db = va_arg(ap, sqlite3*);
140302      sqlite3_mutex_enter(db->mutex);
140303      db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
140304      db->init.busy = db->init.imposterTable = va_arg(ap,int);
140305      db->init.newTnum = va_arg(ap,int);
140306      if( db->init.busy==0 && db->init.newTnum>0 ){
140307        sqlite3ResetAllSchemasOfConnection(db);
140308      }
140309      sqlite3_mutex_leave(db->mutex);
140310      break;
140311    }
140312  }
140313  va_end(ap);
140314#endif /* SQLITE_OMIT_BUILTIN_TEST */
140315  return rc;
140316}
140317
140318/*
140319** This is a utility routine, useful to VFS implementations, that checks
140320** to see if a database file was a URI that contained a specific query
140321** parameter, and if so obtains the value of the query parameter.
140322**
140323** The zFilename argument is the filename pointer passed into the xOpen()
140324** method of a VFS implementation.  The zParam argument is the name of the
140325** query parameter we seek.  This routine returns the value of the zParam
140326** parameter if it exists.  If the parameter does not exist, this routine
140327** returns a NULL pointer.
140328*/
140329SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam){
140330  if( zFilename==0 || zParam==0 ) return 0;
140331  zFilename += sqlite3Strlen30(zFilename) + 1;
140332  while( zFilename[0] ){
140333    int x = strcmp(zFilename, zParam);
140334    zFilename += sqlite3Strlen30(zFilename) + 1;
140335    if( x==0 ) return zFilename;
140336    zFilename += sqlite3Strlen30(zFilename) + 1;
140337  }
140338  return 0;
140339}
140340
140341/*
140342** Return a boolean value for a query parameter.
140343*/
140344SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
140345  const char *z = sqlite3_uri_parameter(zFilename, zParam);
140346  bDflt = bDflt!=0;
140347  return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
140348}
140349
140350/*
140351** Return a 64-bit integer value for a query parameter.
140352*/
140353SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(
140354  const char *zFilename,    /* Filename as passed to xOpen */
140355  const char *zParam,       /* URI parameter sought */
140356  sqlite3_int64 bDflt       /* return if parameter is missing */
140357){
140358  const char *z = sqlite3_uri_parameter(zFilename, zParam);
140359  sqlite3_int64 v;
140360  if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
140361    bDflt = v;
140362  }
140363  return bDflt;
140364}
140365
140366/*
140367** Return the Btree pointer identified by zDbName.  Return NULL if not found.
140368*/
140369SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
140370  int i;
140371  for(i=0; i<db->nDb; i++){
140372    if( db->aDb[i].pBt
140373     && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
140374    ){
140375      return db->aDb[i].pBt;
140376    }
140377  }
140378  return 0;
140379}
140380
140381/*
140382** Return the filename of the database associated with a database
140383** connection.
140384*/
140385SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName){
140386  Btree *pBt;
140387#ifdef SQLITE_ENABLE_API_ARMOR
140388  if( !sqlite3SafetyCheckOk(db) ){
140389    (void)SQLITE_MISUSE_BKPT;
140390    return 0;
140391  }
140392#endif
140393  pBt = sqlite3DbNameToBtree(db, zDbName);
140394  return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
140395}
140396
140397/*
140398** Return 1 if database is read-only or 0 if read/write.  Return -1 if
140399** no such database exists.
140400*/
140401SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
140402  Btree *pBt;
140403#ifdef SQLITE_ENABLE_API_ARMOR
140404  if( !sqlite3SafetyCheckOk(db) ){
140405    (void)SQLITE_MISUSE_BKPT;
140406    return -1;
140407  }
140408#endif
140409  pBt = sqlite3DbNameToBtree(db, zDbName);
140410  return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
140411}
140412
140413#ifdef SQLITE_ENABLE_SNAPSHOT
140414/*
140415** Obtain a snapshot handle for the snapshot of database zDb currently
140416** being read by handle db.
140417*/
140418SQLITE_API int SQLITE_STDCALL sqlite3_snapshot_get(
140419  sqlite3 *db,
140420  const char *zDb,
140421  sqlite3_snapshot **ppSnapshot
140422){
140423  int rc = SQLITE_ERROR;
140424#ifndef SQLITE_OMIT_WAL
140425  int iDb;
140426
140427#ifdef SQLITE_ENABLE_API_ARMOR
140428  if( !sqlite3SafetyCheckOk(db) ){
140429    return SQLITE_MISUSE_BKPT;
140430  }
140431#endif
140432  sqlite3_mutex_enter(db->mutex);
140433
140434  iDb = sqlite3FindDbName(db, zDb);
140435  if( iDb==0 || iDb>1 ){
140436    Btree *pBt = db->aDb[iDb].pBt;
140437    if( 0==sqlite3BtreeIsInTrans(pBt) ){
140438      rc = sqlite3BtreeBeginTrans(pBt, 0);
140439      if( rc==SQLITE_OK ){
140440        rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
140441      }
140442    }
140443  }
140444
140445  sqlite3_mutex_leave(db->mutex);
140446#endif   /* SQLITE_OMIT_WAL */
140447  return rc;
140448}
140449
140450/*
140451** Open a read-transaction on the snapshot idendified by pSnapshot.
140452*/
140453SQLITE_API int SQLITE_STDCALL sqlite3_snapshot_open(
140454  sqlite3 *db,
140455  const char *zDb,
140456  sqlite3_snapshot *pSnapshot
140457){
140458  int rc = SQLITE_ERROR;
140459#ifndef SQLITE_OMIT_WAL
140460
140461#ifdef SQLITE_ENABLE_API_ARMOR
140462  if( !sqlite3SafetyCheckOk(db) ){
140463    return SQLITE_MISUSE_BKPT;
140464  }
140465#endif
140466  sqlite3_mutex_enter(db->mutex);
140467  if( db->autoCommit==0 ){
140468    int iDb;
140469    iDb = sqlite3FindDbName(db, zDb);
140470    if( iDb==0 || iDb>1 ){
140471      Btree *pBt = db->aDb[iDb].pBt;
140472      if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
140473        rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
140474        if( rc==SQLITE_OK ){
140475          rc = sqlite3BtreeBeginTrans(pBt, 0);
140476          sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
140477        }
140478      }
140479    }
140480  }
140481
140482  sqlite3_mutex_leave(db->mutex);
140483#endif   /* SQLITE_OMIT_WAL */
140484  return rc;
140485}
140486
140487/*
140488** Free a snapshot handle obtained from sqlite3_snapshot_get().
140489*/
140490SQLITE_API void SQLITE_STDCALL sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
140491  sqlite3_free(pSnapshot);
140492}
140493#endif /* SQLITE_ENABLE_SNAPSHOT */
140494
140495/************** End of main.c ************************************************/
140496/************** Begin file notify.c ******************************************/
140497/*
140498** 2009 March 3
140499**
140500** The author disclaims copyright to this source code.  In place of
140501** a legal notice, here is a blessing:
140502**
140503**    May you do good and not evil.
140504**    May you find forgiveness for yourself and forgive others.
140505**    May you share freely, never taking more than you give.
140506**
140507*************************************************************************
140508**
140509** This file contains the implementation of the sqlite3_unlock_notify()
140510** API method and its associated functionality.
140511*/
140512/* #include "sqliteInt.h" */
140513/* #include "btreeInt.h" */
140514
140515/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
140516#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
140517
140518/*
140519** Public interfaces:
140520**
140521**   sqlite3ConnectionBlocked()
140522**   sqlite3ConnectionUnlocked()
140523**   sqlite3ConnectionClosed()
140524**   sqlite3_unlock_notify()
140525*/
140526
140527#define assertMutexHeld() \
140528  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
140529
140530/*
140531** Head of a linked list of all sqlite3 objects created by this process
140532** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
140533** is not NULL. This variable may only accessed while the STATIC_MASTER
140534** mutex is held.
140535*/
140536static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
140537
140538#ifndef NDEBUG
140539/*
140540** This function is a complex assert() that verifies the following
140541** properties of the blocked connections list:
140542**
140543**   1) Each entry in the list has a non-NULL value for either
140544**      pUnlockConnection or pBlockingConnection, or both.
140545**
140546**   2) All entries in the list that share a common value for
140547**      xUnlockNotify are grouped together.
140548**
140549**   3) If the argument db is not NULL, then none of the entries in the
140550**      blocked connections list have pUnlockConnection or pBlockingConnection
140551**      set to db. This is used when closing connection db.
140552*/
140553static void checkListProperties(sqlite3 *db){
140554  sqlite3 *p;
140555  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
140556    int seen = 0;
140557    sqlite3 *p2;
140558
140559    /* Verify property (1) */
140560    assert( p->pUnlockConnection || p->pBlockingConnection );
140561
140562    /* Verify property (2) */
140563    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
140564      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
140565      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
140566      assert( db==0 || p->pUnlockConnection!=db );
140567      assert( db==0 || p->pBlockingConnection!=db );
140568    }
140569  }
140570}
140571#else
140572# define checkListProperties(x)
140573#endif
140574
140575/*
140576** Remove connection db from the blocked connections list. If connection
140577** db is not currently a part of the list, this function is a no-op.
140578*/
140579static void removeFromBlockedList(sqlite3 *db){
140580  sqlite3 **pp;
140581  assertMutexHeld();
140582  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
140583    if( *pp==db ){
140584      *pp = (*pp)->pNextBlocked;
140585      break;
140586    }
140587  }
140588}
140589
140590/*
140591** Add connection db to the blocked connections list. It is assumed
140592** that it is not already a part of the list.
140593*/
140594static void addToBlockedList(sqlite3 *db){
140595  sqlite3 **pp;
140596  assertMutexHeld();
140597  for(
140598    pp=&sqlite3BlockedList;
140599    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
140600    pp=&(*pp)->pNextBlocked
140601  );
140602  db->pNextBlocked = *pp;
140603  *pp = db;
140604}
140605
140606/*
140607** Obtain the STATIC_MASTER mutex.
140608*/
140609static void enterMutex(void){
140610  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
140611  checkListProperties(0);
140612}
140613
140614/*
140615** Release the STATIC_MASTER mutex.
140616*/
140617static void leaveMutex(void){
140618  assertMutexHeld();
140619  checkListProperties(0);
140620  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
140621}
140622
140623/*
140624** Register an unlock-notify callback.
140625**
140626** This is called after connection "db" has attempted some operation
140627** but has received an SQLITE_LOCKED error because another connection
140628** (call it pOther) in the same process was busy using the same shared
140629** cache.  pOther is found by looking at db->pBlockingConnection.
140630**
140631** If there is no blocking connection, the callback is invoked immediately,
140632** before this routine returns.
140633**
140634** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
140635** a deadlock.
140636**
140637** Otherwise, make arrangements to invoke xNotify when pOther drops
140638** its locks.
140639**
140640** Each call to this routine overrides any prior callbacks registered
140641** on the same "db".  If xNotify==0 then any prior callbacks are immediately
140642** cancelled.
140643*/
140644SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
140645  sqlite3 *db,
140646  void (*xNotify)(void **, int),
140647  void *pArg
140648){
140649  int rc = SQLITE_OK;
140650
140651  sqlite3_mutex_enter(db->mutex);
140652  enterMutex();
140653
140654  if( xNotify==0 ){
140655    removeFromBlockedList(db);
140656    db->pBlockingConnection = 0;
140657    db->pUnlockConnection = 0;
140658    db->xUnlockNotify = 0;
140659    db->pUnlockArg = 0;
140660  }else if( 0==db->pBlockingConnection ){
140661    /* The blocking transaction has been concluded. Or there never was a
140662    ** blocking transaction. In either case, invoke the notify callback
140663    ** immediately.
140664    */
140665    xNotify(&pArg, 1);
140666  }else{
140667    sqlite3 *p;
140668
140669    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
140670    if( p ){
140671      rc = SQLITE_LOCKED;              /* Deadlock detected. */
140672    }else{
140673      db->pUnlockConnection = db->pBlockingConnection;
140674      db->xUnlockNotify = xNotify;
140675      db->pUnlockArg = pArg;
140676      removeFromBlockedList(db);
140677      addToBlockedList(db);
140678    }
140679  }
140680
140681  leaveMutex();
140682  assert( !db->mallocFailed );
140683  sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
140684  sqlite3_mutex_leave(db->mutex);
140685  return rc;
140686}
140687
140688/*
140689** This function is called while stepping or preparing a statement
140690** associated with connection db. The operation will return SQLITE_LOCKED
140691** to the user because it requires a lock that will not be available
140692** until connection pBlocker concludes its current transaction.
140693*/
140694SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
140695  enterMutex();
140696  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
140697    addToBlockedList(db);
140698  }
140699  db->pBlockingConnection = pBlocker;
140700  leaveMutex();
140701}
140702
140703/*
140704** This function is called when
140705** the transaction opened by database db has just finished. Locks held
140706** by database connection db have been released.
140707**
140708** This function loops through each entry in the blocked connections
140709** list and does the following:
140710**
140711**   1) If the sqlite3.pBlockingConnection member of a list entry is
140712**      set to db, then set pBlockingConnection=0.
140713**
140714**   2) If the sqlite3.pUnlockConnection member of a list entry is
140715**      set to db, then invoke the configured unlock-notify callback and
140716**      set pUnlockConnection=0.
140717**
140718**   3) If the two steps above mean that pBlockingConnection==0 and
140719**      pUnlockConnection==0, remove the entry from the blocked connections
140720**      list.
140721*/
140722SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
140723  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
140724  int nArg = 0;                            /* Number of entries in aArg[] */
140725  sqlite3 **pp;                            /* Iterator variable */
140726  void **aArg;               /* Arguments to the unlock callback */
140727  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
140728  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
140729
140730  aArg = aStatic;
140731  enterMutex();         /* Enter STATIC_MASTER mutex */
140732
140733  /* This loop runs once for each entry in the blocked-connections list. */
140734  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
140735    sqlite3 *p = *pp;
140736
140737    /* Step 1. */
140738    if( p->pBlockingConnection==db ){
140739      p->pBlockingConnection = 0;
140740    }
140741
140742    /* Step 2. */
140743    if( p->pUnlockConnection==db ){
140744      assert( p->xUnlockNotify );
140745      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
140746        xUnlockNotify(aArg, nArg);
140747        nArg = 0;
140748      }
140749
140750      sqlite3BeginBenignMalloc();
140751      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
140752      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
140753      if( (!aDyn && nArg==(int)ArraySize(aStatic))
140754       || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
140755      ){
140756        /* The aArg[] array needs to grow. */
140757        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
140758        if( pNew ){
140759          memcpy(pNew, aArg, nArg*sizeof(void *));
140760          sqlite3_free(aDyn);
140761          aDyn = aArg = pNew;
140762        }else{
140763          /* This occurs when the array of context pointers that need to
140764          ** be passed to the unlock-notify callback is larger than the
140765          ** aStatic[] array allocated on the stack and the attempt to
140766          ** allocate a larger array from the heap has failed.
140767          **
140768          ** This is a difficult situation to handle. Returning an error
140769          ** code to the caller is insufficient, as even if an error code
140770          ** is returned the transaction on connection db will still be
140771          ** closed and the unlock-notify callbacks on blocked connections
140772          ** will go unissued. This might cause the application to wait
140773          ** indefinitely for an unlock-notify callback that will never
140774          ** arrive.
140775          **
140776          ** Instead, invoke the unlock-notify callback with the context
140777          ** array already accumulated. We can then clear the array and
140778          ** begin accumulating any further context pointers without
140779          ** requiring any dynamic allocation. This is sub-optimal because
140780          ** it means that instead of one callback with a large array of
140781          ** context pointers the application will receive two or more
140782          ** callbacks with smaller arrays of context pointers, which will
140783          ** reduce the applications ability to prioritize multiple
140784          ** connections. But it is the best that can be done under the
140785          ** circumstances.
140786          */
140787          xUnlockNotify(aArg, nArg);
140788          nArg = 0;
140789        }
140790      }
140791      sqlite3EndBenignMalloc();
140792
140793      aArg[nArg++] = p->pUnlockArg;
140794      xUnlockNotify = p->xUnlockNotify;
140795      p->pUnlockConnection = 0;
140796      p->xUnlockNotify = 0;
140797      p->pUnlockArg = 0;
140798    }
140799
140800    /* Step 3. */
140801    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
140802      /* Remove connection p from the blocked connections list. */
140803      *pp = p->pNextBlocked;
140804      p->pNextBlocked = 0;
140805    }else{
140806      pp = &p->pNextBlocked;
140807    }
140808  }
140809
140810  if( nArg!=0 ){
140811    xUnlockNotify(aArg, nArg);
140812  }
140813  sqlite3_free(aDyn);
140814  leaveMutex();         /* Leave STATIC_MASTER mutex */
140815}
140816
140817/*
140818** This is called when the database connection passed as an argument is
140819** being closed. The connection is removed from the blocked list.
140820*/
140821SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
140822  sqlite3ConnectionUnlocked(db);
140823  enterMutex();
140824  removeFromBlockedList(db);
140825  checkListProperties(db);
140826  leaveMutex();
140827}
140828#endif
140829
140830/************** End of notify.c **********************************************/
140831/************** Begin file fts3.c ********************************************/
140832/*
140833** 2006 Oct 10
140834**
140835** The author disclaims copyright to this source code.  In place of
140836** a legal notice, here is a blessing:
140837**
140838**    May you do good and not evil.
140839**    May you find forgiveness for yourself and forgive others.
140840**    May you share freely, never taking more than you give.
140841**
140842******************************************************************************
140843**
140844** This is an SQLite module implementing full-text search.
140845*/
140846
140847/*
140848** The code in this file is only compiled if:
140849**
140850**     * The FTS3 module is being built as an extension
140851**       (in which case SQLITE_CORE is not defined), or
140852**
140853**     * The FTS3 module is being built into the core of
140854**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
140855*/
140856
140857/* The full-text index is stored in a series of b+tree (-like)
140858** structures called segments which map terms to doclists.  The
140859** structures are like b+trees in layout, but are constructed from the
140860** bottom up in optimal fashion and are not updatable.  Since trees
140861** are built from the bottom up, things will be described from the
140862** bottom up.
140863**
140864**
140865**** Varints ****
140866** The basic unit of encoding is a variable-length integer called a
140867** varint.  We encode variable-length integers in little-endian order
140868** using seven bits * per byte as follows:
140869**
140870** KEY:
140871**         A = 0xxxxxxx    7 bits of data and one flag bit
140872**         B = 1xxxxxxx    7 bits of data and one flag bit
140873**
140874**  7 bits - A
140875** 14 bits - BA
140876** 21 bits - BBA
140877** and so on.
140878**
140879** This is similar in concept to how sqlite encodes "varints" but
140880** the encoding is not the same.  SQLite varints are big-endian
140881** are are limited to 9 bytes in length whereas FTS3 varints are
140882** little-endian and can be up to 10 bytes in length (in theory).
140883**
140884** Example encodings:
140885**
140886**     1:    0x01
140887**   127:    0x7f
140888**   128:    0x81 0x00
140889**
140890**
140891**** Document lists ****
140892** A doclist (document list) holds a docid-sorted list of hits for a
140893** given term.  Doclists hold docids and associated token positions.
140894** A docid is the unique integer identifier for a single document.
140895** A position is the index of a word within the document.  The first
140896** word of the document has a position of 0.
140897**
140898** FTS3 used to optionally store character offsets using a compile-time
140899** option.  But that functionality is no longer supported.
140900**
140901** A doclist is stored like this:
140902**
140903** array {
140904**   varint docid;          (delta from previous doclist)
140905**   array {                (position list for column 0)
140906**     varint position;     (2 more than the delta from previous position)
140907**   }
140908**   array {
140909**     varint POS_COLUMN;   (marks start of position list for new column)
140910**     varint column;       (index of new column)
140911**     array {
140912**       varint position;   (2 more than the delta from previous position)
140913**     }
140914**   }
140915**   varint POS_END;        (marks end of positions for this document.
140916** }
140917**
140918** Here, array { X } means zero or more occurrences of X, adjacent in
140919** memory.  A "position" is an index of a token in the token stream
140920** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
140921** in the same logical place as the position element, and act as sentinals
140922** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
140923** The positions numbers are not stored literally but rather as two more
140924** than the difference from the prior position, or the just the position plus
140925** 2 for the first position.  Example:
140926**
140927**   label:       A B C D E  F  G H   I  J K
140928**   value:     123 5 9 1 1 14 35 0 234 72 0
140929**
140930** The 123 value is the first docid.  For column zero in this document
140931** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
140932** at D signals the start of a new column; the 1 at E indicates that the
140933** new column is column number 1.  There are two positions at 12 and 45
140934** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
140935** 234 at I is the delta to next docid (357).  It has one position 70
140936** (72-2) and then terminates with the 0 at K.
140937**
140938** A "position-list" is the list of positions for multiple columns for
140939** a single docid.  A "column-list" is the set of positions for a single
140940** column.  Hence, a position-list consists of one or more column-lists,
140941** a document record consists of a docid followed by a position-list and
140942** a doclist consists of one or more document records.
140943**
140944** A bare doclist omits the position information, becoming an
140945** array of varint-encoded docids.
140946**
140947**** Segment leaf nodes ****
140948** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
140949** nodes are written using LeafWriter, and read using LeafReader (to
140950** iterate through a single leaf node's data) and LeavesReader (to
140951** iterate through a segment's entire leaf layer).  Leaf nodes have
140952** the format:
140953**
140954** varint iHeight;             (height from leaf level, always 0)
140955** varint nTerm;               (length of first term)
140956** char pTerm[nTerm];          (content of first term)
140957** varint nDoclist;            (length of term's associated doclist)
140958** char pDoclist[nDoclist];    (content of doclist)
140959** array {
140960**                             (further terms are delta-encoded)
140961**   varint nPrefix;           (length of prefix shared with previous term)
140962**   varint nSuffix;           (length of unshared suffix)
140963**   char pTermSuffix[nSuffix];(unshared suffix of next term)
140964**   varint nDoclist;          (length of term's associated doclist)
140965**   char pDoclist[nDoclist];  (content of doclist)
140966** }
140967**
140968** Here, array { X } means zero or more occurrences of X, adjacent in
140969** memory.
140970**
140971** Leaf nodes are broken into blocks which are stored contiguously in
140972** the %_segments table in sorted order.  This means that when the end
140973** of a node is reached, the next term is in the node with the next
140974** greater node id.
140975**
140976** New data is spilled to a new leaf node when the current node
140977** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
140978** larger than STANDALONE_MIN (default 1024) is placed in a standalone
140979** node (a leaf node with a single term and doclist).  The goal of
140980** these settings is to pack together groups of small doclists while
140981** making it efficient to directly access large doclists.  The
140982** assumption is that large doclists represent terms which are more
140983** likely to be query targets.
140984**
140985** TODO(shess) It may be useful for blocking decisions to be more
140986** dynamic.  For instance, it may make more sense to have a 2.5k leaf
140987** node rather than splitting into 2k and .5k nodes.  My intuition is
140988** that this might extend through 2x or 4x the pagesize.
140989**
140990**
140991**** Segment interior nodes ****
140992** Segment interior nodes store blockids for subtree nodes and terms
140993** to describe what data is stored by the each subtree.  Interior
140994** nodes are written using InteriorWriter, and read using
140995** InteriorReader.  InteriorWriters are created as needed when
140996** SegmentWriter creates new leaf nodes, or when an interior node
140997** itself grows too big and must be split.  The format of interior
140998** nodes:
140999**
141000** varint iHeight;           (height from leaf level, always >0)
141001** varint iBlockid;          (block id of node's leftmost subtree)
141002** optional {
141003**   varint nTerm;           (length of first term)
141004**   char pTerm[nTerm];      (content of first term)
141005**   array {
141006**                                (further terms are delta-encoded)
141007**     varint nPrefix;            (length of shared prefix with previous term)
141008**     varint nSuffix;            (length of unshared suffix)
141009**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
141010**   }
141011** }
141012**
141013** Here, optional { X } means an optional element, while array { X }
141014** means zero or more occurrences of X, adjacent in memory.
141015**
141016** An interior node encodes n terms separating n+1 subtrees.  The
141017** subtree blocks are contiguous, so only the first subtree's blockid
141018** is encoded.  The subtree at iBlockid will contain all terms less
141019** than the first term encoded (or all terms if no term is encoded).
141020** Otherwise, for terms greater than or equal to pTerm[i] but less
141021** than pTerm[i+1], the subtree for that term will be rooted at
141022** iBlockid+i.  Interior nodes only store enough term data to
141023** distinguish adjacent children (if the rightmost term of the left
141024** child is "something", and the leftmost term of the right child is
141025** "wicked", only "w" is stored).
141026**
141027** New data is spilled to a new interior node at the same height when
141028** the current node exceeds INTERIOR_MAX bytes (default 2048).
141029** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
141030** interior nodes and making the tree too skinny.  The interior nodes
141031** at a given height are naturally tracked by interior nodes at
141032** height+1, and so on.
141033**
141034**
141035**** Segment directory ****
141036** The segment directory in table %_segdir stores meta-information for
141037** merging and deleting segments, and also the root node of the
141038** segment's tree.
141039**
141040** The root node is the top node of the segment's tree after encoding
141041** the entire segment, restricted to ROOT_MAX bytes (default 1024).
141042** This could be either a leaf node or an interior node.  If the top
141043** node requires more than ROOT_MAX bytes, it is flushed to %_segments
141044** and a new root interior node is generated (which should always fit
141045** within ROOT_MAX because it only needs space for 2 varints, the
141046** height and the blockid of the previous root).
141047**
141048** The meta-information in the segment directory is:
141049**   level               - segment level (see below)
141050**   idx                 - index within level
141051**                       - (level,idx uniquely identify a segment)
141052**   start_block         - first leaf node
141053**   leaves_end_block    - last leaf node
141054**   end_block           - last block (including interior nodes)
141055**   root                - contents of root node
141056**
141057** If the root node is a leaf node, then start_block,
141058** leaves_end_block, and end_block are all 0.
141059**
141060**
141061**** Segment merging ****
141062** To amortize update costs, segments are grouped into levels and
141063** merged in batches.  Each increase in level represents exponentially
141064** more documents.
141065**
141066** New documents (actually, document updates) are tokenized and
141067** written individually (using LeafWriter) to a level 0 segment, with
141068** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
141069** level 0 segments are merged into a single level 1 segment.  Level 1
141070** is populated like level 0, and eventually MERGE_COUNT level 1
141071** segments are merged to a single level 2 segment (representing
141072** MERGE_COUNT^2 updates), and so on.
141073**
141074** A segment merge traverses all segments at a given level in
141075** parallel, performing a straightforward sorted merge.  Since segment
141076** leaf nodes are written in to the %_segments table in order, this
141077** merge traverses the underlying sqlite disk structures efficiently.
141078** After the merge, all segment blocks from the merged level are
141079** deleted.
141080**
141081** MERGE_COUNT controls how often we merge segments.  16 seems to be
141082** somewhat of a sweet spot for insertion performance.  32 and 64 show
141083** very similar performance numbers to 16 on insertion, though they're
141084** a tiny bit slower (perhaps due to more overhead in merge-time
141085** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
141086** 16, 2 about 66% slower than 16.
141087**
141088** At query time, high MERGE_COUNT increases the number of segments
141089** which need to be scanned and merged.  For instance, with 100k docs
141090** inserted:
141091**
141092**    MERGE_COUNT   segments
141093**       16           25
141094**        8           12
141095**        4           10
141096**        2            6
141097**
141098** This appears to have only a moderate impact on queries for very
141099** frequent terms (which are somewhat dominated by segment merge
141100** costs), and infrequent and non-existent terms still seem to be fast
141101** even with many segments.
141102**
141103** TODO(shess) That said, it would be nice to have a better query-side
141104** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
141105** optimizations to things like doclist merging will swing the sweet
141106** spot around.
141107**
141108**
141109**
141110**** Handling of deletions and updates ****
141111** Since we're using a segmented structure, with no docid-oriented
141112** index into the term index, we clearly cannot simply update the term
141113** index when a document is deleted or updated.  For deletions, we
141114** write an empty doclist (varint(docid) varint(POS_END)), for updates
141115** we simply write the new doclist.  Segment merges overwrite older
141116** data for a particular docid with newer data, so deletes or updates
141117** will eventually overtake the earlier data and knock it out.  The
141118** query logic likewise merges doclists so that newer data knocks out
141119** older data.
141120*/
141121
141122/************** Include fts3Int.h in the middle of fts3.c ********************/
141123/************** Begin file fts3Int.h *****************************************/
141124/*
141125** 2009 Nov 12
141126**
141127** The author disclaims copyright to this source code.  In place of
141128** a legal notice, here is a blessing:
141129**
141130**    May you do good and not evil.
141131**    May you find forgiveness for yourself and forgive others.
141132**    May you share freely, never taking more than you give.
141133**
141134******************************************************************************
141135**
141136*/
141137#ifndef _FTSINT_H
141138#define _FTSINT_H
141139
141140#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
141141# define NDEBUG 1
141142#endif
141143
141144/* FTS3/FTS4 require virtual tables */
141145#ifdef SQLITE_OMIT_VIRTUALTABLE
141146# undef SQLITE_ENABLE_FTS3
141147# undef SQLITE_ENABLE_FTS4
141148#endif
141149
141150/*
141151** FTS4 is really an extension for FTS3.  It is enabled using the
141152** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
141153** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
141154*/
141155#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
141156# define SQLITE_ENABLE_FTS3
141157#endif
141158
141159#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141160
141161/* If not building as part of the core, include sqlite3ext.h. */
141162#ifndef SQLITE_CORE
141163/* # include "sqlite3ext.h"  */
141164SQLITE_EXTENSION_INIT3
141165#endif
141166
141167/* #include "sqlite3.h" */
141168/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
141169/************** Begin file fts3_tokenizer.h **********************************/
141170/*
141171** 2006 July 10
141172**
141173** The author disclaims copyright to this source code.
141174**
141175*************************************************************************
141176** Defines the interface to tokenizers used by fulltext-search.  There
141177** are three basic components:
141178**
141179** sqlite3_tokenizer_module is a singleton defining the tokenizer
141180** interface functions.  This is essentially the class structure for
141181** tokenizers.
141182**
141183** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
141184** including customization information defined at creation time.
141185**
141186** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
141187** tokens from a particular input.
141188*/
141189#ifndef _FTS3_TOKENIZER_H_
141190#define _FTS3_TOKENIZER_H_
141191
141192/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
141193** If tokenizers are to be allowed to call sqlite3_*() functions, then
141194** we will need a way to register the API consistently.
141195*/
141196/* #include "sqlite3.h" */
141197
141198/*
141199** Structures used by the tokenizer interface. When a new tokenizer
141200** implementation is registered, the caller provides a pointer to
141201** an sqlite3_tokenizer_module containing pointers to the callback
141202** functions that make up an implementation.
141203**
141204** When an fts3 table is created, it passes any arguments passed to
141205** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
141206** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
141207** implementation. The xCreate() function in turn returns an
141208** sqlite3_tokenizer structure representing the specific tokenizer to
141209** be used for the fts3 table (customized by the tokenizer clause arguments).
141210**
141211** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
141212** method is called. It returns an sqlite3_tokenizer_cursor object
141213** that may be used to tokenize a specific input buffer based on
141214** the tokenization rules supplied by a specific sqlite3_tokenizer
141215** object.
141216*/
141217typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
141218typedef struct sqlite3_tokenizer sqlite3_tokenizer;
141219typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
141220
141221struct sqlite3_tokenizer_module {
141222
141223  /*
141224  ** Structure version. Should always be set to 0 or 1.
141225  */
141226  int iVersion;
141227
141228  /*
141229  ** Create a new tokenizer. The values in the argv[] array are the
141230  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
141231  ** TABLE statement that created the fts3 table. For example, if
141232  ** the following SQL is executed:
141233  **
141234  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
141235  **
141236  ** then argc is set to 2, and the argv[] array contains pointers
141237  ** to the strings "arg1" and "arg2".
141238  **
141239  ** This method should return either SQLITE_OK (0), or an SQLite error
141240  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
141241  ** to point at the newly created tokenizer structure. The generic
141242  ** sqlite3_tokenizer.pModule variable should not be initialized by
141243  ** this callback. The caller will do so.
141244  */
141245  int (*xCreate)(
141246    int argc,                           /* Size of argv array */
141247    const char *const*argv,             /* Tokenizer argument strings */
141248    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
141249  );
141250
141251  /*
141252  ** Destroy an existing tokenizer. The fts3 module calls this method
141253  ** exactly once for each successful call to xCreate().
141254  */
141255  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
141256
141257  /*
141258  ** Create a tokenizer cursor to tokenize an input buffer. The caller
141259  ** is responsible for ensuring that the input buffer remains valid
141260  ** until the cursor is closed (using the xClose() method).
141261  */
141262  int (*xOpen)(
141263    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
141264    const char *pInput, int nBytes,      /* Input buffer */
141265    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
141266  );
141267
141268  /*
141269  ** Destroy an existing tokenizer cursor. The fts3 module calls this
141270  ** method exactly once for each successful call to xOpen().
141271  */
141272  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
141273
141274  /*
141275  ** Retrieve the next token from the tokenizer cursor pCursor. This
141276  ** method should either return SQLITE_OK and set the values of the
141277  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
141278  ** the end of the buffer has been reached, or an SQLite error code.
141279  **
141280  ** *ppToken should be set to point at a buffer containing the
141281  ** normalized version of the token (i.e. after any case-folding and/or
141282  ** stemming has been performed). *pnBytes should be set to the length
141283  ** of this buffer in bytes. The input text that generated the token is
141284  ** identified by the byte offsets returned in *piStartOffset and
141285  ** *piEndOffset. *piStartOffset should be set to the index of the first
141286  ** byte of the token in the input buffer. *piEndOffset should be set
141287  ** to the index of the first byte just past the end of the token in
141288  ** the input buffer.
141289  **
141290  ** The buffer *ppToken is set to point at is managed by the tokenizer
141291  ** implementation. It is only required to be valid until the next call
141292  ** to xNext() or xClose().
141293  */
141294  /* TODO(shess) current implementation requires pInput to be
141295  ** nul-terminated.  This should either be fixed, or pInput/nBytes
141296  ** should be converted to zInput.
141297  */
141298  int (*xNext)(
141299    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
141300    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
141301    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
141302    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
141303    int *piPosition      /* OUT: Number of tokens returned before this one */
141304  );
141305
141306  /***********************************************************************
141307  ** Methods below this point are only available if iVersion>=1.
141308  */
141309
141310  /*
141311  ** Configure the language id of a tokenizer cursor.
141312  */
141313  int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
141314};
141315
141316struct sqlite3_tokenizer {
141317  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
141318  /* Tokenizer implementations will typically add additional fields */
141319};
141320
141321struct sqlite3_tokenizer_cursor {
141322  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
141323  /* Tokenizer implementations will typically add additional fields */
141324};
141325
141326int fts3_global_term_cnt(int iTerm, int iCol);
141327int fts3_term_cnt(int iTerm, int iCol);
141328
141329
141330#endif /* _FTS3_TOKENIZER_H_ */
141331
141332/************** End of fts3_tokenizer.h **************************************/
141333/************** Continuing where we left off in fts3Int.h ********************/
141334/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
141335/************** Begin file fts3_hash.h ***************************************/
141336/*
141337** 2001 September 22
141338**
141339** The author disclaims copyright to this source code.  In place of
141340** a legal notice, here is a blessing:
141341**
141342**    May you do good and not evil.
141343**    May you find forgiveness for yourself and forgive others.
141344**    May you share freely, never taking more than you give.
141345**
141346*************************************************************************
141347** This is the header file for the generic hash-table implementation
141348** used in SQLite.  We've modified it slightly to serve as a standalone
141349** hash table implementation for the full-text indexing module.
141350**
141351*/
141352#ifndef _FTS3_HASH_H_
141353#define _FTS3_HASH_H_
141354
141355/* Forward declarations of structures. */
141356typedef struct Fts3Hash Fts3Hash;
141357typedef struct Fts3HashElem Fts3HashElem;
141358
141359/* A complete hash table is an instance of the following structure.
141360** The internals of this structure are intended to be opaque -- client
141361** code should not attempt to access or modify the fields of this structure
141362** directly.  Change this structure only by using the routines below.
141363** However, many of the "procedures" and "functions" for modifying and
141364** accessing this structure are really macros, so we can't really make
141365** this structure opaque.
141366*/
141367struct Fts3Hash {
141368  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
141369  char copyKey;           /* True if copy of key made on insert */
141370  int count;              /* Number of entries in this table */
141371  Fts3HashElem *first;    /* The first element of the array */
141372  int htsize;             /* Number of buckets in the hash table */
141373  struct _fts3ht {        /* the hash table */
141374    int count;               /* Number of entries with this hash */
141375    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
141376  } *ht;
141377};
141378
141379/* Each element in the hash table is an instance of the following
141380** structure.  All elements are stored on a single doubly-linked list.
141381**
141382** Again, this structure is intended to be opaque, but it can't really
141383** be opaque because it is used by macros.
141384*/
141385struct Fts3HashElem {
141386  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
141387  void *data;                /* Data associated with this element */
141388  void *pKey; int nKey;      /* Key associated with this element */
141389};
141390
141391/*
141392** There are 2 different modes of operation for a hash table:
141393**
141394**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
141395**                           (including the null-terminator, if any).  Case
141396**                           is respected in comparisons.
141397**
141398**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
141399**                           memcmp() is used to compare keys.
141400**
141401** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
141402*/
141403#define FTS3_HASH_STRING    1
141404#define FTS3_HASH_BINARY    2
141405
141406/*
141407** Access routines.  To delete, insert a NULL pointer.
141408*/
141409SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
141410SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
141411SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
141412SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
141413SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
141414
141415/*
141416** Shorthand for the functions above
141417*/
141418#define fts3HashInit     sqlite3Fts3HashInit
141419#define fts3HashInsert   sqlite3Fts3HashInsert
141420#define fts3HashFind     sqlite3Fts3HashFind
141421#define fts3HashClear    sqlite3Fts3HashClear
141422#define fts3HashFindElem sqlite3Fts3HashFindElem
141423
141424/*
141425** Macros for looping over all elements of a hash table.  The idiom is
141426** like this:
141427**
141428**   Fts3Hash h;
141429**   Fts3HashElem *p;
141430**   ...
141431**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
141432**     SomeStructure *pData = fts3HashData(p);
141433**     // do something with pData
141434**   }
141435*/
141436#define fts3HashFirst(H)  ((H)->first)
141437#define fts3HashNext(E)   ((E)->next)
141438#define fts3HashData(E)   ((E)->data)
141439#define fts3HashKey(E)    ((E)->pKey)
141440#define fts3HashKeysize(E) ((E)->nKey)
141441
141442/*
141443** Number of entries in a hash table
141444*/
141445#define fts3HashCount(H)  ((H)->count)
141446
141447#endif /* _FTS3_HASH_H_ */
141448
141449/************** End of fts3_hash.h *******************************************/
141450/************** Continuing where we left off in fts3Int.h ********************/
141451
141452/*
141453** This constant determines the maximum depth of an FTS expression tree
141454** that the library will create and use. FTS uses recursion to perform
141455** various operations on the query tree, so the disadvantage of a large
141456** limit is that it may allow very large queries to use large amounts
141457** of stack space (perhaps causing a stack overflow).
141458*/
141459#ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
141460# define SQLITE_FTS3_MAX_EXPR_DEPTH 12
141461#endif
141462
141463
141464/*
141465** This constant controls how often segments are merged. Once there are
141466** FTS3_MERGE_COUNT segments of level N, they are merged into a single
141467** segment of level N+1.
141468*/
141469#define FTS3_MERGE_COUNT 16
141470
141471/*
141472** This is the maximum amount of data (in bytes) to store in the
141473** Fts3Table.pendingTerms hash table. Normally, the hash table is
141474** populated as documents are inserted/updated/deleted in a transaction
141475** and used to create a new segment when the transaction is committed.
141476** However if this limit is reached midway through a transaction, a new
141477** segment is created and the hash table cleared immediately.
141478*/
141479#define FTS3_MAX_PENDING_DATA (1*1024*1024)
141480
141481/*
141482** Macro to return the number of elements in an array. SQLite has a
141483** similar macro called ArraySize(). Use a different name to avoid
141484** a collision when building an amalgamation with built-in FTS3.
141485*/
141486#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
141487
141488
141489#ifndef MIN
141490# define MIN(x,y) ((x)<(y)?(x):(y))
141491#endif
141492#ifndef MAX
141493# define MAX(x,y) ((x)>(y)?(x):(y))
141494#endif
141495
141496/*
141497** Maximum length of a varint encoded integer. The varint format is different
141498** from that used by SQLite, so the maximum length is 10, not 9.
141499*/
141500#define FTS3_VARINT_MAX 10
141501
141502/*
141503** FTS4 virtual tables may maintain multiple indexes - one index of all terms
141504** in the document set and zero or more prefix indexes. All indexes are stored
141505** as one or more b+-trees in the %_segments and %_segdir tables.
141506**
141507** It is possible to determine which index a b+-tree belongs to based on the
141508** value stored in the "%_segdir.level" column. Given this value L, the index
141509** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
141510** level values between 0 and 1023 (inclusive) belong to index 0, all levels
141511** between 1024 and 2047 to index 1, and so on.
141512**
141513** It is considered impossible for an index to use more than 1024 levels. In
141514** theory though this may happen, but only after at least
141515** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
141516*/
141517#define FTS3_SEGDIR_MAXLEVEL      1024
141518#define FTS3_SEGDIR_MAXLEVEL_STR "1024"
141519
141520/*
141521** The testcase() macro is only used by the amalgamation.  If undefined,
141522** make it a no-op.
141523*/
141524#ifndef testcase
141525# define testcase(X)
141526#endif
141527
141528/*
141529** Terminator values for position-lists and column-lists.
141530*/
141531#define POS_COLUMN  (1)     /* Column-list terminator */
141532#define POS_END     (0)     /* Position-list terminator */
141533
141534/*
141535** This section provides definitions to allow the
141536** FTS3 extension to be compiled outside of the
141537** amalgamation.
141538*/
141539#ifndef SQLITE_AMALGAMATION
141540/*
141541** Macros indicating that conditional expressions are always true or
141542** false.
141543*/
141544#ifdef SQLITE_COVERAGE_TEST
141545# define ALWAYS(x) (1)
141546# define NEVER(X)  (0)
141547#elif defined(SQLITE_DEBUG)
141548# define ALWAYS(x) sqlite3Fts3Always((x)!=0)
141549# define NEVER(x) sqlite3Fts3Never((x)!=0)
141550SQLITE_PRIVATE int sqlite3Fts3Always(int b);
141551SQLITE_PRIVATE int sqlite3Fts3Never(int b);
141552#else
141553# define ALWAYS(x) (x)
141554# define NEVER(x)  (x)
141555#endif
141556
141557/*
141558** Internal types used by SQLite.
141559*/
141560typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
141561typedef short int i16;            /* 2-byte (or larger) signed integer */
141562typedef unsigned int u32;         /* 4-byte unsigned integer */
141563typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
141564typedef sqlite3_int64 i64;        /* 8-byte signed integer */
141565
141566/*
141567** Macro used to suppress compiler warnings for unused parameters.
141568*/
141569#define UNUSED_PARAMETER(x) (void)(x)
141570
141571/*
141572** Activate assert() only if SQLITE_TEST is enabled.
141573*/
141574#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
141575# define NDEBUG 1
141576#endif
141577
141578/*
141579** The TESTONLY macro is used to enclose variable declarations or
141580** other bits of code that are needed to support the arguments
141581** within testcase() and assert() macros.
141582*/
141583#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
141584# define TESTONLY(X)  X
141585#else
141586# define TESTONLY(X)
141587#endif
141588
141589#endif /* SQLITE_AMALGAMATION */
141590
141591#ifdef SQLITE_DEBUG
141592SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
141593# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
141594#else
141595# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
141596#endif
141597
141598typedef struct Fts3Table Fts3Table;
141599typedef struct Fts3Cursor Fts3Cursor;
141600typedef struct Fts3Expr Fts3Expr;
141601typedef struct Fts3Phrase Fts3Phrase;
141602typedef struct Fts3PhraseToken Fts3PhraseToken;
141603
141604typedef struct Fts3Doclist Fts3Doclist;
141605typedef struct Fts3SegFilter Fts3SegFilter;
141606typedef struct Fts3DeferredToken Fts3DeferredToken;
141607typedef struct Fts3SegReader Fts3SegReader;
141608typedef struct Fts3MultiSegReader Fts3MultiSegReader;
141609
141610typedef struct MatchinfoBuffer MatchinfoBuffer;
141611
141612/*
141613** A connection to a fulltext index is an instance of the following
141614** structure. The xCreate and xConnect methods create an instance
141615** of this structure and xDestroy and xDisconnect free that instance.
141616** All other methods receive a pointer to the structure as one of their
141617** arguments.
141618*/
141619struct Fts3Table {
141620  sqlite3_vtab base;              /* Base class used by SQLite core */
141621  sqlite3 *db;                    /* The database connection */
141622  const char *zDb;                /* logical database name */
141623  const char *zName;              /* virtual table name */
141624  int nColumn;                    /* number of named columns in virtual table */
141625  char **azColumn;                /* column names.  malloced */
141626  u8 *abNotindexed;               /* True for 'notindexed' columns */
141627  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
141628  char *zContentTbl;              /* content=xxx option, or NULL */
141629  char *zLanguageid;              /* languageid=xxx option, or NULL */
141630  int nAutoincrmerge;             /* Value configured by 'automerge' */
141631  u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
141632
141633  /* Precompiled statements used by the implementation. Each of these
141634  ** statements is run and reset within a single virtual table API call.
141635  */
141636  sqlite3_stmt *aStmt[40];
141637
141638  char *zReadExprlist;
141639  char *zWriteExprlist;
141640
141641  int nNodeSize;                  /* Soft limit for node size */
141642  u8 bFts4;                       /* True for FTS4, false for FTS3 */
141643  u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */
141644  u8 bHasDocsize;                 /* True if %_docsize table exists */
141645  u8 bDescIdx;                    /* True if doclists are in reverse order */
141646  u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
141647  int nPgsz;                      /* Page size for host database */
141648  char *zSegmentsTbl;             /* Name of %_segments table */
141649  sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
141650
141651  /*
141652  ** The following array of hash tables is used to buffer pending index
141653  ** updates during transactions. All pending updates buffered at any one
141654  ** time must share a common language-id (see the FTS4 langid= feature).
141655  ** The current language id is stored in variable iPrevLangid.
141656  **
141657  ** A single FTS4 table may have multiple full-text indexes. For each index
141658  ** there is an entry in the aIndex[] array. Index 0 is an index of all the
141659  ** terms that appear in the document set. Each subsequent index in aIndex[]
141660  ** is an index of prefixes of a specific length.
141661  **
141662  ** Variable nPendingData contains an estimate the memory consumed by the
141663  ** pending data structures, including hash table overhead, but not including
141664  ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
141665  ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
141666  ** recently inserted record.
141667  */
141668  int nIndex;                     /* Size of aIndex[] */
141669  struct Fts3Index {
141670    int nPrefix;                  /* Prefix length (0 for main terms index) */
141671    Fts3Hash hPending;            /* Pending terms table for this index */
141672  } *aIndex;
141673  int nMaxPendingData;            /* Max pending data before flush to disk */
141674  int nPendingData;               /* Current bytes of pending data */
141675  sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
141676  int iPrevLangid;                /* Langid of recently inserted document */
141677  int bPrevDelete;                /* True if last operation was a delete */
141678
141679#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
141680  /* State variables used for validating that the transaction control
141681  ** methods of the virtual table are called at appropriate times.  These
141682  ** values do not contribute to FTS functionality; they are used for
141683  ** verifying the operation of the SQLite core.
141684  */
141685  int inTransaction;     /* True after xBegin but before xCommit/xRollback */
141686  int mxSavepoint;       /* Largest valid xSavepoint integer */
141687#endif
141688
141689#ifdef SQLITE_TEST
141690  /* True to disable the incremental doclist optimization. This is controled
141691  ** by special insert command 'test-no-incr-doclist'.  */
141692  int bNoIncrDoclist;
141693#endif
141694};
141695
141696/*
141697** When the core wants to read from the virtual table, it creates a
141698** virtual table cursor (an instance of the following structure) using
141699** the xOpen method. Cursors are destroyed using the xClose method.
141700*/
141701struct Fts3Cursor {
141702  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
141703  i16 eSearch;                    /* Search strategy (see below) */
141704  u8 isEof;                       /* True if at End Of Results */
141705  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
141706  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
141707  Fts3Expr *pExpr;                /* Parsed MATCH query string */
141708  int iLangid;                    /* Language being queried for */
141709  int nPhrase;                    /* Number of matchable phrases in query */
141710  Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
141711  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
141712  char *pNextId;                  /* Pointer into the body of aDoclist */
141713  char *aDoclist;                 /* List of docids for full-text queries */
141714  int nDoclist;                   /* Size of buffer at aDoclist */
141715  u8 bDesc;                       /* True to sort in descending order */
141716  int eEvalmode;                  /* An FTS3_EVAL_XX constant */
141717  int nRowAvg;                    /* Average size of database rows, in pages */
141718  sqlite3_int64 nDoc;             /* Documents in table */
141719  i64 iMinDocid;                  /* Minimum docid to return */
141720  i64 iMaxDocid;                  /* Maximum docid to return */
141721  int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
141722  MatchinfoBuffer *pMIBuffer;     /* Buffer for matchinfo data */
141723};
141724
141725#define FTS3_EVAL_FILTER    0
141726#define FTS3_EVAL_NEXT      1
141727#define FTS3_EVAL_MATCHINFO 2
141728
141729/*
141730** The Fts3Cursor.eSearch member is always set to one of the following.
141731** Actualy, Fts3Cursor.eSearch can be greater than or equal to
141732** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
141733** of the column to be searched.  For example, in
141734**
141735**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
141736**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
141737**
141738** Because the LHS of the MATCH operator is 2nd column "b",
141739** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
141740** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
141741** indicating that all columns should be searched,
141742** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
141743*/
141744#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
141745#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
141746#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
141747
141748/*
141749** The lower 16-bits of the sqlite3_index_info.idxNum value set by
141750** the xBestIndex() method contains the Fts3Cursor.eSearch value described
141751** above. The upper 16-bits contain a combination of the following
141752** bits, used to describe extra constraints on full-text searches.
141753*/
141754#define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
141755#define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
141756#define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
141757
141758struct Fts3Doclist {
141759  char *aAll;                    /* Array containing doclist (or NULL) */
141760  int nAll;                      /* Size of a[] in bytes */
141761  char *pNextDocid;              /* Pointer to next docid */
141762
141763  sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
141764  int bFreeList;                 /* True if pList should be sqlite3_free()d */
141765  char *pList;                   /* Pointer to position list following iDocid */
141766  int nList;                     /* Length of position list */
141767};
141768
141769/*
141770** A "phrase" is a sequence of one or more tokens that must match in
141771** sequence.  A single token is the base case and the most common case.
141772** For a sequence of tokens contained in double-quotes (i.e. "one two three")
141773** nToken will be the number of tokens in the string.
141774*/
141775struct Fts3PhraseToken {
141776  char *z;                        /* Text of the token */
141777  int n;                          /* Number of bytes in buffer z */
141778  int isPrefix;                   /* True if token ends with a "*" character */
141779  int bFirst;                     /* True if token must appear at position 0 */
141780
141781  /* Variables above this point are populated when the expression is
141782  ** parsed (by code in fts3_expr.c). Below this point the variables are
141783  ** used when evaluating the expression. */
141784  Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
141785  Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
141786};
141787
141788struct Fts3Phrase {
141789  /* Cache of doclist for this phrase. */
141790  Fts3Doclist doclist;
141791  int bIncr;                 /* True if doclist is loaded incrementally */
141792  int iDoclistToken;
141793
141794  /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
141795  ** OR condition.  */
141796  char *pOrPoslist;
141797  i64 iOrDocid;
141798
141799  /* Variables below this point are populated by fts3_expr.c when parsing
141800  ** a MATCH expression. Everything above is part of the evaluation phase.
141801  */
141802  int nToken;                /* Number of tokens in the phrase */
141803  int iColumn;               /* Index of column this phrase must match */
141804  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
141805};
141806
141807/*
141808** A tree of these objects forms the RHS of a MATCH operator.
141809**
141810** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
141811** points to a malloced buffer, size nDoclist bytes, containing the results
141812** of this phrase query in FTS3 doclist format. As usual, the initial
141813** "Length" field found in doclists stored on disk is omitted from this
141814** buffer.
141815**
141816** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
141817** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
141818** where nCol is the number of columns in the queried FTS table. The array
141819** is populated as follows:
141820**
141821**   aMI[iCol*3 + 0] = Undefined
141822**   aMI[iCol*3 + 1] = Number of occurrences
141823**   aMI[iCol*3 + 2] = Number of rows containing at least one instance
141824**
141825** The aMI array is allocated using sqlite3_malloc(). It should be freed
141826** when the expression node is.
141827*/
141828struct Fts3Expr {
141829  int eType;                 /* One of the FTSQUERY_XXX values defined below */
141830  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
141831  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
141832  Fts3Expr *pLeft;           /* Left operand */
141833  Fts3Expr *pRight;          /* Right operand */
141834  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
141835
141836  /* The following are used by the fts3_eval.c module. */
141837  sqlite3_int64 iDocid;      /* Current docid */
141838  u8 bEof;                   /* True this expression is at EOF already */
141839  u8 bStart;                 /* True if iDocid is valid */
141840  u8 bDeferred;              /* True if this expression is entirely deferred */
141841
141842  /* The following are used by the fts3_snippet.c module. */
141843  int iPhrase;               /* Index of this phrase in matchinfo() results */
141844  u32 *aMI;                  /* See above */
141845};
141846
141847/*
141848** Candidate values for Fts3Query.eType. Note that the order of the first
141849** four values is in order of precedence when parsing expressions. For
141850** example, the following:
141851**
141852**   "a OR b AND c NOT d NEAR e"
141853**
141854** is equivalent to:
141855**
141856**   "a OR (b AND (c NOT (d NEAR e)))"
141857*/
141858#define FTSQUERY_NEAR   1
141859#define FTSQUERY_NOT    2
141860#define FTSQUERY_AND    3
141861#define FTSQUERY_OR     4
141862#define FTSQUERY_PHRASE 5
141863
141864
141865/* fts3_write.c */
141866SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
141867SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
141868SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
141869SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
141870SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
141871  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
141872SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
141873  Fts3Table*,int,const char*,int,int,Fts3SegReader**);
141874SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
141875SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
141876SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
141877
141878SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
141879SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
141880
141881#ifndef SQLITE_DISABLE_FTS4_DEFERRED
141882SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
141883SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
141884SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
141885SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
141886SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
141887#else
141888# define sqlite3Fts3FreeDeferredTokens(x)
141889# define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
141890# define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
141891# define sqlite3Fts3FreeDeferredDoclists(x)
141892# define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
141893#endif
141894
141895SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
141896SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
141897
141898/* Special values interpreted by sqlite3SegReaderCursor() */
141899#define FTS3_SEGCURSOR_PENDING        -1
141900#define FTS3_SEGCURSOR_ALL            -2
141901
141902SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
141903SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
141904SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
141905
141906SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
141907    int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
141908
141909/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
141910#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
141911#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
141912#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
141913#define FTS3_SEGMENT_PREFIX        0x00000008
141914#define FTS3_SEGMENT_SCAN          0x00000010
141915#define FTS3_SEGMENT_FIRST         0x00000020
141916
141917/* Type passed as 4th argument to SegmentReaderIterate() */
141918struct Fts3SegFilter {
141919  const char *zTerm;
141920  int nTerm;
141921  int iCol;
141922  int flags;
141923};
141924
141925struct Fts3MultiSegReader {
141926  /* Used internally by sqlite3Fts3SegReaderXXX() calls */
141927  Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
141928  int nSegment;                   /* Size of apSegment array */
141929  int nAdvance;                   /* How many seg-readers to advance */
141930  Fts3SegFilter *pFilter;         /* Pointer to filter object */
141931  char *aBuffer;                  /* Buffer to merge doclists in */
141932  int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
141933
141934  int iColFilter;                 /* If >=0, filter for this column */
141935  int bRestart;
141936
141937  /* Used by fts3.c only. */
141938  int nCost;                      /* Cost of running iterator */
141939  int bLookup;                    /* True if a lookup of a single entry. */
141940
141941  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
141942  char *zTerm;                    /* Pointer to term buffer */
141943  int nTerm;                      /* Size of zTerm in bytes */
141944  char *aDoclist;                 /* Pointer to doclist buffer */
141945  int nDoclist;                   /* Size of aDoclist[] in bytes */
141946};
141947
141948SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
141949
141950#define fts3GetVarint32(p, piVal) (                                           \
141951  (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
141952)
141953
141954/* fts3.c */
141955SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
141956SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
141957SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
141958SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
141959SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
141960SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
141961SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
141962SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
141963SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
141964SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
141965SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
141966
141967/* fts3_tokenizer.c */
141968SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
141969SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
141970SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
141971    sqlite3_tokenizer **, char **
141972);
141973SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
141974
141975/* fts3_snippet.c */
141976SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
141977SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
141978  const char *, const char *, int, int
141979);
141980SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
141981SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
141982
141983/* fts3_expr.c */
141984SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
141985  char **, int, int, int, const char *, int, Fts3Expr **, char **
141986);
141987SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
141988#ifdef SQLITE_TEST
141989SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
141990SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
141991#endif
141992
141993SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
141994  sqlite3_tokenizer_cursor **
141995);
141996
141997/* fts3_aux.c */
141998SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
141999
142000SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
142001
142002SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
142003    Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
142004SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
142005    Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
142006SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
142007SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
142008SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
142009
142010/* fts3_tokenize_vtab.c */
142011SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
142012
142013/* fts3_unicode2.c (functions generated by parsing unicode text files) */
142014#ifndef SQLITE_DISABLE_FTS3_UNICODE
142015SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
142016SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
142017SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
142018#endif
142019
142020#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
142021#endif /* _FTSINT_H */
142022
142023/************** End of fts3Int.h *********************************************/
142024/************** Continuing where we left off in fts3.c ***********************/
142025#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
142026
142027#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
142028# define SQLITE_CORE 1
142029#endif
142030
142031/* #include <assert.h> */
142032/* #include <stdlib.h> */
142033/* #include <stddef.h> */
142034/* #include <stdio.h> */
142035/* #include <string.h> */
142036/* #include <stdarg.h> */
142037
142038/* #include "fts3.h" */
142039#ifndef SQLITE_CORE
142040/* # include "sqlite3ext.h" */
142041  SQLITE_EXTENSION_INIT1
142042#endif
142043
142044static int fts3EvalNext(Fts3Cursor *pCsr);
142045static int fts3EvalStart(Fts3Cursor *pCsr);
142046static int fts3TermSegReaderCursor(
142047    Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
142048
142049#ifndef SQLITE_AMALGAMATION
142050# if defined(SQLITE_DEBUG)
142051SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
142052SQLITE_PRIVATE int sqlite3Fts3Never(int b)  { assert( !b ); return b; }
142053# endif
142054#endif
142055
142056/*
142057** Write a 64-bit variable-length integer to memory starting at p[0].
142058** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
142059** The number of bytes written is returned.
142060*/
142061SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
142062  unsigned char *q = (unsigned char *) p;
142063  sqlite_uint64 vu = v;
142064  do{
142065    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
142066    vu >>= 7;
142067  }while( vu!=0 );
142068  q[-1] &= 0x7f;  /* turn off high bit in final byte */
142069  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
142070  return (int) (q - (unsigned char *)p);
142071}
142072
142073#define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
142074  v = (v & mask1) | ( (*ptr++) << shift );                    \
142075  if( (v & mask2)==0 ){ var = v; return ret; }
142076#define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
142077  v = (*ptr++);                                               \
142078  if( (v & mask2)==0 ){ var = v; return ret; }
142079
142080/*
142081** Read a 64-bit variable-length integer from memory starting at p[0].
142082** Return the number of bytes read, or 0 on error.
142083** The value is stored in *v.
142084*/
142085SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
142086  const char *pStart = p;
142087  u32 a;
142088  u64 b;
142089  int shift;
142090
142091  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
142092  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
142093  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
142094  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
142095  b = (a & 0x0FFFFFFF );
142096
142097  for(shift=28; shift<=63; shift+=7){
142098    u64 c = *p++;
142099    b += (c&0x7F) << shift;
142100    if( (c & 0x80)==0 ) break;
142101  }
142102  *v = b;
142103  return (int)(p - pStart);
142104}
142105
142106/*
142107** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
142108** 32-bit integer before it is returned.
142109*/
142110SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
142111  u32 a;
142112
142113#ifndef fts3GetVarint32
142114  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *pi, 1);
142115#else
142116  a = (*p++);
142117  assert( a & 0x80 );
142118#endif
142119
142120  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *pi, 2);
142121  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *pi, 3);
142122  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
142123  a = (a & 0x0FFFFFFF );
142124  *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
142125  return 5;
142126}
142127
142128/*
142129** Return the number of bytes required to encode v as a varint
142130*/
142131SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
142132  int i = 0;
142133  do{
142134    i++;
142135    v >>= 7;
142136  }while( v!=0 );
142137  return i;
142138}
142139
142140/*
142141** Convert an SQL-style quoted string into a normal string by removing
142142** the quote characters.  The conversion is done in-place.  If the
142143** input does not begin with a quote character, then this routine
142144** is a no-op.
142145**
142146** Examples:
142147**
142148**     "abc"   becomes   abc
142149**     'xyz'   becomes   xyz
142150**     [pqr]   becomes   pqr
142151**     `mno`   becomes   mno
142152**
142153*/
142154SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
142155  char quote;                     /* Quote character (if any ) */
142156
142157  quote = z[0];
142158  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
142159    int iIn = 1;                  /* Index of next byte to read from input */
142160    int iOut = 0;                 /* Index of next byte to write to output */
142161
142162    /* If the first byte was a '[', then the close-quote character is a ']' */
142163    if( quote=='[' ) quote = ']';
142164
142165    while( z[iIn] ){
142166      if( z[iIn]==quote ){
142167        if( z[iIn+1]!=quote ) break;
142168        z[iOut++] = quote;
142169        iIn += 2;
142170      }else{
142171        z[iOut++] = z[iIn++];
142172      }
142173    }
142174    z[iOut] = '\0';
142175  }
142176}
142177
142178/*
142179** Read a single varint from the doclist at *pp and advance *pp to point
142180** to the first byte past the end of the varint.  Add the value of the varint
142181** to *pVal.
142182*/
142183static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
142184  sqlite3_int64 iVal;
142185  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
142186  *pVal += iVal;
142187}
142188
142189/*
142190** When this function is called, *pp points to the first byte following a
142191** varint that is part of a doclist (or position-list, or any other list
142192** of varints). This function moves *pp to point to the start of that varint,
142193** and sets *pVal by the varint value.
142194**
142195** Argument pStart points to the first byte of the doclist that the
142196** varint is part of.
142197*/
142198static void fts3GetReverseVarint(
142199  char **pp,
142200  char *pStart,
142201  sqlite3_int64 *pVal
142202){
142203  sqlite3_int64 iVal;
142204  char *p;
142205
142206  /* Pointer p now points at the first byte past the varint we are
142207  ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
142208  ** clear on character p[-1]. */
142209  for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
142210  p++;
142211  *pp = p;
142212
142213  sqlite3Fts3GetVarint(p, &iVal);
142214  *pVal = iVal;
142215}
142216
142217/*
142218** The xDisconnect() virtual table method.
142219*/
142220static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
142221  Fts3Table *p = (Fts3Table *)pVtab;
142222  int i;
142223
142224  assert( p->nPendingData==0 );
142225  assert( p->pSegments==0 );
142226
142227  /* Free any prepared statements held */
142228  for(i=0; i<SizeofArray(p->aStmt); i++){
142229    sqlite3_finalize(p->aStmt[i]);
142230  }
142231  sqlite3_free(p->zSegmentsTbl);
142232  sqlite3_free(p->zReadExprlist);
142233  sqlite3_free(p->zWriteExprlist);
142234  sqlite3_free(p->zContentTbl);
142235  sqlite3_free(p->zLanguageid);
142236
142237  /* Invoke the tokenizer destructor to free the tokenizer. */
142238  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
142239
142240  sqlite3_free(p);
142241  return SQLITE_OK;
142242}
142243
142244/*
142245** Write an error message into *pzErr
142246*/
142247SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
142248  va_list ap;
142249  sqlite3_free(*pzErr);
142250  va_start(ap, zFormat);
142251  *pzErr = sqlite3_vmprintf(zFormat, ap);
142252  va_end(ap);
142253}
142254
142255/*
142256** Construct one or more SQL statements from the format string given
142257** and then evaluate those statements. The success code is written
142258** into *pRc.
142259**
142260** If *pRc is initially non-zero then this routine is a no-op.
142261*/
142262static void fts3DbExec(
142263  int *pRc,              /* Success code */
142264  sqlite3 *db,           /* Database in which to run SQL */
142265  const char *zFormat,   /* Format string for SQL */
142266  ...                    /* Arguments to the format string */
142267){
142268  va_list ap;
142269  char *zSql;
142270  if( *pRc ) return;
142271  va_start(ap, zFormat);
142272  zSql = sqlite3_vmprintf(zFormat, ap);
142273  va_end(ap);
142274  if( zSql==0 ){
142275    *pRc = SQLITE_NOMEM;
142276  }else{
142277    *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
142278    sqlite3_free(zSql);
142279  }
142280}
142281
142282/*
142283** The xDestroy() virtual table method.
142284*/
142285static int fts3DestroyMethod(sqlite3_vtab *pVtab){
142286  Fts3Table *p = (Fts3Table *)pVtab;
142287  int rc = SQLITE_OK;              /* Return code */
142288  const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
142289  sqlite3 *db = p->db;             /* Database handle */
142290
142291  /* Drop the shadow tables */
142292  if( p->zContentTbl==0 ){
142293    fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
142294  }
142295  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
142296  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
142297  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
142298  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
142299
142300  /* If everything has worked, invoke fts3DisconnectMethod() to free the
142301  ** memory associated with the Fts3Table structure and return SQLITE_OK.
142302  ** Otherwise, return an SQLite error code.
142303  */
142304  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
142305}
142306
142307
142308/*
142309** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
142310** passed as the first argument. This is done as part of the xConnect()
142311** and xCreate() methods.
142312**
142313** If *pRc is non-zero when this function is called, it is a no-op.
142314** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
142315** before returning.
142316*/
142317static void fts3DeclareVtab(int *pRc, Fts3Table *p){
142318  if( *pRc==SQLITE_OK ){
142319    int i;                        /* Iterator variable */
142320    int rc;                       /* Return code */
142321    char *zSql;                   /* SQL statement passed to declare_vtab() */
142322    char *zCols;                  /* List of user defined columns */
142323    const char *zLanguageid;
142324
142325    zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
142326    sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
142327
142328    /* Create a list of user columns for the virtual table */
142329    zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
142330    for(i=1; zCols && i<p->nColumn; i++){
142331      zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
142332    }
142333
142334    /* Create the whole "CREATE TABLE" statement to pass to SQLite */
142335    zSql = sqlite3_mprintf(
142336        "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
142337        zCols, p->zName, zLanguageid
142338    );
142339    if( !zCols || !zSql ){
142340      rc = SQLITE_NOMEM;
142341    }else{
142342      rc = sqlite3_declare_vtab(p->db, zSql);
142343    }
142344
142345    sqlite3_free(zSql);
142346    sqlite3_free(zCols);
142347    *pRc = rc;
142348  }
142349}
142350
142351/*
142352** Create the %_stat table if it does not already exist.
142353*/
142354SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
142355  fts3DbExec(pRc, p->db,
142356      "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
142357          "(id INTEGER PRIMARY KEY, value BLOB);",
142358      p->zDb, p->zName
142359  );
142360  if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
142361}
142362
142363/*
142364** Create the backing store tables (%_content, %_segments and %_segdir)
142365** required by the FTS3 table passed as the only argument. This is done
142366** as part of the vtab xCreate() method.
142367**
142368** If the p->bHasDocsize boolean is true (indicating that this is an
142369** FTS4 table, not an FTS3 table) then also create the %_docsize and
142370** %_stat tables required by FTS4.
142371*/
142372static int fts3CreateTables(Fts3Table *p){
142373  int rc = SQLITE_OK;             /* Return code */
142374  int i;                          /* Iterator variable */
142375  sqlite3 *db = p->db;            /* The database connection */
142376
142377  if( p->zContentTbl==0 ){
142378    const char *zLanguageid = p->zLanguageid;
142379    char *zContentCols;           /* Columns of %_content table */
142380
142381    /* Create a list of user columns for the content table */
142382    zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
142383    for(i=0; zContentCols && i<p->nColumn; i++){
142384      char *z = p->azColumn[i];
142385      zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
142386    }
142387    if( zLanguageid && zContentCols ){
142388      zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
142389    }
142390    if( zContentCols==0 ) rc = SQLITE_NOMEM;
142391
142392    /* Create the content table */
142393    fts3DbExec(&rc, db,
142394       "CREATE TABLE %Q.'%q_content'(%s)",
142395       p->zDb, p->zName, zContentCols
142396    );
142397    sqlite3_free(zContentCols);
142398  }
142399
142400  /* Create other tables */
142401  fts3DbExec(&rc, db,
142402      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
142403      p->zDb, p->zName
142404  );
142405  fts3DbExec(&rc, db,
142406      "CREATE TABLE %Q.'%q_segdir'("
142407        "level INTEGER,"
142408        "idx INTEGER,"
142409        "start_block INTEGER,"
142410        "leaves_end_block INTEGER,"
142411        "end_block INTEGER,"
142412        "root BLOB,"
142413        "PRIMARY KEY(level, idx)"
142414      ");",
142415      p->zDb, p->zName
142416  );
142417  if( p->bHasDocsize ){
142418    fts3DbExec(&rc, db,
142419        "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
142420        p->zDb, p->zName
142421    );
142422  }
142423  assert( p->bHasStat==p->bFts4 );
142424  if( p->bHasStat ){
142425    sqlite3Fts3CreateStatTable(&rc, p);
142426  }
142427  return rc;
142428}
142429
142430/*
142431** Store the current database page-size in bytes in p->nPgsz.
142432**
142433** If *pRc is non-zero when this function is called, it is a no-op.
142434** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
142435** before returning.
142436*/
142437static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
142438  if( *pRc==SQLITE_OK ){
142439    int rc;                       /* Return code */
142440    char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
142441    sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
142442
142443    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
142444    if( !zSql ){
142445      rc = SQLITE_NOMEM;
142446    }else{
142447      rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
142448      if( rc==SQLITE_OK ){
142449        sqlite3_step(pStmt);
142450        p->nPgsz = sqlite3_column_int(pStmt, 0);
142451        rc = sqlite3_finalize(pStmt);
142452      }else if( rc==SQLITE_AUTH ){
142453        p->nPgsz = 1024;
142454        rc = SQLITE_OK;
142455      }
142456    }
142457    assert( p->nPgsz>0 || rc!=SQLITE_OK );
142458    sqlite3_free(zSql);
142459    *pRc = rc;
142460  }
142461}
142462
142463/*
142464** "Special" FTS4 arguments are column specifications of the following form:
142465**
142466**   <key> = <value>
142467**
142468** There may not be whitespace surrounding the "=" character. The <value>
142469** term may be quoted, but the <key> may not.
142470*/
142471static int fts3IsSpecialColumn(
142472  const char *z,
142473  int *pnKey,
142474  char **pzValue
142475){
142476  char *zValue;
142477  const char *zCsr = z;
142478
142479  while( *zCsr!='=' ){
142480    if( *zCsr=='\0' ) return 0;
142481    zCsr++;
142482  }
142483
142484  *pnKey = (int)(zCsr-z);
142485  zValue = sqlite3_mprintf("%s", &zCsr[1]);
142486  if( zValue ){
142487    sqlite3Fts3Dequote(zValue);
142488  }
142489  *pzValue = zValue;
142490  return 1;
142491}
142492
142493/*
142494** Append the output of a printf() style formatting to an existing string.
142495*/
142496static void fts3Appendf(
142497  int *pRc,                       /* IN/OUT: Error code */
142498  char **pz,                      /* IN/OUT: Pointer to string buffer */
142499  const char *zFormat,            /* Printf format string to append */
142500  ...                             /* Arguments for printf format string */
142501){
142502  if( *pRc==SQLITE_OK ){
142503    va_list ap;
142504    char *z;
142505    va_start(ap, zFormat);
142506    z = sqlite3_vmprintf(zFormat, ap);
142507    va_end(ap);
142508    if( z && *pz ){
142509      char *z2 = sqlite3_mprintf("%s%s", *pz, z);
142510      sqlite3_free(z);
142511      z = z2;
142512    }
142513    if( z==0 ) *pRc = SQLITE_NOMEM;
142514    sqlite3_free(*pz);
142515    *pz = z;
142516  }
142517}
142518
142519/*
142520** Return a copy of input string zInput enclosed in double-quotes (") and
142521** with all double quote characters escaped. For example:
142522**
142523**     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
142524**
142525** The pointer returned points to memory obtained from sqlite3_malloc(). It
142526** is the callers responsibility to call sqlite3_free() to release this
142527** memory.
142528*/
142529static char *fts3QuoteId(char const *zInput){
142530  int nRet;
142531  char *zRet;
142532  nRet = 2 + (int)strlen(zInput)*2 + 1;
142533  zRet = sqlite3_malloc(nRet);
142534  if( zRet ){
142535    int i;
142536    char *z = zRet;
142537    *(z++) = '"';
142538    for(i=0; zInput[i]; i++){
142539      if( zInput[i]=='"' ) *(z++) = '"';
142540      *(z++) = zInput[i];
142541    }
142542    *(z++) = '"';
142543    *(z++) = '\0';
142544  }
142545  return zRet;
142546}
142547
142548/*
142549** Return a list of comma separated SQL expressions and a FROM clause that
142550** could be used in a SELECT statement such as the following:
142551**
142552**     SELECT <list of expressions> FROM %_content AS x ...
142553**
142554** to return the docid, followed by each column of text data in order
142555** from left to write. If parameter zFunc is not NULL, then instead of
142556** being returned directly each column of text data is passed to an SQL
142557** function named zFunc first. For example, if zFunc is "unzip" and the
142558** table has the three user-defined columns "a", "b", and "c", the following
142559** string is returned:
142560**
142561**     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
142562**
142563** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
142564** is the responsibility of the caller to eventually free it.
142565**
142566** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
142567** a NULL pointer is returned). Otherwise, if an OOM error is encountered
142568** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
142569** no error occurs, *pRc is left unmodified.
142570*/
142571static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
142572  char *zRet = 0;
142573  char *zFree = 0;
142574  char *zFunction;
142575  int i;
142576
142577  if( p->zContentTbl==0 ){
142578    if( !zFunc ){
142579      zFunction = "";
142580    }else{
142581      zFree = zFunction = fts3QuoteId(zFunc);
142582    }
142583    fts3Appendf(pRc, &zRet, "docid");
142584    for(i=0; i<p->nColumn; i++){
142585      fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
142586    }
142587    if( p->zLanguageid ){
142588      fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
142589    }
142590    sqlite3_free(zFree);
142591  }else{
142592    fts3Appendf(pRc, &zRet, "rowid");
142593    for(i=0; i<p->nColumn; i++){
142594      fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
142595    }
142596    if( p->zLanguageid ){
142597      fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
142598    }
142599  }
142600  fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
142601      p->zDb,
142602      (p->zContentTbl ? p->zContentTbl : p->zName),
142603      (p->zContentTbl ? "" : "_content")
142604  );
142605  return zRet;
142606}
142607
142608/*
142609** Return a list of N comma separated question marks, where N is the number
142610** of columns in the %_content table (one for the docid plus one for each
142611** user-defined text column).
142612**
142613** If argument zFunc is not NULL, then all but the first question mark
142614** is preceded by zFunc and an open bracket, and followed by a closed
142615** bracket. For example, if zFunc is "zip" and the FTS3 table has three
142616** user-defined text columns, the following string is returned:
142617**
142618**     "?, zip(?), zip(?), zip(?)"
142619**
142620** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
142621** is the responsibility of the caller to eventually free it.
142622**
142623** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
142624** a NULL pointer is returned). Otherwise, if an OOM error is encountered
142625** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
142626** no error occurs, *pRc is left unmodified.
142627*/
142628static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
142629  char *zRet = 0;
142630  char *zFree = 0;
142631  char *zFunction;
142632  int i;
142633
142634  if( !zFunc ){
142635    zFunction = "";
142636  }else{
142637    zFree = zFunction = fts3QuoteId(zFunc);
142638  }
142639  fts3Appendf(pRc, &zRet, "?");
142640  for(i=0; i<p->nColumn; i++){
142641    fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
142642  }
142643  if( p->zLanguageid ){
142644    fts3Appendf(pRc, &zRet, ", ?");
142645  }
142646  sqlite3_free(zFree);
142647  return zRet;
142648}
142649
142650/*
142651** This function interprets the string at (*pp) as a non-negative integer
142652** value. It reads the integer and sets *pnOut to the value read, then
142653** sets *pp to point to the byte immediately following the last byte of
142654** the integer value.
142655**
142656** Only decimal digits ('0'..'9') may be part of an integer value.
142657**
142658** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
142659** the output value undefined. Otherwise SQLITE_OK is returned.
142660**
142661** This function is used when parsing the "prefix=" FTS4 parameter.
142662*/
142663static int fts3GobbleInt(const char **pp, int *pnOut){
142664  const int MAX_NPREFIX = 10000000;
142665  const char *p;                  /* Iterator pointer */
142666  int nInt = 0;                   /* Output value */
142667
142668  for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
142669    nInt = nInt * 10 + (p[0] - '0');
142670    if( nInt>MAX_NPREFIX ){
142671      nInt = 0;
142672      break;
142673    }
142674  }
142675  if( p==*pp ) return SQLITE_ERROR;
142676  *pnOut = nInt;
142677  *pp = p;
142678  return SQLITE_OK;
142679}
142680
142681/*
142682** This function is called to allocate an array of Fts3Index structures
142683** representing the indexes maintained by the current FTS table. FTS tables
142684** always maintain the main "terms" index, but may also maintain one or
142685** more "prefix" indexes, depending on the value of the "prefix=" parameter
142686** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
142687**
142688** Argument zParam is passed the value of the "prefix=" option if one was
142689** specified, or NULL otherwise.
142690**
142691** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
142692** the allocated array. *pnIndex is set to the number of elements in the
142693** array. If an error does occur, an SQLite error code is returned.
142694**
142695** Regardless of whether or not an error is returned, it is the responsibility
142696** of the caller to call sqlite3_free() on the output array to free it.
142697*/
142698static int fts3PrefixParameter(
142699  const char *zParam,             /* ABC in prefix=ABC parameter to parse */
142700  int *pnIndex,                   /* OUT: size of *apIndex[] array */
142701  struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
142702){
142703  struct Fts3Index *aIndex;       /* Allocated array */
142704  int nIndex = 1;                 /* Number of entries in array */
142705
142706  if( zParam && zParam[0] ){
142707    const char *p;
142708    nIndex++;
142709    for(p=zParam; *p; p++){
142710      if( *p==',' ) nIndex++;
142711    }
142712  }
142713
142714  aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
142715  *apIndex = aIndex;
142716  if( !aIndex ){
142717    return SQLITE_NOMEM;
142718  }
142719
142720  memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
142721  if( zParam ){
142722    const char *p = zParam;
142723    int i;
142724    for(i=1; i<nIndex; i++){
142725      int nPrefix = 0;
142726      if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
142727      assert( nPrefix>=0 );
142728      if( nPrefix==0 ){
142729        nIndex--;
142730        i--;
142731      }else{
142732        aIndex[i].nPrefix = nPrefix;
142733      }
142734      p++;
142735    }
142736  }
142737
142738  *pnIndex = nIndex;
142739  return SQLITE_OK;
142740}
142741
142742/*
142743** This function is called when initializing an FTS4 table that uses the
142744** content=xxx option. It determines the number of and names of the columns
142745** of the new FTS4 table.
142746**
142747** The third argument passed to this function is the value passed to the
142748** config=xxx option (i.e. "xxx"). This function queries the database for
142749** a table of that name. If found, the output variables are populated
142750** as follows:
142751**
142752**   *pnCol:   Set to the number of columns table xxx has,
142753**
142754**   *pnStr:   Set to the total amount of space required to store a copy
142755**             of each columns name, including the nul-terminator.
142756**
142757**   *pazCol:  Set to point to an array of *pnCol strings. Each string is
142758**             the name of the corresponding column in table xxx. The array
142759**             and its contents are allocated using a single allocation. It
142760**             is the responsibility of the caller to free this allocation
142761**             by eventually passing the *pazCol value to sqlite3_free().
142762**
142763** If the table cannot be found, an error code is returned and the output
142764** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
142765** returned (and the output variables are undefined).
142766*/
142767static int fts3ContentColumns(
142768  sqlite3 *db,                    /* Database handle */
142769  const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
142770  const char *zTbl,               /* Name of content table */
142771  const char ***pazCol,           /* OUT: Malloc'd array of column names */
142772  int *pnCol,                     /* OUT: Size of array *pazCol */
142773  int *pnStr,                     /* OUT: Bytes of string content */
142774  char **pzErr                    /* OUT: error message */
142775){
142776  int rc = SQLITE_OK;             /* Return code */
142777  char *zSql;                     /* "SELECT *" statement on zTbl */
142778  sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
142779
142780  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
142781  if( !zSql ){
142782    rc = SQLITE_NOMEM;
142783  }else{
142784    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
142785    if( rc!=SQLITE_OK ){
142786      sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
142787    }
142788  }
142789  sqlite3_free(zSql);
142790
142791  if( rc==SQLITE_OK ){
142792    const char **azCol;           /* Output array */
142793    int nStr = 0;                 /* Size of all column names (incl. 0x00) */
142794    int nCol;                     /* Number of table columns */
142795    int i;                        /* Used to iterate through columns */
142796
142797    /* Loop through the returned columns. Set nStr to the number of bytes of
142798    ** space required to store a copy of each column name, including the
142799    ** nul-terminator byte.  */
142800    nCol = sqlite3_column_count(pStmt);
142801    for(i=0; i<nCol; i++){
142802      const char *zCol = sqlite3_column_name(pStmt, i);
142803      nStr += (int)strlen(zCol) + 1;
142804    }
142805
142806    /* Allocate and populate the array to return. */
142807    azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
142808    if( azCol==0 ){
142809      rc = SQLITE_NOMEM;
142810    }else{
142811      char *p = (char *)&azCol[nCol];
142812      for(i=0; i<nCol; i++){
142813        const char *zCol = sqlite3_column_name(pStmt, i);
142814        int n = (int)strlen(zCol)+1;
142815        memcpy(p, zCol, n);
142816        azCol[i] = p;
142817        p += n;
142818      }
142819    }
142820    sqlite3_finalize(pStmt);
142821
142822    /* Set the output variables. */
142823    *pnCol = nCol;
142824    *pnStr = nStr;
142825    *pazCol = azCol;
142826  }
142827
142828  return rc;
142829}
142830
142831/*
142832** This function is the implementation of both the xConnect and xCreate
142833** methods of the FTS3 virtual table.
142834**
142835** The argv[] array contains the following:
142836**
142837**   argv[0]   -> module name  ("fts3" or "fts4")
142838**   argv[1]   -> database name
142839**   argv[2]   -> table name
142840**   argv[...] -> "column name" and other module argument fields.
142841*/
142842static int fts3InitVtab(
142843  int isCreate,                   /* True for xCreate, false for xConnect */
142844  sqlite3 *db,                    /* The SQLite database connection */
142845  void *pAux,                     /* Hash table containing tokenizers */
142846  int argc,                       /* Number of elements in argv array */
142847  const char * const *argv,       /* xCreate/xConnect argument array */
142848  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
142849  char **pzErr                    /* Write any error message here */
142850){
142851  Fts3Hash *pHash = (Fts3Hash *)pAux;
142852  Fts3Table *p = 0;               /* Pointer to allocated vtab */
142853  int rc = SQLITE_OK;             /* Return code */
142854  int i;                          /* Iterator variable */
142855  int nByte;                      /* Size of allocation used for *p */
142856  int iCol;                       /* Column index */
142857  int nString = 0;                /* Bytes required to hold all column names */
142858  int nCol = 0;                   /* Number of columns in the FTS table */
142859  char *zCsr;                     /* Space for holding column names */
142860  int nDb;                        /* Bytes required to hold database name */
142861  int nName;                      /* Bytes required to hold table name */
142862  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
142863  const char **aCol;              /* Array of column names */
142864  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
142865
142866  int nIndex = 0;                 /* Size of aIndex[] array */
142867  struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
142868
142869  /* The results of parsing supported FTS4 key=value options: */
142870  int bNoDocsize = 0;             /* True to omit %_docsize table */
142871  int bDescIdx = 0;               /* True to store descending indexes */
142872  char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
142873  char *zCompress = 0;            /* compress=? parameter (or NULL) */
142874  char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
142875  char *zContent = 0;             /* content=? parameter (or NULL) */
142876  char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
142877  char **azNotindexed = 0;        /* The set of notindexed= columns */
142878  int nNotindexed = 0;            /* Size of azNotindexed[] array */
142879
142880  assert( strlen(argv[0])==4 );
142881  assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
142882       || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
142883  );
142884
142885  nDb = (int)strlen(argv[1]) + 1;
142886  nName = (int)strlen(argv[2]) + 1;
142887
142888  nByte = sizeof(const char *) * (argc-2);
142889  aCol = (const char **)sqlite3_malloc(nByte);
142890  if( aCol ){
142891    memset((void*)aCol, 0, nByte);
142892    azNotindexed = (char **)sqlite3_malloc(nByte);
142893  }
142894  if( azNotindexed ){
142895    memset(azNotindexed, 0, nByte);
142896  }
142897  if( !aCol || !azNotindexed ){
142898    rc = SQLITE_NOMEM;
142899    goto fts3_init_out;
142900  }
142901
142902  /* Loop through all of the arguments passed by the user to the FTS3/4
142903  ** module (i.e. all the column names and special arguments). This loop
142904  ** does the following:
142905  **
142906  **   + Figures out the number of columns the FTSX table will have, and
142907  **     the number of bytes of space that must be allocated to store copies
142908  **     of the column names.
142909  **
142910  **   + If there is a tokenizer specification included in the arguments,
142911  **     initializes the tokenizer pTokenizer.
142912  */
142913  for(i=3; rc==SQLITE_OK && i<argc; i++){
142914    char const *z = argv[i];
142915    int nKey;
142916    char *zVal;
142917
142918    /* Check if this is a tokenizer specification */
142919    if( !pTokenizer
142920     && strlen(z)>8
142921     && 0==sqlite3_strnicmp(z, "tokenize", 8)
142922     && 0==sqlite3Fts3IsIdChar(z[8])
142923    ){
142924      rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
142925    }
142926
142927    /* Check if it is an FTS4 special argument. */
142928    else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
142929      struct Fts4Option {
142930        const char *zOpt;
142931        int nOpt;
142932      } aFts4Opt[] = {
142933        { "matchinfo",   9 },     /* 0 -> MATCHINFO */
142934        { "prefix",      6 },     /* 1 -> PREFIX */
142935        { "compress",    8 },     /* 2 -> COMPRESS */
142936        { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
142937        { "order",       5 },     /* 4 -> ORDER */
142938        { "content",     7 },     /* 5 -> CONTENT */
142939        { "languageid", 10 },     /* 6 -> LANGUAGEID */
142940        { "notindexed", 10 }      /* 7 -> NOTINDEXED */
142941      };
142942
142943      int iOpt;
142944      if( !zVal ){
142945        rc = SQLITE_NOMEM;
142946      }else{
142947        for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
142948          struct Fts4Option *pOp = &aFts4Opt[iOpt];
142949          if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
142950            break;
142951          }
142952        }
142953        if( iOpt==SizeofArray(aFts4Opt) ){
142954          sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
142955          rc = SQLITE_ERROR;
142956        }else{
142957          switch( iOpt ){
142958            case 0:               /* MATCHINFO */
142959              if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
142960                sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
142961                rc = SQLITE_ERROR;
142962              }
142963              bNoDocsize = 1;
142964              break;
142965
142966            case 1:               /* PREFIX */
142967              sqlite3_free(zPrefix);
142968              zPrefix = zVal;
142969              zVal = 0;
142970              break;
142971
142972            case 2:               /* COMPRESS */
142973              sqlite3_free(zCompress);
142974              zCompress = zVal;
142975              zVal = 0;
142976              break;
142977
142978            case 3:               /* UNCOMPRESS */
142979              sqlite3_free(zUncompress);
142980              zUncompress = zVal;
142981              zVal = 0;
142982              break;
142983
142984            case 4:               /* ORDER */
142985              if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
142986               && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
142987              ){
142988                sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
142989                rc = SQLITE_ERROR;
142990              }
142991              bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
142992              break;
142993
142994            case 5:              /* CONTENT */
142995              sqlite3_free(zContent);
142996              zContent = zVal;
142997              zVal = 0;
142998              break;
142999
143000            case 6:              /* LANGUAGEID */
143001              assert( iOpt==6 );
143002              sqlite3_free(zLanguageid);
143003              zLanguageid = zVal;
143004              zVal = 0;
143005              break;
143006
143007            case 7:              /* NOTINDEXED */
143008              azNotindexed[nNotindexed++] = zVal;
143009              zVal = 0;
143010              break;
143011          }
143012        }
143013        sqlite3_free(zVal);
143014      }
143015    }
143016
143017    /* Otherwise, the argument is a column name. */
143018    else {
143019      nString += (int)(strlen(z) + 1);
143020      aCol[nCol++] = z;
143021    }
143022  }
143023
143024  /* If a content=xxx option was specified, the following:
143025  **
143026  **   1. Ignore any compress= and uncompress= options.
143027  **
143028  **   2. If no column names were specified as part of the CREATE VIRTUAL
143029  **      TABLE statement, use all columns from the content table.
143030  */
143031  if( rc==SQLITE_OK && zContent ){
143032    sqlite3_free(zCompress);
143033    sqlite3_free(zUncompress);
143034    zCompress = 0;
143035    zUncompress = 0;
143036    if( nCol==0 ){
143037      sqlite3_free((void*)aCol);
143038      aCol = 0;
143039      rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
143040
143041      /* If a languageid= option was specified, remove the language id
143042      ** column from the aCol[] array. */
143043      if( rc==SQLITE_OK && zLanguageid ){
143044        int j;
143045        for(j=0; j<nCol; j++){
143046          if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
143047            int k;
143048            for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
143049            nCol--;
143050            break;
143051          }
143052        }
143053      }
143054    }
143055  }
143056  if( rc!=SQLITE_OK ) goto fts3_init_out;
143057
143058  if( nCol==0 ){
143059    assert( nString==0 );
143060    aCol[0] = "content";
143061    nString = 8;
143062    nCol = 1;
143063  }
143064
143065  if( pTokenizer==0 ){
143066    rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
143067    if( rc!=SQLITE_OK ) goto fts3_init_out;
143068  }
143069  assert( pTokenizer );
143070
143071  rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
143072  if( rc==SQLITE_ERROR ){
143073    assert( zPrefix );
143074    sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
143075  }
143076  if( rc!=SQLITE_OK ) goto fts3_init_out;
143077
143078  /* Allocate and populate the Fts3Table structure. */
143079  nByte = sizeof(Fts3Table) +                  /* Fts3Table */
143080          nCol * sizeof(char *) +              /* azColumn */
143081          nIndex * sizeof(struct Fts3Index) +  /* aIndex */
143082          nCol * sizeof(u8) +                  /* abNotindexed */
143083          nName +                              /* zName */
143084          nDb +                                /* zDb */
143085          nString;                             /* Space for azColumn strings */
143086  p = (Fts3Table*)sqlite3_malloc(nByte);
143087  if( p==0 ){
143088    rc = SQLITE_NOMEM;
143089    goto fts3_init_out;
143090  }
143091  memset(p, 0, nByte);
143092  p->db = db;
143093  p->nColumn = nCol;
143094  p->nPendingData = 0;
143095  p->azColumn = (char **)&p[1];
143096  p->pTokenizer = pTokenizer;
143097  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
143098  p->bHasDocsize = (isFts4 && bNoDocsize==0);
143099  p->bHasStat = isFts4;
143100  p->bFts4 = isFts4;
143101  p->bDescIdx = bDescIdx;
143102  p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
143103  p->zContentTbl = zContent;
143104  p->zLanguageid = zLanguageid;
143105  zContent = 0;
143106  zLanguageid = 0;
143107  TESTONLY( p->inTransaction = -1 );
143108  TESTONLY( p->mxSavepoint = -1 );
143109
143110  p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
143111  memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
143112  p->nIndex = nIndex;
143113  for(i=0; i<nIndex; i++){
143114    fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
143115  }
143116  p->abNotindexed = (u8 *)&p->aIndex[nIndex];
143117
143118  /* Fill in the zName and zDb fields of the vtab structure. */
143119  zCsr = (char *)&p->abNotindexed[nCol];
143120  p->zName = zCsr;
143121  memcpy(zCsr, argv[2], nName);
143122  zCsr += nName;
143123  p->zDb = zCsr;
143124  memcpy(zCsr, argv[1], nDb);
143125  zCsr += nDb;
143126
143127  /* Fill in the azColumn array */
143128  for(iCol=0; iCol<nCol; iCol++){
143129    char *z;
143130    int n = 0;
143131    z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
143132    memcpy(zCsr, z, n);
143133    zCsr[n] = '\0';
143134    sqlite3Fts3Dequote(zCsr);
143135    p->azColumn[iCol] = zCsr;
143136    zCsr += n+1;
143137    assert( zCsr <= &((char *)p)[nByte] );
143138  }
143139
143140  /* Fill in the abNotindexed array */
143141  for(iCol=0; iCol<nCol; iCol++){
143142    int n = (int)strlen(p->azColumn[iCol]);
143143    for(i=0; i<nNotindexed; i++){
143144      char *zNot = azNotindexed[i];
143145      if( zNot && n==(int)strlen(zNot)
143146       && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
143147      ){
143148        p->abNotindexed[iCol] = 1;
143149        sqlite3_free(zNot);
143150        azNotindexed[i] = 0;
143151      }
143152    }
143153  }
143154  for(i=0; i<nNotindexed; i++){
143155    if( azNotindexed[i] ){
143156      sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
143157      rc = SQLITE_ERROR;
143158    }
143159  }
143160
143161  if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
143162    char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
143163    rc = SQLITE_ERROR;
143164    sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
143165  }
143166  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
143167  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
143168  if( rc!=SQLITE_OK ) goto fts3_init_out;
143169
143170  /* If this is an xCreate call, create the underlying tables in the
143171  ** database. TODO: For xConnect(), it could verify that said tables exist.
143172  */
143173  if( isCreate ){
143174    rc = fts3CreateTables(p);
143175  }
143176
143177  /* Check to see if a legacy fts3 table has been "upgraded" by the
143178  ** addition of a %_stat table so that it can use incremental merge.
143179  */
143180  if( !isFts4 && !isCreate ){
143181    p->bHasStat = 2;
143182  }
143183
143184  /* Figure out the page-size for the database. This is required in order to
143185  ** estimate the cost of loading large doclists from the database.  */
143186  fts3DatabasePageSize(&rc, p);
143187  p->nNodeSize = p->nPgsz-35;
143188
143189  /* Declare the table schema to SQLite. */
143190  fts3DeclareVtab(&rc, p);
143191
143192fts3_init_out:
143193  sqlite3_free(zPrefix);
143194  sqlite3_free(aIndex);
143195  sqlite3_free(zCompress);
143196  sqlite3_free(zUncompress);
143197  sqlite3_free(zContent);
143198  sqlite3_free(zLanguageid);
143199  for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
143200  sqlite3_free((void *)aCol);
143201  sqlite3_free((void *)azNotindexed);
143202  if( rc!=SQLITE_OK ){
143203    if( p ){
143204      fts3DisconnectMethod((sqlite3_vtab *)p);
143205    }else if( pTokenizer ){
143206      pTokenizer->pModule->xDestroy(pTokenizer);
143207    }
143208  }else{
143209    assert( p->pSegments==0 );
143210    *ppVTab = &p->base;
143211  }
143212  return rc;
143213}
143214
143215/*
143216** The xConnect() and xCreate() methods for the virtual table. All the
143217** work is done in function fts3InitVtab().
143218*/
143219static int fts3ConnectMethod(
143220  sqlite3 *db,                    /* Database connection */
143221  void *pAux,                     /* Pointer to tokenizer hash table */
143222  int argc,                       /* Number of elements in argv array */
143223  const char * const *argv,       /* xCreate/xConnect argument array */
143224  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
143225  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
143226){
143227  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
143228}
143229static int fts3CreateMethod(
143230  sqlite3 *db,                    /* Database connection */
143231  void *pAux,                     /* Pointer to tokenizer hash table */
143232  int argc,                       /* Number of elements in argv array */
143233  const char * const *argv,       /* xCreate/xConnect argument array */
143234  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
143235  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
143236){
143237  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
143238}
143239
143240/*
143241** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
143242** extension is currently being used by a version of SQLite too old to
143243** support estimatedRows. In that case this function is a no-op.
143244*/
143245static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
143246#if SQLITE_VERSION_NUMBER>=3008002
143247  if( sqlite3_libversion_number()>=3008002 ){
143248    pIdxInfo->estimatedRows = nRow;
143249  }
143250#endif
143251}
143252
143253/*
143254** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
143255** extension is currently being used by a version of SQLite too old to
143256** support index-info flags. In that case this function is a no-op.
143257*/
143258static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
143259#if SQLITE_VERSION_NUMBER>=3008012
143260  if( sqlite3_libversion_number()>=3008012 ){
143261    pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
143262  }
143263#endif
143264}
143265
143266/*
143267** Implementation of the xBestIndex method for FTS3 tables. There
143268** are three possible strategies, in order of preference:
143269**
143270**   1. Direct lookup by rowid or docid.
143271**   2. Full-text search using a MATCH operator on a non-docid column.
143272**   3. Linear scan of %_content table.
143273*/
143274static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
143275  Fts3Table *p = (Fts3Table *)pVTab;
143276  int i;                          /* Iterator variable */
143277  int iCons = -1;                 /* Index of constraint to use */
143278
143279  int iLangidCons = -1;           /* Index of langid=x constraint, if present */
143280  int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
143281  int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
143282  int iIdx;
143283
143284  /* By default use a full table scan. This is an expensive option,
143285  ** so search through the constraints to see if a more efficient
143286  ** strategy is possible.
143287  */
143288  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
143289  pInfo->estimatedCost = 5000000;
143290  for(i=0; i<pInfo->nConstraint; i++){
143291    int bDocid;                 /* True if this constraint is on docid */
143292    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
143293    if( pCons->usable==0 ){
143294      if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
143295        /* There exists an unusable MATCH constraint. This means that if
143296        ** the planner does elect to use the results of this call as part
143297        ** of the overall query plan the user will see an "unable to use
143298        ** function MATCH in the requested context" error. To discourage
143299        ** this, return a very high cost here.  */
143300        pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
143301        pInfo->estimatedCost = 1e50;
143302        fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
143303        return SQLITE_OK;
143304      }
143305      continue;
143306    }
143307
143308    bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
143309
143310    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
143311    if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
143312      pInfo->idxNum = FTS3_DOCID_SEARCH;
143313      pInfo->estimatedCost = 1.0;
143314      iCons = i;
143315    }
143316
143317    /* A MATCH constraint. Use a full-text search.
143318    **
143319    ** If there is more than one MATCH constraint available, use the first
143320    ** one encountered. If there is both a MATCH constraint and a direct
143321    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
143322    ** though the rowid/docid lookup is faster than a MATCH query, selecting
143323    ** it would lead to an "unable to use function MATCH in the requested
143324    ** context" error.
143325    */
143326    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
143327     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
143328    ){
143329      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
143330      pInfo->estimatedCost = 2.0;
143331      iCons = i;
143332    }
143333
143334    /* Equality constraint on the langid column */
143335    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
143336     && pCons->iColumn==p->nColumn + 2
143337    ){
143338      iLangidCons = i;
143339    }
143340
143341    if( bDocid ){
143342      switch( pCons->op ){
143343        case SQLITE_INDEX_CONSTRAINT_GE:
143344        case SQLITE_INDEX_CONSTRAINT_GT:
143345          iDocidGe = i;
143346          break;
143347
143348        case SQLITE_INDEX_CONSTRAINT_LE:
143349        case SQLITE_INDEX_CONSTRAINT_LT:
143350          iDocidLe = i;
143351          break;
143352      }
143353    }
143354  }
143355
143356  /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
143357  if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
143358
143359  iIdx = 1;
143360  if( iCons>=0 ){
143361    pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
143362    pInfo->aConstraintUsage[iCons].omit = 1;
143363  }
143364  if( iLangidCons>=0 ){
143365    pInfo->idxNum |= FTS3_HAVE_LANGID;
143366    pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
143367  }
143368  if( iDocidGe>=0 ){
143369    pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
143370    pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
143371  }
143372  if( iDocidLe>=0 ){
143373    pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
143374    pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
143375  }
143376
143377  /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
143378  ** docid) order. Both ascending and descending are possible.
143379  */
143380  if( pInfo->nOrderBy==1 ){
143381    struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
143382    if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
143383      if( pOrder->desc ){
143384        pInfo->idxStr = "DESC";
143385      }else{
143386        pInfo->idxStr = "ASC";
143387      }
143388      pInfo->orderByConsumed = 1;
143389    }
143390  }
143391
143392  assert( p->pSegments==0 );
143393  return SQLITE_OK;
143394}
143395
143396/*
143397** Implementation of xOpen method.
143398*/
143399static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
143400  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
143401
143402  UNUSED_PARAMETER(pVTab);
143403
143404  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
143405  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
143406  ** if the allocation fails, return SQLITE_NOMEM.
143407  */
143408  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
143409  if( !pCsr ){
143410    return SQLITE_NOMEM;
143411  }
143412  memset(pCsr, 0, sizeof(Fts3Cursor));
143413  return SQLITE_OK;
143414}
143415
143416/*
143417** Close the cursor.  For additional information see the documentation
143418** on the xClose method of the virtual table interface.
143419*/
143420static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
143421  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
143422  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
143423  sqlite3_finalize(pCsr->pStmt);
143424  sqlite3Fts3ExprFree(pCsr->pExpr);
143425  sqlite3Fts3FreeDeferredTokens(pCsr);
143426  sqlite3_free(pCsr->aDoclist);
143427  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
143428  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
143429  sqlite3_free(pCsr);
143430  return SQLITE_OK;
143431}
143432
143433/*
143434** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
143435** compose and prepare an SQL statement of the form:
143436**
143437**    "SELECT <columns> FROM %_content WHERE rowid = ?"
143438**
143439** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
143440** it. If an error occurs, return an SQLite error code.
143441**
143442** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
143443*/
143444static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
143445  int rc = SQLITE_OK;
143446  if( pCsr->pStmt==0 ){
143447    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
143448    char *zSql;
143449    zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
143450    if( !zSql ) return SQLITE_NOMEM;
143451    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
143452    sqlite3_free(zSql);
143453  }
143454  *ppStmt = pCsr->pStmt;
143455  return rc;
143456}
143457
143458/*
143459** Position the pCsr->pStmt statement so that it is on the row
143460** of the %_content table that contains the last match.  Return
143461** SQLITE_OK on success.
143462*/
143463static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
143464  int rc = SQLITE_OK;
143465  if( pCsr->isRequireSeek ){
143466    sqlite3_stmt *pStmt = 0;
143467
143468    rc = fts3CursorSeekStmt(pCsr, &pStmt);
143469    if( rc==SQLITE_OK ){
143470      sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
143471      pCsr->isRequireSeek = 0;
143472      if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
143473        return SQLITE_OK;
143474      }else{
143475        rc = sqlite3_reset(pCsr->pStmt);
143476        if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
143477          /* If no row was found and no error has occurred, then the %_content
143478          ** table is missing a row that is present in the full-text index.
143479          ** The data structures are corrupt.  */
143480          rc = FTS_CORRUPT_VTAB;
143481          pCsr->isEof = 1;
143482        }
143483      }
143484    }
143485  }
143486
143487  if( rc!=SQLITE_OK && pContext ){
143488    sqlite3_result_error_code(pContext, rc);
143489  }
143490  return rc;
143491}
143492
143493/*
143494** This function is used to process a single interior node when searching
143495** a b-tree for a term or term prefix. The node data is passed to this
143496** function via the zNode/nNode parameters. The term to search for is
143497** passed in zTerm/nTerm.
143498**
143499** If piFirst is not NULL, then this function sets *piFirst to the blockid
143500** of the child node that heads the sub-tree that may contain the term.
143501**
143502** If piLast is not NULL, then *piLast is set to the right-most child node
143503** that heads a sub-tree that may contain a term for which zTerm/nTerm is
143504** a prefix.
143505**
143506** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
143507*/
143508static int fts3ScanInteriorNode(
143509  const char *zTerm,              /* Term to select leaves for */
143510  int nTerm,                      /* Size of term zTerm in bytes */
143511  const char *zNode,              /* Buffer containing segment interior node */
143512  int nNode,                      /* Size of buffer at zNode */
143513  sqlite3_int64 *piFirst,         /* OUT: Selected child node */
143514  sqlite3_int64 *piLast           /* OUT: Selected child node */
143515){
143516  int rc = SQLITE_OK;             /* Return code */
143517  const char *zCsr = zNode;       /* Cursor to iterate through node */
143518  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
143519  char *zBuffer = 0;              /* Buffer to load terms into */
143520  int nAlloc = 0;                 /* Size of allocated buffer */
143521  int isFirstTerm = 1;            /* True when processing first term on page */
143522  sqlite3_int64 iChild;           /* Block id of child node to descend to */
143523
143524  /* Skip over the 'height' varint that occurs at the start of every
143525  ** interior node. Then load the blockid of the left-child of the b-tree
143526  ** node into variable iChild.
143527  **
143528  ** Even if the data structure on disk is corrupted, this (reading two
143529  ** varints from the buffer) does not risk an overread. If zNode is a
143530  ** root node, then the buffer comes from a SELECT statement. SQLite does
143531  ** not make this guarantee explicitly, but in practice there are always
143532  ** either more than 20 bytes of allocated space following the nNode bytes of
143533  ** contents, or two zero bytes. Or, if the node is read from the %_segments
143534  ** table, then there are always 20 bytes of zeroed padding following the
143535  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
143536  */
143537  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
143538  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
143539  if( zCsr>zEnd ){
143540    return FTS_CORRUPT_VTAB;
143541  }
143542
143543  while( zCsr<zEnd && (piFirst || piLast) ){
143544    int cmp;                      /* memcmp() result */
143545    int nSuffix;                  /* Size of term suffix */
143546    int nPrefix = 0;              /* Size of term prefix */
143547    int nBuffer;                  /* Total term size */
143548
143549    /* Load the next term on the node into zBuffer. Use realloc() to expand
143550    ** the size of zBuffer if required.  */
143551    if( !isFirstTerm ){
143552      zCsr += fts3GetVarint32(zCsr, &nPrefix);
143553    }
143554    isFirstTerm = 0;
143555    zCsr += fts3GetVarint32(zCsr, &nSuffix);
143556
143557    if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
143558      rc = FTS_CORRUPT_VTAB;
143559      goto finish_scan;
143560    }
143561    if( nPrefix+nSuffix>nAlloc ){
143562      char *zNew;
143563      nAlloc = (nPrefix+nSuffix) * 2;
143564      zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
143565      if( !zNew ){
143566        rc = SQLITE_NOMEM;
143567        goto finish_scan;
143568      }
143569      zBuffer = zNew;
143570    }
143571    assert( zBuffer );
143572    memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
143573    nBuffer = nPrefix + nSuffix;
143574    zCsr += nSuffix;
143575
143576    /* Compare the term we are searching for with the term just loaded from
143577    ** the interior node. If the specified term is greater than or equal
143578    ** to the term from the interior node, then all terms on the sub-tree
143579    ** headed by node iChild are smaller than zTerm. No need to search
143580    ** iChild.
143581    **
143582    ** If the interior node term is larger than the specified term, then
143583    ** the tree headed by iChild may contain the specified term.
143584    */
143585    cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
143586    if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
143587      *piFirst = iChild;
143588      piFirst = 0;
143589    }
143590
143591    if( piLast && cmp<0 ){
143592      *piLast = iChild;
143593      piLast = 0;
143594    }
143595
143596    iChild++;
143597  };
143598
143599  if( piFirst ) *piFirst = iChild;
143600  if( piLast ) *piLast = iChild;
143601
143602 finish_scan:
143603  sqlite3_free(zBuffer);
143604  return rc;
143605}
143606
143607
143608/*
143609** The buffer pointed to by argument zNode (size nNode bytes) contains an
143610** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
143611** contains a term. This function searches the sub-tree headed by the zNode
143612** node for the range of leaf nodes that may contain the specified term
143613** or terms for which the specified term is a prefix.
143614**
143615** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
143616** left-most leaf node in the tree that may contain the specified term.
143617** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
143618** right-most leaf node that may contain a term for which the specified
143619** term is a prefix.
143620**
143621** It is possible that the range of returned leaf nodes does not contain
143622** the specified term or any terms for which it is a prefix. However, if the
143623** segment does contain any such terms, they are stored within the identified
143624** range. Because this function only inspects interior segment nodes (and
143625** never loads leaf nodes into memory), it is not possible to be sure.
143626**
143627** If an error occurs, an error code other than SQLITE_OK is returned.
143628*/
143629static int fts3SelectLeaf(
143630  Fts3Table *p,                   /* Virtual table handle */
143631  const char *zTerm,              /* Term to select leaves for */
143632  int nTerm,                      /* Size of term zTerm in bytes */
143633  const char *zNode,              /* Buffer containing segment interior node */
143634  int nNode,                      /* Size of buffer at zNode */
143635  sqlite3_int64 *piLeaf,          /* Selected leaf node */
143636  sqlite3_int64 *piLeaf2          /* Selected leaf node */
143637){
143638  int rc = SQLITE_OK;             /* Return code */
143639  int iHeight;                    /* Height of this node in tree */
143640
143641  assert( piLeaf || piLeaf2 );
143642
143643  fts3GetVarint32(zNode, &iHeight);
143644  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
143645  assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
143646
143647  if( rc==SQLITE_OK && iHeight>1 ){
143648    char *zBlob = 0;              /* Blob read from %_segments table */
143649    int nBlob = 0;                /* Size of zBlob in bytes */
143650
143651    if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
143652      rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
143653      if( rc==SQLITE_OK ){
143654        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
143655      }
143656      sqlite3_free(zBlob);
143657      piLeaf = 0;
143658      zBlob = 0;
143659    }
143660
143661    if( rc==SQLITE_OK ){
143662      rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
143663    }
143664    if( rc==SQLITE_OK ){
143665      rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
143666    }
143667    sqlite3_free(zBlob);
143668  }
143669
143670  return rc;
143671}
143672
143673/*
143674** This function is used to create delta-encoded serialized lists of FTS3
143675** varints. Each call to this function appends a single varint to a list.
143676*/
143677static void fts3PutDeltaVarint(
143678  char **pp,                      /* IN/OUT: Output pointer */
143679  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
143680  sqlite3_int64 iVal              /* Write this value to the list */
143681){
143682  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
143683  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
143684  *piPrev = iVal;
143685}
143686
143687/*
143688** When this function is called, *ppPoslist is assumed to point to the
143689** start of a position-list. After it returns, *ppPoslist points to the
143690** first byte after the position-list.
143691**
143692** A position list is list of positions (delta encoded) and columns for
143693** a single document record of a doclist.  So, in other words, this
143694** routine advances *ppPoslist so that it points to the next docid in
143695** the doclist, or to the first byte past the end of the doclist.
143696**
143697** If pp is not NULL, then the contents of the position list are copied
143698** to *pp. *pp is set to point to the first byte past the last byte copied
143699** before this function returns.
143700*/
143701static void fts3PoslistCopy(char **pp, char **ppPoslist){
143702  char *pEnd = *ppPoslist;
143703  char c = 0;
143704
143705  /* The end of a position list is marked by a zero encoded as an FTS3
143706  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
143707  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
143708  ** of some other, multi-byte, value.
143709  **
143710  ** The following while-loop moves pEnd to point to the first byte that is not
143711  ** immediately preceded by a byte with the 0x80 bit set. Then increments
143712  ** pEnd once more so that it points to the byte immediately following the
143713  ** last byte in the position-list.
143714  */
143715  while( *pEnd | c ){
143716    c = *pEnd++ & 0x80;
143717    testcase( c!=0 && (*pEnd)==0 );
143718  }
143719  pEnd++;  /* Advance past the POS_END terminator byte */
143720
143721  if( pp ){
143722    int n = (int)(pEnd - *ppPoslist);
143723    char *p = *pp;
143724    memcpy(p, *ppPoslist, n);
143725    p += n;
143726    *pp = p;
143727  }
143728  *ppPoslist = pEnd;
143729}
143730
143731/*
143732** When this function is called, *ppPoslist is assumed to point to the
143733** start of a column-list. After it returns, *ppPoslist points to the
143734** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
143735**
143736** A column-list is list of delta-encoded positions for a single column
143737** within a single document within a doclist.
143738**
143739** The column-list is terminated either by a POS_COLUMN varint (1) or
143740** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
143741** the POS_COLUMN or POS_END that terminates the column-list.
143742**
143743** If pp is not NULL, then the contents of the column-list are copied
143744** to *pp. *pp is set to point to the first byte past the last byte copied
143745** before this function returns.  The POS_COLUMN or POS_END terminator
143746** is not copied into *pp.
143747*/
143748static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
143749  char *pEnd = *ppPoslist;
143750  char c = 0;
143751
143752  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
143753  ** not part of a multi-byte varint.
143754  */
143755  while( 0xFE & (*pEnd | c) ){
143756    c = *pEnd++ & 0x80;
143757    testcase( c!=0 && ((*pEnd)&0xfe)==0 );
143758  }
143759  if( pp ){
143760    int n = (int)(pEnd - *ppPoslist);
143761    char *p = *pp;
143762    memcpy(p, *ppPoslist, n);
143763    p += n;
143764    *pp = p;
143765  }
143766  *ppPoslist = pEnd;
143767}
143768
143769/*
143770** Value used to signify the end of an position-list. This is safe because
143771** it is not possible to have a document with 2^31 terms.
143772*/
143773#define POSITION_LIST_END 0x7fffffff
143774
143775/*
143776** This function is used to help parse position-lists. When this function is
143777** called, *pp may point to the start of the next varint in the position-list
143778** being parsed, or it may point to 1 byte past the end of the position-list
143779** (in which case **pp will be a terminator bytes POS_END (0) or
143780** (1)).
143781**
143782** If *pp points past the end of the current position-list, set *pi to
143783** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
143784** increment the current value of *pi by the value read, and set *pp to
143785** point to the next value before returning.
143786**
143787** Before calling this routine *pi must be initialized to the value of
143788** the previous position, or zero if we are reading the first position
143789** in the position-list.  Because positions are delta-encoded, the value
143790** of the previous position is needed in order to compute the value of
143791** the next position.
143792*/
143793static void fts3ReadNextPos(
143794  char **pp,                    /* IN/OUT: Pointer into position-list buffer */
143795  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
143796){
143797  if( (**pp)&0xFE ){
143798    fts3GetDeltaVarint(pp, pi);
143799    *pi -= 2;
143800  }else{
143801    *pi = POSITION_LIST_END;
143802  }
143803}
143804
143805/*
143806** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
143807** the value of iCol encoded as a varint to *pp.   This will start a new
143808** column list.
143809**
143810** Set *pp to point to the byte just after the last byte written before
143811** returning (do not modify it if iCol==0). Return the total number of bytes
143812** written (0 if iCol==0).
143813*/
143814static int fts3PutColNumber(char **pp, int iCol){
143815  int n = 0;                      /* Number of bytes written */
143816  if( iCol ){
143817    char *p = *pp;                /* Output pointer */
143818    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
143819    *p = 0x01;
143820    *pp = &p[n];
143821  }
143822  return n;
143823}
143824
143825/*
143826** Compute the union of two position lists.  The output written
143827** into *pp contains all positions of both *pp1 and *pp2 in sorted
143828** order and with any duplicates removed.  All pointers are
143829** updated appropriately.   The caller is responsible for insuring
143830** that there is enough space in *pp to hold the complete output.
143831*/
143832static void fts3PoslistMerge(
143833  char **pp,                      /* Output buffer */
143834  char **pp1,                     /* Left input list */
143835  char **pp2                      /* Right input list */
143836){
143837  char *p = *pp;
143838  char *p1 = *pp1;
143839  char *p2 = *pp2;
143840
143841  while( *p1 || *p2 ){
143842    int iCol1;         /* The current column index in pp1 */
143843    int iCol2;         /* The current column index in pp2 */
143844
143845    if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
143846    else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
143847    else iCol1 = 0;
143848
143849    if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
143850    else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
143851    else iCol2 = 0;
143852
143853    if( iCol1==iCol2 ){
143854      sqlite3_int64 i1 = 0;       /* Last position from pp1 */
143855      sqlite3_int64 i2 = 0;       /* Last position from pp2 */
143856      sqlite3_int64 iPrev = 0;
143857      int n = fts3PutColNumber(&p, iCol1);
143858      p1 += n;
143859      p2 += n;
143860
143861      /* At this point, both p1 and p2 point to the start of column-lists
143862      ** for the same column (the column with index iCol1 and iCol2).
143863      ** A column-list is a list of non-negative delta-encoded varints, each
143864      ** incremented by 2 before being stored. Each list is terminated by a
143865      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
143866      ** and writes the results to buffer p. p is left pointing to the byte
143867      ** after the list written. No terminator (POS_END or POS_COLUMN) is
143868      ** written to the output.
143869      */
143870      fts3GetDeltaVarint(&p1, &i1);
143871      fts3GetDeltaVarint(&p2, &i2);
143872      do {
143873        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
143874        iPrev -= 2;
143875        if( i1==i2 ){
143876          fts3ReadNextPos(&p1, &i1);
143877          fts3ReadNextPos(&p2, &i2);
143878        }else if( i1<i2 ){
143879          fts3ReadNextPos(&p1, &i1);
143880        }else{
143881          fts3ReadNextPos(&p2, &i2);
143882        }
143883      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
143884    }else if( iCol1<iCol2 ){
143885      p1 += fts3PutColNumber(&p, iCol1);
143886      fts3ColumnlistCopy(&p, &p1);
143887    }else{
143888      p2 += fts3PutColNumber(&p, iCol2);
143889      fts3ColumnlistCopy(&p, &p2);
143890    }
143891  }
143892
143893  *p++ = POS_END;
143894  *pp = p;
143895  *pp1 = p1 + 1;
143896  *pp2 = p2 + 1;
143897}
143898
143899/*
143900** This function is used to merge two position lists into one. When it is
143901** called, *pp1 and *pp2 must both point to position lists. A position-list is
143902** the part of a doclist that follows each document id. For example, if a row
143903** contains:
143904**
143905**     'a b c'|'x y z'|'a b b a'
143906**
143907** Then the position list for this row for token 'b' would consist of:
143908**
143909**     0x02 0x01 0x02 0x03 0x03 0x00
143910**
143911** When this function returns, both *pp1 and *pp2 are left pointing to the
143912** byte following the 0x00 terminator of their respective position lists.
143913**
143914** If isSaveLeft is 0, an entry is added to the output position list for
143915** each position in *pp2 for which there exists one or more positions in
143916** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
143917** when the *pp1 token appears before the *pp2 token, but not more than nToken
143918** slots before it.
143919**
143920** e.g. nToken==1 searches for adjacent positions.
143921*/
143922static int fts3PoslistPhraseMerge(
143923  char **pp,                      /* IN/OUT: Preallocated output buffer */
143924  int nToken,                     /* Maximum difference in token positions */
143925  int isSaveLeft,                 /* Save the left position */
143926  int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
143927  char **pp1,                     /* IN/OUT: Left input list */
143928  char **pp2                      /* IN/OUT: Right input list */
143929){
143930  char *p = *pp;
143931  char *p1 = *pp1;
143932  char *p2 = *pp2;
143933  int iCol1 = 0;
143934  int iCol2 = 0;
143935
143936  /* Never set both isSaveLeft and isExact for the same invocation. */
143937  assert( isSaveLeft==0 || isExact==0 );
143938
143939  assert( p!=0 && *p1!=0 && *p2!=0 );
143940  if( *p1==POS_COLUMN ){
143941    p1++;
143942    p1 += fts3GetVarint32(p1, &iCol1);
143943  }
143944  if( *p2==POS_COLUMN ){
143945    p2++;
143946    p2 += fts3GetVarint32(p2, &iCol2);
143947  }
143948
143949  while( 1 ){
143950    if( iCol1==iCol2 ){
143951      char *pSave = p;
143952      sqlite3_int64 iPrev = 0;
143953      sqlite3_int64 iPos1 = 0;
143954      sqlite3_int64 iPos2 = 0;
143955
143956      if( iCol1 ){
143957        *p++ = POS_COLUMN;
143958        p += sqlite3Fts3PutVarint(p, iCol1);
143959      }
143960
143961      assert( *p1!=POS_END && *p1!=POS_COLUMN );
143962      assert( *p2!=POS_END && *p2!=POS_COLUMN );
143963      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
143964      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
143965
143966      while( 1 ){
143967        if( iPos2==iPos1+nToken
143968         || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
143969        ){
143970          sqlite3_int64 iSave;
143971          iSave = isSaveLeft ? iPos1 : iPos2;
143972          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
143973          pSave = 0;
143974          assert( p );
143975        }
143976        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
143977          if( (*p2&0xFE)==0 ) break;
143978          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
143979        }else{
143980          if( (*p1&0xFE)==0 ) break;
143981          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
143982        }
143983      }
143984
143985      if( pSave ){
143986        assert( pp && p );
143987        p = pSave;
143988      }
143989
143990      fts3ColumnlistCopy(0, &p1);
143991      fts3ColumnlistCopy(0, &p2);
143992      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
143993      if( 0==*p1 || 0==*p2 ) break;
143994
143995      p1++;
143996      p1 += fts3GetVarint32(p1, &iCol1);
143997      p2++;
143998      p2 += fts3GetVarint32(p2, &iCol2);
143999    }
144000
144001    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
144002    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
144003    ** end of the position list, or the 0x01 that precedes the next
144004    ** column-number in the position list.
144005    */
144006    else if( iCol1<iCol2 ){
144007      fts3ColumnlistCopy(0, &p1);
144008      if( 0==*p1 ) break;
144009      p1++;
144010      p1 += fts3GetVarint32(p1, &iCol1);
144011    }else{
144012      fts3ColumnlistCopy(0, &p2);
144013      if( 0==*p2 ) break;
144014      p2++;
144015      p2 += fts3GetVarint32(p2, &iCol2);
144016    }
144017  }
144018
144019  fts3PoslistCopy(0, &p2);
144020  fts3PoslistCopy(0, &p1);
144021  *pp1 = p1;
144022  *pp2 = p2;
144023  if( *pp==p ){
144024    return 0;
144025  }
144026  *p++ = 0x00;
144027  *pp = p;
144028  return 1;
144029}
144030
144031/*
144032** Merge two position-lists as required by the NEAR operator. The argument
144033** position lists correspond to the left and right phrases of an expression
144034** like:
144035**
144036**     "phrase 1" NEAR "phrase number 2"
144037**
144038** Position list *pp1 corresponds to the left-hand side of the NEAR
144039** expression and *pp2 to the right. As usual, the indexes in the position
144040** lists are the offsets of the last token in each phrase (tokens "1" and "2"
144041** in the example above).
144042**
144043** The output position list - written to *pp - is a copy of *pp2 with those
144044** entries that are not sufficiently NEAR entries in *pp1 removed.
144045*/
144046static int fts3PoslistNearMerge(
144047  char **pp,                      /* Output buffer */
144048  char *aTmp,                     /* Temporary buffer space */
144049  int nRight,                     /* Maximum difference in token positions */
144050  int nLeft,                      /* Maximum difference in token positions */
144051  char **pp1,                     /* IN/OUT: Left input list */
144052  char **pp2                      /* IN/OUT: Right input list */
144053){
144054  char *p1 = *pp1;
144055  char *p2 = *pp2;
144056
144057  char *pTmp1 = aTmp;
144058  char *pTmp2;
144059  char *aTmp2;
144060  int res = 1;
144061
144062  fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
144063  aTmp2 = pTmp2 = pTmp1;
144064  *pp1 = p1;
144065  *pp2 = p2;
144066  fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
144067  if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
144068    fts3PoslistMerge(pp, &aTmp, &aTmp2);
144069  }else if( pTmp1!=aTmp ){
144070    fts3PoslistCopy(pp, &aTmp);
144071  }else if( pTmp2!=aTmp2 ){
144072    fts3PoslistCopy(pp, &aTmp2);
144073  }else{
144074    res = 0;
144075  }
144076
144077  return res;
144078}
144079
144080/*
144081** An instance of this function is used to merge together the (potentially
144082** large number of) doclists for each term that matches a prefix query.
144083** See function fts3TermSelectMerge() for details.
144084*/
144085typedef struct TermSelect TermSelect;
144086struct TermSelect {
144087  char *aaOutput[16];             /* Malloc'd output buffers */
144088  int anOutput[16];               /* Size each output buffer in bytes */
144089};
144090
144091/*
144092** This function is used to read a single varint from a buffer. Parameter
144093** pEnd points 1 byte past the end of the buffer. When this function is
144094** called, if *pp points to pEnd or greater, then the end of the buffer
144095** has been reached. In this case *pp is set to 0 and the function returns.
144096**
144097** If *pp does not point to or past pEnd, then a single varint is read
144098** from *pp. *pp is then set to point 1 byte past the end of the read varint.
144099**
144100** If bDescIdx is false, the value read is added to *pVal before returning.
144101** If it is true, the value read is subtracted from *pVal before this
144102** function returns.
144103*/
144104static void fts3GetDeltaVarint3(
144105  char **pp,                      /* IN/OUT: Point to read varint from */
144106  char *pEnd,                     /* End of buffer */
144107  int bDescIdx,                   /* True if docids are descending */
144108  sqlite3_int64 *pVal             /* IN/OUT: Integer value */
144109){
144110  if( *pp>=pEnd ){
144111    *pp = 0;
144112  }else{
144113    sqlite3_int64 iVal;
144114    *pp += sqlite3Fts3GetVarint(*pp, &iVal);
144115    if( bDescIdx ){
144116      *pVal -= iVal;
144117    }else{
144118      *pVal += iVal;
144119    }
144120  }
144121}
144122
144123/*
144124** This function is used to write a single varint to a buffer. The varint
144125** is written to *pp. Before returning, *pp is set to point 1 byte past the
144126** end of the value written.
144127**
144128** If *pbFirst is zero when this function is called, the value written to
144129** the buffer is that of parameter iVal.
144130**
144131** If *pbFirst is non-zero when this function is called, then the value
144132** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
144133** (if bDescIdx is non-zero).
144134**
144135** Before returning, this function always sets *pbFirst to 1 and *piPrev
144136** to the value of parameter iVal.
144137*/
144138static void fts3PutDeltaVarint3(
144139  char **pp,                      /* IN/OUT: Output pointer */
144140  int bDescIdx,                   /* True for descending docids */
144141  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
144142  int *pbFirst,                   /* IN/OUT: True after first int written */
144143  sqlite3_int64 iVal              /* Write this value to the list */
144144){
144145  sqlite3_int64 iWrite;
144146  if( bDescIdx==0 || *pbFirst==0 ){
144147    iWrite = iVal - *piPrev;
144148  }else{
144149    iWrite = *piPrev - iVal;
144150  }
144151  assert( *pbFirst || *piPrev==0 );
144152  assert( *pbFirst==0 || iWrite>0 );
144153  *pp += sqlite3Fts3PutVarint(*pp, iWrite);
144154  *piPrev = iVal;
144155  *pbFirst = 1;
144156}
144157
144158
144159/*
144160** This macro is used by various functions that merge doclists. The two
144161** arguments are 64-bit docid values. If the value of the stack variable
144162** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
144163** Otherwise, (i2-i1).
144164**
144165** Using this makes it easier to write code that can merge doclists that are
144166** sorted in either ascending or descending order.
144167*/
144168#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
144169
144170/*
144171** This function does an "OR" merge of two doclists (output contains all
144172** positions contained in either argument doclist). If the docids in the
144173** input doclists are sorted in ascending order, parameter bDescDoclist
144174** should be false. If they are sorted in ascending order, it should be
144175** passed a non-zero value.
144176**
144177** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
144178** containing the output doclist and SQLITE_OK is returned. In this case
144179** *pnOut is set to the number of bytes in the output doclist.
144180**
144181** If an error occurs, an SQLite error code is returned. The output values
144182** are undefined in this case.
144183*/
144184static int fts3DoclistOrMerge(
144185  int bDescDoclist,               /* True if arguments are desc */
144186  char *a1, int n1,               /* First doclist */
144187  char *a2, int n2,               /* Second doclist */
144188  char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
144189){
144190  sqlite3_int64 i1 = 0;
144191  sqlite3_int64 i2 = 0;
144192  sqlite3_int64 iPrev = 0;
144193  char *pEnd1 = &a1[n1];
144194  char *pEnd2 = &a2[n2];
144195  char *p1 = a1;
144196  char *p2 = a2;
144197  char *p;
144198  char *aOut;
144199  int bFirstOut = 0;
144200
144201  *paOut = 0;
144202  *pnOut = 0;
144203
144204  /* Allocate space for the output. Both the input and output doclists
144205  ** are delta encoded. If they are in ascending order (bDescDoclist==0),
144206  ** then the first docid in each list is simply encoded as a varint. For
144207  ** each subsequent docid, the varint stored is the difference between the
144208  ** current and previous docid (a positive number - since the list is in
144209  ** ascending order).
144210  **
144211  ** The first docid written to the output is therefore encoded using the
144212  ** same number of bytes as it is in whichever of the input lists it is
144213  ** read from. And each subsequent docid read from the same input list
144214  ** consumes either the same or less bytes as it did in the input (since
144215  ** the difference between it and the previous value in the output must
144216  ** be a positive value less than or equal to the delta value read from
144217  ** the input list). The same argument applies to all but the first docid
144218  ** read from the 'other' list. And to the contents of all position lists
144219  ** that will be copied and merged from the input to the output.
144220  **
144221  ** However, if the first docid copied to the output is a negative number,
144222  ** then the encoding of the first docid from the 'other' input list may
144223  ** be larger in the output than it was in the input (since the delta value
144224  ** may be a larger positive integer than the actual docid).
144225  **
144226  ** The space required to store the output is therefore the sum of the
144227  ** sizes of the two inputs, plus enough space for exactly one of the input
144228  ** docids to grow.
144229  **
144230  ** A symetric argument may be made if the doclists are in descending
144231  ** order.
144232  */
144233  aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
144234  if( !aOut ) return SQLITE_NOMEM;
144235
144236  p = aOut;
144237  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
144238  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
144239  while( p1 || p2 ){
144240    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
144241
144242    if( p2 && p1 && iDiff==0 ){
144243      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
144244      fts3PoslistMerge(&p, &p1, &p2);
144245      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
144246      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
144247    }else if( !p2 || (p1 && iDiff<0) ){
144248      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
144249      fts3PoslistCopy(&p, &p1);
144250      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
144251    }else{
144252      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
144253      fts3PoslistCopy(&p, &p2);
144254      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
144255    }
144256  }
144257
144258  *paOut = aOut;
144259  *pnOut = (int)(p-aOut);
144260  assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
144261  return SQLITE_OK;
144262}
144263
144264/*
144265** This function does a "phrase" merge of two doclists. In a phrase merge,
144266** the output contains a copy of each position from the right-hand input
144267** doclist for which there is a position in the left-hand input doclist
144268** exactly nDist tokens before it.
144269**
144270** If the docids in the input doclists are sorted in ascending order,
144271** parameter bDescDoclist should be false. If they are sorted in ascending
144272** order, it should be passed a non-zero value.
144273**
144274** The right-hand input doclist is overwritten by this function.
144275*/
144276static int fts3DoclistPhraseMerge(
144277  int bDescDoclist,               /* True if arguments are desc */
144278  int nDist,                      /* Distance from left to right (1=adjacent) */
144279  char *aLeft, int nLeft,         /* Left doclist */
144280  char **paRight, int *pnRight    /* IN/OUT: Right/output doclist */
144281){
144282  sqlite3_int64 i1 = 0;
144283  sqlite3_int64 i2 = 0;
144284  sqlite3_int64 iPrev = 0;
144285  char *aRight = *paRight;
144286  char *pEnd1 = &aLeft[nLeft];
144287  char *pEnd2 = &aRight[*pnRight];
144288  char *p1 = aLeft;
144289  char *p2 = aRight;
144290  char *p;
144291  int bFirstOut = 0;
144292  char *aOut;
144293
144294  assert( nDist>0 );
144295  if( bDescDoclist ){
144296    aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
144297    if( aOut==0 ) return SQLITE_NOMEM;
144298  }else{
144299    aOut = aRight;
144300  }
144301  p = aOut;
144302
144303  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
144304  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
144305
144306  while( p1 && p2 ){
144307    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
144308    if( iDiff==0 ){
144309      char *pSave = p;
144310      sqlite3_int64 iPrevSave = iPrev;
144311      int bFirstOutSave = bFirstOut;
144312
144313      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
144314      if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
144315        p = pSave;
144316        iPrev = iPrevSave;
144317        bFirstOut = bFirstOutSave;
144318      }
144319      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
144320      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
144321    }else if( iDiff<0 ){
144322      fts3PoslistCopy(0, &p1);
144323      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
144324    }else{
144325      fts3PoslistCopy(0, &p2);
144326      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
144327    }
144328  }
144329
144330  *pnRight = (int)(p - aOut);
144331  if( bDescDoclist ){
144332    sqlite3_free(aRight);
144333    *paRight = aOut;
144334  }
144335
144336  return SQLITE_OK;
144337}
144338
144339/*
144340** Argument pList points to a position list nList bytes in size. This
144341** function checks to see if the position list contains any entries for
144342** a token in position 0 (of any column). If so, it writes argument iDelta
144343** to the output buffer pOut, followed by a position list consisting only
144344** of the entries from pList at position 0, and terminated by an 0x00 byte.
144345** The value returned is the number of bytes written to pOut (if any).
144346*/
144347SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
144348  sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
144349  char *pList,                    /* Position list (no 0x00 term) */
144350  int nList,                      /* Size of pList in bytes */
144351  char *pOut                      /* Write output here */
144352){
144353  int nOut = 0;
144354  int bWritten = 0;               /* True once iDelta has been written */
144355  char *p = pList;
144356  char *pEnd = &pList[nList];
144357
144358  if( *p!=0x01 ){
144359    if( *p==0x02 ){
144360      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
144361      pOut[nOut++] = 0x02;
144362      bWritten = 1;
144363    }
144364    fts3ColumnlistCopy(0, &p);
144365  }
144366
144367  while( p<pEnd && *p==0x01 ){
144368    sqlite3_int64 iCol;
144369    p++;
144370    p += sqlite3Fts3GetVarint(p, &iCol);
144371    if( *p==0x02 ){
144372      if( bWritten==0 ){
144373        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
144374        bWritten = 1;
144375      }
144376      pOut[nOut++] = 0x01;
144377      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
144378      pOut[nOut++] = 0x02;
144379    }
144380    fts3ColumnlistCopy(0, &p);
144381  }
144382  if( bWritten ){
144383    pOut[nOut++] = 0x00;
144384  }
144385
144386  return nOut;
144387}
144388
144389
144390/*
144391** Merge all doclists in the TermSelect.aaOutput[] array into a single
144392** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
144393** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
144394**
144395** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
144396** the responsibility of the caller to free any doclists left in the
144397** TermSelect.aaOutput[] array.
144398*/
144399static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
144400  char *aOut = 0;
144401  int nOut = 0;
144402  int i;
144403
144404  /* Loop through the doclists in the aaOutput[] array. Merge them all
144405  ** into a single doclist.
144406  */
144407  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
144408    if( pTS->aaOutput[i] ){
144409      if( !aOut ){
144410        aOut = pTS->aaOutput[i];
144411        nOut = pTS->anOutput[i];
144412        pTS->aaOutput[i] = 0;
144413      }else{
144414        int nNew;
144415        char *aNew;
144416
144417        int rc = fts3DoclistOrMerge(p->bDescIdx,
144418            pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
144419        );
144420        if( rc!=SQLITE_OK ){
144421          sqlite3_free(aOut);
144422          return rc;
144423        }
144424
144425        sqlite3_free(pTS->aaOutput[i]);
144426        sqlite3_free(aOut);
144427        pTS->aaOutput[i] = 0;
144428        aOut = aNew;
144429        nOut = nNew;
144430      }
144431    }
144432  }
144433
144434  pTS->aaOutput[0] = aOut;
144435  pTS->anOutput[0] = nOut;
144436  return SQLITE_OK;
144437}
144438
144439/*
144440** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
144441** as the first argument. The merge is an "OR" merge (see function
144442** fts3DoclistOrMerge() for details).
144443**
144444** This function is called with the doclist for each term that matches
144445** a queried prefix. It merges all these doclists into one, the doclist
144446** for the specified prefix. Since there can be a very large number of
144447** doclists to merge, the merging is done pair-wise using the TermSelect
144448** object.
144449**
144450** This function returns SQLITE_OK if the merge is successful, or an
144451** SQLite error code (SQLITE_NOMEM) if an error occurs.
144452*/
144453static int fts3TermSelectMerge(
144454  Fts3Table *p,                   /* FTS table handle */
144455  TermSelect *pTS,                /* TermSelect object to merge into */
144456  char *aDoclist,                 /* Pointer to doclist */
144457  int nDoclist                    /* Size of aDoclist in bytes */
144458){
144459  if( pTS->aaOutput[0]==0 ){
144460    /* If this is the first term selected, copy the doclist to the output
144461    ** buffer using memcpy().
144462    **
144463    ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
144464    ** allocation. This is so as to ensure that the buffer is big enough
144465    ** to hold the current doclist AND'd with any other doclist. If the
144466    ** doclists are stored in order=ASC order, this padding would not be
144467    ** required (since the size of [doclistA AND doclistB] is always less
144468    ** than or equal to the size of [doclistA] in that case). But this is
144469    ** not true for order=DESC. For example, a doclist containing (1, -1)
144470    ** may be smaller than (-1), as in the first example the -1 may be stored
144471    ** as a single-byte delta, whereas in the second it must be stored as a
144472    ** FTS3_VARINT_MAX byte varint.
144473    **
144474    ** Similar padding is added in the fts3DoclistOrMerge() function.
144475    */
144476    pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
144477    pTS->anOutput[0] = nDoclist;
144478    if( pTS->aaOutput[0] ){
144479      memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
144480    }else{
144481      return SQLITE_NOMEM;
144482    }
144483  }else{
144484    char *aMerge = aDoclist;
144485    int nMerge = nDoclist;
144486    int iOut;
144487
144488    for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
144489      if( pTS->aaOutput[iOut]==0 ){
144490        assert( iOut>0 );
144491        pTS->aaOutput[iOut] = aMerge;
144492        pTS->anOutput[iOut] = nMerge;
144493        break;
144494      }else{
144495        char *aNew;
144496        int nNew;
144497
144498        int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
144499            pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
144500        );
144501        if( rc!=SQLITE_OK ){
144502          if( aMerge!=aDoclist ) sqlite3_free(aMerge);
144503          return rc;
144504        }
144505
144506        if( aMerge!=aDoclist ) sqlite3_free(aMerge);
144507        sqlite3_free(pTS->aaOutput[iOut]);
144508        pTS->aaOutput[iOut] = 0;
144509
144510        aMerge = aNew;
144511        nMerge = nNew;
144512        if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
144513          pTS->aaOutput[iOut] = aMerge;
144514          pTS->anOutput[iOut] = nMerge;
144515        }
144516      }
144517    }
144518  }
144519  return SQLITE_OK;
144520}
144521
144522/*
144523** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
144524*/
144525static int fts3SegReaderCursorAppend(
144526  Fts3MultiSegReader *pCsr,
144527  Fts3SegReader *pNew
144528){
144529  if( (pCsr->nSegment%16)==0 ){
144530    Fts3SegReader **apNew;
144531    int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
144532    apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
144533    if( !apNew ){
144534      sqlite3Fts3SegReaderFree(pNew);
144535      return SQLITE_NOMEM;
144536    }
144537    pCsr->apSegment = apNew;
144538  }
144539  pCsr->apSegment[pCsr->nSegment++] = pNew;
144540  return SQLITE_OK;
144541}
144542
144543/*
144544** Add seg-reader objects to the Fts3MultiSegReader object passed as the
144545** 8th argument.
144546**
144547** This function returns SQLITE_OK if successful, or an SQLite error code
144548** otherwise.
144549*/
144550static int fts3SegReaderCursor(
144551  Fts3Table *p,                   /* FTS3 table handle */
144552  int iLangid,                    /* Language id */
144553  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
144554  int iLevel,                     /* Level of segments to scan */
144555  const char *zTerm,              /* Term to query for */
144556  int nTerm,                      /* Size of zTerm in bytes */
144557  int isPrefix,                   /* True for a prefix search */
144558  int isScan,                     /* True to scan from zTerm to EOF */
144559  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
144560){
144561  int rc = SQLITE_OK;             /* Error code */
144562  sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
144563  int rc2;                        /* Result of sqlite3_reset() */
144564
144565  /* If iLevel is less than 0 and this is not a scan, include a seg-reader
144566  ** for the pending-terms. If this is a scan, then this call must be being
144567  ** made by an fts4aux module, not an FTS table. In this case calling
144568  ** Fts3SegReaderPending might segfault, as the data structures used by
144569  ** fts4aux are not completely populated. So it's easiest to filter these
144570  ** calls out here.  */
144571  if( iLevel<0 && p->aIndex ){
144572    Fts3SegReader *pSeg = 0;
144573    rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
144574    if( rc==SQLITE_OK && pSeg ){
144575      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
144576    }
144577  }
144578
144579  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
144580    if( rc==SQLITE_OK ){
144581      rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
144582    }
144583
144584    while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
144585      Fts3SegReader *pSeg = 0;
144586
144587      /* Read the values returned by the SELECT into local variables. */
144588      sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
144589      sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
144590      sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
144591      int nRoot = sqlite3_column_bytes(pStmt, 4);
144592      char const *zRoot = sqlite3_column_blob(pStmt, 4);
144593
144594      /* If zTerm is not NULL, and this segment is not stored entirely on its
144595      ** root node, the range of leaves scanned can be reduced. Do this. */
144596      if( iStartBlock && zTerm ){
144597        sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
144598        rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
144599        if( rc!=SQLITE_OK ) goto finished;
144600        if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
144601      }
144602
144603      rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
144604          (isPrefix==0 && isScan==0),
144605          iStartBlock, iLeavesEndBlock,
144606          iEndBlock, zRoot, nRoot, &pSeg
144607      );
144608      if( rc!=SQLITE_OK ) goto finished;
144609      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
144610    }
144611  }
144612
144613 finished:
144614  rc2 = sqlite3_reset(pStmt);
144615  if( rc==SQLITE_DONE ) rc = rc2;
144616
144617  return rc;
144618}
144619
144620/*
144621** Set up a cursor object for iterating through a full-text index or a
144622** single level therein.
144623*/
144624SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
144625  Fts3Table *p,                   /* FTS3 table handle */
144626  int iLangid,                    /* Language-id to search */
144627  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
144628  int iLevel,                     /* Level of segments to scan */
144629  const char *zTerm,              /* Term to query for */
144630  int nTerm,                      /* Size of zTerm in bytes */
144631  int isPrefix,                   /* True for a prefix search */
144632  int isScan,                     /* True to scan from zTerm to EOF */
144633  Fts3MultiSegReader *pCsr       /* Cursor object to populate */
144634){
144635  assert( iIndex>=0 && iIndex<p->nIndex );
144636  assert( iLevel==FTS3_SEGCURSOR_ALL
144637      ||  iLevel==FTS3_SEGCURSOR_PENDING
144638      ||  iLevel>=0
144639  );
144640  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
144641  assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
144642  assert( isPrefix==0 || isScan==0 );
144643
144644  memset(pCsr, 0, sizeof(Fts3MultiSegReader));
144645  return fts3SegReaderCursor(
144646      p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
144647  );
144648}
144649
144650/*
144651** In addition to its current configuration, have the Fts3MultiSegReader
144652** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
144653**
144654** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
144655*/
144656static int fts3SegReaderCursorAddZero(
144657  Fts3Table *p,                   /* FTS virtual table handle */
144658  int iLangid,
144659  const char *zTerm,              /* Term to scan doclist of */
144660  int nTerm,                      /* Number of bytes in zTerm */
144661  Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
144662){
144663  return fts3SegReaderCursor(p,
144664      iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
144665  );
144666}
144667
144668/*
144669** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
144670** if isPrefix is true, to scan the doclist for all terms for which
144671** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
144672** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
144673** an SQLite error code.
144674**
144675** It is the responsibility of the caller to free this object by eventually
144676** passing it to fts3SegReaderCursorFree()
144677**
144678** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
144679** Output parameter *ppSegcsr is set to 0 if an error occurs.
144680*/
144681static int fts3TermSegReaderCursor(
144682  Fts3Cursor *pCsr,               /* Virtual table cursor handle */
144683  const char *zTerm,              /* Term to query for */
144684  int nTerm,                      /* Size of zTerm in bytes */
144685  int isPrefix,                   /* True for a prefix search */
144686  Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
144687){
144688  Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
144689  int rc = SQLITE_NOMEM;          /* Return code */
144690
144691  pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
144692  if( pSegcsr ){
144693    int i;
144694    int bFound = 0;               /* True once an index has been found */
144695    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
144696
144697    if( isPrefix ){
144698      for(i=1; bFound==0 && i<p->nIndex; i++){
144699        if( p->aIndex[i].nPrefix==nTerm ){
144700          bFound = 1;
144701          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
144702              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
144703          );
144704          pSegcsr->bLookup = 1;
144705        }
144706      }
144707
144708      for(i=1; bFound==0 && i<p->nIndex; i++){
144709        if( p->aIndex[i].nPrefix==nTerm+1 ){
144710          bFound = 1;
144711          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
144712              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
144713          );
144714          if( rc==SQLITE_OK ){
144715            rc = fts3SegReaderCursorAddZero(
144716                p, pCsr->iLangid, zTerm, nTerm, pSegcsr
144717            );
144718          }
144719        }
144720      }
144721    }
144722
144723    if( bFound==0 ){
144724      rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
144725          0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
144726      );
144727      pSegcsr->bLookup = !isPrefix;
144728    }
144729  }
144730
144731  *ppSegcsr = pSegcsr;
144732  return rc;
144733}
144734
144735/*
144736** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
144737*/
144738static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
144739  sqlite3Fts3SegReaderFinish(pSegcsr);
144740  sqlite3_free(pSegcsr);
144741}
144742
144743/*
144744** This function retrieves the doclist for the specified term (or term
144745** prefix) from the database.
144746*/
144747static int fts3TermSelect(
144748  Fts3Table *p,                   /* Virtual table handle */
144749  Fts3PhraseToken *pTok,          /* Token to query for */
144750  int iColumn,                    /* Column to query (or -ve for all columns) */
144751  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
144752  char **ppOut                    /* OUT: Malloced result buffer */
144753){
144754  int rc;                         /* Return code */
144755  Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
144756  TermSelect tsc;                 /* Object for pair-wise doclist merging */
144757  Fts3SegFilter filter;           /* Segment term filter configuration */
144758
144759  pSegcsr = pTok->pSegcsr;
144760  memset(&tsc, 0, sizeof(TermSelect));
144761
144762  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
144763        | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
144764        | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
144765        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
144766  filter.iCol = iColumn;
144767  filter.zTerm = pTok->z;
144768  filter.nTerm = pTok->n;
144769
144770  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
144771  while( SQLITE_OK==rc
144772      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
144773  ){
144774    rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
144775  }
144776
144777  if( rc==SQLITE_OK ){
144778    rc = fts3TermSelectFinishMerge(p, &tsc);
144779  }
144780  if( rc==SQLITE_OK ){
144781    *ppOut = tsc.aaOutput[0];
144782    *pnOut = tsc.anOutput[0];
144783  }else{
144784    int i;
144785    for(i=0; i<SizeofArray(tsc.aaOutput); i++){
144786      sqlite3_free(tsc.aaOutput[i]);
144787    }
144788  }
144789
144790  fts3SegReaderCursorFree(pSegcsr);
144791  pTok->pSegcsr = 0;
144792  return rc;
144793}
144794
144795/*
144796** This function counts the total number of docids in the doclist stored
144797** in buffer aList[], size nList bytes.
144798**
144799** If the isPoslist argument is true, then it is assumed that the doclist
144800** contains a position-list following each docid. Otherwise, it is assumed
144801** that the doclist is simply a list of docids stored as delta encoded
144802** varints.
144803*/
144804static int fts3DoclistCountDocids(char *aList, int nList){
144805  int nDoc = 0;                   /* Return value */
144806  if( aList ){
144807    char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
144808    char *p = aList;              /* Cursor */
144809    while( p<aEnd ){
144810      nDoc++;
144811      while( (*p++)&0x80 );     /* Skip docid varint */
144812      fts3PoslistCopy(0, &p);   /* Skip over position list */
144813    }
144814  }
144815
144816  return nDoc;
144817}
144818
144819/*
144820** Advance the cursor to the next row in the %_content table that
144821** matches the search criteria.  For a MATCH search, this will be
144822** the next row that matches. For a full-table scan, this will be
144823** simply the next row in the %_content table.  For a docid lookup,
144824** this routine simply sets the EOF flag.
144825**
144826** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
144827** even if we reach end-of-file.  The fts3EofMethod() will be called
144828** subsequently to determine whether or not an EOF was hit.
144829*/
144830static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
144831  int rc;
144832  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
144833  if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
144834    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
144835      pCsr->isEof = 1;
144836      rc = sqlite3_reset(pCsr->pStmt);
144837    }else{
144838      pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
144839      rc = SQLITE_OK;
144840    }
144841  }else{
144842    rc = fts3EvalNext((Fts3Cursor *)pCursor);
144843  }
144844  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
144845  return rc;
144846}
144847
144848/*
144849** The following are copied from sqliteInt.h.
144850**
144851** Constants for the largest and smallest possible 64-bit signed integers.
144852** These macros are designed to work correctly on both 32-bit and 64-bit
144853** compilers.
144854*/
144855#ifndef SQLITE_AMALGAMATION
144856# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
144857# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
144858#endif
144859
144860/*
144861** If the numeric type of argument pVal is "integer", then return it
144862** converted to a 64-bit signed integer. Otherwise, return a copy of
144863** the second parameter, iDefault.
144864*/
144865static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
144866  if( pVal ){
144867    int eType = sqlite3_value_numeric_type(pVal);
144868    if( eType==SQLITE_INTEGER ){
144869      return sqlite3_value_int64(pVal);
144870    }
144871  }
144872  return iDefault;
144873}
144874
144875/*
144876** This is the xFilter interface for the virtual table.  See
144877** the virtual table xFilter method documentation for additional
144878** information.
144879**
144880** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
144881** the %_content table.
144882**
144883** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
144884** in the %_content table.
144885**
144886** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
144887** column on the left-hand side of the MATCH operator is column
144888** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
144889** side of the MATCH operator.
144890*/
144891static int fts3FilterMethod(
144892  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
144893  int idxNum,                     /* Strategy index */
144894  const char *idxStr,             /* Unused */
144895  int nVal,                       /* Number of elements in apVal */
144896  sqlite3_value **apVal           /* Arguments for the indexing scheme */
144897){
144898  int rc = SQLITE_OK;
144899  char *zSql;                     /* SQL statement used to access %_content */
144900  int eSearch;
144901  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
144902  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
144903
144904  sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
144905  sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
144906  sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
144907  sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
144908  int iIdx;
144909
144910  UNUSED_PARAMETER(idxStr);
144911  UNUSED_PARAMETER(nVal);
144912
144913  eSearch = (idxNum & 0x0000FFFF);
144914  assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
144915  assert( p->pSegments==0 );
144916
144917  /* Collect arguments into local variables */
144918  iIdx = 0;
144919  if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
144920  if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
144921  if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
144922  if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
144923  assert( iIdx==nVal );
144924
144925  /* In case the cursor has been used before, clear it now. */
144926  sqlite3_finalize(pCsr->pStmt);
144927  sqlite3_free(pCsr->aDoclist);
144928  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
144929  sqlite3Fts3ExprFree(pCsr->pExpr);
144930  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
144931
144932  /* Set the lower and upper bounds on docids to return */
144933  pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
144934  pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
144935
144936  if( idxStr ){
144937    pCsr->bDesc = (idxStr[0]=='D');
144938  }else{
144939    pCsr->bDesc = p->bDescIdx;
144940  }
144941  pCsr->eSearch = (i16)eSearch;
144942
144943  if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
144944    int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
144945    const char *zQuery = (const char *)sqlite3_value_text(pCons);
144946
144947    if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
144948      return SQLITE_NOMEM;
144949    }
144950
144951    pCsr->iLangid = 0;
144952    if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
144953
144954    assert( p->base.zErrMsg==0 );
144955    rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
144956        p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
144957        &p->base.zErrMsg
144958    );
144959    if( rc!=SQLITE_OK ){
144960      return rc;
144961    }
144962
144963    rc = fts3EvalStart(pCsr);
144964    sqlite3Fts3SegmentsClose(p);
144965    if( rc!=SQLITE_OK ) return rc;
144966    pCsr->pNextId = pCsr->aDoclist;
144967    pCsr->iPrevId = 0;
144968  }
144969
144970  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
144971  ** statement loops through all rows of the %_content table. For a
144972  ** full-text query or docid lookup, the statement retrieves a single
144973  ** row by docid.
144974  */
144975  if( eSearch==FTS3_FULLSCAN_SEARCH ){
144976    if( pDocidGe || pDocidLe ){
144977      zSql = sqlite3_mprintf(
144978          "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
144979          p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
144980          (pCsr->bDesc ? "DESC" : "ASC")
144981      );
144982    }else{
144983      zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
144984          p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
144985      );
144986    }
144987    if( zSql ){
144988      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
144989      sqlite3_free(zSql);
144990    }else{
144991      rc = SQLITE_NOMEM;
144992    }
144993  }else if( eSearch==FTS3_DOCID_SEARCH ){
144994    rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
144995    if( rc==SQLITE_OK ){
144996      rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
144997    }
144998  }
144999  if( rc!=SQLITE_OK ) return rc;
145000
145001  return fts3NextMethod(pCursor);
145002}
145003
145004/*
145005** This is the xEof method of the virtual table. SQLite calls this
145006** routine to find out if it has reached the end of a result set.
145007*/
145008static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
145009  return ((Fts3Cursor *)pCursor)->isEof;
145010}
145011
145012/*
145013** This is the xRowid method. The SQLite core calls this routine to
145014** retrieve the rowid for the current row of the result set. fts3
145015** exposes %_content.docid as the rowid for the virtual table. The
145016** rowid should be written to *pRowid.
145017*/
145018static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
145019  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
145020  *pRowid = pCsr->iPrevId;
145021  return SQLITE_OK;
145022}
145023
145024/*
145025** This is the xColumn method, called by SQLite to request a value from
145026** the row that the supplied cursor currently points to.
145027**
145028** If:
145029**
145030**   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
145031**   (iCol == p->nColumn)   -> Magic column with the same name as the table.
145032**   (iCol == p->nColumn+1) -> Docid column
145033**   (iCol == p->nColumn+2) -> Langid column
145034*/
145035static int fts3ColumnMethod(
145036  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
145037  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
145038  int iCol                        /* Index of column to read value from */
145039){
145040  int rc = SQLITE_OK;             /* Return Code */
145041  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
145042  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
145043
145044  /* The column value supplied by SQLite must be in range. */
145045  assert( iCol>=0 && iCol<=p->nColumn+2 );
145046
145047  if( iCol==p->nColumn+1 ){
145048    /* This call is a request for the "docid" column. Since "docid" is an
145049    ** alias for "rowid", use the xRowid() method to obtain the value.
145050    */
145051    sqlite3_result_int64(pCtx, pCsr->iPrevId);
145052  }else if( iCol==p->nColumn ){
145053    /* The extra column whose name is the same as the table.
145054    ** Return a blob which is a pointer to the cursor.  */
145055    sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
145056  }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
145057    sqlite3_result_int64(pCtx, pCsr->iLangid);
145058  }else{
145059    /* The requested column is either a user column (one that contains
145060    ** indexed data), or the language-id column.  */
145061    rc = fts3CursorSeek(0, pCsr);
145062
145063    if( rc==SQLITE_OK ){
145064      if( iCol==p->nColumn+2 ){
145065        int iLangid = 0;
145066        if( p->zLanguageid ){
145067          iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
145068        }
145069        sqlite3_result_int(pCtx, iLangid);
145070      }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
145071        sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
145072      }
145073    }
145074  }
145075
145076  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
145077  return rc;
145078}
145079
145080/*
145081** This function is the implementation of the xUpdate callback used by
145082** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
145083** inserted, updated or deleted.
145084*/
145085static int fts3UpdateMethod(
145086  sqlite3_vtab *pVtab,            /* Virtual table handle */
145087  int nArg,                       /* Size of argument array */
145088  sqlite3_value **apVal,          /* Array of arguments */
145089  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
145090){
145091  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
145092}
145093
145094/*
145095** Implementation of xSync() method. Flush the contents of the pending-terms
145096** hash-table to the database.
145097*/
145098static int fts3SyncMethod(sqlite3_vtab *pVtab){
145099
145100  /* Following an incremental-merge operation, assuming that the input
145101  ** segments are not completely consumed (the usual case), they are updated
145102  ** in place to remove the entries that have already been merged. This
145103  ** involves updating the leaf block that contains the smallest unmerged
145104  ** entry and each block (if any) between the leaf and the root node. So
145105  ** if the height of the input segment b-trees is N, and input segments
145106  ** are merged eight at a time, updating the input segments at the end
145107  ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
145108  ** small - often between 0 and 2. So the overhead of the incremental
145109  ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
145110  ** dwarfing the actual productive work accomplished, the incremental merge
145111  ** is only attempted if it will write at least 64 leaf blocks. Hence
145112  ** nMinMerge.
145113  **
145114  ** Of course, updating the input segments also involves deleting a bunch
145115  ** of blocks from the segments table. But this is not considered overhead
145116  ** as it would also be required by a crisis-merge that used the same input
145117  ** segments.
145118  */
145119  const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
145120
145121  Fts3Table *p = (Fts3Table*)pVtab;
145122  int rc = sqlite3Fts3PendingTermsFlush(p);
145123
145124  if( rc==SQLITE_OK
145125   && p->nLeafAdd>(nMinMerge/16)
145126   && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
145127  ){
145128    int mxLevel = 0;              /* Maximum relative level value in db */
145129    int A;                        /* Incr-merge parameter A */
145130
145131    rc = sqlite3Fts3MaxLevel(p, &mxLevel);
145132    assert( rc==SQLITE_OK || mxLevel==0 );
145133    A = p->nLeafAdd * mxLevel;
145134    A += (A/2);
145135    if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
145136  }
145137  sqlite3Fts3SegmentsClose(p);
145138  return rc;
145139}
145140
145141/*
145142** If it is currently unknown whether or not the FTS table has an %_stat
145143** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
145144** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
145145** if an error occurs.
145146*/
145147static int fts3SetHasStat(Fts3Table *p){
145148  int rc = SQLITE_OK;
145149  if( p->bHasStat==2 ){
145150    const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
145151    char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
145152    if( zSql ){
145153      sqlite3_stmt *pStmt = 0;
145154      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
145155      if( rc==SQLITE_OK ){
145156        int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
145157        rc = sqlite3_finalize(pStmt);
145158        if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
145159      }
145160      sqlite3_free(zSql);
145161    }else{
145162      rc = SQLITE_NOMEM;
145163    }
145164  }
145165  return rc;
145166}
145167
145168/*
145169** Implementation of xBegin() method.
145170*/
145171static int fts3BeginMethod(sqlite3_vtab *pVtab){
145172  Fts3Table *p = (Fts3Table*)pVtab;
145173  UNUSED_PARAMETER(pVtab);
145174  assert( p->pSegments==0 );
145175  assert( p->nPendingData==0 );
145176  assert( p->inTransaction!=1 );
145177  TESTONLY( p->inTransaction = 1 );
145178  TESTONLY( p->mxSavepoint = -1; );
145179  p->nLeafAdd = 0;
145180  return fts3SetHasStat(p);
145181}
145182
145183/*
145184** Implementation of xCommit() method. This is a no-op. The contents of
145185** the pending-terms hash-table have already been flushed into the database
145186** by fts3SyncMethod().
145187*/
145188static int fts3CommitMethod(sqlite3_vtab *pVtab){
145189  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
145190  UNUSED_PARAMETER(pVtab);
145191  assert( p->nPendingData==0 );
145192  assert( p->inTransaction!=0 );
145193  assert( p->pSegments==0 );
145194  TESTONLY( p->inTransaction = 0 );
145195  TESTONLY( p->mxSavepoint = -1; );
145196  return SQLITE_OK;
145197}
145198
145199/*
145200** Implementation of xRollback(). Discard the contents of the pending-terms
145201** hash-table. Any changes made to the database are reverted by SQLite.
145202*/
145203static int fts3RollbackMethod(sqlite3_vtab *pVtab){
145204  Fts3Table *p = (Fts3Table*)pVtab;
145205  sqlite3Fts3PendingTermsClear(p);
145206  assert( p->inTransaction!=0 );
145207  TESTONLY( p->inTransaction = 0 );
145208  TESTONLY( p->mxSavepoint = -1; );
145209  return SQLITE_OK;
145210}
145211
145212/*
145213** When called, *ppPoslist must point to the byte immediately following the
145214** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
145215** moves *ppPoslist so that it instead points to the first byte of the
145216** same position list.
145217*/
145218static void fts3ReversePoslist(char *pStart, char **ppPoslist){
145219  char *p = &(*ppPoslist)[-2];
145220  char c = 0;
145221
145222  /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
145223  while( p>pStart && (c=*p--)==0 );
145224
145225  /* Search backwards for a varint with value zero (the end of the previous
145226  ** poslist). This is an 0x00 byte preceded by some byte that does not
145227  ** have the 0x80 bit set.  */
145228  while( p>pStart && (*p & 0x80) | c ){
145229    c = *p--;
145230  }
145231  assert( p==pStart || c==0 );
145232
145233  /* At this point p points to that preceding byte without the 0x80 bit
145234  ** set. So to find the start of the poslist, skip forward 2 bytes then
145235  ** over a varint.
145236  **
145237  ** Normally. The other case is that p==pStart and the poslist to return
145238  ** is the first in the doclist. In this case do not skip forward 2 bytes.
145239  ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
145240  ** is required for cases where the first byte of a doclist and the
145241  ** doclist is empty. For example, if the first docid is 10, a doclist
145242  ** that begins with:
145243  **
145244  **   0x0A 0x00 <next docid delta varint>
145245  */
145246  if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
145247  while( *p++&0x80 );
145248  *ppPoslist = p;
145249}
145250
145251/*
145252** Helper function used by the implementation of the overloaded snippet(),
145253** offsets() and optimize() SQL functions.
145254**
145255** If the value passed as the third argument is a blob of size
145256** sizeof(Fts3Cursor*), then the blob contents are copied to the
145257** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
145258** message is written to context pContext and SQLITE_ERROR returned. The
145259** string passed via zFunc is used as part of the error message.
145260*/
145261static int fts3FunctionArg(
145262  sqlite3_context *pContext,      /* SQL function call context */
145263  const char *zFunc,              /* Function name */
145264  sqlite3_value *pVal,            /* argv[0] passed to function */
145265  Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
145266){
145267  Fts3Cursor *pRet;
145268  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
145269   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
145270  ){
145271    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
145272    sqlite3_result_error(pContext, zErr, -1);
145273    sqlite3_free(zErr);
145274    return SQLITE_ERROR;
145275  }
145276  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
145277  *ppCsr = pRet;
145278  return SQLITE_OK;
145279}
145280
145281/*
145282** Implementation of the snippet() function for FTS3
145283*/
145284static void fts3SnippetFunc(
145285  sqlite3_context *pContext,      /* SQLite function call context */
145286  int nVal,                       /* Size of apVal[] array */
145287  sqlite3_value **apVal           /* Array of arguments */
145288){
145289  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
145290  const char *zStart = "<b>";
145291  const char *zEnd = "</b>";
145292  const char *zEllipsis = "<b>...</b>";
145293  int iCol = -1;
145294  int nToken = 15;                /* Default number of tokens in snippet */
145295
145296  /* There must be at least one argument passed to this function (otherwise
145297  ** the non-overloaded version would have been called instead of this one).
145298  */
145299  assert( nVal>=1 );
145300
145301  if( nVal>6 ){
145302    sqlite3_result_error(pContext,
145303        "wrong number of arguments to function snippet()", -1);
145304    return;
145305  }
145306  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
145307
145308  switch( nVal ){
145309    case 6: nToken = sqlite3_value_int(apVal[5]);
145310    case 5: iCol = sqlite3_value_int(apVal[4]);
145311    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
145312    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
145313    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
145314  }
145315  if( !zEllipsis || !zEnd || !zStart ){
145316    sqlite3_result_error_nomem(pContext);
145317  }else if( nToken==0 ){
145318    sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
145319  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
145320    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
145321  }
145322}
145323
145324/*
145325** Implementation of the offsets() function for FTS3
145326*/
145327static void fts3OffsetsFunc(
145328  sqlite3_context *pContext,      /* SQLite function call context */
145329  int nVal,                       /* Size of argument array */
145330  sqlite3_value **apVal           /* Array of arguments */
145331){
145332  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
145333
145334  UNUSED_PARAMETER(nVal);
145335
145336  assert( nVal==1 );
145337  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
145338  assert( pCsr );
145339  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
145340    sqlite3Fts3Offsets(pContext, pCsr);
145341  }
145342}
145343
145344/*
145345** Implementation of the special optimize() function for FTS3. This
145346** function merges all segments in the database to a single segment.
145347** Example usage is:
145348**
145349**   SELECT optimize(t) FROM t LIMIT 1;
145350**
145351** where 't' is the name of an FTS3 table.
145352*/
145353static void fts3OptimizeFunc(
145354  sqlite3_context *pContext,      /* SQLite function call context */
145355  int nVal,                       /* Size of argument array */
145356  sqlite3_value **apVal           /* Array of arguments */
145357){
145358  int rc;                         /* Return code */
145359  Fts3Table *p;                   /* Virtual table handle */
145360  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
145361
145362  UNUSED_PARAMETER(nVal);
145363
145364  assert( nVal==1 );
145365  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
145366  p = (Fts3Table *)pCursor->base.pVtab;
145367  assert( p );
145368
145369  rc = sqlite3Fts3Optimize(p);
145370
145371  switch( rc ){
145372    case SQLITE_OK:
145373      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
145374      break;
145375    case SQLITE_DONE:
145376      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
145377      break;
145378    default:
145379      sqlite3_result_error_code(pContext, rc);
145380      break;
145381  }
145382}
145383
145384/*
145385** Implementation of the matchinfo() function for FTS3
145386*/
145387static void fts3MatchinfoFunc(
145388  sqlite3_context *pContext,      /* SQLite function call context */
145389  int nVal,                       /* Size of argument array */
145390  sqlite3_value **apVal           /* Array of arguments */
145391){
145392  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
145393  assert( nVal==1 || nVal==2 );
145394  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
145395    const char *zArg = 0;
145396    if( nVal>1 ){
145397      zArg = (const char *)sqlite3_value_text(apVal[1]);
145398    }
145399    sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
145400  }
145401}
145402
145403/*
145404** This routine implements the xFindFunction method for the FTS3
145405** virtual table.
145406*/
145407static int fts3FindFunctionMethod(
145408  sqlite3_vtab *pVtab,            /* Virtual table handle */
145409  int nArg,                       /* Number of SQL function arguments */
145410  const char *zName,              /* Name of SQL function */
145411  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
145412  void **ppArg                    /* Unused */
145413){
145414  struct Overloaded {
145415    const char *zName;
145416    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
145417  } aOverload[] = {
145418    { "snippet", fts3SnippetFunc },
145419    { "offsets", fts3OffsetsFunc },
145420    { "optimize", fts3OptimizeFunc },
145421    { "matchinfo", fts3MatchinfoFunc },
145422  };
145423  int i;                          /* Iterator variable */
145424
145425  UNUSED_PARAMETER(pVtab);
145426  UNUSED_PARAMETER(nArg);
145427  UNUSED_PARAMETER(ppArg);
145428
145429  for(i=0; i<SizeofArray(aOverload); i++){
145430    if( strcmp(zName, aOverload[i].zName)==0 ){
145431      *pxFunc = aOverload[i].xFunc;
145432      return 1;
145433    }
145434  }
145435
145436  /* No function of the specified name was found. Return 0. */
145437  return 0;
145438}
145439
145440/*
145441** Implementation of FTS3 xRename method. Rename an fts3 table.
145442*/
145443static int fts3RenameMethod(
145444  sqlite3_vtab *pVtab,            /* Virtual table handle */
145445  const char *zName               /* New name of table */
145446){
145447  Fts3Table *p = (Fts3Table *)pVtab;
145448  sqlite3 *db = p->db;            /* Database connection */
145449  int rc;                         /* Return Code */
145450
145451  /* At this point it must be known if the %_stat table exists or not.
145452  ** So bHasStat may not be 2.  */
145453  rc = fts3SetHasStat(p);
145454
145455  /* As it happens, the pending terms table is always empty here. This is
145456  ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
145457  ** always opens a savepoint transaction. And the xSavepoint() method
145458  ** flushes the pending terms table. But leave the (no-op) call to
145459  ** PendingTermsFlush() in in case that changes.
145460  */
145461  assert( p->nPendingData==0 );
145462  if( rc==SQLITE_OK ){
145463    rc = sqlite3Fts3PendingTermsFlush(p);
145464  }
145465
145466  if( p->zContentTbl==0 ){
145467    fts3DbExec(&rc, db,
145468      "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
145469      p->zDb, p->zName, zName
145470    );
145471  }
145472
145473  if( p->bHasDocsize ){
145474    fts3DbExec(&rc, db,
145475      "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
145476      p->zDb, p->zName, zName
145477    );
145478  }
145479  if( p->bHasStat ){
145480    fts3DbExec(&rc, db,
145481      "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
145482      p->zDb, p->zName, zName
145483    );
145484  }
145485  fts3DbExec(&rc, db,
145486    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
145487    p->zDb, p->zName, zName
145488  );
145489  fts3DbExec(&rc, db,
145490    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
145491    p->zDb, p->zName, zName
145492  );
145493  return rc;
145494}
145495
145496/*
145497** The xSavepoint() method.
145498**
145499** Flush the contents of the pending-terms table to disk.
145500*/
145501static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
145502  int rc = SQLITE_OK;
145503  UNUSED_PARAMETER(iSavepoint);
145504  assert( ((Fts3Table *)pVtab)->inTransaction );
145505  assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
145506  TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
145507  if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
145508    rc = fts3SyncMethod(pVtab);
145509  }
145510  return rc;
145511}
145512
145513/*
145514** The xRelease() method.
145515**
145516** This is a no-op.
145517*/
145518static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
145519  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
145520  UNUSED_PARAMETER(iSavepoint);
145521  UNUSED_PARAMETER(pVtab);
145522  assert( p->inTransaction );
145523  assert( p->mxSavepoint >= iSavepoint );
145524  TESTONLY( p->mxSavepoint = iSavepoint-1 );
145525  return SQLITE_OK;
145526}
145527
145528/*
145529** The xRollbackTo() method.
145530**
145531** Discard the contents of the pending terms table.
145532*/
145533static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
145534  Fts3Table *p = (Fts3Table*)pVtab;
145535  UNUSED_PARAMETER(iSavepoint);
145536  assert( p->inTransaction );
145537  assert( p->mxSavepoint >= iSavepoint );
145538  TESTONLY( p->mxSavepoint = iSavepoint );
145539  sqlite3Fts3PendingTermsClear(p);
145540  return SQLITE_OK;
145541}
145542
145543static const sqlite3_module fts3Module = {
145544  /* iVersion      */ 2,
145545  /* xCreate       */ fts3CreateMethod,
145546  /* xConnect      */ fts3ConnectMethod,
145547  /* xBestIndex    */ fts3BestIndexMethod,
145548  /* xDisconnect   */ fts3DisconnectMethod,
145549  /* xDestroy      */ fts3DestroyMethod,
145550  /* xOpen         */ fts3OpenMethod,
145551  /* xClose        */ fts3CloseMethod,
145552  /* xFilter       */ fts3FilterMethod,
145553  /* xNext         */ fts3NextMethod,
145554  /* xEof          */ fts3EofMethod,
145555  /* xColumn       */ fts3ColumnMethod,
145556  /* xRowid        */ fts3RowidMethod,
145557  /* xUpdate       */ fts3UpdateMethod,
145558  /* xBegin        */ fts3BeginMethod,
145559  /* xSync         */ fts3SyncMethod,
145560  /* xCommit       */ fts3CommitMethod,
145561  /* xRollback     */ fts3RollbackMethod,
145562  /* xFindFunction */ fts3FindFunctionMethod,
145563  /* xRename */       fts3RenameMethod,
145564  /* xSavepoint    */ fts3SavepointMethod,
145565  /* xRelease      */ fts3ReleaseMethod,
145566  /* xRollbackTo   */ fts3RollbackToMethod,
145567};
145568
145569/*
145570** This function is registered as the module destructor (called when an
145571** FTS3 enabled database connection is closed). It frees the memory
145572** allocated for the tokenizer hash table.
145573*/
145574static void hashDestroy(void *p){
145575  Fts3Hash *pHash = (Fts3Hash *)p;
145576  sqlite3Fts3HashClear(pHash);
145577  sqlite3_free(pHash);
145578}
145579
145580/*
145581** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
145582** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
145583** respectively. The following three forward declarations are for functions
145584** declared in these files used to retrieve the respective implementations.
145585**
145586** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
145587** to by the argument to point to the "simple" tokenizer implementation.
145588** And so on.
145589*/
145590SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
145591SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
145592#ifndef SQLITE_DISABLE_FTS3_UNICODE
145593SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
145594#endif
145595#ifdef SQLITE_ENABLE_ICU
145596SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
145597#endif
145598
145599/*
145600** Initialize the fts3 extension. If this extension is built as part
145601** of the sqlite library, then this function is called directly by
145602** SQLite. If fts3 is built as a dynamically loadable extension, this
145603** function is called by the sqlite3_extension_init() entry point.
145604*/
145605SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
145606  int rc = SQLITE_OK;
145607  Fts3Hash *pHash = 0;
145608  const sqlite3_tokenizer_module *pSimple = 0;
145609  const sqlite3_tokenizer_module *pPorter = 0;
145610#ifndef SQLITE_DISABLE_FTS3_UNICODE
145611  const sqlite3_tokenizer_module *pUnicode = 0;
145612#endif
145613
145614#ifdef SQLITE_ENABLE_ICU
145615  const sqlite3_tokenizer_module *pIcu = 0;
145616  sqlite3Fts3IcuTokenizerModule(&pIcu);
145617#endif
145618
145619#ifndef SQLITE_DISABLE_FTS3_UNICODE
145620  sqlite3Fts3UnicodeTokenizer(&pUnicode);
145621#endif
145622
145623#ifdef SQLITE_TEST
145624  rc = sqlite3Fts3InitTerm(db);
145625  if( rc!=SQLITE_OK ) return rc;
145626#endif
145627
145628  rc = sqlite3Fts3InitAux(db);
145629  if( rc!=SQLITE_OK ) return rc;
145630
145631  sqlite3Fts3SimpleTokenizerModule(&pSimple);
145632  sqlite3Fts3PorterTokenizerModule(&pPorter);
145633
145634  /* Allocate and initialize the hash-table used to store tokenizers. */
145635  pHash = sqlite3_malloc(sizeof(Fts3Hash));
145636  if( !pHash ){
145637    rc = SQLITE_NOMEM;
145638  }else{
145639    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
145640  }
145641
145642  /* Load the built-in tokenizers into the hash table */
145643  if( rc==SQLITE_OK ){
145644    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
145645     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
145646
145647#ifndef SQLITE_DISABLE_FTS3_UNICODE
145648     || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
145649#endif
145650#ifdef SQLITE_ENABLE_ICU
145651     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
145652#endif
145653    ){
145654      rc = SQLITE_NOMEM;
145655    }
145656  }
145657
145658#ifdef SQLITE_TEST
145659  if( rc==SQLITE_OK ){
145660    rc = sqlite3Fts3ExprInitTestInterface(db);
145661  }
145662#endif
145663
145664  /* Create the virtual table wrapper around the hash-table and overload
145665  ** the two scalar functions. If this is successful, register the
145666  ** module with sqlite.
145667  */
145668  if( SQLITE_OK==rc
145669   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
145670   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
145671   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
145672   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
145673   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
145674   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
145675  ){
145676    rc = sqlite3_create_module_v2(
145677        db, "fts3", &fts3Module, (void *)pHash, hashDestroy
145678    );
145679    if( rc==SQLITE_OK ){
145680      rc = sqlite3_create_module_v2(
145681          db, "fts4", &fts3Module, (void *)pHash, 0
145682      );
145683    }
145684    if( rc==SQLITE_OK ){
145685      rc = sqlite3Fts3InitTok(db, (void *)pHash);
145686    }
145687    return rc;
145688  }
145689
145690
145691  /* An error has occurred. Delete the hash table and return the error code. */
145692  assert( rc!=SQLITE_OK );
145693  if( pHash ){
145694    sqlite3Fts3HashClear(pHash);
145695    sqlite3_free(pHash);
145696  }
145697  return rc;
145698}
145699
145700/*
145701** Allocate an Fts3MultiSegReader for each token in the expression headed
145702** by pExpr.
145703**
145704** An Fts3SegReader object is a cursor that can seek or scan a range of
145705** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
145706** Fts3SegReader objects internally to provide an interface to seek or scan
145707** within the union of all segments of a b-tree. Hence the name.
145708**
145709** If the allocated Fts3MultiSegReader just seeks to a single entry in a
145710** segment b-tree (if the term is not a prefix or it is a prefix for which
145711** there exists prefix b-tree of the right length) then it may be traversed
145712** and merged incrementally. Otherwise, it has to be merged into an in-memory
145713** doclist and then traversed.
145714*/
145715static void fts3EvalAllocateReaders(
145716  Fts3Cursor *pCsr,               /* FTS cursor handle */
145717  Fts3Expr *pExpr,                /* Allocate readers for this expression */
145718  int *pnToken,                   /* OUT: Total number of tokens in phrase. */
145719  int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
145720  int *pRc                        /* IN/OUT: Error code */
145721){
145722  if( pExpr && SQLITE_OK==*pRc ){
145723    if( pExpr->eType==FTSQUERY_PHRASE ){
145724      int i;
145725      int nToken = pExpr->pPhrase->nToken;
145726      *pnToken += nToken;
145727      for(i=0; i<nToken; i++){
145728        Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
145729        int rc = fts3TermSegReaderCursor(pCsr,
145730            pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
145731        );
145732        if( rc!=SQLITE_OK ){
145733          *pRc = rc;
145734          return;
145735        }
145736      }
145737      assert( pExpr->pPhrase->iDoclistToken==0 );
145738      pExpr->pPhrase->iDoclistToken = -1;
145739    }else{
145740      *pnOr += (pExpr->eType==FTSQUERY_OR);
145741      fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
145742      fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
145743    }
145744  }
145745}
145746
145747/*
145748** Arguments pList/nList contain the doclist for token iToken of phrase p.
145749** It is merged into the main doclist stored in p->doclist.aAll/nAll.
145750**
145751** This function assumes that pList points to a buffer allocated using
145752** sqlite3_malloc(). This function takes responsibility for eventually
145753** freeing the buffer.
145754**
145755** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
145756*/
145757static int fts3EvalPhraseMergeToken(
145758  Fts3Table *pTab,                /* FTS Table pointer */
145759  Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
145760  int iToken,                     /* Token pList/nList corresponds to */
145761  char *pList,                    /* Pointer to doclist */
145762  int nList                       /* Number of bytes in pList */
145763){
145764  int rc = SQLITE_OK;
145765  assert( iToken!=p->iDoclistToken );
145766
145767  if( pList==0 ){
145768    sqlite3_free(p->doclist.aAll);
145769    p->doclist.aAll = 0;
145770    p->doclist.nAll = 0;
145771  }
145772
145773  else if( p->iDoclistToken<0 ){
145774    p->doclist.aAll = pList;
145775    p->doclist.nAll = nList;
145776  }
145777
145778  else if( p->doclist.aAll==0 ){
145779    sqlite3_free(pList);
145780  }
145781
145782  else {
145783    char *pLeft;
145784    char *pRight;
145785    int nLeft;
145786    int nRight;
145787    int nDiff;
145788
145789    if( p->iDoclistToken<iToken ){
145790      pLeft = p->doclist.aAll;
145791      nLeft = p->doclist.nAll;
145792      pRight = pList;
145793      nRight = nList;
145794      nDiff = iToken - p->iDoclistToken;
145795    }else{
145796      pRight = p->doclist.aAll;
145797      nRight = p->doclist.nAll;
145798      pLeft = pList;
145799      nLeft = nList;
145800      nDiff = p->iDoclistToken - iToken;
145801    }
145802
145803    rc = fts3DoclistPhraseMerge(
145804        pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
145805    );
145806    sqlite3_free(pLeft);
145807    p->doclist.aAll = pRight;
145808    p->doclist.nAll = nRight;
145809  }
145810
145811  if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
145812  return rc;
145813}
145814
145815/*
145816** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
145817** does not take deferred tokens into account.
145818**
145819** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
145820*/
145821static int fts3EvalPhraseLoad(
145822  Fts3Cursor *pCsr,               /* FTS Cursor handle */
145823  Fts3Phrase *p                   /* Phrase object */
145824){
145825  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
145826  int iToken;
145827  int rc = SQLITE_OK;
145828
145829  for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
145830    Fts3PhraseToken *pToken = &p->aToken[iToken];
145831    assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
145832
145833    if( pToken->pSegcsr ){
145834      int nThis = 0;
145835      char *pThis = 0;
145836      rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
145837      if( rc==SQLITE_OK ){
145838        rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
145839      }
145840    }
145841    assert( pToken->pSegcsr==0 );
145842  }
145843
145844  return rc;
145845}
145846
145847/*
145848** This function is called on each phrase after the position lists for
145849** any deferred tokens have been loaded into memory. It updates the phrases
145850** current position list to include only those positions that are really
145851** instances of the phrase (after considering deferred tokens). If this
145852** means that the phrase does not appear in the current row, doclist.pList
145853** and doclist.nList are both zeroed.
145854**
145855** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
145856*/
145857static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
145858  int iToken;                     /* Used to iterate through phrase tokens */
145859  char *aPoslist = 0;             /* Position list for deferred tokens */
145860  int nPoslist = 0;               /* Number of bytes in aPoslist */
145861  int iPrev = -1;                 /* Token number of previous deferred token */
145862
145863  assert( pPhrase->doclist.bFreeList==0 );
145864
145865  for(iToken=0; iToken<pPhrase->nToken; iToken++){
145866    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
145867    Fts3DeferredToken *pDeferred = pToken->pDeferred;
145868
145869    if( pDeferred ){
145870      char *pList;
145871      int nList;
145872      int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
145873      if( rc!=SQLITE_OK ) return rc;
145874
145875      if( pList==0 ){
145876        sqlite3_free(aPoslist);
145877        pPhrase->doclist.pList = 0;
145878        pPhrase->doclist.nList = 0;
145879        return SQLITE_OK;
145880
145881      }else if( aPoslist==0 ){
145882        aPoslist = pList;
145883        nPoslist = nList;
145884
145885      }else{
145886        char *aOut = pList;
145887        char *p1 = aPoslist;
145888        char *p2 = aOut;
145889
145890        assert( iPrev>=0 );
145891        fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
145892        sqlite3_free(aPoslist);
145893        aPoslist = pList;
145894        nPoslist = (int)(aOut - aPoslist);
145895        if( nPoslist==0 ){
145896          sqlite3_free(aPoslist);
145897          pPhrase->doclist.pList = 0;
145898          pPhrase->doclist.nList = 0;
145899          return SQLITE_OK;
145900        }
145901      }
145902      iPrev = iToken;
145903    }
145904  }
145905
145906  if( iPrev>=0 ){
145907    int nMaxUndeferred = pPhrase->iDoclistToken;
145908    if( nMaxUndeferred<0 ){
145909      pPhrase->doclist.pList = aPoslist;
145910      pPhrase->doclist.nList = nPoslist;
145911      pPhrase->doclist.iDocid = pCsr->iPrevId;
145912      pPhrase->doclist.bFreeList = 1;
145913    }else{
145914      int nDistance;
145915      char *p1;
145916      char *p2;
145917      char *aOut;
145918
145919      if( nMaxUndeferred>iPrev ){
145920        p1 = aPoslist;
145921        p2 = pPhrase->doclist.pList;
145922        nDistance = nMaxUndeferred - iPrev;
145923      }else{
145924        p1 = pPhrase->doclist.pList;
145925        p2 = aPoslist;
145926        nDistance = iPrev - nMaxUndeferred;
145927      }
145928
145929      aOut = (char *)sqlite3_malloc(nPoslist+8);
145930      if( !aOut ){
145931        sqlite3_free(aPoslist);
145932        return SQLITE_NOMEM;
145933      }
145934
145935      pPhrase->doclist.pList = aOut;
145936      if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
145937        pPhrase->doclist.bFreeList = 1;
145938        pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
145939      }else{
145940        sqlite3_free(aOut);
145941        pPhrase->doclist.pList = 0;
145942        pPhrase->doclist.nList = 0;
145943      }
145944      sqlite3_free(aPoslist);
145945    }
145946  }
145947
145948  return SQLITE_OK;
145949}
145950
145951/*
145952** Maximum number of tokens a phrase may have to be considered for the
145953** incremental doclists strategy.
145954*/
145955#define MAX_INCR_PHRASE_TOKENS 4
145956
145957/*
145958** This function is called for each Fts3Phrase in a full-text query
145959** expression to initialize the mechanism for returning rows. Once this
145960** function has been called successfully on an Fts3Phrase, it may be
145961** used with fts3EvalPhraseNext() to iterate through the matching docids.
145962**
145963** If parameter bOptOk is true, then the phrase may (or may not) use the
145964** incremental loading strategy. Otherwise, the entire doclist is loaded into
145965** memory within this call.
145966**
145967** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
145968*/
145969static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
145970  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
145971  int rc = SQLITE_OK;             /* Error code */
145972  int i;
145973
145974  /* Determine if doclists may be loaded from disk incrementally. This is
145975  ** possible if the bOptOk argument is true, the FTS doclists will be
145976  ** scanned in forward order, and the phrase consists of
145977  ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
145978  ** tokens or prefix tokens that cannot use a prefix-index.  */
145979  int bHaveIncr = 0;
145980  int bIncrOk = (bOptOk
145981   && pCsr->bDesc==pTab->bDescIdx
145982   && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
145983#ifdef SQLITE_TEST
145984   && pTab->bNoIncrDoclist==0
145985#endif
145986  );
145987  for(i=0; bIncrOk==1 && i<p->nToken; i++){
145988    Fts3PhraseToken *pToken = &p->aToken[i];
145989    if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
145990      bIncrOk = 0;
145991    }
145992    if( pToken->pSegcsr ) bHaveIncr = 1;
145993  }
145994
145995  if( bIncrOk && bHaveIncr ){
145996    /* Use the incremental approach. */
145997    int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
145998    for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
145999      Fts3PhraseToken *pToken = &p->aToken[i];
146000      Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
146001      if( pSegcsr ){
146002        rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
146003      }
146004    }
146005    p->bIncr = 1;
146006  }else{
146007    /* Load the full doclist for the phrase into memory. */
146008    rc = fts3EvalPhraseLoad(pCsr, p);
146009    p->bIncr = 0;
146010  }
146011
146012  assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
146013  return rc;
146014}
146015
146016/*
146017** This function is used to iterate backwards (from the end to start)
146018** through doclists. It is used by this module to iterate through phrase
146019** doclists in reverse and by the fts3_write.c module to iterate through
146020** pending-terms lists when writing to databases with "order=desc".
146021**
146022** The doclist may be sorted in ascending (parameter bDescIdx==0) or
146023** descending (parameter bDescIdx==1) order of docid. Regardless, this
146024** function iterates from the end of the doclist to the beginning.
146025*/
146026SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
146027  int bDescIdx,                   /* True if the doclist is desc */
146028  char *aDoclist,                 /* Pointer to entire doclist */
146029  int nDoclist,                   /* Length of aDoclist in bytes */
146030  char **ppIter,                  /* IN/OUT: Iterator pointer */
146031  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
146032  int *pnList,                    /* OUT: List length pointer */
146033  u8 *pbEof                       /* OUT: End-of-file flag */
146034){
146035  char *p = *ppIter;
146036
146037  assert( nDoclist>0 );
146038  assert( *pbEof==0 );
146039  assert( p || *piDocid==0 );
146040  assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
146041
146042  if( p==0 ){
146043    sqlite3_int64 iDocid = 0;
146044    char *pNext = 0;
146045    char *pDocid = aDoclist;
146046    char *pEnd = &aDoclist[nDoclist];
146047    int iMul = 1;
146048
146049    while( pDocid<pEnd ){
146050      sqlite3_int64 iDelta;
146051      pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
146052      iDocid += (iMul * iDelta);
146053      pNext = pDocid;
146054      fts3PoslistCopy(0, &pDocid);
146055      while( pDocid<pEnd && *pDocid==0 ) pDocid++;
146056      iMul = (bDescIdx ? -1 : 1);
146057    }
146058
146059    *pnList = (int)(pEnd - pNext);
146060    *ppIter = pNext;
146061    *piDocid = iDocid;
146062  }else{
146063    int iMul = (bDescIdx ? -1 : 1);
146064    sqlite3_int64 iDelta;
146065    fts3GetReverseVarint(&p, aDoclist, &iDelta);
146066    *piDocid -= (iMul * iDelta);
146067
146068    if( p==aDoclist ){
146069      *pbEof = 1;
146070    }else{
146071      char *pSave = p;
146072      fts3ReversePoslist(aDoclist, &p);
146073      *pnList = (int)(pSave - p);
146074    }
146075    *ppIter = p;
146076  }
146077}
146078
146079/*
146080** Iterate forwards through a doclist.
146081*/
146082SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
146083  int bDescIdx,                   /* True if the doclist is desc */
146084  char *aDoclist,                 /* Pointer to entire doclist */
146085  int nDoclist,                   /* Length of aDoclist in bytes */
146086  char **ppIter,                  /* IN/OUT: Iterator pointer */
146087  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
146088  u8 *pbEof                       /* OUT: End-of-file flag */
146089){
146090  char *p = *ppIter;
146091
146092  assert( nDoclist>0 );
146093  assert( *pbEof==0 );
146094  assert( p || *piDocid==0 );
146095  assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
146096
146097  if( p==0 ){
146098    p = aDoclist;
146099    p += sqlite3Fts3GetVarint(p, piDocid);
146100  }else{
146101    fts3PoslistCopy(0, &p);
146102    while( p<&aDoclist[nDoclist] && *p==0 ) p++;
146103    if( p>=&aDoclist[nDoclist] ){
146104      *pbEof = 1;
146105    }else{
146106      sqlite3_int64 iVar;
146107      p += sqlite3Fts3GetVarint(p, &iVar);
146108      *piDocid += ((bDescIdx ? -1 : 1) * iVar);
146109    }
146110  }
146111
146112  *ppIter = p;
146113}
146114
146115/*
146116** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
146117** to true if EOF is reached.
146118*/
146119static void fts3EvalDlPhraseNext(
146120  Fts3Table *pTab,
146121  Fts3Doclist *pDL,
146122  u8 *pbEof
146123){
146124  char *pIter;                            /* Used to iterate through aAll */
146125  char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
146126
146127  if( pDL->pNextDocid ){
146128    pIter = pDL->pNextDocid;
146129  }else{
146130    pIter = pDL->aAll;
146131  }
146132
146133  if( pIter>=pEnd ){
146134    /* We have already reached the end of this doclist. EOF. */
146135    *pbEof = 1;
146136  }else{
146137    sqlite3_int64 iDelta;
146138    pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
146139    if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
146140      pDL->iDocid += iDelta;
146141    }else{
146142      pDL->iDocid -= iDelta;
146143    }
146144    pDL->pList = pIter;
146145    fts3PoslistCopy(0, &pIter);
146146    pDL->nList = (int)(pIter - pDL->pList);
146147
146148    /* pIter now points just past the 0x00 that terminates the position-
146149    ** list for document pDL->iDocid. However, if this position-list was
146150    ** edited in place by fts3EvalNearTrim(), then pIter may not actually
146151    ** point to the start of the next docid value. The following line deals
146152    ** with this case by advancing pIter past the zero-padding added by
146153    ** fts3EvalNearTrim().  */
146154    while( pIter<pEnd && *pIter==0 ) pIter++;
146155
146156    pDL->pNextDocid = pIter;
146157    assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
146158    *pbEof = 0;
146159  }
146160}
146161
146162/*
146163** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
146164*/
146165typedef struct TokenDoclist TokenDoclist;
146166struct TokenDoclist {
146167  int bIgnore;
146168  sqlite3_int64 iDocid;
146169  char *pList;
146170  int nList;
146171};
146172
146173/*
146174** Token pToken is an incrementally loaded token that is part of a
146175** multi-token phrase. Advance it to the next matching document in the
146176** database and populate output variable *p with the details of the new
146177** entry. Or, if the iterator has reached EOF, set *pbEof to true.
146178**
146179** If an error occurs, return an SQLite error code. Otherwise, return
146180** SQLITE_OK.
146181*/
146182static int incrPhraseTokenNext(
146183  Fts3Table *pTab,                /* Virtual table handle */
146184  Fts3Phrase *pPhrase,            /* Phrase to advance token of */
146185  int iToken,                     /* Specific token to advance */
146186  TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
146187  u8 *pbEof                       /* OUT: True if iterator is at EOF */
146188){
146189  int rc = SQLITE_OK;
146190
146191  if( pPhrase->iDoclistToken==iToken ){
146192    assert( p->bIgnore==0 );
146193    assert( pPhrase->aToken[iToken].pSegcsr==0 );
146194    fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
146195    p->pList = pPhrase->doclist.pList;
146196    p->nList = pPhrase->doclist.nList;
146197    p->iDocid = pPhrase->doclist.iDocid;
146198  }else{
146199    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
146200    assert( pToken->pDeferred==0 );
146201    assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
146202    if( pToken->pSegcsr ){
146203      assert( p->bIgnore==0 );
146204      rc = sqlite3Fts3MsrIncrNext(
146205          pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
146206      );
146207      if( p->pList==0 ) *pbEof = 1;
146208    }else{
146209      p->bIgnore = 1;
146210    }
146211  }
146212
146213  return rc;
146214}
146215
146216
146217/*
146218** The phrase iterator passed as the second argument:
146219**
146220**   * features at least one token that uses an incremental doclist, and
146221**
146222**   * does not contain any deferred tokens.
146223**
146224** Advance it to the next matching documnent in the database and populate
146225** the Fts3Doclist.pList and nList fields.
146226**
146227** If there is no "next" entry and no error occurs, then *pbEof is set to
146228** 1 before returning. Otherwise, if no error occurs and the iterator is
146229** successfully advanced, *pbEof is set to 0.
146230**
146231** If an error occurs, return an SQLite error code. Otherwise, return
146232** SQLITE_OK.
146233*/
146234static int fts3EvalIncrPhraseNext(
146235  Fts3Cursor *pCsr,               /* FTS Cursor handle */
146236  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
146237  u8 *pbEof                       /* OUT: Set to 1 if EOF */
146238){
146239  int rc = SQLITE_OK;
146240  Fts3Doclist *pDL = &p->doclist;
146241  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146242  u8 bEof = 0;
146243
146244  /* This is only called if it is guaranteed that the phrase has at least
146245  ** one incremental token. In which case the bIncr flag is set. */
146246  assert( p->bIncr==1 );
146247
146248  if( p->nToken==1 && p->bIncr ){
146249    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
146250        &pDL->iDocid, &pDL->pList, &pDL->nList
146251    );
146252    if( pDL->pList==0 ) bEof = 1;
146253  }else{
146254    int bDescDoclist = pCsr->bDesc;
146255    struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
146256
146257    memset(a, 0, sizeof(a));
146258    assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
146259    assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
146260
146261    while( bEof==0 ){
146262      int bMaxSet = 0;
146263      sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
146264      int i;                      /* Used to iterate through tokens */
146265
146266      /* Advance the iterator for each token in the phrase once. */
146267      for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
146268        rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
146269        if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
146270          iMax = a[i].iDocid;
146271          bMaxSet = 1;
146272        }
146273      }
146274      assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
146275      assert( rc!=SQLITE_OK || bMaxSet );
146276
146277      /* Keep advancing iterators until they all point to the same document */
146278      for(i=0; i<p->nToken; i++){
146279        while( rc==SQLITE_OK && bEof==0
146280            && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
146281        ){
146282          rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
146283          if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
146284            iMax = a[i].iDocid;
146285            i = 0;
146286          }
146287        }
146288      }
146289
146290      /* Check if the current entries really are a phrase match */
146291      if( bEof==0 ){
146292        int nList = 0;
146293        int nByte = a[p->nToken-1].nList;
146294        char *aDoclist = sqlite3_malloc(nByte+1);
146295        if( !aDoclist ) return SQLITE_NOMEM;
146296        memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
146297
146298        for(i=0; i<(p->nToken-1); i++){
146299          if( a[i].bIgnore==0 ){
146300            char *pL = a[i].pList;
146301            char *pR = aDoclist;
146302            char *pOut = aDoclist;
146303            int nDist = p->nToken-1-i;
146304            int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
146305            if( res==0 ) break;
146306            nList = (int)(pOut - aDoclist);
146307          }
146308        }
146309        if( i==(p->nToken-1) ){
146310          pDL->iDocid = iMax;
146311          pDL->pList = aDoclist;
146312          pDL->nList = nList;
146313          pDL->bFreeList = 1;
146314          break;
146315        }
146316        sqlite3_free(aDoclist);
146317      }
146318    }
146319  }
146320
146321  *pbEof = bEof;
146322  return rc;
146323}
146324
146325/*
146326** Attempt to move the phrase iterator to point to the next matching docid.
146327** If an error occurs, return an SQLite error code. Otherwise, return
146328** SQLITE_OK.
146329**
146330** If there is no "next" entry and no error occurs, then *pbEof is set to
146331** 1 before returning. Otherwise, if no error occurs and the iterator is
146332** successfully advanced, *pbEof is set to 0.
146333*/
146334static int fts3EvalPhraseNext(
146335  Fts3Cursor *pCsr,               /* FTS Cursor handle */
146336  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
146337  u8 *pbEof                       /* OUT: Set to 1 if EOF */
146338){
146339  int rc = SQLITE_OK;
146340  Fts3Doclist *pDL = &p->doclist;
146341  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146342
146343  if( p->bIncr ){
146344    rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
146345  }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
146346    sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
146347        &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
146348    );
146349    pDL->pList = pDL->pNextDocid;
146350  }else{
146351    fts3EvalDlPhraseNext(pTab, pDL, pbEof);
146352  }
146353
146354  return rc;
146355}
146356
146357/*
146358**
146359** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
146360** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
146361** expression. Also the Fts3Expr.bDeferred variable is set to true for any
146362** expressions for which all descendent tokens are deferred.
146363**
146364** If parameter bOptOk is zero, then it is guaranteed that the
146365** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
146366** each phrase in the expression (subject to deferred token processing).
146367** Or, if bOptOk is non-zero, then one or more tokens within the expression
146368** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
146369**
146370** If an error occurs within this function, *pRc is set to an SQLite error
146371** code before returning.
146372*/
146373static void fts3EvalStartReaders(
146374  Fts3Cursor *pCsr,               /* FTS Cursor handle */
146375  Fts3Expr *pExpr,                /* Expression to initialize phrases in */
146376  int *pRc                        /* IN/OUT: Error code */
146377){
146378  if( pExpr && SQLITE_OK==*pRc ){
146379    if( pExpr->eType==FTSQUERY_PHRASE ){
146380      int nToken = pExpr->pPhrase->nToken;
146381      if( nToken ){
146382        int i;
146383        for(i=0; i<nToken; i++){
146384          if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
146385        }
146386        pExpr->bDeferred = (i==nToken);
146387      }
146388      *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
146389    }else{
146390      fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
146391      fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
146392      pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
146393    }
146394  }
146395}
146396
146397/*
146398** An array of the following structures is assembled as part of the process
146399** of selecting tokens to defer before the query starts executing (as part
146400** of the xFilter() method). There is one element in the array for each
146401** token in the FTS expression.
146402**
146403** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
146404** to phrases that are connected only by AND and NEAR operators (not OR or
146405** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
146406** separately. The root of a tokens AND/NEAR cluster is stored in
146407** Fts3TokenAndCost.pRoot.
146408*/
146409typedef struct Fts3TokenAndCost Fts3TokenAndCost;
146410struct Fts3TokenAndCost {
146411  Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
146412  int iToken;                     /* Position of token in phrase */
146413  Fts3PhraseToken *pToken;        /* The token itself */
146414  Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
146415  int nOvfl;                      /* Number of overflow pages to load doclist */
146416  int iCol;                       /* The column the token must match */
146417};
146418
146419/*
146420** This function is used to populate an allocated Fts3TokenAndCost array.
146421**
146422** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
146423** Otherwise, if an error occurs during execution, *pRc is set to an
146424** SQLite error code.
146425*/
146426static void fts3EvalTokenCosts(
146427  Fts3Cursor *pCsr,               /* FTS Cursor handle */
146428  Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
146429  Fts3Expr *pExpr,                /* Expression to consider */
146430  Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
146431  Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
146432  int *pRc                        /* IN/OUT: Error code */
146433){
146434  if( *pRc==SQLITE_OK ){
146435    if( pExpr->eType==FTSQUERY_PHRASE ){
146436      Fts3Phrase *pPhrase = pExpr->pPhrase;
146437      int i;
146438      for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
146439        Fts3TokenAndCost *pTC = (*ppTC)++;
146440        pTC->pPhrase = pPhrase;
146441        pTC->iToken = i;
146442        pTC->pRoot = pRoot;
146443        pTC->pToken = &pPhrase->aToken[i];
146444        pTC->iCol = pPhrase->iColumn;
146445        *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
146446      }
146447    }else if( pExpr->eType!=FTSQUERY_NOT ){
146448      assert( pExpr->eType==FTSQUERY_OR
146449           || pExpr->eType==FTSQUERY_AND
146450           || pExpr->eType==FTSQUERY_NEAR
146451      );
146452      assert( pExpr->pLeft && pExpr->pRight );
146453      if( pExpr->eType==FTSQUERY_OR ){
146454        pRoot = pExpr->pLeft;
146455        **ppOr = pRoot;
146456        (*ppOr)++;
146457      }
146458      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
146459      if( pExpr->eType==FTSQUERY_OR ){
146460        pRoot = pExpr->pRight;
146461        **ppOr = pRoot;
146462        (*ppOr)++;
146463      }
146464      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
146465    }
146466  }
146467}
146468
146469/*
146470** Determine the average document (row) size in pages. If successful,
146471** write this value to *pnPage and return SQLITE_OK. Otherwise, return
146472** an SQLite error code.
146473**
146474** The average document size in pages is calculated by first calculating
146475** determining the average size in bytes, B. If B is less than the amount
146476** of data that will fit on a single leaf page of an intkey table in
146477** this database, then the average docsize is 1. Otherwise, it is 1 plus
146478** the number of overflow pages consumed by a record B bytes in size.
146479*/
146480static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
146481  if( pCsr->nRowAvg==0 ){
146482    /* The average document size, which is required to calculate the cost
146483    ** of each doclist, has not yet been determined. Read the required
146484    ** data from the %_stat table to calculate it.
146485    **
146486    ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
146487    ** varints, where nCol is the number of columns in the FTS3 table.
146488    ** The first varint is the number of documents currently stored in
146489    ** the table. The following nCol varints contain the total amount of
146490    ** data stored in all rows of each column of the table, from left
146491    ** to right.
146492    */
146493    int rc;
146494    Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
146495    sqlite3_stmt *pStmt;
146496    sqlite3_int64 nDoc = 0;
146497    sqlite3_int64 nByte = 0;
146498    const char *pEnd;
146499    const char *a;
146500
146501    rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
146502    if( rc!=SQLITE_OK ) return rc;
146503    a = sqlite3_column_blob(pStmt, 0);
146504    assert( a );
146505
146506    pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
146507    a += sqlite3Fts3GetVarint(a, &nDoc);
146508    while( a<pEnd ){
146509      a += sqlite3Fts3GetVarint(a, &nByte);
146510    }
146511    if( nDoc==0 || nByte==0 ){
146512      sqlite3_reset(pStmt);
146513      return FTS_CORRUPT_VTAB;
146514    }
146515
146516    pCsr->nDoc = nDoc;
146517    pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
146518    assert( pCsr->nRowAvg>0 );
146519    rc = sqlite3_reset(pStmt);
146520    if( rc!=SQLITE_OK ) return rc;
146521  }
146522
146523  *pnPage = pCsr->nRowAvg;
146524  return SQLITE_OK;
146525}
146526
146527/*
146528** This function is called to select the tokens (if any) that will be
146529** deferred. The array aTC[] has already been populated when this is
146530** called.
146531**
146532** This function is called once for each AND/NEAR cluster in the
146533** expression. Each invocation determines which tokens to defer within
146534** the cluster with root node pRoot. See comments above the definition
146535** of struct Fts3TokenAndCost for more details.
146536**
146537** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
146538** called on each token to defer. Otherwise, an SQLite error code is
146539** returned.
146540*/
146541static int fts3EvalSelectDeferred(
146542  Fts3Cursor *pCsr,               /* FTS Cursor handle */
146543  Fts3Expr *pRoot,                /* Consider tokens with this root node */
146544  Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
146545  int nTC                         /* Number of entries in aTC[] */
146546){
146547  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146548  int nDocSize = 0;               /* Number of pages per doc loaded */
146549  int rc = SQLITE_OK;             /* Return code */
146550  int ii;                         /* Iterator variable for various purposes */
146551  int nOvfl = 0;                  /* Total overflow pages used by doclists */
146552  int nToken = 0;                 /* Total number of tokens in cluster */
146553
146554  int nMinEst = 0;                /* The minimum count for any phrase so far. */
146555  int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
146556
146557  /* Tokens are never deferred for FTS tables created using the content=xxx
146558  ** option. The reason being that it is not guaranteed that the content
146559  ** table actually contains the same data as the index. To prevent this from
146560  ** causing any problems, the deferred token optimization is completely
146561  ** disabled for content=xxx tables. */
146562  if( pTab->zContentTbl ){
146563    return SQLITE_OK;
146564  }
146565
146566  /* Count the tokens in this AND/NEAR cluster. If none of the doclists
146567  ** associated with the tokens spill onto overflow pages, or if there is
146568  ** only 1 token, exit early. No tokens to defer in this case. */
146569  for(ii=0; ii<nTC; ii++){
146570    if( aTC[ii].pRoot==pRoot ){
146571      nOvfl += aTC[ii].nOvfl;
146572      nToken++;
146573    }
146574  }
146575  if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
146576
146577  /* Obtain the average docsize (in pages). */
146578  rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
146579  assert( rc!=SQLITE_OK || nDocSize>0 );
146580
146581
146582  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
146583  ** of the number of overflow pages that will be loaded by the pager layer
146584  ** to retrieve the entire doclist for the token from the full-text index.
146585  ** Load the doclists for tokens that are either:
146586  **
146587  **   a. The cheapest token in the entire query (i.e. the one visited by the
146588  **      first iteration of this loop), or
146589  **
146590  **   b. Part of a multi-token phrase.
146591  **
146592  ** After each token doclist is loaded, merge it with the others from the
146593  ** same phrase and count the number of documents that the merged doclist
146594  ** contains. Set variable "nMinEst" to the smallest number of documents in
146595  ** any phrase doclist for which 1 or more token doclists have been loaded.
146596  ** Let nOther be the number of other phrases for which it is certain that
146597  ** one or more tokens will not be deferred.
146598  **
146599  ** Then, for each token, defer it if loading the doclist would result in
146600  ** loading N or more overflow pages into memory, where N is computed as:
146601  **
146602  **    (nMinEst + 4^nOther - 1) / (4^nOther)
146603  */
146604  for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
146605    int iTC;                      /* Used to iterate through aTC[] array. */
146606    Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
146607
146608    /* Set pTC to point to the cheapest remaining token. */
146609    for(iTC=0; iTC<nTC; iTC++){
146610      if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
146611       && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
146612      ){
146613        pTC = &aTC[iTC];
146614      }
146615    }
146616    assert( pTC );
146617
146618    if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
146619      /* The number of overflow pages to load for this (and therefore all
146620      ** subsequent) tokens is greater than the estimated number of pages
146621      ** that will be loaded if all subsequent tokens are deferred.
146622      */
146623      Fts3PhraseToken *pToken = pTC->pToken;
146624      rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
146625      fts3SegReaderCursorFree(pToken->pSegcsr);
146626      pToken->pSegcsr = 0;
146627    }else{
146628      /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
146629      ** for-loop. Except, limit the value to 2^24 to prevent it from
146630      ** overflowing the 32-bit integer it is stored in. */
146631      if( ii<12 ) nLoad4 = nLoad4*4;
146632
146633      if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
146634        /* Either this is the cheapest token in the entire query, or it is
146635        ** part of a multi-token phrase. Either way, the entire doclist will
146636        ** (eventually) be loaded into memory. It may as well be now. */
146637        Fts3PhraseToken *pToken = pTC->pToken;
146638        int nList = 0;
146639        char *pList = 0;
146640        rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
146641        assert( rc==SQLITE_OK || pList==0 );
146642        if( rc==SQLITE_OK ){
146643          rc = fts3EvalPhraseMergeToken(
146644              pTab, pTC->pPhrase, pTC->iToken,pList,nList
146645          );
146646        }
146647        if( rc==SQLITE_OK ){
146648          int nCount;
146649          nCount = fts3DoclistCountDocids(
146650              pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
146651          );
146652          if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
146653        }
146654      }
146655    }
146656    pTC->pToken = 0;
146657  }
146658
146659  return rc;
146660}
146661
146662/*
146663** This function is called from within the xFilter method. It initializes
146664** the full-text query currently stored in pCsr->pExpr. To iterate through
146665** the results of a query, the caller does:
146666**
146667**    fts3EvalStart(pCsr);
146668**    while( 1 ){
146669**      fts3EvalNext(pCsr);
146670**      if( pCsr->bEof ) break;
146671**      ... return row pCsr->iPrevId to the caller ...
146672**    }
146673*/
146674static int fts3EvalStart(Fts3Cursor *pCsr){
146675  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146676  int rc = SQLITE_OK;
146677  int nToken = 0;
146678  int nOr = 0;
146679
146680  /* Allocate a MultiSegReader for each token in the expression. */
146681  fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
146682
146683  /* Determine which, if any, tokens in the expression should be deferred. */
146684#ifndef SQLITE_DISABLE_FTS4_DEFERRED
146685  if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
146686    Fts3TokenAndCost *aTC;
146687    Fts3Expr **apOr;
146688    aTC = (Fts3TokenAndCost *)sqlite3_malloc(
146689        sizeof(Fts3TokenAndCost) * nToken
146690      + sizeof(Fts3Expr *) * nOr * 2
146691    );
146692    apOr = (Fts3Expr **)&aTC[nToken];
146693
146694    if( !aTC ){
146695      rc = SQLITE_NOMEM;
146696    }else{
146697      int ii;
146698      Fts3TokenAndCost *pTC = aTC;
146699      Fts3Expr **ppOr = apOr;
146700
146701      fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
146702      nToken = (int)(pTC-aTC);
146703      nOr = (int)(ppOr-apOr);
146704
146705      if( rc==SQLITE_OK ){
146706        rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
146707        for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
146708          rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
146709        }
146710      }
146711
146712      sqlite3_free(aTC);
146713    }
146714  }
146715#endif
146716
146717  fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
146718  return rc;
146719}
146720
146721/*
146722** Invalidate the current position list for phrase pPhrase.
146723*/
146724static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
146725  if( pPhrase->doclist.bFreeList ){
146726    sqlite3_free(pPhrase->doclist.pList);
146727  }
146728  pPhrase->doclist.pList = 0;
146729  pPhrase->doclist.nList = 0;
146730  pPhrase->doclist.bFreeList = 0;
146731}
146732
146733/*
146734** This function is called to edit the position list associated with
146735** the phrase object passed as the fifth argument according to a NEAR
146736** condition. For example:
146737**
146738**     abc NEAR/5 "def ghi"
146739**
146740** Parameter nNear is passed the NEAR distance of the expression (5 in
146741** the example above). When this function is called, *paPoslist points to
146742** the position list, and *pnToken is the number of phrase tokens in, the
146743** phrase on the other side of the NEAR operator to pPhrase. For example,
146744** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
146745** the position list associated with phrase "abc".
146746**
146747** All positions in the pPhrase position list that are not sufficiently
146748** close to a position in the *paPoslist position list are removed. If this
146749** leaves 0 positions, zero is returned. Otherwise, non-zero.
146750**
146751** Before returning, *paPoslist is set to point to the position lsit
146752** associated with pPhrase. And *pnToken is set to the number of tokens in
146753** pPhrase.
146754*/
146755static int fts3EvalNearTrim(
146756  int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
146757  char *aTmp,                     /* Temporary space to use */
146758  char **paPoslist,               /* IN/OUT: Position list */
146759  int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
146760  Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
146761){
146762  int nParam1 = nNear + pPhrase->nToken;
146763  int nParam2 = nNear + *pnToken;
146764  int nNew;
146765  char *p2;
146766  char *pOut;
146767  int res;
146768
146769  assert( pPhrase->doclist.pList );
146770
146771  p2 = pOut = pPhrase->doclist.pList;
146772  res = fts3PoslistNearMerge(
146773    &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
146774  );
146775  if( res ){
146776    nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
146777    assert( pPhrase->doclist.pList[nNew]=='\0' );
146778    assert( nNew<=pPhrase->doclist.nList && nNew>0 );
146779    memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
146780    pPhrase->doclist.nList = nNew;
146781    *paPoslist = pPhrase->doclist.pList;
146782    *pnToken = pPhrase->nToken;
146783  }
146784
146785  return res;
146786}
146787
146788/*
146789** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
146790** Otherwise, it advances the expression passed as the second argument to
146791** point to the next matching row in the database. Expressions iterate through
146792** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
146793** or descending if it is non-zero.
146794**
146795** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
146796** successful, the following variables in pExpr are set:
146797**
146798**   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
146799**   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
146800**
146801** If the expression is of type FTSQUERY_PHRASE, and the expression is not
146802** at EOF, then the following variables are populated with the position list
146803** for the phrase for the visited row:
146804**
146805**   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
146806**   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
146807**
146808** It says above that this function advances the expression to the next
146809** matching row. This is usually true, but there are the following exceptions:
146810**
146811**   1. Deferred tokens are not taken into account. If a phrase consists
146812**      entirely of deferred tokens, it is assumed to match every row in
146813**      the db. In this case the position-list is not populated at all.
146814**
146815**      Or, if a phrase contains one or more deferred tokens and one or
146816**      more non-deferred tokens, then the expression is advanced to the
146817**      next possible match, considering only non-deferred tokens. In other
146818**      words, if the phrase is "A B C", and "B" is deferred, the expression
146819**      is advanced to the next row that contains an instance of "A * C",
146820**      where "*" may match any single token. The position list in this case
146821**      is populated as for "A * C" before returning.
146822**
146823**   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
146824**      advanced to point to the next row that matches "x AND y".
146825**
146826** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
146827** really a match, taking into account deferred tokens and NEAR operators.
146828*/
146829static void fts3EvalNextRow(
146830  Fts3Cursor *pCsr,               /* FTS Cursor handle */
146831  Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
146832  int *pRc                        /* IN/OUT: Error code */
146833){
146834  if( *pRc==SQLITE_OK ){
146835    int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
146836    assert( pExpr->bEof==0 );
146837    pExpr->bStart = 1;
146838
146839    switch( pExpr->eType ){
146840      case FTSQUERY_NEAR:
146841      case FTSQUERY_AND: {
146842        Fts3Expr *pLeft = pExpr->pLeft;
146843        Fts3Expr *pRight = pExpr->pRight;
146844        assert( !pLeft->bDeferred || !pRight->bDeferred );
146845
146846        if( pLeft->bDeferred ){
146847          /* LHS is entirely deferred. So we assume it matches every row.
146848          ** Advance the RHS iterator to find the next row visited. */
146849          fts3EvalNextRow(pCsr, pRight, pRc);
146850          pExpr->iDocid = pRight->iDocid;
146851          pExpr->bEof = pRight->bEof;
146852        }else if( pRight->bDeferred ){
146853          /* RHS is entirely deferred. So we assume it matches every row.
146854          ** Advance the LHS iterator to find the next row visited. */
146855          fts3EvalNextRow(pCsr, pLeft, pRc);
146856          pExpr->iDocid = pLeft->iDocid;
146857          pExpr->bEof = pLeft->bEof;
146858        }else{
146859          /* Neither the RHS or LHS are deferred. */
146860          fts3EvalNextRow(pCsr, pLeft, pRc);
146861          fts3EvalNextRow(pCsr, pRight, pRc);
146862          while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
146863            sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
146864            if( iDiff==0 ) break;
146865            if( iDiff<0 ){
146866              fts3EvalNextRow(pCsr, pLeft, pRc);
146867            }else{
146868              fts3EvalNextRow(pCsr, pRight, pRc);
146869            }
146870          }
146871          pExpr->iDocid = pLeft->iDocid;
146872          pExpr->bEof = (pLeft->bEof || pRight->bEof);
146873          if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
146874            if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){
146875              Fts3Doclist *pDl = &pRight->pPhrase->doclist;
146876              while( *pRc==SQLITE_OK && pRight->bEof==0 ){
146877                memset(pDl->pList, 0, pDl->nList);
146878                fts3EvalNextRow(pCsr, pRight, pRc);
146879              }
146880            }
146881            if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
146882              Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
146883              while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
146884                memset(pDl->pList, 0, pDl->nList);
146885                fts3EvalNextRow(pCsr, pLeft, pRc);
146886              }
146887            }
146888          }
146889        }
146890        break;
146891      }
146892
146893      case FTSQUERY_OR: {
146894        Fts3Expr *pLeft = pExpr->pLeft;
146895        Fts3Expr *pRight = pExpr->pRight;
146896        sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
146897
146898        assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
146899        assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
146900
146901        if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
146902          fts3EvalNextRow(pCsr, pLeft, pRc);
146903        }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
146904          fts3EvalNextRow(pCsr, pRight, pRc);
146905        }else{
146906          fts3EvalNextRow(pCsr, pLeft, pRc);
146907          fts3EvalNextRow(pCsr, pRight, pRc);
146908        }
146909
146910        pExpr->bEof = (pLeft->bEof && pRight->bEof);
146911        iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
146912        if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
146913          pExpr->iDocid = pLeft->iDocid;
146914        }else{
146915          pExpr->iDocid = pRight->iDocid;
146916        }
146917
146918        break;
146919      }
146920
146921      case FTSQUERY_NOT: {
146922        Fts3Expr *pLeft = pExpr->pLeft;
146923        Fts3Expr *pRight = pExpr->pRight;
146924
146925        if( pRight->bStart==0 ){
146926          fts3EvalNextRow(pCsr, pRight, pRc);
146927          assert( *pRc!=SQLITE_OK || pRight->bStart );
146928        }
146929
146930        fts3EvalNextRow(pCsr, pLeft, pRc);
146931        if( pLeft->bEof==0 ){
146932          while( !*pRc
146933              && !pRight->bEof
146934              && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
146935          ){
146936            fts3EvalNextRow(pCsr, pRight, pRc);
146937          }
146938        }
146939        pExpr->iDocid = pLeft->iDocid;
146940        pExpr->bEof = pLeft->bEof;
146941        break;
146942      }
146943
146944      default: {
146945        Fts3Phrase *pPhrase = pExpr->pPhrase;
146946        fts3EvalInvalidatePoslist(pPhrase);
146947        *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
146948        pExpr->iDocid = pPhrase->doclist.iDocid;
146949        break;
146950      }
146951    }
146952  }
146953}
146954
146955/*
146956** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
146957** cluster, then this function returns 1 immediately.
146958**
146959** Otherwise, it checks if the current row really does match the NEAR
146960** expression, using the data currently stored in the position lists
146961** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
146962**
146963** If the current row is a match, the position list associated with each
146964** phrase in the NEAR expression is edited in place to contain only those
146965** phrase instances sufficiently close to their peers to satisfy all NEAR
146966** constraints. In this case it returns 1. If the NEAR expression does not
146967** match the current row, 0 is returned. The position lists may or may not
146968** be edited if 0 is returned.
146969*/
146970static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
146971  int res = 1;
146972
146973  /* The following block runs if pExpr is the root of a NEAR query.
146974  ** For example, the query:
146975  **
146976  **         "w" NEAR "x" NEAR "y" NEAR "z"
146977  **
146978  ** which is represented in tree form as:
146979  **
146980  **                               |
146981  **                          +--NEAR--+      <-- root of NEAR query
146982  **                          |        |
146983  **                     +--NEAR--+   "z"
146984  **                     |        |
146985  **                +--NEAR--+   "y"
146986  **                |        |
146987  **               "w"      "x"
146988  **
146989  ** The right-hand child of a NEAR node is always a phrase. The
146990  ** left-hand child may be either a phrase or a NEAR node. There are
146991  ** no exceptions to this - it's the way the parser in fts3_expr.c works.
146992  */
146993  if( *pRc==SQLITE_OK
146994   && pExpr->eType==FTSQUERY_NEAR
146995   && pExpr->bEof==0
146996   && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
146997  ){
146998    Fts3Expr *p;
146999    int nTmp = 0;                 /* Bytes of temp space */
147000    char *aTmp;                   /* Temp space for PoslistNearMerge() */
147001
147002    /* Allocate temporary working space. */
147003    for(p=pExpr; p->pLeft; p=p->pLeft){
147004      nTmp += p->pRight->pPhrase->doclist.nList;
147005    }
147006    nTmp += p->pPhrase->doclist.nList;
147007    if( nTmp==0 ){
147008      res = 0;
147009    }else{
147010      aTmp = sqlite3_malloc(nTmp*2);
147011      if( !aTmp ){
147012        *pRc = SQLITE_NOMEM;
147013        res = 0;
147014      }else{
147015        char *aPoslist = p->pPhrase->doclist.pList;
147016        int nToken = p->pPhrase->nToken;
147017
147018        for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
147019          Fts3Phrase *pPhrase = p->pRight->pPhrase;
147020          int nNear = p->nNear;
147021          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
147022        }
147023
147024        aPoslist = pExpr->pRight->pPhrase->doclist.pList;
147025        nToken = pExpr->pRight->pPhrase->nToken;
147026        for(p=pExpr->pLeft; p && res; p=p->pLeft){
147027          int nNear;
147028          Fts3Phrase *pPhrase;
147029          assert( p->pParent && p->pParent->pLeft==p );
147030          nNear = p->pParent->nNear;
147031          pPhrase = (
147032              p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
147033              );
147034          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
147035        }
147036      }
147037
147038      sqlite3_free(aTmp);
147039    }
147040  }
147041
147042  return res;
147043}
147044
147045/*
147046** This function is a helper function for sqlite3Fts3EvalTestDeferred().
147047** Assuming no error occurs or has occurred, It returns non-zero if the
147048** expression passed as the second argument matches the row that pCsr
147049** currently points to, or zero if it does not.
147050**
147051** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
147052** If an error occurs during execution of this function, *pRc is set to
147053** the appropriate SQLite error code. In this case the returned value is
147054** undefined.
147055*/
147056static int fts3EvalTestExpr(
147057  Fts3Cursor *pCsr,               /* FTS cursor handle */
147058  Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
147059  int *pRc                        /* IN/OUT: Error code */
147060){
147061  int bHit = 1;                   /* Return value */
147062  if( *pRc==SQLITE_OK ){
147063    switch( pExpr->eType ){
147064      case FTSQUERY_NEAR:
147065      case FTSQUERY_AND:
147066        bHit = (
147067            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
147068         && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
147069         && fts3EvalNearTest(pExpr, pRc)
147070        );
147071
147072        /* If the NEAR expression does not match any rows, zero the doclist for
147073        ** all phrases involved in the NEAR. This is because the snippet(),
147074        ** offsets() and matchinfo() functions are not supposed to recognize
147075        ** any instances of phrases that are part of unmatched NEAR queries.
147076        ** For example if this expression:
147077        **
147078        **    ... MATCH 'a OR (b NEAR c)'
147079        **
147080        ** is matched against a row containing:
147081        **
147082        **        'a b d e'
147083        **
147084        ** then any snippet() should ony highlight the "a" term, not the "b"
147085        ** (as "b" is part of a non-matching NEAR clause).
147086        */
147087        if( bHit==0
147088         && pExpr->eType==FTSQUERY_NEAR
147089         && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
147090        ){
147091          Fts3Expr *p;
147092          for(p=pExpr; p->pPhrase==0; p=p->pLeft){
147093            if( p->pRight->iDocid==pCsr->iPrevId ){
147094              fts3EvalInvalidatePoslist(p->pRight->pPhrase);
147095            }
147096          }
147097          if( p->iDocid==pCsr->iPrevId ){
147098            fts3EvalInvalidatePoslist(p->pPhrase);
147099          }
147100        }
147101
147102        break;
147103
147104      case FTSQUERY_OR: {
147105        int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
147106        int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
147107        bHit = bHit1 || bHit2;
147108        break;
147109      }
147110
147111      case FTSQUERY_NOT:
147112        bHit = (
147113            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
147114         && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
147115        );
147116        break;
147117
147118      default: {
147119#ifndef SQLITE_DISABLE_FTS4_DEFERRED
147120        if( pCsr->pDeferred
147121         && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
147122        ){
147123          Fts3Phrase *pPhrase = pExpr->pPhrase;
147124          assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
147125          if( pExpr->bDeferred ){
147126            fts3EvalInvalidatePoslist(pPhrase);
147127          }
147128          *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
147129          bHit = (pPhrase->doclist.pList!=0);
147130          pExpr->iDocid = pCsr->iPrevId;
147131        }else
147132#endif
147133        {
147134          bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
147135        }
147136        break;
147137      }
147138    }
147139  }
147140  return bHit;
147141}
147142
147143/*
147144** This function is called as the second part of each xNext operation when
147145** iterating through the results of a full-text query. At this point the
147146** cursor points to a row that matches the query expression, with the
147147** following caveats:
147148**
147149**   * Up until this point, "NEAR" operators in the expression have been
147150**     treated as "AND".
147151**
147152**   * Deferred tokens have not yet been considered.
147153**
147154** If *pRc is not SQLITE_OK when this function is called, it immediately
147155** returns 0. Otherwise, it tests whether or not after considering NEAR
147156** operators and deferred tokens the current row is still a match for the
147157** expression. It returns 1 if both of the following are true:
147158**
147159**   1. *pRc is SQLITE_OK when this function returns, and
147160**
147161**   2. After scanning the current FTS table row for the deferred tokens,
147162**      it is determined that the row does *not* match the query.
147163**
147164** Or, if no error occurs and it seems the current row does match the FTS
147165** query, return 0.
147166*/
147167SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
147168  int rc = *pRc;
147169  int bMiss = 0;
147170  if( rc==SQLITE_OK ){
147171
147172    /* If there are one or more deferred tokens, load the current row into
147173    ** memory and scan it to determine the position list for each deferred
147174    ** token. Then, see if this row is really a match, considering deferred
147175    ** tokens and NEAR operators (neither of which were taken into account
147176    ** earlier, by fts3EvalNextRow()).
147177    */
147178    if( pCsr->pDeferred ){
147179      rc = fts3CursorSeek(0, pCsr);
147180      if( rc==SQLITE_OK ){
147181        rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
147182      }
147183    }
147184    bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
147185
147186    /* Free the position-lists accumulated for each deferred token above. */
147187    sqlite3Fts3FreeDeferredDoclists(pCsr);
147188    *pRc = rc;
147189  }
147190  return (rc==SQLITE_OK && bMiss);
147191}
147192
147193/*
147194** Advance to the next document that matches the FTS expression in
147195** Fts3Cursor.pExpr.
147196*/
147197static int fts3EvalNext(Fts3Cursor *pCsr){
147198  int rc = SQLITE_OK;             /* Return Code */
147199  Fts3Expr *pExpr = pCsr->pExpr;
147200  assert( pCsr->isEof==0 );
147201  if( pExpr==0 ){
147202    pCsr->isEof = 1;
147203  }else{
147204    do {
147205      if( pCsr->isRequireSeek==0 ){
147206        sqlite3_reset(pCsr->pStmt);
147207      }
147208      assert( sqlite3_data_count(pCsr->pStmt)==0 );
147209      fts3EvalNextRow(pCsr, pExpr, &rc);
147210      pCsr->isEof = pExpr->bEof;
147211      pCsr->isRequireSeek = 1;
147212      pCsr->isMatchinfoNeeded = 1;
147213      pCsr->iPrevId = pExpr->iDocid;
147214    }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
147215  }
147216
147217  /* Check if the cursor is past the end of the docid range specified
147218  ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
147219  if( rc==SQLITE_OK && (
147220        (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
147221     || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
147222  )){
147223    pCsr->isEof = 1;
147224  }
147225
147226  return rc;
147227}
147228
147229/*
147230** Restart interation for expression pExpr so that the next call to
147231** fts3EvalNext() visits the first row. Do not allow incremental
147232** loading or merging of phrase doclists for this iteration.
147233**
147234** If *pRc is other than SQLITE_OK when this function is called, it is
147235** a no-op. If an error occurs within this function, *pRc is set to an
147236** SQLite error code before returning.
147237*/
147238static void fts3EvalRestart(
147239  Fts3Cursor *pCsr,
147240  Fts3Expr *pExpr,
147241  int *pRc
147242){
147243  if( pExpr && *pRc==SQLITE_OK ){
147244    Fts3Phrase *pPhrase = pExpr->pPhrase;
147245
147246    if( pPhrase ){
147247      fts3EvalInvalidatePoslist(pPhrase);
147248      if( pPhrase->bIncr ){
147249        int i;
147250        for(i=0; i<pPhrase->nToken; i++){
147251          Fts3PhraseToken *pToken = &pPhrase->aToken[i];
147252          assert( pToken->pDeferred==0 );
147253          if( pToken->pSegcsr ){
147254            sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
147255          }
147256        }
147257        *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
147258      }
147259      pPhrase->doclist.pNextDocid = 0;
147260      pPhrase->doclist.iDocid = 0;
147261      pPhrase->pOrPoslist = 0;
147262    }
147263
147264    pExpr->iDocid = 0;
147265    pExpr->bEof = 0;
147266    pExpr->bStart = 0;
147267
147268    fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
147269    fts3EvalRestart(pCsr, pExpr->pRight, pRc);
147270  }
147271}
147272
147273/*
147274** After allocating the Fts3Expr.aMI[] array for each phrase in the
147275** expression rooted at pExpr, the cursor iterates through all rows matched
147276** by pExpr, calling this function for each row. This function increments
147277** the values in Fts3Expr.aMI[] according to the position-list currently
147278** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
147279** expression nodes.
147280*/
147281static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
147282  if( pExpr ){
147283    Fts3Phrase *pPhrase = pExpr->pPhrase;
147284    if( pPhrase && pPhrase->doclist.pList ){
147285      int iCol = 0;
147286      char *p = pPhrase->doclist.pList;
147287
147288      assert( *p );
147289      while( 1 ){
147290        u8 c = 0;
147291        int iCnt = 0;
147292        while( 0xFE & (*p | c) ){
147293          if( (c&0x80)==0 ) iCnt++;
147294          c = *p++ & 0x80;
147295        }
147296
147297        /* aMI[iCol*3 + 1] = Number of occurrences
147298        ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
147299        */
147300        pExpr->aMI[iCol*3 + 1] += iCnt;
147301        pExpr->aMI[iCol*3 + 2] += (iCnt>0);
147302        if( *p==0x00 ) break;
147303        p++;
147304        p += fts3GetVarint32(p, &iCol);
147305      }
147306    }
147307
147308    fts3EvalUpdateCounts(pExpr->pLeft);
147309    fts3EvalUpdateCounts(pExpr->pRight);
147310  }
147311}
147312
147313/*
147314** Expression pExpr must be of type FTSQUERY_PHRASE.
147315**
147316** If it is not already allocated and populated, this function allocates and
147317** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
147318** of a NEAR expression, then it also allocates and populates the same array
147319** for all other phrases that are part of the NEAR expression.
147320**
147321** SQLITE_OK is returned if the aMI[] array is successfully allocated and
147322** populated. Otherwise, if an error occurs, an SQLite error code is returned.
147323*/
147324static int fts3EvalGatherStats(
147325  Fts3Cursor *pCsr,               /* Cursor object */
147326  Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
147327){
147328  int rc = SQLITE_OK;             /* Return code */
147329
147330  assert( pExpr->eType==FTSQUERY_PHRASE );
147331  if( pExpr->aMI==0 ){
147332    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147333    Fts3Expr *pRoot;                /* Root of NEAR expression */
147334    Fts3Expr *p;                    /* Iterator used for several purposes */
147335
147336    sqlite3_int64 iPrevId = pCsr->iPrevId;
147337    sqlite3_int64 iDocid;
147338    u8 bEof;
147339
147340    /* Find the root of the NEAR expression */
147341    pRoot = pExpr;
147342    while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
147343      pRoot = pRoot->pParent;
147344    }
147345    iDocid = pRoot->iDocid;
147346    bEof = pRoot->bEof;
147347    assert( pRoot->bStart );
147348
147349    /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
147350    for(p=pRoot; p; p=p->pLeft){
147351      Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
147352      assert( pE->aMI==0 );
147353      pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
147354      if( !pE->aMI ) return SQLITE_NOMEM;
147355      memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
147356    }
147357
147358    fts3EvalRestart(pCsr, pRoot, &rc);
147359
147360    while( pCsr->isEof==0 && rc==SQLITE_OK ){
147361
147362      do {
147363        /* Ensure the %_content statement is reset. */
147364        if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
147365        assert( sqlite3_data_count(pCsr->pStmt)==0 );
147366
147367        /* Advance to the next document */
147368        fts3EvalNextRow(pCsr, pRoot, &rc);
147369        pCsr->isEof = pRoot->bEof;
147370        pCsr->isRequireSeek = 1;
147371        pCsr->isMatchinfoNeeded = 1;
147372        pCsr->iPrevId = pRoot->iDocid;
147373      }while( pCsr->isEof==0
147374           && pRoot->eType==FTSQUERY_NEAR
147375           && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
147376      );
147377
147378      if( rc==SQLITE_OK && pCsr->isEof==0 ){
147379        fts3EvalUpdateCounts(pRoot);
147380      }
147381    }
147382
147383    pCsr->isEof = 0;
147384    pCsr->iPrevId = iPrevId;
147385
147386    if( bEof ){
147387      pRoot->bEof = bEof;
147388    }else{
147389      /* Caution: pRoot may iterate through docids in ascending or descending
147390      ** order. For this reason, even though it seems more defensive, the
147391      ** do loop can not be written:
147392      **
147393      **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
147394      */
147395      fts3EvalRestart(pCsr, pRoot, &rc);
147396      do {
147397        fts3EvalNextRow(pCsr, pRoot, &rc);
147398        assert( pRoot->bEof==0 );
147399      }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
147400    }
147401  }
147402  return rc;
147403}
147404
147405/*
147406** This function is used by the matchinfo() module to query a phrase
147407** expression node for the following information:
147408**
147409**   1. The total number of occurrences of the phrase in each column of
147410**      the FTS table (considering all rows), and
147411**
147412**   2. For each column, the number of rows in the table for which the
147413**      column contains at least one instance of the phrase.
147414**
147415** If no error occurs, SQLITE_OK is returned and the values for each column
147416** written into the array aiOut as follows:
147417**
147418**   aiOut[iCol*3 + 1] = Number of occurrences
147419**   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
147420**
147421** Caveats:
147422**
147423**   * If a phrase consists entirely of deferred tokens, then all output
147424**     values are set to the number of documents in the table. In other
147425**     words we assume that very common tokens occur exactly once in each
147426**     column of each row of the table.
147427**
147428**   * If a phrase contains some deferred tokens (and some non-deferred
147429**     tokens), count the potential occurrence identified by considering
147430**     the non-deferred tokens instead of actual phrase occurrences.
147431**
147432**   * If the phrase is part of a NEAR expression, then only phrase instances
147433**     that meet the NEAR constraint are included in the counts.
147434*/
147435SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
147436  Fts3Cursor *pCsr,               /* FTS cursor handle */
147437  Fts3Expr *pExpr,                /* Phrase expression */
147438  u32 *aiOut                      /* Array to write results into (see above) */
147439){
147440  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147441  int rc = SQLITE_OK;
147442  int iCol;
147443
147444  if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
147445    assert( pCsr->nDoc>0 );
147446    for(iCol=0; iCol<pTab->nColumn; iCol++){
147447      aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
147448      aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
147449    }
147450  }else{
147451    rc = fts3EvalGatherStats(pCsr, pExpr);
147452    if( rc==SQLITE_OK ){
147453      assert( pExpr->aMI );
147454      for(iCol=0; iCol<pTab->nColumn; iCol++){
147455        aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
147456        aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
147457      }
147458    }
147459  }
147460
147461  return rc;
147462}
147463
147464/*
147465** The expression pExpr passed as the second argument to this function
147466** must be of type FTSQUERY_PHRASE.
147467**
147468** The returned value is either NULL or a pointer to a buffer containing
147469** a position-list indicating the occurrences of the phrase in column iCol
147470** of the current row.
147471**
147472** More specifically, the returned buffer contains 1 varint for each
147473** occurrence of the phrase in the column, stored using the normal (delta+2)
147474** compression and is terminated by either an 0x01 or 0x00 byte. For example,
147475** if the requested column contains "a b X c d X X" and the position-list
147476** for 'X' is requested, the buffer returned may contain:
147477**
147478**     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
147479**
147480** This function works regardless of whether or not the phrase is deferred,
147481** incremental, or neither.
147482*/
147483SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
147484  Fts3Cursor *pCsr,               /* FTS3 cursor object */
147485  Fts3Expr *pExpr,                /* Phrase to return doclist for */
147486  int iCol,                       /* Column to return position list for */
147487  char **ppOut                    /* OUT: Pointer to position list */
147488){
147489  Fts3Phrase *pPhrase = pExpr->pPhrase;
147490  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147491  char *pIter;
147492  int iThis;
147493  sqlite3_int64 iDocid;
147494
147495  /* If this phrase is applies specifically to some column other than
147496  ** column iCol, return a NULL pointer.  */
147497  *ppOut = 0;
147498  assert( iCol>=0 && iCol<pTab->nColumn );
147499  if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
147500    return SQLITE_OK;
147501  }
147502
147503  iDocid = pExpr->iDocid;
147504  pIter = pPhrase->doclist.pList;
147505  if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
147506    int rc = SQLITE_OK;
147507    int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
147508    int bOr = 0;
147509    u8 bTreeEof = 0;
147510    Fts3Expr *p;                  /* Used to iterate from pExpr to root */
147511    Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
147512    int bMatch;
147513
147514    /* Check if this phrase descends from an OR expression node. If not,
147515    ** return NULL. Otherwise, the entry that corresponds to docid
147516    ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
147517    ** tree that the node is part of has been marked as EOF, but the node
147518    ** itself is not EOF, then it may point to an earlier entry. */
147519    pNear = pExpr;
147520    for(p=pExpr->pParent; p; p=p->pParent){
147521      if( p->eType==FTSQUERY_OR ) bOr = 1;
147522      if( p->eType==FTSQUERY_NEAR ) pNear = p;
147523      if( p->bEof ) bTreeEof = 1;
147524    }
147525    if( bOr==0 ) return SQLITE_OK;
147526
147527    /* This is the descendent of an OR node. In this case we cannot use
147528    ** an incremental phrase. Load the entire doclist for the phrase
147529    ** into memory in this case.  */
147530    if( pPhrase->bIncr ){
147531      int bEofSave = pNear->bEof;
147532      fts3EvalRestart(pCsr, pNear, &rc);
147533      while( rc==SQLITE_OK && !pNear->bEof ){
147534        fts3EvalNextRow(pCsr, pNear, &rc);
147535        if( bEofSave==0 && pNear->iDocid==iDocid ) break;
147536      }
147537      assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
147538    }
147539    if( bTreeEof ){
147540      while( rc==SQLITE_OK && !pNear->bEof ){
147541        fts3EvalNextRow(pCsr, pNear, &rc);
147542      }
147543    }
147544    if( rc!=SQLITE_OK ) return rc;
147545
147546    bMatch = 1;
147547    for(p=pNear; p; p=p->pLeft){
147548      u8 bEof = 0;
147549      Fts3Expr *pTest = p;
147550      Fts3Phrase *pPh;
147551      assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
147552      if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
147553      assert( pTest->eType==FTSQUERY_PHRASE );
147554      pPh = pTest->pPhrase;
147555
147556      pIter = pPh->pOrPoslist;
147557      iDocid = pPh->iOrDocid;
147558      if( pCsr->bDesc==bDescDoclist ){
147559        bEof = !pPh->doclist.nAll ||
147560          (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
147561        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
147562          sqlite3Fts3DoclistNext(
147563              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
147564              &pIter, &iDocid, &bEof
147565          );
147566        }
147567      }else{
147568        bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
147569        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
147570          int dummy;
147571          sqlite3Fts3DoclistPrev(
147572              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
147573              &pIter, &iDocid, &dummy, &bEof
147574              );
147575        }
147576      }
147577      pPh->pOrPoslist = pIter;
147578      pPh->iOrDocid = iDocid;
147579      if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
147580    }
147581
147582    if( bMatch ){
147583      pIter = pPhrase->pOrPoslist;
147584    }else{
147585      pIter = 0;
147586    }
147587  }
147588  if( pIter==0 ) return SQLITE_OK;
147589
147590  if( *pIter==0x01 ){
147591    pIter++;
147592    pIter += fts3GetVarint32(pIter, &iThis);
147593  }else{
147594    iThis = 0;
147595  }
147596  while( iThis<iCol ){
147597    fts3ColumnlistCopy(0, &pIter);
147598    if( *pIter==0x00 ) return SQLITE_OK;
147599    pIter++;
147600    pIter += fts3GetVarint32(pIter, &iThis);
147601  }
147602  if( *pIter==0x00 ){
147603    pIter = 0;
147604  }
147605
147606  *ppOut = ((iCol==iThis)?pIter:0);
147607  return SQLITE_OK;
147608}
147609
147610/*
147611** Free all components of the Fts3Phrase structure that were allocated by
147612** the eval module. Specifically, this means to free:
147613**
147614**   * the contents of pPhrase->doclist, and
147615**   * any Fts3MultiSegReader objects held by phrase tokens.
147616*/
147617SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
147618  if( pPhrase ){
147619    int i;
147620    sqlite3_free(pPhrase->doclist.aAll);
147621    fts3EvalInvalidatePoslist(pPhrase);
147622    memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
147623    for(i=0; i<pPhrase->nToken; i++){
147624      fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
147625      pPhrase->aToken[i].pSegcsr = 0;
147626    }
147627  }
147628}
147629
147630
147631/*
147632** Return SQLITE_CORRUPT_VTAB.
147633*/
147634#ifdef SQLITE_DEBUG
147635SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
147636  return SQLITE_CORRUPT_VTAB;
147637}
147638#endif
147639
147640#if !SQLITE_CORE
147641/*
147642** Initialize API pointer table, if required.
147643*/
147644#ifdef _WIN32
147645__declspec(dllexport)
147646#endif
147647SQLITE_API int SQLITE_STDCALL sqlite3_fts3_init(
147648  sqlite3 *db,
147649  char **pzErrMsg,
147650  const sqlite3_api_routines *pApi
147651){
147652  SQLITE_EXTENSION_INIT2(pApi)
147653  return sqlite3Fts3Init(db);
147654}
147655#endif
147656
147657#endif
147658
147659/************** End of fts3.c ************************************************/
147660/************** Begin file fts3_aux.c ****************************************/
147661/*
147662** 2011 Jan 27
147663**
147664** The author disclaims copyright to this source code.  In place of
147665** a legal notice, here is a blessing:
147666**
147667**    May you do good and not evil.
147668**    May you find forgiveness for yourself and forgive others.
147669**    May you share freely, never taking more than you give.
147670**
147671******************************************************************************
147672**
147673*/
147674/* #include "fts3Int.h" */
147675#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
147676
147677/* #include <string.h> */
147678/* #include <assert.h> */
147679
147680typedef struct Fts3auxTable Fts3auxTable;
147681typedef struct Fts3auxCursor Fts3auxCursor;
147682
147683struct Fts3auxTable {
147684  sqlite3_vtab base;              /* Base class used by SQLite core */
147685  Fts3Table *pFts3Tab;
147686};
147687
147688struct Fts3auxCursor {
147689  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
147690  Fts3MultiSegReader csr;        /* Must be right after "base" */
147691  Fts3SegFilter filter;
147692  char *zStop;
147693  int nStop;                      /* Byte-length of string zStop */
147694  int iLangid;                    /* Language id to query */
147695  int isEof;                      /* True if cursor is at EOF */
147696  sqlite3_int64 iRowid;           /* Current rowid */
147697
147698  int iCol;                       /* Current value of 'col' column */
147699  int nStat;                      /* Size of aStat[] array */
147700  struct Fts3auxColstats {
147701    sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
147702    sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
147703  } *aStat;
147704};
147705
147706/*
147707** Schema of the terms table.
147708*/
147709#define FTS3_AUX_SCHEMA \
147710  "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
147711
147712/*
147713** This function does all the work for both the xConnect and xCreate methods.
147714** These tables have no persistent representation of their own, so xConnect
147715** and xCreate are identical operations.
147716*/
147717static int fts3auxConnectMethod(
147718  sqlite3 *db,                    /* Database connection */
147719  void *pUnused,                  /* Unused */
147720  int argc,                       /* Number of elements in argv array */
147721  const char * const *argv,       /* xCreate/xConnect argument array */
147722  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
147723  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
147724){
147725  char const *zDb;                /* Name of database (e.g. "main") */
147726  char const *zFts3;              /* Name of fts3 table */
147727  int nDb;                        /* Result of strlen(zDb) */
147728  int nFts3;                      /* Result of strlen(zFts3) */
147729  int nByte;                      /* Bytes of space to allocate here */
147730  int rc;                         /* value returned by declare_vtab() */
147731  Fts3auxTable *p;                /* Virtual table object to return */
147732
147733  UNUSED_PARAMETER(pUnused);
147734
147735  /* The user should invoke this in one of two forms:
147736  **
147737  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
147738  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
147739  */
147740  if( argc!=4 && argc!=5 ) goto bad_args;
147741
147742  zDb = argv[1];
147743  nDb = (int)strlen(zDb);
147744  if( argc==5 ){
147745    if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
147746      zDb = argv[3];
147747      nDb = (int)strlen(zDb);
147748      zFts3 = argv[4];
147749    }else{
147750      goto bad_args;
147751    }
147752  }else{
147753    zFts3 = argv[3];
147754  }
147755  nFts3 = (int)strlen(zFts3);
147756
147757  rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
147758  if( rc!=SQLITE_OK ) return rc;
147759
147760  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
147761  p = (Fts3auxTable *)sqlite3_malloc(nByte);
147762  if( !p ) return SQLITE_NOMEM;
147763  memset(p, 0, nByte);
147764
147765  p->pFts3Tab = (Fts3Table *)&p[1];
147766  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
147767  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
147768  p->pFts3Tab->db = db;
147769  p->pFts3Tab->nIndex = 1;
147770
147771  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
147772  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
147773  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
147774
147775  *ppVtab = (sqlite3_vtab *)p;
147776  return SQLITE_OK;
147777
147778 bad_args:
147779  sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
147780  return SQLITE_ERROR;
147781}
147782
147783/*
147784** This function does the work for both the xDisconnect and xDestroy methods.
147785** These tables have no persistent representation of their own, so xDisconnect
147786** and xDestroy are identical operations.
147787*/
147788static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
147789  Fts3auxTable *p = (Fts3auxTable *)pVtab;
147790  Fts3Table *pFts3 = p->pFts3Tab;
147791  int i;
147792
147793  /* Free any prepared statements held */
147794  for(i=0; i<SizeofArray(pFts3->aStmt); i++){
147795    sqlite3_finalize(pFts3->aStmt[i]);
147796  }
147797  sqlite3_free(pFts3->zSegmentsTbl);
147798  sqlite3_free(p);
147799  return SQLITE_OK;
147800}
147801
147802#define FTS4AUX_EQ_CONSTRAINT 1
147803#define FTS4AUX_GE_CONSTRAINT 2
147804#define FTS4AUX_LE_CONSTRAINT 4
147805
147806/*
147807** xBestIndex - Analyze a WHERE and ORDER BY clause.
147808*/
147809static int fts3auxBestIndexMethod(
147810  sqlite3_vtab *pVTab,
147811  sqlite3_index_info *pInfo
147812){
147813  int i;
147814  int iEq = -1;
147815  int iGe = -1;
147816  int iLe = -1;
147817  int iLangid = -1;
147818  int iNext = 1;                  /* Next free argvIndex value */
147819
147820  UNUSED_PARAMETER(pVTab);
147821
147822  /* This vtab delivers always results in "ORDER BY term ASC" order. */
147823  if( pInfo->nOrderBy==1
147824   && pInfo->aOrderBy[0].iColumn==0
147825   && pInfo->aOrderBy[0].desc==0
147826  ){
147827    pInfo->orderByConsumed = 1;
147828  }
147829
147830  /* Search for equality and range constraints on the "term" column.
147831  ** And equality constraints on the hidden "languageid" column. */
147832  for(i=0; i<pInfo->nConstraint; i++){
147833    if( pInfo->aConstraint[i].usable ){
147834      int op = pInfo->aConstraint[i].op;
147835      int iCol = pInfo->aConstraint[i].iColumn;
147836
147837      if( iCol==0 ){
147838        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
147839        if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
147840        if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
147841        if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
147842        if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
147843      }
147844      if( iCol==4 ){
147845        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
147846      }
147847    }
147848  }
147849
147850  if( iEq>=0 ){
147851    pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
147852    pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
147853    pInfo->estimatedCost = 5;
147854  }else{
147855    pInfo->idxNum = 0;
147856    pInfo->estimatedCost = 20000;
147857    if( iGe>=0 ){
147858      pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
147859      pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
147860      pInfo->estimatedCost /= 2;
147861    }
147862    if( iLe>=0 ){
147863      pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
147864      pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
147865      pInfo->estimatedCost /= 2;
147866    }
147867  }
147868  if( iLangid>=0 ){
147869    pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
147870    pInfo->estimatedCost--;
147871  }
147872
147873  return SQLITE_OK;
147874}
147875
147876/*
147877** xOpen - Open a cursor.
147878*/
147879static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
147880  Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
147881
147882  UNUSED_PARAMETER(pVTab);
147883
147884  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
147885  if( !pCsr ) return SQLITE_NOMEM;
147886  memset(pCsr, 0, sizeof(Fts3auxCursor));
147887
147888  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
147889  return SQLITE_OK;
147890}
147891
147892/*
147893** xClose - Close a cursor.
147894*/
147895static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
147896  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
147897  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
147898
147899  sqlite3Fts3SegmentsClose(pFts3);
147900  sqlite3Fts3SegReaderFinish(&pCsr->csr);
147901  sqlite3_free((void *)pCsr->filter.zTerm);
147902  sqlite3_free(pCsr->zStop);
147903  sqlite3_free(pCsr->aStat);
147904  sqlite3_free(pCsr);
147905  return SQLITE_OK;
147906}
147907
147908static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
147909  if( nSize>pCsr->nStat ){
147910    struct Fts3auxColstats *aNew;
147911    aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
147912        sizeof(struct Fts3auxColstats) * nSize
147913    );
147914    if( aNew==0 ) return SQLITE_NOMEM;
147915    memset(&aNew[pCsr->nStat], 0,
147916        sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
147917    );
147918    pCsr->aStat = aNew;
147919    pCsr->nStat = nSize;
147920  }
147921  return SQLITE_OK;
147922}
147923
147924/*
147925** xNext - Advance the cursor to the next row, if any.
147926*/
147927static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
147928  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
147929  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
147930  int rc;
147931
147932  /* Increment our pretend rowid value. */
147933  pCsr->iRowid++;
147934
147935  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
147936    if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
147937  }
147938
147939  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
147940  if( rc==SQLITE_ROW ){
147941    int i = 0;
147942    int nDoclist = pCsr->csr.nDoclist;
147943    char *aDoclist = pCsr->csr.aDoclist;
147944    int iCol;
147945
147946    int eState = 0;
147947
147948    if( pCsr->zStop ){
147949      int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
147950      int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
147951      if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
147952        pCsr->isEof = 1;
147953        return SQLITE_OK;
147954      }
147955    }
147956
147957    if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
147958    memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
147959    iCol = 0;
147960
147961    while( i<nDoclist ){
147962      sqlite3_int64 v = 0;
147963
147964      i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
147965      switch( eState ){
147966        /* State 0. In this state the integer just read was a docid. */
147967        case 0:
147968          pCsr->aStat[0].nDoc++;
147969          eState = 1;
147970          iCol = 0;
147971          break;
147972
147973        /* State 1. In this state we are expecting either a 1, indicating
147974        ** that the following integer will be a column number, or the
147975        ** start of a position list for column 0.
147976        **
147977        ** The only difference between state 1 and state 2 is that if the
147978        ** integer encountered in state 1 is not 0 or 1, then we need to
147979        ** increment the column 0 "nDoc" count for this term.
147980        */
147981        case 1:
147982          assert( iCol==0 );
147983          if( v>1 ){
147984            pCsr->aStat[1].nDoc++;
147985          }
147986          eState = 2;
147987          /* fall through */
147988
147989        case 2:
147990          if( v==0 ){       /* 0x00. Next integer will be a docid. */
147991            eState = 0;
147992          }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
147993            eState = 3;
147994          }else{            /* 2 or greater. A position. */
147995            pCsr->aStat[iCol+1].nOcc++;
147996            pCsr->aStat[0].nOcc++;
147997          }
147998          break;
147999
148000        /* State 3. The integer just read is a column number. */
148001        default: assert( eState==3 );
148002          iCol = (int)v;
148003          if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
148004          pCsr->aStat[iCol+1].nDoc++;
148005          eState = 2;
148006          break;
148007      }
148008    }
148009
148010    pCsr->iCol = 0;
148011    rc = SQLITE_OK;
148012  }else{
148013    pCsr->isEof = 1;
148014  }
148015  return rc;
148016}
148017
148018/*
148019** xFilter - Initialize a cursor to point at the start of its data.
148020*/
148021static int fts3auxFilterMethod(
148022  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
148023  int idxNum,                     /* Strategy index */
148024  const char *idxStr,             /* Unused */
148025  int nVal,                       /* Number of elements in apVal */
148026  sqlite3_value **apVal           /* Arguments for the indexing scheme */
148027){
148028  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
148029  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
148030  int rc;
148031  int isScan = 0;
148032  int iLangVal = 0;               /* Language id to query */
148033
148034  int iEq = -1;                   /* Index of term=? value in apVal */
148035  int iGe = -1;                   /* Index of term>=? value in apVal */
148036  int iLe = -1;                   /* Index of term<=? value in apVal */
148037  int iLangid = -1;               /* Index of languageid=? value in apVal */
148038  int iNext = 0;
148039
148040  UNUSED_PARAMETER(nVal);
148041  UNUSED_PARAMETER(idxStr);
148042
148043  assert( idxStr==0 );
148044  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
148045       || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
148046       || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
148047  );
148048
148049  if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
148050    iEq = iNext++;
148051  }else{
148052    isScan = 1;
148053    if( idxNum & FTS4AUX_GE_CONSTRAINT ){
148054      iGe = iNext++;
148055    }
148056    if( idxNum & FTS4AUX_LE_CONSTRAINT ){
148057      iLe = iNext++;
148058    }
148059  }
148060  if( iNext<nVal ){
148061    iLangid = iNext++;
148062  }
148063
148064  /* In case this cursor is being reused, close and zero it. */
148065  testcase(pCsr->filter.zTerm);
148066  sqlite3Fts3SegReaderFinish(&pCsr->csr);
148067  sqlite3_free((void *)pCsr->filter.zTerm);
148068  sqlite3_free(pCsr->aStat);
148069  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
148070
148071  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
148072  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
148073
148074  if( iEq>=0 || iGe>=0 ){
148075    const unsigned char *zStr = sqlite3_value_text(apVal[0]);
148076    assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
148077    if( zStr ){
148078      pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
148079      pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
148080      if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
148081    }
148082  }
148083
148084  if( iLe>=0 ){
148085    pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
148086    pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
148087    if( pCsr->zStop==0 ) return SQLITE_NOMEM;
148088  }
148089
148090  if( iLangid>=0 ){
148091    iLangVal = sqlite3_value_int(apVal[iLangid]);
148092
148093    /* If the user specified a negative value for the languageid, use zero
148094    ** instead. This works, as the "languageid=?" constraint will also
148095    ** be tested by the VDBE layer. The test will always be false (since
148096    ** this module will not return a row with a negative languageid), and
148097    ** so the overall query will return zero rows.  */
148098    if( iLangVal<0 ) iLangVal = 0;
148099  }
148100  pCsr->iLangid = iLangVal;
148101
148102  rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
148103      pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
148104  );
148105  if( rc==SQLITE_OK ){
148106    rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
148107  }
148108
148109  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
148110  return rc;
148111}
148112
148113/*
148114** xEof - Return true if the cursor is at EOF, or false otherwise.
148115*/
148116static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
148117  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
148118  return pCsr->isEof;
148119}
148120
148121/*
148122** xColumn - Return a column value.
148123*/
148124static int fts3auxColumnMethod(
148125  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
148126  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
148127  int iCol                        /* Index of column to read value from */
148128){
148129  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
148130
148131  assert( p->isEof==0 );
148132  switch( iCol ){
148133    case 0: /* term */
148134      sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
148135      break;
148136
148137    case 1: /* col */
148138      if( p->iCol ){
148139        sqlite3_result_int(pCtx, p->iCol-1);
148140      }else{
148141        sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
148142      }
148143      break;
148144
148145    case 2: /* documents */
148146      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
148147      break;
148148
148149    case 3: /* occurrences */
148150      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
148151      break;
148152
148153    default: /* languageid */
148154      assert( iCol==4 );
148155      sqlite3_result_int(pCtx, p->iLangid);
148156      break;
148157  }
148158
148159  return SQLITE_OK;
148160}
148161
148162/*
148163** xRowid - Return the current rowid for the cursor.
148164*/
148165static int fts3auxRowidMethod(
148166  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
148167  sqlite_int64 *pRowid            /* OUT: Rowid value */
148168){
148169  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
148170  *pRowid = pCsr->iRowid;
148171  return SQLITE_OK;
148172}
148173
148174/*
148175** Register the fts3aux module with database connection db. Return SQLITE_OK
148176** if successful or an error code if sqlite3_create_module() fails.
148177*/
148178SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
148179  static const sqlite3_module fts3aux_module = {
148180     0,                           /* iVersion      */
148181     fts3auxConnectMethod,        /* xCreate       */
148182     fts3auxConnectMethod,        /* xConnect      */
148183     fts3auxBestIndexMethod,      /* xBestIndex    */
148184     fts3auxDisconnectMethod,     /* xDisconnect   */
148185     fts3auxDisconnectMethod,     /* xDestroy      */
148186     fts3auxOpenMethod,           /* xOpen         */
148187     fts3auxCloseMethod,          /* xClose        */
148188     fts3auxFilterMethod,         /* xFilter       */
148189     fts3auxNextMethod,           /* xNext         */
148190     fts3auxEofMethod,            /* xEof          */
148191     fts3auxColumnMethod,         /* xColumn       */
148192     fts3auxRowidMethod,          /* xRowid        */
148193     0,                           /* xUpdate       */
148194     0,                           /* xBegin        */
148195     0,                           /* xSync         */
148196     0,                           /* xCommit       */
148197     0,                           /* xRollback     */
148198     0,                           /* xFindFunction */
148199     0,                           /* xRename       */
148200     0,                           /* xSavepoint    */
148201     0,                           /* xRelease      */
148202     0                            /* xRollbackTo   */
148203  };
148204  int rc;                         /* Return code */
148205
148206  rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
148207  return rc;
148208}
148209
148210#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
148211
148212/************** End of fts3_aux.c ********************************************/
148213/************** Begin file fts3_expr.c ***************************************/
148214/*
148215** 2008 Nov 28
148216**
148217** The author disclaims copyright to this source code.  In place of
148218** a legal notice, here is a blessing:
148219**
148220**    May you do good and not evil.
148221**    May you find forgiveness for yourself and forgive others.
148222**    May you share freely, never taking more than you give.
148223**
148224******************************************************************************
148225**
148226** This module contains code that implements a parser for fts3 query strings
148227** (the right-hand argument to the MATCH operator). Because the supported
148228** syntax is relatively simple, the whole tokenizer/parser system is
148229** hand-coded.
148230*/
148231/* #include "fts3Int.h" */
148232#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
148233
148234/*
148235** By default, this module parses the legacy syntax that has been
148236** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
148237** is defined, then it uses the new syntax. The differences between
148238** the new and the old syntaxes are:
148239**
148240**  a) The new syntax supports parenthesis. The old does not.
148241**
148242**  b) The new syntax supports the AND and NOT operators. The old does not.
148243**
148244**  c) The old syntax supports the "-" token qualifier. This is not
148245**     supported by the new syntax (it is replaced by the NOT operator).
148246**
148247**  d) When using the old syntax, the OR operator has a greater precedence
148248**     than an implicit AND. When using the new, both implicity and explicit
148249**     AND operators have a higher precedence than OR.
148250**
148251** If compiled with SQLITE_TEST defined, then this module exports the
148252** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
148253** to zero causes the module to use the old syntax. If it is set to
148254** non-zero the new syntax is activated. This is so both syntaxes can
148255** be tested using a single build of testfixture.
148256**
148257** The following describes the syntax supported by the fts3 MATCH
148258** operator in a similar format to that used by the lemon parser
148259** generator. This module does not use actually lemon, it uses a
148260** custom parser.
148261**
148262**   query ::= andexpr (OR andexpr)*.
148263**
148264**   andexpr ::= notexpr (AND? notexpr)*.
148265**
148266**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
148267**   notexpr ::= LP query RP.
148268**
148269**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
148270**
148271**   distance_opt ::= .
148272**   distance_opt ::= / INTEGER.
148273**
148274**   phrase ::= TOKEN.
148275**   phrase ::= COLUMN:TOKEN.
148276**   phrase ::= "TOKEN TOKEN TOKEN...".
148277*/
148278
148279#ifdef SQLITE_TEST
148280SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
148281#else
148282# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
148283#  define sqlite3_fts3_enable_parentheses 1
148284# else
148285#  define sqlite3_fts3_enable_parentheses 0
148286# endif
148287#endif
148288
148289/*
148290** Default span for NEAR operators.
148291*/
148292#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
148293
148294/* #include <string.h> */
148295/* #include <assert.h> */
148296
148297/*
148298** isNot:
148299**   This variable is used by function getNextNode(). When getNextNode() is
148300**   called, it sets ParseContext.isNot to true if the 'next node' is a
148301**   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
148302**   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
148303**   zero.
148304*/
148305typedef struct ParseContext ParseContext;
148306struct ParseContext {
148307  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
148308  int iLangid;                        /* Language id used with tokenizer */
148309  const char **azCol;                 /* Array of column names for fts3 table */
148310  int bFts4;                          /* True to allow FTS4-only syntax */
148311  int nCol;                           /* Number of entries in azCol[] */
148312  int iDefaultCol;                    /* Default column to query */
148313  int isNot;                          /* True if getNextNode() sees a unary - */
148314  sqlite3_context *pCtx;              /* Write error message here */
148315  int nNest;                          /* Number of nested brackets */
148316};
148317
148318/*
148319** This function is equivalent to the standard isspace() function.
148320**
148321** The standard isspace() can be awkward to use safely, because although it
148322** is defined to accept an argument of type int, its behavior when passed
148323** an integer that falls outside of the range of the unsigned char type
148324** is undefined (and sometimes, "undefined" means segfault). This wrapper
148325** is defined to accept an argument of type char, and always returns 0 for
148326** any values that fall outside of the range of the unsigned char type (i.e.
148327** negative values).
148328*/
148329static int fts3isspace(char c){
148330  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
148331}
148332
148333/*
148334** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
148335** zero the memory before returning a pointer to it. If unsuccessful,
148336** return NULL.
148337*/
148338static void *fts3MallocZero(int nByte){
148339  void *pRet = sqlite3_malloc(nByte);
148340  if( pRet ) memset(pRet, 0, nByte);
148341  return pRet;
148342}
148343
148344SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
148345  sqlite3_tokenizer *pTokenizer,
148346  int iLangid,
148347  const char *z,
148348  int n,
148349  sqlite3_tokenizer_cursor **ppCsr
148350){
148351  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
148352  sqlite3_tokenizer_cursor *pCsr = 0;
148353  int rc;
148354
148355  rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
148356  assert( rc==SQLITE_OK || pCsr==0 );
148357  if( rc==SQLITE_OK ){
148358    pCsr->pTokenizer = pTokenizer;
148359    if( pModule->iVersion>=1 ){
148360      rc = pModule->xLanguageid(pCsr, iLangid);
148361      if( rc!=SQLITE_OK ){
148362        pModule->xClose(pCsr);
148363        pCsr = 0;
148364      }
148365    }
148366  }
148367  *ppCsr = pCsr;
148368  return rc;
148369}
148370
148371/*
148372** Function getNextNode(), which is called by fts3ExprParse(), may itself
148373** call fts3ExprParse(). So this forward declaration is required.
148374*/
148375static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
148376
148377/*
148378** Extract the next token from buffer z (length n) using the tokenizer
148379** and other information (column names etc.) in pParse. Create an Fts3Expr
148380** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
148381** single token and set *ppExpr to point to it. If the end of the buffer is
148382** reached before a token is found, set *ppExpr to zero. It is the
148383** responsibility of the caller to eventually deallocate the allocated
148384** Fts3Expr structure (if any) by passing it to sqlite3_free().
148385**
148386** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
148387** fails.
148388*/
148389static int getNextToken(
148390  ParseContext *pParse,                   /* fts3 query parse context */
148391  int iCol,                               /* Value for Fts3Phrase.iColumn */
148392  const char *z, int n,                   /* Input string */
148393  Fts3Expr **ppExpr,                      /* OUT: expression */
148394  int *pnConsumed                         /* OUT: Number of bytes consumed */
148395){
148396  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
148397  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
148398  int rc;
148399  sqlite3_tokenizer_cursor *pCursor;
148400  Fts3Expr *pRet = 0;
148401  int i = 0;
148402
148403  /* Set variable i to the maximum number of bytes of input to tokenize. */
148404  for(i=0; i<n; i++){
148405    if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
148406    if( z[i]=='"' ) break;
148407  }
148408
148409  *pnConsumed = i;
148410  rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
148411  if( rc==SQLITE_OK ){
148412    const char *zToken;
148413    int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
148414    int nByte;                               /* total space to allocate */
148415
148416    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
148417    if( rc==SQLITE_OK ){
148418      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
148419      pRet = (Fts3Expr *)fts3MallocZero(nByte);
148420      if( !pRet ){
148421        rc = SQLITE_NOMEM;
148422      }else{
148423        pRet->eType = FTSQUERY_PHRASE;
148424        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
148425        pRet->pPhrase->nToken = 1;
148426        pRet->pPhrase->iColumn = iCol;
148427        pRet->pPhrase->aToken[0].n = nToken;
148428        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
148429        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
148430
148431        if( iEnd<n && z[iEnd]=='*' ){
148432          pRet->pPhrase->aToken[0].isPrefix = 1;
148433          iEnd++;
148434        }
148435
148436        while( 1 ){
148437          if( !sqlite3_fts3_enable_parentheses
148438           && iStart>0 && z[iStart-1]=='-'
148439          ){
148440            pParse->isNot = 1;
148441            iStart--;
148442          }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
148443            pRet->pPhrase->aToken[0].bFirst = 1;
148444            iStart--;
148445          }else{
148446            break;
148447          }
148448        }
148449
148450      }
148451      *pnConsumed = iEnd;
148452    }else if( i && rc==SQLITE_DONE ){
148453      rc = SQLITE_OK;
148454    }
148455
148456    pModule->xClose(pCursor);
148457  }
148458
148459  *ppExpr = pRet;
148460  return rc;
148461}
148462
148463
148464/*
148465** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
148466** then free the old allocation.
148467*/
148468static void *fts3ReallocOrFree(void *pOrig, int nNew){
148469  void *pRet = sqlite3_realloc(pOrig, nNew);
148470  if( !pRet ){
148471    sqlite3_free(pOrig);
148472  }
148473  return pRet;
148474}
148475
148476/*
148477** Buffer zInput, length nInput, contains the contents of a quoted string
148478** that appeared as part of an fts3 query expression. Neither quote character
148479** is included in the buffer. This function attempts to tokenize the entire
148480** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
148481** containing the results.
148482**
148483** If successful, SQLITE_OK is returned and *ppExpr set to point at the
148484** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
148485** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
148486** to 0.
148487*/
148488static int getNextString(
148489  ParseContext *pParse,                   /* fts3 query parse context */
148490  const char *zInput, int nInput,         /* Input string */
148491  Fts3Expr **ppExpr                       /* OUT: expression */
148492){
148493  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
148494  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
148495  int rc;
148496  Fts3Expr *p = 0;
148497  sqlite3_tokenizer_cursor *pCursor = 0;
148498  char *zTemp = 0;
148499  int nTemp = 0;
148500
148501  const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
148502  int nToken = 0;
148503
148504  /* The final Fts3Expr data structure, including the Fts3Phrase,
148505  ** Fts3PhraseToken structures token buffers are all stored as a single
148506  ** allocation so that the expression can be freed with a single call to
148507  ** sqlite3_free(). Setting this up requires a two pass approach.
148508  **
148509  ** The first pass, in the block below, uses a tokenizer cursor to iterate
148510  ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
148511  ** to assemble data in two dynamic buffers:
148512  **
148513  **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
148514  **             structure, followed by the array of Fts3PhraseToken
148515  **             structures. This pass only populates the Fts3PhraseToken array.
148516  **
148517  **   Buffer zTemp: Contains copies of all tokens.
148518  **
148519  ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
148520  ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
148521  ** structures.
148522  */
148523  rc = sqlite3Fts3OpenTokenizer(
148524      pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
148525  if( rc==SQLITE_OK ){
148526    int ii;
148527    for(ii=0; rc==SQLITE_OK; ii++){
148528      const char *zByte;
148529      int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
148530      rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
148531      if( rc==SQLITE_OK ){
148532        Fts3PhraseToken *pToken;
148533
148534        p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
148535        if( !p ) goto no_mem;
148536
148537        zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
148538        if( !zTemp ) goto no_mem;
148539
148540        assert( nToken==ii );
148541        pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
148542        memset(pToken, 0, sizeof(Fts3PhraseToken));
148543
148544        memcpy(&zTemp[nTemp], zByte, nByte);
148545        nTemp += nByte;
148546
148547        pToken->n = nByte;
148548        pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
148549        pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
148550        nToken = ii+1;
148551      }
148552    }
148553
148554    pModule->xClose(pCursor);
148555    pCursor = 0;
148556  }
148557
148558  if( rc==SQLITE_DONE ){
148559    int jj;
148560    char *zBuf = 0;
148561
148562    p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
148563    if( !p ) goto no_mem;
148564    memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
148565    p->eType = FTSQUERY_PHRASE;
148566    p->pPhrase = (Fts3Phrase *)&p[1];
148567    p->pPhrase->iColumn = pParse->iDefaultCol;
148568    p->pPhrase->nToken = nToken;
148569
148570    zBuf = (char *)&p->pPhrase->aToken[nToken];
148571    if( zTemp ){
148572      memcpy(zBuf, zTemp, nTemp);
148573      sqlite3_free(zTemp);
148574    }else{
148575      assert( nTemp==0 );
148576    }
148577
148578    for(jj=0; jj<p->pPhrase->nToken; jj++){
148579      p->pPhrase->aToken[jj].z = zBuf;
148580      zBuf += p->pPhrase->aToken[jj].n;
148581    }
148582    rc = SQLITE_OK;
148583  }
148584
148585  *ppExpr = p;
148586  return rc;
148587no_mem:
148588
148589  if( pCursor ){
148590    pModule->xClose(pCursor);
148591  }
148592  sqlite3_free(zTemp);
148593  sqlite3_free(p);
148594  *ppExpr = 0;
148595  return SQLITE_NOMEM;
148596}
148597
148598/*
148599** The output variable *ppExpr is populated with an allocated Fts3Expr
148600** structure, or set to 0 if the end of the input buffer is reached.
148601**
148602** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
148603** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
148604** If SQLITE_ERROR is returned, pContext is populated with an error message.
148605*/
148606static int getNextNode(
148607  ParseContext *pParse,                   /* fts3 query parse context */
148608  const char *z, int n,                   /* Input string */
148609  Fts3Expr **ppExpr,                      /* OUT: expression */
148610  int *pnConsumed                         /* OUT: Number of bytes consumed */
148611){
148612  static const struct Fts3Keyword {
148613    char *z;                              /* Keyword text */
148614    unsigned char n;                      /* Length of the keyword */
148615    unsigned char parenOnly;              /* Only valid in paren mode */
148616    unsigned char eType;                  /* Keyword code */
148617  } aKeyword[] = {
148618    { "OR" ,  2, 0, FTSQUERY_OR   },
148619    { "AND",  3, 1, FTSQUERY_AND  },
148620    { "NOT",  3, 1, FTSQUERY_NOT  },
148621    { "NEAR", 4, 0, FTSQUERY_NEAR }
148622  };
148623  int ii;
148624  int iCol;
148625  int iColLen;
148626  int rc;
148627  Fts3Expr *pRet = 0;
148628
148629  const char *zInput = z;
148630  int nInput = n;
148631
148632  pParse->isNot = 0;
148633
148634  /* Skip over any whitespace before checking for a keyword, an open or
148635  ** close bracket, or a quoted string.
148636  */
148637  while( nInput>0 && fts3isspace(*zInput) ){
148638    nInput--;
148639    zInput++;
148640  }
148641  if( nInput==0 ){
148642    return SQLITE_DONE;
148643  }
148644
148645  /* See if we are dealing with a keyword. */
148646  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
148647    const struct Fts3Keyword *pKey = &aKeyword[ii];
148648
148649    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
148650      continue;
148651    }
148652
148653    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
148654      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
148655      int nKey = pKey->n;
148656      char cNext;
148657
148658      /* If this is a "NEAR" keyword, check for an explicit nearness. */
148659      if( pKey->eType==FTSQUERY_NEAR ){
148660        assert( nKey==4 );
148661        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
148662          nNear = 0;
148663          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
148664            nNear = nNear * 10 + (zInput[nKey] - '0');
148665          }
148666        }
148667      }
148668
148669      /* At this point this is probably a keyword. But for that to be true,
148670      ** the next byte must contain either whitespace, an open or close
148671      ** parenthesis, a quote character, or EOF.
148672      */
148673      cNext = zInput[nKey];
148674      if( fts3isspace(cNext)
148675       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
148676      ){
148677        pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
148678        if( !pRet ){
148679          return SQLITE_NOMEM;
148680        }
148681        pRet->eType = pKey->eType;
148682        pRet->nNear = nNear;
148683        *ppExpr = pRet;
148684        *pnConsumed = (int)((zInput - z) + nKey);
148685        return SQLITE_OK;
148686      }
148687
148688      /* Turns out that wasn't a keyword after all. This happens if the
148689      ** user has supplied a token such as "ORacle". Continue.
148690      */
148691    }
148692  }
148693
148694  /* See if we are dealing with a quoted phrase. If this is the case, then
148695  ** search for the closing quote and pass the whole string to getNextString()
148696  ** for processing. This is easy to do, as fts3 has no syntax for escaping
148697  ** a quote character embedded in a string.
148698  */
148699  if( *zInput=='"' ){
148700    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
148701    *pnConsumed = (int)((zInput - z) + ii + 1);
148702    if( ii==nInput ){
148703      return SQLITE_ERROR;
148704    }
148705    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
148706  }
148707
148708  if( sqlite3_fts3_enable_parentheses ){
148709    if( *zInput=='(' ){
148710      int nConsumed = 0;
148711      pParse->nNest++;
148712      rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
148713      if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
148714      *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
148715      return rc;
148716    }else if( *zInput==')' ){
148717      pParse->nNest--;
148718      *pnConsumed = (int)((zInput - z) + 1);
148719      *ppExpr = 0;
148720      return SQLITE_DONE;
148721    }
148722  }
148723
148724  /* If control flows to this point, this must be a regular token, or
148725  ** the end of the input. Read a regular token using the sqlite3_tokenizer
148726  ** interface. Before doing so, figure out if there is an explicit
148727  ** column specifier for the token.
148728  **
148729  ** TODO: Strangely, it is not possible to associate a column specifier
148730  ** with a quoted phrase, only with a single token. Not sure if this was
148731  ** an implementation artifact or an intentional decision when fts3 was
148732  ** first implemented. Whichever it was, this module duplicates the
148733  ** limitation.
148734  */
148735  iCol = pParse->iDefaultCol;
148736  iColLen = 0;
148737  for(ii=0; ii<pParse->nCol; ii++){
148738    const char *zStr = pParse->azCol[ii];
148739    int nStr = (int)strlen(zStr);
148740    if( nInput>nStr && zInput[nStr]==':'
148741     && sqlite3_strnicmp(zStr, zInput, nStr)==0
148742    ){
148743      iCol = ii;
148744      iColLen = (int)((zInput - z) + nStr + 1);
148745      break;
148746    }
148747  }
148748  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
148749  *pnConsumed += iColLen;
148750  return rc;
148751}
148752
148753/*
148754** The argument is an Fts3Expr structure for a binary operator (any type
148755** except an FTSQUERY_PHRASE). Return an integer value representing the
148756** precedence of the operator. Lower values have a higher precedence (i.e.
148757** group more tightly). For example, in the C language, the == operator
148758** groups more tightly than ||, and would therefore have a higher precedence.
148759**
148760** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
148761** is defined), the order of the operators in precedence from highest to
148762** lowest is:
148763**
148764**   NEAR
148765**   NOT
148766**   AND (including implicit ANDs)
148767**   OR
148768**
148769** Note that when using the old query syntax, the OR operator has a higher
148770** precedence than the AND operator.
148771*/
148772static int opPrecedence(Fts3Expr *p){
148773  assert( p->eType!=FTSQUERY_PHRASE );
148774  if( sqlite3_fts3_enable_parentheses ){
148775    return p->eType;
148776  }else if( p->eType==FTSQUERY_NEAR ){
148777    return 1;
148778  }else if( p->eType==FTSQUERY_OR ){
148779    return 2;
148780  }
148781  assert( p->eType==FTSQUERY_AND );
148782  return 3;
148783}
148784
148785/*
148786** Argument ppHead contains a pointer to the current head of a query
148787** expression tree being parsed. pPrev is the expression node most recently
148788** inserted into the tree. This function adds pNew, which is always a binary
148789** operator node, into the expression tree based on the relative precedence
148790** of pNew and the existing nodes of the tree. This may result in the head
148791** of the tree changing, in which case *ppHead is set to the new root node.
148792*/
148793static void insertBinaryOperator(
148794  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
148795  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
148796  Fts3Expr *pNew           /* New binary node to insert into expression tree */
148797){
148798  Fts3Expr *pSplit = pPrev;
148799  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
148800    pSplit = pSplit->pParent;
148801  }
148802
148803  if( pSplit->pParent ){
148804    assert( pSplit->pParent->pRight==pSplit );
148805    pSplit->pParent->pRight = pNew;
148806    pNew->pParent = pSplit->pParent;
148807  }else{
148808    *ppHead = pNew;
148809  }
148810  pNew->pLeft = pSplit;
148811  pSplit->pParent = pNew;
148812}
148813
148814/*
148815** Parse the fts3 query expression found in buffer z, length n. This function
148816** returns either when the end of the buffer is reached or an unmatched
148817** closing bracket - ')' - is encountered.
148818**
148819** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
148820** parsed form of the expression and *pnConsumed is set to the number of
148821** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
148822** (out of memory error) or SQLITE_ERROR (parse error) is returned.
148823*/
148824static int fts3ExprParse(
148825  ParseContext *pParse,                   /* fts3 query parse context */
148826  const char *z, int n,                   /* Text of MATCH query */
148827  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
148828  int *pnConsumed                         /* OUT: Number of bytes consumed */
148829){
148830  Fts3Expr *pRet = 0;
148831  Fts3Expr *pPrev = 0;
148832  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
148833  int nIn = n;
148834  const char *zIn = z;
148835  int rc = SQLITE_OK;
148836  int isRequirePhrase = 1;
148837
148838  while( rc==SQLITE_OK ){
148839    Fts3Expr *p = 0;
148840    int nByte = 0;
148841
148842    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
148843    assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
148844    if( rc==SQLITE_OK ){
148845      if( p ){
148846        int isPhrase;
148847
148848        if( !sqlite3_fts3_enable_parentheses
148849            && p->eType==FTSQUERY_PHRASE && pParse->isNot
148850        ){
148851          /* Create an implicit NOT operator. */
148852          Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
148853          if( !pNot ){
148854            sqlite3Fts3ExprFree(p);
148855            rc = SQLITE_NOMEM;
148856            goto exprparse_out;
148857          }
148858          pNot->eType = FTSQUERY_NOT;
148859          pNot->pRight = p;
148860          p->pParent = pNot;
148861          if( pNotBranch ){
148862            pNot->pLeft = pNotBranch;
148863            pNotBranch->pParent = pNot;
148864          }
148865          pNotBranch = pNot;
148866          p = pPrev;
148867        }else{
148868          int eType = p->eType;
148869          isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
148870
148871          /* The isRequirePhrase variable is set to true if a phrase or
148872          ** an expression contained in parenthesis is required. If a
148873          ** binary operator (AND, OR, NOT or NEAR) is encounted when
148874          ** isRequirePhrase is set, this is a syntax error.
148875          */
148876          if( !isPhrase && isRequirePhrase ){
148877            sqlite3Fts3ExprFree(p);
148878            rc = SQLITE_ERROR;
148879            goto exprparse_out;
148880          }
148881
148882          if( isPhrase && !isRequirePhrase ){
148883            /* Insert an implicit AND operator. */
148884            Fts3Expr *pAnd;
148885            assert( pRet && pPrev );
148886            pAnd = fts3MallocZero(sizeof(Fts3Expr));
148887            if( !pAnd ){
148888              sqlite3Fts3ExprFree(p);
148889              rc = SQLITE_NOMEM;
148890              goto exprparse_out;
148891            }
148892            pAnd->eType = FTSQUERY_AND;
148893            insertBinaryOperator(&pRet, pPrev, pAnd);
148894            pPrev = pAnd;
148895          }
148896
148897          /* This test catches attempts to make either operand of a NEAR
148898           ** operator something other than a phrase. For example, either of
148899           ** the following:
148900           **
148901           **    (bracketed expression) NEAR phrase
148902           **    phrase NEAR (bracketed expression)
148903           **
148904           ** Return an error in either case.
148905           */
148906          if( pPrev && (
148907            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
148908         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
148909          )){
148910            sqlite3Fts3ExprFree(p);
148911            rc = SQLITE_ERROR;
148912            goto exprparse_out;
148913          }
148914
148915          if( isPhrase ){
148916            if( pRet ){
148917              assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
148918              pPrev->pRight = p;
148919              p->pParent = pPrev;
148920            }else{
148921              pRet = p;
148922            }
148923          }else{
148924            insertBinaryOperator(&pRet, pPrev, p);
148925          }
148926          isRequirePhrase = !isPhrase;
148927        }
148928        pPrev = p;
148929      }
148930      assert( nByte>0 );
148931    }
148932    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
148933    nIn -= nByte;
148934    zIn += nByte;
148935  }
148936
148937  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
148938    rc = SQLITE_ERROR;
148939  }
148940
148941  if( rc==SQLITE_DONE ){
148942    rc = SQLITE_OK;
148943    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
148944      if( !pRet ){
148945        rc = SQLITE_ERROR;
148946      }else{
148947        Fts3Expr *pIter = pNotBranch;
148948        while( pIter->pLeft ){
148949          pIter = pIter->pLeft;
148950        }
148951        pIter->pLeft = pRet;
148952        pRet->pParent = pIter;
148953        pRet = pNotBranch;
148954      }
148955    }
148956  }
148957  *pnConsumed = n - nIn;
148958
148959exprparse_out:
148960  if( rc!=SQLITE_OK ){
148961    sqlite3Fts3ExprFree(pRet);
148962    sqlite3Fts3ExprFree(pNotBranch);
148963    pRet = 0;
148964  }
148965  *ppExpr = pRet;
148966  return rc;
148967}
148968
148969/*
148970** Return SQLITE_ERROR if the maximum depth of the expression tree passed
148971** as the only argument is more than nMaxDepth.
148972*/
148973static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
148974  int rc = SQLITE_OK;
148975  if( p ){
148976    if( nMaxDepth<0 ){
148977      rc = SQLITE_TOOBIG;
148978    }else{
148979      rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
148980      if( rc==SQLITE_OK ){
148981        rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
148982      }
148983    }
148984  }
148985  return rc;
148986}
148987
148988/*
148989** This function attempts to transform the expression tree at (*pp) to
148990** an equivalent but more balanced form. The tree is modified in place.
148991** If successful, SQLITE_OK is returned and (*pp) set to point to the
148992** new root expression node.
148993**
148994** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
148995**
148996** Otherwise, if an error occurs, an SQLite error code is returned and
148997** expression (*pp) freed.
148998*/
148999static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
149000  int rc = SQLITE_OK;             /* Return code */
149001  Fts3Expr *pRoot = *pp;          /* Initial root node */
149002  Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
149003  int eType = pRoot->eType;       /* Type of node in this tree */
149004
149005  if( nMaxDepth==0 ){
149006    rc = SQLITE_ERROR;
149007  }
149008
149009  if( rc==SQLITE_OK ){
149010    if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
149011      Fts3Expr **apLeaf;
149012      apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
149013      if( 0==apLeaf ){
149014        rc = SQLITE_NOMEM;
149015      }else{
149016        memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
149017      }
149018
149019      if( rc==SQLITE_OK ){
149020        int i;
149021        Fts3Expr *p;
149022
149023        /* Set $p to point to the left-most leaf in the tree of eType nodes. */
149024        for(p=pRoot; p->eType==eType; p=p->pLeft){
149025          assert( p->pParent==0 || p->pParent->pLeft==p );
149026          assert( p->pLeft && p->pRight );
149027        }
149028
149029        /* This loop runs once for each leaf in the tree of eType nodes. */
149030        while( 1 ){
149031          int iLvl;
149032          Fts3Expr *pParent = p->pParent;     /* Current parent of p */
149033
149034          assert( pParent==0 || pParent->pLeft==p );
149035          p->pParent = 0;
149036          if( pParent ){
149037            pParent->pLeft = 0;
149038          }else{
149039            pRoot = 0;
149040          }
149041          rc = fts3ExprBalance(&p, nMaxDepth-1);
149042          if( rc!=SQLITE_OK ) break;
149043
149044          for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
149045            if( apLeaf[iLvl]==0 ){
149046              apLeaf[iLvl] = p;
149047              p = 0;
149048            }else{
149049              assert( pFree );
149050              pFree->pLeft = apLeaf[iLvl];
149051              pFree->pRight = p;
149052              pFree->pLeft->pParent = pFree;
149053              pFree->pRight->pParent = pFree;
149054
149055              p = pFree;
149056              pFree = pFree->pParent;
149057              p->pParent = 0;
149058              apLeaf[iLvl] = 0;
149059            }
149060          }
149061          if( p ){
149062            sqlite3Fts3ExprFree(p);
149063            rc = SQLITE_TOOBIG;
149064            break;
149065          }
149066
149067          /* If that was the last leaf node, break out of the loop */
149068          if( pParent==0 ) break;
149069
149070          /* Set $p to point to the next leaf in the tree of eType nodes */
149071          for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
149072
149073          /* Remove pParent from the original tree. */
149074          assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
149075          pParent->pRight->pParent = pParent->pParent;
149076          if( pParent->pParent ){
149077            pParent->pParent->pLeft = pParent->pRight;
149078          }else{
149079            assert( pParent==pRoot );
149080            pRoot = pParent->pRight;
149081          }
149082
149083          /* Link pParent into the free node list. It will be used as an
149084          ** internal node of the new tree.  */
149085          pParent->pParent = pFree;
149086          pFree = pParent;
149087        }
149088
149089        if( rc==SQLITE_OK ){
149090          p = 0;
149091          for(i=0; i<nMaxDepth; i++){
149092            if( apLeaf[i] ){
149093              if( p==0 ){
149094                p = apLeaf[i];
149095                p->pParent = 0;
149096              }else{
149097                assert( pFree!=0 );
149098                pFree->pRight = p;
149099                pFree->pLeft = apLeaf[i];
149100                pFree->pLeft->pParent = pFree;
149101                pFree->pRight->pParent = pFree;
149102
149103                p = pFree;
149104                pFree = pFree->pParent;
149105                p->pParent = 0;
149106              }
149107            }
149108          }
149109          pRoot = p;
149110        }else{
149111          /* An error occurred. Delete the contents of the apLeaf[] array
149112          ** and pFree list. Everything else is cleaned up by the call to
149113          ** sqlite3Fts3ExprFree(pRoot) below.  */
149114          Fts3Expr *pDel;
149115          for(i=0; i<nMaxDepth; i++){
149116            sqlite3Fts3ExprFree(apLeaf[i]);
149117          }
149118          while( (pDel=pFree)!=0 ){
149119            pFree = pDel->pParent;
149120            sqlite3_free(pDel);
149121          }
149122        }
149123
149124        assert( pFree==0 );
149125        sqlite3_free( apLeaf );
149126      }
149127    }else if( eType==FTSQUERY_NOT ){
149128      Fts3Expr *pLeft = pRoot->pLeft;
149129      Fts3Expr *pRight = pRoot->pRight;
149130
149131      pRoot->pLeft = 0;
149132      pRoot->pRight = 0;
149133      pLeft->pParent = 0;
149134      pRight->pParent = 0;
149135
149136      rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
149137      if( rc==SQLITE_OK ){
149138        rc = fts3ExprBalance(&pRight, nMaxDepth-1);
149139      }
149140
149141      if( rc!=SQLITE_OK ){
149142        sqlite3Fts3ExprFree(pRight);
149143        sqlite3Fts3ExprFree(pLeft);
149144      }else{
149145        assert( pLeft && pRight );
149146        pRoot->pLeft = pLeft;
149147        pLeft->pParent = pRoot;
149148        pRoot->pRight = pRight;
149149        pRight->pParent = pRoot;
149150      }
149151    }
149152  }
149153
149154  if( rc!=SQLITE_OK ){
149155    sqlite3Fts3ExprFree(pRoot);
149156    pRoot = 0;
149157  }
149158  *pp = pRoot;
149159  return rc;
149160}
149161
149162/*
149163** This function is similar to sqlite3Fts3ExprParse(), with the following
149164** differences:
149165**
149166**   1. It does not do expression rebalancing.
149167**   2. It does not check that the expression does not exceed the
149168**      maximum allowable depth.
149169**   3. Even if it fails, *ppExpr may still be set to point to an
149170**      expression tree. It should be deleted using sqlite3Fts3ExprFree()
149171**      in this case.
149172*/
149173static int fts3ExprParseUnbalanced(
149174  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
149175  int iLangid,                        /* Language id for tokenizer */
149176  char **azCol,                       /* Array of column names for fts3 table */
149177  int bFts4,                          /* True to allow FTS4-only syntax */
149178  int nCol,                           /* Number of entries in azCol[] */
149179  int iDefaultCol,                    /* Default column to query */
149180  const char *z, int n,               /* Text of MATCH query */
149181  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
149182){
149183  int nParsed;
149184  int rc;
149185  ParseContext sParse;
149186
149187  memset(&sParse, 0, sizeof(ParseContext));
149188  sParse.pTokenizer = pTokenizer;
149189  sParse.iLangid = iLangid;
149190  sParse.azCol = (const char **)azCol;
149191  sParse.nCol = nCol;
149192  sParse.iDefaultCol = iDefaultCol;
149193  sParse.bFts4 = bFts4;
149194  if( z==0 ){
149195    *ppExpr = 0;
149196    return SQLITE_OK;
149197  }
149198  if( n<0 ){
149199    n = (int)strlen(z);
149200  }
149201  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
149202  assert( rc==SQLITE_OK || *ppExpr==0 );
149203
149204  /* Check for mismatched parenthesis */
149205  if( rc==SQLITE_OK && sParse.nNest ){
149206    rc = SQLITE_ERROR;
149207  }
149208
149209  return rc;
149210}
149211
149212/*
149213** Parameters z and n contain a pointer to and length of a buffer containing
149214** an fts3 query expression, respectively. This function attempts to parse the
149215** query expression and create a tree of Fts3Expr structures representing the
149216** parsed expression. If successful, *ppExpr is set to point to the head
149217** of the parsed expression tree and SQLITE_OK is returned. If an error
149218** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
149219** error) is returned and *ppExpr is set to 0.
149220**
149221** If parameter n is a negative number, then z is assumed to point to a
149222** nul-terminated string and the length is determined using strlen().
149223**
149224** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
149225** use to normalize query tokens while parsing the expression. The azCol[]
149226** array, which is assumed to contain nCol entries, should contain the names
149227** of each column in the target fts3 table, in order from left to right.
149228** Column names must be nul-terminated strings.
149229**
149230** The iDefaultCol parameter should be passed the index of the table column
149231** that appears on the left-hand-side of the MATCH operator (the default
149232** column to match against for tokens for which a column name is not explicitly
149233** specified as part of the query string), or -1 if tokens may by default
149234** match any table column.
149235*/
149236SQLITE_PRIVATE int sqlite3Fts3ExprParse(
149237  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
149238  int iLangid,                        /* Language id for tokenizer */
149239  char **azCol,                       /* Array of column names for fts3 table */
149240  int bFts4,                          /* True to allow FTS4-only syntax */
149241  int nCol,                           /* Number of entries in azCol[] */
149242  int iDefaultCol,                    /* Default column to query */
149243  const char *z, int n,               /* Text of MATCH query */
149244  Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
149245  char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
149246){
149247  int rc = fts3ExprParseUnbalanced(
149248      pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
149249  );
149250
149251  /* Rebalance the expression. And check that its depth does not exceed
149252  ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
149253  if( rc==SQLITE_OK && *ppExpr ){
149254    rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
149255    if( rc==SQLITE_OK ){
149256      rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
149257    }
149258  }
149259
149260  if( rc!=SQLITE_OK ){
149261    sqlite3Fts3ExprFree(*ppExpr);
149262    *ppExpr = 0;
149263    if( rc==SQLITE_TOOBIG ){
149264      sqlite3Fts3ErrMsg(pzErr,
149265          "FTS expression tree is too large (maximum depth %d)",
149266          SQLITE_FTS3_MAX_EXPR_DEPTH
149267      );
149268      rc = SQLITE_ERROR;
149269    }else if( rc==SQLITE_ERROR ){
149270      sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
149271    }
149272  }
149273
149274  return rc;
149275}
149276
149277/*
149278** Free a single node of an expression tree.
149279*/
149280static void fts3FreeExprNode(Fts3Expr *p){
149281  assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
149282  sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
149283  sqlite3_free(p->aMI);
149284  sqlite3_free(p);
149285}
149286
149287/*
149288** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
149289**
149290** This function would be simpler if it recursively called itself. But
149291** that would mean passing a sufficiently large expression to ExprParse()
149292** could cause a stack overflow.
149293*/
149294SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
149295  Fts3Expr *p;
149296  assert( pDel==0 || pDel->pParent==0 );
149297  for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
149298    assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
149299  }
149300  while( p ){
149301    Fts3Expr *pParent = p->pParent;
149302    fts3FreeExprNode(p);
149303    if( pParent && p==pParent->pLeft && pParent->pRight ){
149304      p = pParent->pRight;
149305      while( p && (p->pLeft || p->pRight) ){
149306        assert( p==p->pParent->pRight || p==p->pParent->pLeft );
149307        p = (p->pLeft ? p->pLeft : p->pRight);
149308      }
149309    }else{
149310      p = pParent;
149311    }
149312  }
149313}
149314
149315/****************************************************************************
149316*****************************************************************************
149317** Everything after this point is just test code.
149318*/
149319
149320#ifdef SQLITE_TEST
149321
149322/* #include <stdio.h> */
149323
149324/*
149325** Function to query the hash-table of tokenizers (see README.tokenizers).
149326*/
149327static int queryTestTokenizer(
149328  sqlite3 *db,
149329  const char *zName,
149330  const sqlite3_tokenizer_module **pp
149331){
149332  int rc;
149333  sqlite3_stmt *pStmt;
149334  const char zSql[] = "SELECT fts3_tokenizer(?)";
149335
149336  *pp = 0;
149337  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
149338  if( rc!=SQLITE_OK ){
149339    return rc;
149340  }
149341
149342  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
149343  if( SQLITE_ROW==sqlite3_step(pStmt) ){
149344    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
149345      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
149346    }
149347  }
149348
149349  return sqlite3_finalize(pStmt);
149350}
149351
149352/*
149353** Return a pointer to a buffer containing a text representation of the
149354** expression passed as the first argument. The buffer is obtained from
149355** sqlite3_malloc(). It is the responsibility of the caller to use
149356** sqlite3_free() to release the memory. If an OOM condition is encountered,
149357** NULL is returned.
149358**
149359** If the second argument is not NULL, then its contents are prepended to
149360** the returned expression text and then freed using sqlite3_free().
149361*/
149362static char *exprToString(Fts3Expr *pExpr, char *zBuf){
149363  if( pExpr==0 ){
149364    return sqlite3_mprintf("");
149365  }
149366  switch( pExpr->eType ){
149367    case FTSQUERY_PHRASE: {
149368      Fts3Phrase *pPhrase = pExpr->pPhrase;
149369      int i;
149370      zBuf = sqlite3_mprintf(
149371          "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
149372      for(i=0; zBuf && i<pPhrase->nToken; i++){
149373        zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
149374            pPhrase->aToken[i].n, pPhrase->aToken[i].z,
149375            (pPhrase->aToken[i].isPrefix?"+":"")
149376        );
149377      }
149378      return zBuf;
149379    }
149380
149381    case FTSQUERY_NEAR:
149382      zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
149383      break;
149384    case FTSQUERY_NOT:
149385      zBuf = sqlite3_mprintf("%zNOT ", zBuf);
149386      break;
149387    case FTSQUERY_AND:
149388      zBuf = sqlite3_mprintf("%zAND ", zBuf);
149389      break;
149390    case FTSQUERY_OR:
149391      zBuf = sqlite3_mprintf("%zOR ", zBuf);
149392      break;
149393  }
149394
149395  if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
149396  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
149397  if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
149398
149399  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
149400  if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
149401
149402  return zBuf;
149403}
149404
149405/*
149406** This is the implementation of a scalar SQL function used to test the
149407** expression parser. It should be called as follows:
149408**
149409**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
149410**
149411** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
149412** to parse the query expression (see README.tokenizers). The second argument
149413** is the query expression to parse. Each subsequent argument is the name
149414** of a column of the fts3 table that the query expression may refer to.
149415** For example:
149416**
149417**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
149418*/
149419static void fts3ExprTest(
149420  sqlite3_context *context,
149421  int argc,
149422  sqlite3_value **argv
149423){
149424  sqlite3_tokenizer_module const *pModule = 0;
149425  sqlite3_tokenizer *pTokenizer = 0;
149426  int rc;
149427  char **azCol = 0;
149428  const char *zExpr;
149429  int nExpr;
149430  int nCol;
149431  int ii;
149432  Fts3Expr *pExpr;
149433  char *zBuf = 0;
149434  sqlite3 *db = sqlite3_context_db_handle(context);
149435
149436  if( argc<3 ){
149437    sqlite3_result_error(context,
149438        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
149439    );
149440    return;
149441  }
149442
149443  rc = queryTestTokenizer(db,
149444                          (const char *)sqlite3_value_text(argv[0]), &pModule);
149445  if( rc==SQLITE_NOMEM ){
149446    sqlite3_result_error_nomem(context);
149447    goto exprtest_out;
149448  }else if( !pModule ){
149449    sqlite3_result_error(context, "No such tokenizer module", -1);
149450    goto exprtest_out;
149451  }
149452
149453  rc = pModule->xCreate(0, 0, &pTokenizer);
149454  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
149455  if( rc==SQLITE_NOMEM ){
149456    sqlite3_result_error_nomem(context);
149457    goto exprtest_out;
149458  }
149459  pTokenizer->pModule = pModule;
149460
149461  zExpr = (const char *)sqlite3_value_text(argv[1]);
149462  nExpr = sqlite3_value_bytes(argv[1]);
149463  nCol = argc-2;
149464  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
149465  if( !azCol ){
149466    sqlite3_result_error_nomem(context);
149467    goto exprtest_out;
149468  }
149469  for(ii=0; ii<nCol; ii++){
149470    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
149471  }
149472
149473  if( sqlite3_user_data(context) ){
149474    char *zDummy = 0;
149475    rc = sqlite3Fts3ExprParse(
149476        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
149477    );
149478    assert( rc==SQLITE_OK || pExpr==0 );
149479    sqlite3_free(zDummy);
149480  }else{
149481    rc = fts3ExprParseUnbalanced(
149482        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
149483    );
149484  }
149485
149486  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
149487    sqlite3Fts3ExprFree(pExpr);
149488    sqlite3_result_error(context, "Error parsing expression", -1);
149489  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
149490    sqlite3_result_error_nomem(context);
149491  }else{
149492    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
149493    sqlite3_free(zBuf);
149494  }
149495
149496  sqlite3Fts3ExprFree(pExpr);
149497
149498exprtest_out:
149499  if( pModule && pTokenizer ){
149500    rc = pModule->xDestroy(pTokenizer);
149501  }
149502  sqlite3_free(azCol);
149503}
149504
149505/*
149506** Register the query expression parser test function fts3_exprtest()
149507** with database connection db.
149508*/
149509SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
149510  int rc = sqlite3_create_function(
149511      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
149512  );
149513  if( rc==SQLITE_OK ){
149514    rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
149515        -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
149516    );
149517  }
149518  return rc;
149519}
149520
149521#endif
149522#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
149523
149524/************** End of fts3_expr.c *******************************************/
149525/************** Begin file fts3_hash.c ***************************************/
149526/*
149527** 2001 September 22
149528**
149529** The author disclaims copyright to this source code.  In place of
149530** a legal notice, here is a blessing:
149531**
149532**    May you do good and not evil.
149533**    May you find forgiveness for yourself and forgive others.
149534**    May you share freely, never taking more than you give.
149535**
149536*************************************************************************
149537** This is the implementation of generic hash-tables used in SQLite.
149538** We've modified it slightly to serve as a standalone hash table
149539** implementation for the full-text indexing module.
149540*/
149541
149542/*
149543** The code in this file is only compiled if:
149544**
149545**     * The FTS3 module is being built as an extension
149546**       (in which case SQLITE_CORE is not defined), or
149547**
149548**     * The FTS3 module is being built into the core of
149549**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
149550*/
149551/* #include "fts3Int.h" */
149552#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
149553
149554/* #include <assert.h> */
149555/* #include <stdlib.h> */
149556/* #include <string.h> */
149557
149558/* #include "fts3_hash.h" */
149559
149560/*
149561** Malloc and Free functions
149562*/
149563static void *fts3HashMalloc(int n){
149564  void *p = sqlite3_malloc(n);
149565  if( p ){
149566    memset(p, 0, n);
149567  }
149568  return p;
149569}
149570static void fts3HashFree(void *p){
149571  sqlite3_free(p);
149572}
149573
149574/* Turn bulk memory into a hash table object by initializing the
149575** fields of the Hash structure.
149576**
149577** "pNew" is a pointer to the hash table that is to be initialized.
149578** keyClass is one of the constants
149579** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
149580** determines what kind of key the hash table will use.  "copyKey" is
149581** true if the hash table should make its own private copy of keys and
149582** false if it should just use the supplied pointer.
149583*/
149584SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
149585  assert( pNew!=0 );
149586  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
149587  pNew->keyClass = keyClass;
149588  pNew->copyKey = copyKey;
149589  pNew->first = 0;
149590  pNew->count = 0;
149591  pNew->htsize = 0;
149592  pNew->ht = 0;
149593}
149594
149595/* Remove all entries from a hash table.  Reclaim all memory.
149596** Call this routine to delete a hash table or to reset a hash table
149597** to the empty state.
149598*/
149599SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
149600  Fts3HashElem *elem;         /* For looping over all elements of the table */
149601
149602  assert( pH!=0 );
149603  elem = pH->first;
149604  pH->first = 0;
149605  fts3HashFree(pH->ht);
149606  pH->ht = 0;
149607  pH->htsize = 0;
149608  while( elem ){
149609    Fts3HashElem *next_elem = elem->next;
149610    if( pH->copyKey && elem->pKey ){
149611      fts3HashFree(elem->pKey);
149612    }
149613    fts3HashFree(elem);
149614    elem = next_elem;
149615  }
149616  pH->count = 0;
149617}
149618
149619/*
149620** Hash and comparison functions when the mode is FTS3_HASH_STRING
149621*/
149622static int fts3StrHash(const void *pKey, int nKey){
149623  const char *z = (const char *)pKey;
149624  unsigned h = 0;
149625  if( nKey<=0 ) nKey = (int) strlen(z);
149626  while( nKey > 0  ){
149627    h = (h<<3) ^ h ^ *z++;
149628    nKey--;
149629  }
149630  return (int)(h & 0x7fffffff);
149631}
149632static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
149633  if( n1!=n2 ) return 1;
149634  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
149635}
149636
149637/*
149638** Hash and comparison functions when the mode is FTS3_HASH_BINARY
149639*/
149640static int fts3BinHash(const void *pKey, int nKey){
149641  int h = 0;
149642  const char *z = (const char *)pKey;
149643  while( nKey-- > 0 ){
149644    h = (h<<3) ^ h ^ *(z++);
149645  }
149646  return h & 0x7fffffff;
149647}
149648static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
149649  if( n1!=n2 ) return 1;
149650  return memcmp(pKey1,pKey2,n1);
149651}
149652
149653/*
149654** Return a pointer to the appropriate hash function given the key class.
149655**
149656** The C syntax in this function definition may be unfamilar to some
149657** programmers, so we provide the following additional explanation:
149658**
149659** The name of the function is "ftsHashFunction".  The function takes a
149660** single parameter "keyClass".  The return value of ftsHashFunction()
149661** is a pointer to another function.  Specifically, the return value
149662** of ftsHashFunction() is a pointer to a function that takes two parameters
149663** with types "const void*" and "int" and returns an "int".
149664*/
149665static int (*ftsHashFunction(int keyClass))(const void*,int){
149666  if( keyClass==FTS3_HASH_STRING ){
149667    return &fts3StrHash;
149668  }else{
149669    assert( keyClass==FTS3_HASH_BINARY );
149670    return &fts3BinHash;
149671  }
149672}
149673
149674/*
149675** Return a pointer to the appropriate hash function given the key class.
149676**
149677** For help in interpreted the obscure C code in the function definition,
149678** see the header comment on the previous function.
149679*/
149680static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
149681  if( keyClass==FTS3_HASH_STRING ){
149682    return &fts3StrCompare;
149683  }else{
149684    assert( keyClass==FTS3_HASH_BINARY );
149685    return &fts3BinCompare;
149686  }
149687}
149688
149689/* Link an element into the hash table
149690*/
149691static void fts3HashInsertElement(
149692  Fts3Hash *pH,            /* The complete hash table */
149693  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
149694  Fts3HashElem *pNew       /* The element to be inserted */
149695){
149696  Fts3HashElem *pHead;     /* First element already in pEntry */
149697  pHead = pEntry->chain;
149698  if( pHead ){
149699    pNew->next = pHead;
149700    pNew->prev = pHead->prev;
149701    if( pHead->prev ){ pHead->prev->next = pNew; }
149702    else             { pH->first = pNew; }
149703    pHead->prev = pNew;
149704  }else{
149705    pNew->next = pH->first;
149706    if( pH->first ){ pH->first->prev = pNew; }
149707    pNew->prev = 0;
149708    pH->first = pNew;
149709  }
149710  pEntry->count++;
149711  pEntry->chain = pNew;
149712}
149713
149714
149715/* Resize the hash table so that it cantains "new_size" buckets.
149716** "new_size" must be a power of 2.  The hash table might fail
149717** to resize if sqliteMalloc() fails.
149718**
149719** Return non-zero if a memory allocation error occurs.
149720*/
149721static int fts3Rehash(Fts3Hash *pH, int new_size){
149722  struct _fts3ht *new_ht;          /* The new hash table */
149723  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
149724  int (*xHash)(const void*,int);   /* The hash function */
149725
149726  assert( (new_size & (new_size-1))==0 );
149727  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
149728  if( new_ht==0 ) return 1;
149729  fts3HashFree(pH->ht);
149730  pH->ht = new_ht;
149731  pH->htsize = new_size;
149732  xHash = ftsHashFunction(pH->keyClass);
149733  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
149734    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
149735    next_elem = elem->next;
149736    fts3HashInsertElement(pH, &new_ht[h], elem);
149737  }
149738  return 0;
149739}
149740
149741/* This function (for internal use only) locates an element in an
149742** hash table that matches the given key.  The hash for this key has
149743** already been computed and is passed as the 4th parameter.
149744*/
149745static Fts3HashElem *fts3FindElementByHash(
149746  const Fts3Hash *pH, /* The pH to be searched */
149747  const void *pKey,   /* The key we are searching for */
149748  int nKey,
149749  int h               /* The hash for this key. */
149750){
149751  Fts3HashElem *elem;            /* Used to loop thru the element list */
149752  int count;                     /* Number of elements left to test */
149753  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
149754
149755  if( pH->ht ){
149756    struct _fts3ht *pEntry = &pH->ht[h];
149757    elem = pEntry->chain;
149758    count = pEntry->count;
149759    xCompare = ftsCompareFunction(pH->keyClass);
149760    while( count-- && elem ){
149761      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
149762        return elem;
149763      }
149764      elem = elem->next;
149765    }
149766  }
149767  return 0;
149768}
149769
149770/* Remove a single entry from the hash table given a pointer to that
149771** element and a hash on the element's key.
149772*/
149773static void fts3RemoveElementByHash(
149774  Fts3Hash *pH,         /* The pH containing "elem" */
149775  Fts3HashElem* elem,   /* The element to be removed from the pH */
149776  int h                 /* Hash value for the element */
149777){
149778  struct _fts3ht *pEntry;
149779  if( elem->prev ){
149780    elem->prev->next = elem->next;
149781  }else{
149782    pH->first = elem->next;
149783  }
149784  if( elem->next ){
149785    elem->next->prev = elem->prev;
149786  }
149787  pEntry = &pH->ht[h];
149788  if( pEntry->chain==elem ){
149789    pEntry->chain = elem->next;
149790  }
149791  pEntry->count--;
149792  if( pEntry->count<=0 ){
149793    pEntry->chain = 0;
149794  }
149795  if( pH->copyKey && elem->pKey ){
149796    fts3HashFree(elem->pKey);
149797  }
149798  fts3HashFree( elem );
149799  pH->count--;
149800  if( pH->count<=0 ){
149801    assert( pH->first==0 );
149802    assert( pH->count==0 );
149803    fts3HashClear(pH);
149804  }
149805}
149806
149807SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
149808  const Fts3Hash *pH,
149809  const void *pKey,
149810  int nKey
149811){
149812  int h;                          /* A hash on key */
149813  int (*xHash)(const void*,int);  /* The hash function */
149814
149815  if( pH==0 || pH->ht==0 ) return 0;
149816  xHash = ftsHashFunction(pH->keyClass);
149817  assert( xHash!=0 );
149818  h = (*xHash)(pKey,nKey);
149819  assert( (pH->htsize & (pH->htsize-1))==0 );
149820  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
149821}
149822
149823/*
149824** Attempt to locate an element of the hash table pH with a key
149825** that matches pKey,nKey.  Return the data for this element if it is
149826** found, or NULL if there is no match.
149827*/
149828SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
149829  Fts3HashElem *pElem;            /* The element that matches key (if any) */
149830
149831  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
149832  return pElem ? pElem->data : 0;
149833}
149834
149835/* Insert an element into the hash table pH.  The key is pKey,nKey
149836** and the data is "data".
149837**
149838** If no element exists with a matching key, then a new
149839** element is created.  A copy of the key is made if the copyKey
149840** flag is set.  NULL is returned.
149841**
149842** If another element already exists with the same key, then the
149843** new data replaces the old data and the old data is returned.
149844** The key is not copied in this instance.  If a malloc fails, then
149845** the new data is returned and the hash table is unchanged.
149846**
149847** If the "data" parameter to this function is NULL, then the
149848** element corresponding to "key" is removed from the hash table.
149849*/
149850SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
149851  Fts3Hash *pH,        /* The hash table to insert into */
149852  const void *pKey,    /* The key */
149853  int nKey,            /* Number of bytes in the key */
149854  void *data           /* The data */
149855){
149856  int hraw;                 /* Raw hash value of the key */
149857  int h;                    /* the hash of the key modulo hash table size */
149858  Fts3HashElem *elem;       /* Used to loop thru the element list */
149859  Fts3HashElem *new_elem;   /* New element added to the pH */
149860  int (*xHash)(const void*,int);  /* The hash function */
149861
149862  assert( pH!=0 );
149863  xHash = ftsHashFunction(pH->keyClass);
149864  assert( xHash!=0 );
149865  hraw = (*xHash)(pKey, nKey);
149866  assert( (pH->htsize & (pH->htsize-1))==0 );
149867  h = hraw & (pH->htsize-1);
149868  elem = fts3FindElementByHash(pH,pKey,nKey,h);
149869  if( elem ){
149870    void *old_data = elem->data;
149871    if( data==0 ){
149872      fts3RemoveElementByHash(pH,elem,h);
149873    }else{
149874      elem->data = data;
149875    }
149876    return old_data;
149877  }
149878  if( data==0 ) return 0;
149879  if( (pH->htsize==0 && fts3Rehash(pH,8))
149880   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
149881  ){
149882    pH->count = 0;
149883    return data;
149884  }
149885  assert( pH->htsize>0 );
149886  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
149887  if( new_elem==0 ) return data;
149888  if( pH->copyKey && pKey!=0 ){
149889    new_elem->pKey = fts3HashMalloc( nKey );
149890    if( new_elem->pKey==0 ){
149891      fts3HashFree(new_elem);
149892      return data;
149893    }
149894    memcpy((void*)new_elem->pKey, pKey, nKey);
149895  }else{
149896    new_elem->pKey = (void*)pKey;
149897  }
149898  new_elem->nKey = nKey;
149899  pH->count++;
149900  assert( pH->htsize>0 );
149901  assert( (pH->htsize & (pH->htsize-1))==0 );
149902  h = hraw & (pH->htsize-1);
149903  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
149904  new_elem->data = data;
149905  return 0;
149906}
149907
149908#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
149909
149910/************** End of fts3_hash.c *******************************************/
149911/************** Begin file fts3_porter.c *************************************/
149912/*
149913** 2006 September 30
149914**
149915** The author disclaims copyright to this source code.  In place of
149916** a legal notice, here is a blessing:
149917**
149918**    May you do good and not evil.
149919**    May you find forgiveness for yourself and forgive others.
149920**    May you share freely, never taking more than you give.
149921**
149922*************************************************************************
149923** Implementation of the full-text-search tokenizer that implements
149924** a Porter stemmer.
149925*/
149926
149927/*
149928** The code in this file is only compiled if:
149929**
149930**     * The FTS3 module is being built as an extension
149931**       (in which case SQLITE_CORE is not defined), or
149932**
149933**     * The FTS3 module is being built into the core of
149934**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
149935*/
149936/* #include "fts3Int.h" */
149937#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
149938
149939/* #include <assert.h> */
149940/* #include <stdlib.h> */
149941/* #include <stdio.h> */
149942/* #include <string.h> */
149943
149944/* #include "fts3_tokenizer.h" */
149945
149946/*
149947** Class derived from sqlite3_tokenizer
149948*/
149949typedef struct porter_tokenizer {
149950  sqlite3_tokenizer base;      /* Base class */
149951} porter_tokenizer;
149952
149953/*
149954** Class derived from sqlite3_tokenizer_cursor
149955*/
149956typedef struct porter_tokenizer_cursor {
149957  sqlite3_tokenizer_cursor base;
149958  const char *zInput;          /* input we are tokenizing */
149959  int nInput;                  /* size of the input */
149960  int iOffset;                 /* current position in zInput */
149961  int iToken;                  /* index of next token to be returned */
149962  char *zToken;                /* storage for current token */
149963  int nAllocated;              /* space allocated to zToken buffer */
149964} porter_tokenizer_cursor;
149965
149966
149967/*
149968** Create a new tokenizer instance.
149969*/
149970static int porterCreate(
149971  int argc, const char * const *argv,
149972  sqlite3_tokenizer **ppTokenizer
149973){
149974  porter_tokenizer *t;
149975
149976  UNUSED_PARAMETER(argc);
149977  UNUSED_PARAMETER(argv);
149978
149979  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
149980  if( t==NULL ) return SQLITE_NOMEM;
149981  memset(t, 0, sizeof(*t));
149982  *ppTokenizer = &t->base;
149983  return SQLITE_OK;
149984}
149985
149986/*
149987** Destroy a tokenizer
149988*/
149989static int porterDestroy(sqlite3_tokenizer *pTokenizer){
149990  sqlite3_free(pTokenizer);
149991  return SQLITE_OK;
149992}
149993
149994/*
149995** Prepare to begin tokenizing a particular string.  The input
149996** string to be tokenized is zInput[0..nInput-1].  A cursor
149997** used to incrementally tokenize this string is returned in
149998** *ppCursor.
149999*/
150000static int porterOpen(
150001  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
150002  const char *zInput, int nInput,        /* String to be tokenized */
150003  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
150004){
150005  porter_tokenizer_cursor *c;
150006
150007  UNUSED_PARAMETER(pTokenizer);
150008
150009  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
150010  if( c==NULL ) return SQLITE_NOMEM;
150011
150012  c->zInput = zInput;
150013  if( zInput==0 ){
150014    c->nInput = 0;
150015  }else if( nInput<0 ){
150016    c->nInput = (int)strlen(zInput);
150017  }else{
150018    c->nInput = nInput;
150019  }
150020  c->iOffset = 0;                 /* start tokenizing at the beginning */
150021  c->iToken = 0;
150022  c->zToken = NULL;               /* no space allocated, yet. */
150023  c->nAllocated = 0;
150024
150025  *ppCursor = &c->base;
150026  return SQLITE_OK;
150027}
150028
150029/*
150030** Close a tokenization cursor previously opened by a call to
150031** porterOpen() above.
150032*/
150033static int porterClose(sqlite3_tokenizer_cursor *pCursor){
150034  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
150035  sqlite3_free(c->zToken);
150036  sqlite3_free(c);
150037  return SQLITE_OK;
150038}
150039/*
150040** Vowel or consonant
150041*/
150042static const char cType[] = {
150043   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
150044   1, 1, 1, 2, 1
150045};
150046
150047/*
150048** isConsonant() and isVowel() determine if their first character in
150049** the string they point to is a consonant or a vowel, according
150050** to Porter ruls.
150051**
150052** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
150053** 'Y' is a consonant unless it follows another consonant,
150054** in which case it is a vowel.
150055**
150056** In these routine, the letters are in reverse order.  So the 'y' rule
150057** is that 'y' is a consonant unless it is followed by another
150058** consonent.
150059*/
150060static int isVowel(const char*);
150061static int isConsonant(const char *z){
150062  int j;
150063  char x = *z;
150064  if( x==0 ) return 0;
150065  assert( x>='a' && x<='z' );
150066  j = cType[x-'a'];
150067  if( j<2 ) return j;
150068  return z[1]==0 || isVowel(z + 1);
150069}
150070static int isVowel(const char *z){
150071  int j;
150072  char x = *z;
150073  if( x==0 ) return 0;
150074  assert( x>='a' && x<='z' );
150075  j = cType[x-'a'];
150076  if( j<2 ) return 1-j;
150077  return isConsonant(z + 1);
150078}
150079
150080/*
150081** Let any sequence of one or more vowels be represented by V and let
150082** C be sequence of one or more consonants.  Then every word can be
150083** represented as:
150084**
150085**           [C] (VC){m} [V]
150086**
150087** In prose:  A word is an optional consonant followed by zero or
150088** vowel-consonant pairs followed by an optional vowel.  "m" is the
150089** number of vowel consonant pairs.  This routine computes the value
150090** of m for the first i bytes of a word.
150091**
150092** Return true if the m-value for z is 1 or more.  In other words,
150093** return true if z contains at least one vowel that is followed
150094** by a consonant.
150095**
150096** In this routine z[] is in reverse order.  So we are really looking
150097** for an instance of a consonant followed by a vowel.
150098*/
150099static int m_gt_0(const char *z){
150100  while( isVowel(z) ){ z++; }
150101  if( *z==0 ) return 0;
150102  while( isConsonant(z) ){ z++; }
150103  return *z!=0;
150104}
150105
150106/* Like mgt0 above except we are looking for a value of m which is
150107** exactly 1
150108*/
150109static int m_eq_1(const char *z){
150110  while( isVowel(z) ){ z++; }
150111  if( *z==0 ) return 0;
150112  while( isConsonant(z) ){ z++; }
150113  if( *z==0 ) return 0;
150114  while( isVowel(z) ){ z++; }
150115  if( *z==0 ) return 1;
150116  while( isConsonant(z) ){ z++; }
150117  return *z==0;
150118}
150119
150120/* Like mgt0 above except we are looking for a value of m>1 instead
150121** or m>0
150122*/
150123static int m_gt_1(const char *z){
150124  while( isVowel(z) ){ z++; }
150125  if( *z==0 ) return 0;
150126  while( isConsonant(z) ){ z++; }
150127  if( *z==0 ) return 0;
150128  while( isVowel(z) ){ z++; }
150129  if( *z==0 ) return 0;
150130  while( isConsonant(z) ){ z++; }
150131  return *z!=0;
150132}
150133
150134/*
150135** Return TRUE if there is a vowel anywhere within z[0..n-1]
150136*/
150137static int hasVowel(const char *z){
150138  while( isConsonant(z) ){ z++; }
150139  return *z!=0;
150140}
150141
150142/*
150143** Return TRUE if the word ends in a double consonant.
150144**
150145** The text is reversed here. So we are really looking at
150146** the first two characters of z[].
150147*/
150148static int doubleConsonant(const char *z){
150149  return isConsonant(z) && z[0]==z[1];
150150}
150151
150152/*
150153** Return TRUE if the word ends with three letters which
150154** are consonant-vowel-consonent and where the final consonant
150155** is not 'w', 'x', or 'y'.
150156**
150157** The word is reversed here.  So we are really checking the
150158** first three letters and the first one cannot be in [wxy].
150159*/
150160static int star_oh(const char *z){
150161  return
150162    isConsonant(z) &&
150163    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
150164    isVowel(z+1) &&
150165    isConsonant(z+2);
150166}
150167
150168/*
150169** If the word ends with zFrom and xCond() is true for the stem
150170** of the word that preceeds the zFrom ending, then change the
150171** ending to zTo.
150172**
150173** The input word *pz and zFrom are both in reverse order.  zTo
150174** is in normal order.
150175**
150176** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
150177** match.  Not that TRUE is returned even if xCond() fails and
150178** no substitution occurs.
150179*/
150180static int stem(
150181  char **pz,             /* The word being stemmed (Reversed) */
150182  const char *zFrom,     /* If the ending matches this... (Reversed) */
150183  const char *zTo,       /* ... change the ending to this (not reversed) */
150184  int (*xCond)(const char*)   /* Condition that must be true */
150185){
150186  char *z = *pz;
150187  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
150188  if( *zFrom!=0 ) return 0;
150189  if( xCond && !xCond(z) ) return 1;
150190  while( *zTo ){
150191    *(--z) = *(zTo++);
150192  }
150193  *pz = z;
150194  return 1;
150195}
150196
150197/*
150198** This is the fallback stemmer used when the porter stemmer is
150199** inappropriate.  The input word is copied into the output with
150200** US-ASCII case folding.  If the input word is too long (more
150201** than 20 bytes if it contains no digits or more than 6 bytes if
150202** it contains digits) then word is truncated to 20 or 6 bytes
150203** by taking 10 or 3 bytes from the beginning and end.
150204*/
150205static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
150206  int i, mx, j;
150207  int hasDigit = 0;
150208  for(i=0; i<nIn; i++){
150209    char c = zIn[i];
150210    if( c>='A' && c<='Z' ){
150211      zOut[i] = c - 'A' + 'a';
150212    }else{
150213      if( c>='0' && c<='9' ) hasDigit = 1;
150214      zOut[i] = c;
150215    }
150216  }
150217  mx = hasDigit ? 3 : 10;
150218  if( nIn>mx*2 ){
150219    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
150220      zOut[j] = zOut[i];
150221    }
150222    i = j;
150223  }
150224  zOut[i] = 0;
150225  *pnOut = i;
150226}
150227
150228
150229/*
150230** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
150231** zOut is at least big enough to hold nIn bytes.  Write the actual
150232** size of the output word (exclusive of the '\0' terminator) into *pnOut.
150233**
150234** Any upper-case characters in the US-ASCII character set ([A-Z])
150235** are converted to lower case.  Upper-case UTF characters are
150236** unchanged.
150237**
150238** Words that are longer than about 20 bytes are stemmed by retaining
150239** a few bytes from the beginning and the end of the word.  If the
150240** word contains digits, 3 bytes are taken from the beginning and
150241** 3 bytes from the end.  For long words without digits, 10 bytes
150242** are taken from each end.  US-ASCII case folding still applies.
150243**
150244** If the input word contains not digits but does characters not
150245** in [a-zA-Z] then no stemming is attempted and this routine just
150246** copies the input into the input into the output with US-ASCII
150247** case folding.
150248**
150249** Stemming never increases the length of the word.  So there is
150250** no chance of overflowing the zOut buffer.
150251*/
150252static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
150253  int i, j;
150254  char zReverse[28];
150255  char *z, *z2;
150256  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
150257    /* The word is too big or too small for the porter stemmer.
150258    ** Fallback to the copy stemmer */
150259    copy_stemmer(zIn, nIn, zOut, pnOut);
150260    return;
150261  }
150262  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
150263    char c = zIn[i];
150264    if( c>='A' && c<='Z' ){
150265      zReverse[j] = c + 'a' - 'A';
150266    }else if( c>='a' && c<='z' ){
150267      zReverse[j] = c;
150268    }else{
150269      /* The use of a character not in [a-zA-Z] means that we fallback
150270      ** to the copy stemmer */
150271      copy_stemmer(zIn, nIn, zOut, pnOut);
150272      return;
150273    }
150274  }
150275  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
150276  z = &zReverse[j+1];
150277
150278
150279  /* Step 1a */
150280  if( z[0]=='s' ){
150281    if(
150282     !stem(&z, "sess", "ss", 0) &&
150283     !stem(&z, "sei", "i", 0)  &&
150284     !stem(&z, "ss", "ss", 0)
150285    ){
150286      z++;
150287    }
150288  }
150289
150290  /* Step 1b */
150291  z2 = z;
150292  if( stem(&z, "dee", "ee", m_gt_0) ){
150293    /* Do nothing.  The work was all in the test */
150294  }else if(
150295     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
150296      && z!=z2
150297  ){
150298     if( stem(&z, "ta", "ate", 0) ||
150299         stem(&z, "lb", "ble", 0) ||
150300         stem(&z, "zi", "ize", 0) ){
150301       /* Do nothing.  The work was all in the test */
150302     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
150303       z++;
150304     }else if( m_eq_1(z) && star_oh(z) ){
150305       *(--z) = 'e';
150306     }
150307  }
150308
150309  /* Step 1c */
150310  if( z[0]=='y' && hasVowel(z+1) ){
150311    z[0] = 'i';
150312  }
150313
150314  /* Step 2 */
150315  switch( z[1] ){
150316   case 'a':
150317     if( !stem(&z, "lanoita", "ate", m_gt_0) ){
150318       stem(&z, "lanoit", "tion", m_gt_0);
150319     }
150320     break;
150321   case 'c':
150322     if( !stem(&z, "icne", "ence", m_gt_0) ){
150323       stem(&z, "icna", "ance", m_gt_0);
150324     }
150325     break;
150326   case 'e':
150327     stem(&z, "rezi", "ize", m_gt_0);
150328     break;
150329   case 'g':
150330     stem(&z, "igol", "log", m_gt_0);
150331     break;
150332   case 'l':
150333     if( !stem(&z, "ilb", "ble", m_gt_0)
150334      && !stem(&z, "illa", "al", m_gt_0)
150335      && !stem(&z, "iltne", "ent", m_gt_0)
150336      && !stem(&z, "ile", "e", m_gt_0)
150337     ){
150338       stem(&z, "ilsuo", "ous", m_gt_0);
150339     }
150340     break;
150341   case 'o':
150342     if( !stem(&z, "noitazi", "ize", m_gt_0)
150343      && !stem(&z, "noita", "ate", m_gt_0)
150344     ){
150345       stem(&z, "rota", "ate", m_gt_0);
150346     }
150347     break;
150348   case 's':
150349     if( !stem(&z, "msila", "al", m_gt_0)
150350      && !stem(&z, "ssenevi", "ive", m_gt_0)
150351      && !stem(&z, "ssenluf", "ful", m_gt_0)
150352     ){
150353       stem(&z, "ssensuo", "ous", m_gt_0);
150354     }
150355     break;
150356   case 't':
150357     if( !stem(&z, "itila", "al", m_gt_0)
150358      && !stem(&z, "itivi", "ive", m_gt_0)
150359     ){
150360       stem(&z, "itilib", "ble", m_gt_0);
150361     }
150362     break;
150363  }
150364
150365  /* Step 3 */
150366  switch( z[0] ){
150367   case 'e':
150368     if( !stem(&z, "etaci", "ic", m_gt_0)
150369      && !stem(&z, "evita", "", m_gt_0)
150370     ){
150371       stem(&z, "ezila", "al", m_gt_0);
150372     }
150373     break;
150374   case 'i':
150375     stem(&z, "itici", "ic", m_gt_0);
150376     break;
150377   case 'l':
150378     if( !stem(&z, "laci", "ic", m_gt_0) ){
150379       stem(&z, "luf", "", m_gt_0);
150380     }
150381     break;
150382   case 's':
150383     stem(&z, "ssen", "", m_gt_0);
150384     break;
150385  }
150386
150387  /* Step 4 */
150388  switch( z[1] ){
150389   case 'a':
150390     if( z[0]=='l' && m_gt_1(z+2) ){
150391       z += 2;
150392     }
150393     break;
150394   case 'c':
150395     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
150396       z += 4;
150397     }
150398     break;
150399   case 'e':
150400     if( z[0]=='r' && m_gt_1(z+2) ){
150401       z += 2;
150402     }
150403     break;
150404   case 'i':
150405     if( z[0]=='c' && m_gt_1(z+2) ){
150406       z += 2;
150407     }
150408     break;
150409   case 'l':
150410     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
150411       z += 4;
150412     }
150413     break;
150414   case 'n':
150415     if( z[0]=='t' ){
150416       if( z[2]=='a' ){
150417         if( m_gt_1(z+3) ){
150418           z += 3;
150419         }
150420       }else if( z[2]=='e' ){
150421         if( !stem(&z, "tneme", "", m_gt_1)
150422          && !stem(&z, "tnem", "", m_gt_1)
150423         ){
150424           stem(&z, "tne", "", m_gt_1);
150425         }
150426       }
150427     }
150428     break;
150429   case 'o':
150430     if( z[0]=='u' ){
150431       if( m_gt_1(z+2) ){
150432         z += 2;
150433       }
150434     }else if( z[3]=='s' || z[3]=='t' ){
150435       stem(&z, "noi", "", m_gt_1);
150436     }
150437     break;
150438   case 's':
150439     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
150440       z += 3;
150441     }
150442     break;
150443   case 't':
150444     if( !stem(&z, "eta", "", m_gt_1) ){
150445       stem(&z, "iti", "", m_gt_1);
150446     }
150447     break;
150448   case 'u':
150449     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
150450       z += 3;
150451     }
150452     break;
150453   case 'v':
150454   case 'z':
150455     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
150456       z += 3;
150457     }
150458     break;
150459  }
150460
150461  /* Step 5a */
150462  if( z[0]=='e' ){
150463    if( m_gt_1(z+1) ){
150464      z++;
150465    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
150466      z++;
150467    }
150468  }
150469
150470  /* Step 5b */
150471  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
150472    z++;
150473  }
150474
150475  /* z[] is now the stemmed word in reverse order.  Flip it back
150476  ** around into forward order and return.
150477  */
150478  *pnOut = i = (int)strlen(z);
150479  zOut[i] = 0;
150480  while( *z ){
150481    zOut[--i] = *(z++);
150482  }
150483}
150484
150485/*
150486** Characters that can be part of a token.  We assume any character
150487** whose value is greater than 0x80 (any UTF character) can be
150488** part of a token.  In other words, delimiters all must have
150489** values of 0x7f or lower.
150490*/
150491static const char porterIdChar[] = {
150492/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
150493    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
150494    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
150495    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
150496    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
150497    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
150498};
150499#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
150500
150501/*
150502** Extract the next token from a tokenization cursor.  The cursor must
150503** have been opened by a prior call to porterOpen().
150504*/
150505static int porterNext(
150506  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
150507  const char **pzToken,               /* OUT: *pzToken is the token text */
150508  int *pnBytes,                       /* OUT: Number of bytes in token */
150509  int *piStartOffset,                 /* OUT: Starting offset of token */
150510  int *piEndOffset,                   /* OUT: Ending offset of token */
150511  int *piPosition                     /* OUT: Position integer of token */
150512){
150513  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
150514  const char *z = c->zInput;
150515
150516  while( c->iOffset<c->nInput ){
150517    int iStartOffset, ch;
150518
150519    /* Scan past delimiter characters */
150520    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
150521      c->iOffset++;
150522    }
150523
150524    /* Count non-delimiter characters. */
150525    iStartOffset = c->iOffset;
150526    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
150527      c->iOffset++;
150528    }
150529
150530    if( c->iOffset>iStartOffset ){
150531      int n = c->iOffset-iStartOffset;
150532      if( n>c->nAllocated ){
150533        char *pNew;
150534        c->nAllocated = n+20;
150535        pNew = sqlite3_realloc(c->zToken, c->nAllocated);
150536        if( !pNew ) return SQLITE_NOMEM;
150537        c->zToken = pNew;
150538      }
150539      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
150540      *pzToken = c->zToken;
150541      *piStartOffset = iStartOffset;
150542      *piEndOffset = c->iOffset;
150543      *piPosition = c->iToken++;
150544      return SQLITE_OK;
150545    }
150546  }
150547  return SQLITE_DONE;
150548}
150549
150550/*
150551** The set of routines that implement the porter-stemmer tokenizer
150552*/
150553static const sqlite3_tokenizer_module porterTokenizerModule = {
150554  0,
150555  porterCreate,
150556  porterDestroy,
150557  porterOpen,
150558  porterClose,
150559  porterNext,
150560  0
150561};
150562
150563/*
150564** Allocate a new porter tokenizer.  Return a pointer to the new
150565** tokenizer in *ppModule
150566*/
150567SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
150568  sqlite3_tokenizer_module const**ppModule
150569){
150570  *ppModule = &porterTokenizerModule;
150571}
150572
150573#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
150574
150575/************** End of fts3_porter.c *****************************************/
150576/************** Begin file fts3_tokenizer.c **********************************/
150577/*
150578** 2007 June 22
150579**
150580** The author disclaims copyright to this source code.  In place of
150581** a legal notice, here is a blessing:
150582**
150583**    May you do good and not evil.
150584**    May you find forgiveness for yourself and forgive others.
150585**    May you share freely, never taking more than you give.
150586**
150587******************************************************************************
150588**
150589** This is part of an SQLite module implementing full-text search.
150590** This particular file implements the generic tokenizer interface.
150591*/
150592
150593/*
150594** The code in this file is only compiled if:
150595**
150596**     * The FTS3 module is being built as an extension
150597**       (in which case SQLITE_CORE is not defined), or
150598**
150599**     * The FTS3 module is being built into the core of
150600**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
150601*/
150602/* #include "fts3Int.h" */
150603#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
150604
150605/* #include <assert.h> */
150606/* #include <string.h> */
150607
150608/*
150609** Return true if the two-argument version of fts3_tokenizer()
150610** has been activated via a prior call to sqlite3_db_config(db,
150611** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
150612*/
150613static int fts3TokenizerEnabled(sqlite3_context *context){
150614  sqlite3 *db = sqlite3_context_db_handle(context);
150615  int isEnabled = 0;
150616  sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
150617  return isEnabled;
150618}
150619
150620/*
150621** Implementation of the SQL scalar function for accessing the underlying
150622** hash table. This function may be called as follows:
150623**
150624**   SELECT <function-name>(<key-name>);
150625**   SELECT <function-name>(<key-name>, <pointer>);
150626**
150627** where <function-name> is the name passed as the second argument
150628** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
150629**
150630** If the <pointer> argument is specified, it must be a blob value
150631** containing a pointer to be stored as the hash data corresponding
150632** to the string <key-name>. If <pointer> is not specified, then
150633** the string <key-name> must already exist in the has table. Otherwise,
150634** an error is returned.
150635**
150636** Whether or not the <pointer> argument is specified, the value returned
150637** is a blob containing the pointer stored as the hash data corresponding
150638** to string <key-name> (after the hash-table is updated, if applicable).
150639*/
150640static void fts3TokenizerFunc(
150641  sqlite3_context *context,
150642  int argc,
150643  sqlite3_value **argv
150644){
150645  Fts3Hash *pHash;
150646  void *pPtr = 0;
150647  const unsigned char *zName;
150648  int nName;
150649
150650  assert( argc==1 || argc==2 );
150651
150652  pHash = (Fts3Hash *)sqlite3_user_data(context);
150653
150654  zName = sqlite3_value_text(argv[0]);
150655  nName = sqlite3_value_bytes(argv[0])+1;
150656
150657  if( argc==2 ){
150658    if( fts3TokenizerEnabled(context) ){
150659      void *pOld;
150660      int n = sqlite3_value_bytes(argv[1]);
150661      if( zName==0 || n!=sizeof(pPtr) ){
150662        sqlite3_result_error(context, "argument type mismatch", -1);
150663        return;
150664      }
150665      pPtr = *(void **)sqlite3_value_blob(argv[1]);
150666      pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
150667      if( pOld==pPtr ){
150668        sqlite3_result_error(context, "out of memory", -1);
150669      }
150670    }else{
150671      sqlite3_result_error(context, "fts3tokenize disabled", -1);
150672      return;
150673    }
150674  }else{
150675    if( zName ){
150676      pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
150677    }
150678    if( !pPtr ){
150679      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
150680      sqlite3_result_error(context, zErr, -1);
150681      sqlite3_free(zErr);
150682      return;
150683    }
150684  }
150685  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
150686}
150687
150688SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
150689  static const char isFtsIdChar[] = {
150690      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
150691      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
150692      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
150693      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
150694      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
150695      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
150696      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
150697      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
150698  };
150699  return (c&0x80 || isFtsIdChar[(int)(c)]);
150700}
150701
150702SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
150703  const char *z1;
150704  const char *z2 = 0;
150705
150706  /* Find the start of the next token. */
150707  z1 = zStr;
150708  while( z2==0 ){
150709    char c = *z1;
150710    switch( c ){
150711      case '\0': return 0;        /* No more tokens here */
150712      case '\'':
150713      case '"':
150714      case '`': {
150715        z2 = z1;
150716        while( *++z2 && (*z2!=c || *++z2==c) );
150717        break;
150718      }
150719      case '[':
150720        z2 = &z1[1];
150721        while( *z2 && z2[0]!=']' ) z2++;
150722        if( *z2 ) z2++;
150723        break;
150724
150725      default:
150726        if( sqlite3Fts3IsIdChar(*z1) ){
150727          z2 = &z1[1];
150728          while( sqlite3Fts3IsIdChar(*z2) ) z2++;
150729        }else{
150730          z1++;
150731        }
150732    }
150733  }
150734
150735  *pn = (int)(z2-z1);
150736  return z1;
150737}
150738
150739SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
150740  Fts3Hash *pHash,                /* Tokenizer hash table */
150741  const char *zArg,               /* Tokenizer name */
150742  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
150743  char **pzErr                    /* OUT: Set to malloced error message */
150744){
150745  int rc;
150746  char *z = (char *)zArg;
150747  int n = 0;
150748  char *zCopy;
150749  char *zEnd;                     /* Pointer to nul-term of zCopy */
150750  sqlite3_tokenizer_module *m;
150751
150752  zCopy = sqlite3_mprintf("%s", zArg);
150753  if( !zCopy ) return SQLITE_NOMEM;
150754  zEnd = &zCopy[strlen(zCopy)];
150755
150756  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
150757  if( z==0 ){
150758    assert( n==0 );
150759    z = zCopy;
150760  }
150761  z[n] = '\0';
150762  sqlite3Fts3Dequote(z);
150763
150764  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
150765  if( !m ){
150766    sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
150767    rc = SQLITE_ERROR;
150768  }else{
150769    char const **aArg = 0;
150770    int iArg = 0;
150771    z = &z[n+1];
150772    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
150773      int nNew = sizeof(char *)*(iArg+1);
150774      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
150775      if( !aNew ){
150776        sqlite3_free(zCopy);
150777        sqlite3_free((void *)aArg);
150778        return SQLITE_NOMEM;
150779      }
150780      aArg = aNew;
150781      aArg[iArg++] = z;
150782      z[n] = '\0';
150783      sqlite3Fts3Dequote(z);
150784      z = &z[n+1];
150785    }
150786    rc = m->xCreate(iArg, aArg, ppTok);
150787    assert( rc!=SQLITE_OK || *ppTok );
150788    if( rc!=SQLITE_OK ){
150789      sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
150790    }else{
150791      (*ppTok)->pModule = m;
150792    }
150793    sqlite3_free((void *)aArg);
150794  }
150795
150796  sqlite3_free(zCopy);
150797  return rc;
150798}
150799
150800
150801#ifdef SQLITE_TEST
150802
150803#if defined(INCLUDE_SQLITE_TCL_H)
150804#  include "sqlite_tcl.h"
150805#else
150806#  include "tcl.h"
150807#endif
150808/* #include <string.h> */
150809
150810/*
150811** Implementation of a special SQL scalar function for testing tokenizers
150812** designed to be used in concert with the Tcl testing framework. This
150813** function must be called with two or more arguments:
150814**
150815**   SELECT <function-name>(<key-name>, ..., <input-string>);
150816**
150817** where <function-name> is the name passed as the second argument
150818** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
150819** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
150820**
150821** The return value is a string that may be interpreted as a Tcl
150822** list. For each token in the <input-string>, three elements are
150823** added to the returned list. The first is the token position, the
150824** second is the token text (folded, stemmed, etc.) and the third is the
150825** substring of <input-string> associated with the token. For example,
150826** using the built-in "simple" tokenizer:
150827**
150828**   SELECT fts_tokenizer_test('simple', 'I don't see how');
150829**
150830** will return the string:
150831**
150832**   "{0 i I 1 dont don't 2 see see 3 how how}"
150833**
150834*/
150835static void testFunc(
150836  sqlite3_context *context,
150837  int argc,
150838  sqlite3_value **argv
150839){
150840  Fts3Hash *pHash;
150841  sqlite3_tokenizer_module *p;
150842  sqlite3_tokenizer *pTokenizer = 0;
150843  sqlite3_tokenizer_cursor *pCsr = 0;
150844
150845  const char *zErr = 0;
150846
150847  const char *zName;
150848  int nName;
150849  const char *zInput;
150850  int nInput;
150851
150852  const char *azArg[64];
150853
150854  const char *zToken;
150855  int nToken = 0;
150856  int iStart = 0;
150857  int iEnd = 0;
150858  int iPos = 0;
150859  int i;
150860
150861  Tcl_Obj *pRet;
150862
150863  if( argc<2 ){
150864    sqlite3_result_error(context, "insufficient arguments", -1);
150865    return;
150866  }
150867
150868  nName = sqlite3_value_bytes(argv[0]);
150869  zName = (const char *)sqlite3_value_text(argv[0]);
150870  nInput = sqlite3_value_bytes(argv[argc-1]);
150871  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
150872
150873  pHash = (Fts3Hash *)sqlite3_user_data(context);
150874  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
150875
150876  if( !p ){
150877    char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
150878    sqlite3_result_error(context, zErr2, -1);
150879    sqlite3_free(zErr2);
150880    return;
150881  }
150882
150883  pRet = Tcl_NewObj();
150884  Tcl_IncrRefCount(pRet);
150885
150886  for(i=1; i<argc-1; i++){
150887    azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
150888  }
150889
150890  if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
150891    zErr = "error in xCreate()";
150892    goto finish;
150893  }
150894  pTokenizer->pModule = p;
150895  if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
150896    zErr = "error in xOpen()";
150897    goto finish;
150898  }
150899
150900  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
150901    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
150902    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
150903    zToken = &zInput[iStart];
150904    nToken = iEnd-iStart;
150905    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
150906  }
150907
150908  if( SQLITE_OK!=p->xClose(pCsr) ){
150909    zErr = "error in xClose()";
150910    goto finish;
150911  }
150912  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
150913    zErr = "error in xDestroy()";
150914    goto finish;
150915  }
150916
150917finish:
150918  if( zErr ){
150919    sqlite3_result_error(context, zErr, -1);
150920  }else{
150921    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
150922  }
150923  Tcl_DecrRefCount(pRet);
150924}
150925
150926static
150927int registerTokenizer(
150928  sqlite3 *db,
150929  char *zName,
150930  const sqlite3_tokenizer_module *p
150931){
150932  int rc;
150933  sqlite3_stmt *pStmt;
150934  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
150935
150936  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
150937  if( rc!=SQLITE_OK ){
150938    return rc;
150939  }
150940
150941  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
150942  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
150943  sqlite3_step(pStmt);
150944
150945  return sqlite3_finalize(pStmt);
150946}
150947
150948
150949static
150950int queryTokenizer(
150951  sqlite3 *db,
150952  char *zName,
150953  const sqlite3_tokenizer_module **pp
150954){
150955  int rc;
150956  sqlite3_stmt *pStmt;
150957  const char zSql[] = "SELECT fts3_tokenizer(?)";
150958
150959  *pp = 0;
150960  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
150961  if( rc!=SQLITE_OK ){
150962    return rc;
150963  }
150964
150965  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
150966  if( SQLITE_ROW==sqlite3_step(pStmt) ){
150967    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
150968      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
150969    }
150970  }
150971
150972  return sqlite3_finalize(pStmt);
150973}
150974
150975SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
150976
150977/*
150978** Implementation of the scalar function fts3_tokenizer_internal_test().
150979** This function is used for testing only, it is not included in the
150980** build unless SQLITE_TEST is defined.
150981**
150982** The purpose of this is to test that the fts3_tokenizer() function
150983** can be used as designed by the C-code in the queryTokenizer and
150984** registerTokenizer() functions above. These two functions are repeated
150985** in the README.tokenizer file as an example, so it is important to
150986** test them.
150987**
150988** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
150989** function with no arguments. An assert() will fail if a problem is
150990** detected. i.e.:
150991**
150992**     SELECT fts3_tokenizer_internal_test();
150993**
150994*/
150995static void intTestFunc(
150996  sqlite3_context *context,
150997  int argc,
150998  sqlite3_value **argv
150999){
151000  int rc;
151001  const sqlite3_tokenizer_module *p1;
151002  const sqlite3_tokenizer_module *p2;
151003  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
151004
151005  UNUSED_PARAMETER(argc);
151006  UNUSED_PARAMETER(argv);
151007
151008  /* Test the query function */
151009  sqlite3Fts3SimpleTokenizerModule(&p1);
151010  rc = queryTokenizer(db, "simple", &p2);
151011  assert( rc==SQLITE_OK );
151012  assert( p1==p2 );
151013  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
151014  assert( rc==SQLITE_ERROR );
151015  assert( p2==0 );
151016  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
151017
151018  /* Test the storage function */
151019  if( fts3TokenizerEnabled(context) ){
151020    rc = registerTokenizer(db, "nosuchtokenizer", p1);
151021    assert( rc==SQLITE_OK );
151022    rc = queryTokenizer(db, "nosuchtokenizer", &p2);
151023    assert( rc==SQLITE_OK );
151024    assert( p2==p1 );
151025  }
151026
151027  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
151028}
151029
151030#endif
151031
151032/*
151033** Set up SQL objects in database db used to access the contents of
151034** the hash table pointed to by argument pHash. The hash table must
151035** been initialized to use string keys, and to take a private copy
151036** of the key when a value is inserted. i.e. by a call similar to:
151037**
151038**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
151039**
151040** This function adds a scalar function (see header comment above
151041** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
151042** defined at compilation time, a temporary virtual table (see header
151043** comment above struct HashTableVtab) to the database schema. Both
151044** provide read/write access to the contents of *pHash.
151045**
151046** The third argument to this function, zName, is used as the name
151047** of both the scalar and, if created, the virtual table.
151048*/
151049SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
151050  sqlite3 *db,
151051  Fts3Hash *pHash,
151052  const char *zName
151053){
151054  int rc = SQLITE_OK;
151055  void *p = (void *)pHash;
151056  const int any = SQLITE_ANY;
151057
151058#ifdef SQLITE_TEST
151059  char *zTest = 0;
151060  char *zTest2 = 0;
151061  void *pdb = (void *)db;
151062  zTest = sqlite3_mprintf("%s_test", zName);
151063  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
151064  if( !zTest || !zTest2 ){
151065    rc = SQLITE_NOMEM;
151066  }
151067#endif
151068
151069  if( SQLITE_OK==rc ){
151070    rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
151071  }
151072  if( SQLITE_OK==rc ){
151073    rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
151074  }
151075#ifdef SQLITE_TEST
151076  if( SQLITE_OK==rc ){
151077    rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
151078  }
151079  if( SQLITE_OK==rc ){
151080    rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
151081  }
151082#endif
151083
151084#ifdef SQLITE_TEST
151085  sqlite3_free(zTest);
151086  sqlite3_free(zTest2);
151087#endif
151088
151089  return rc;
151090}
151091
151092#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
151093
151094/************** End of fts3_tokenizer.c **************************************/
151095/************** Begin file fts3_tokenizer1.c *********************************/
151096/*
151097** 2006 Oct 10
151098**
151099** The author disclaims copyright to this source code.  In place of
151100** a legal notice, here is a blessing:
151101**
151102**    May you do good and not evil.
151103**    May you find forgiveness for yourself and forgive others.
151104**    May you share freely, never taking more than you give.
151105**
151106******************************************************************************
151107**
151108** Implementation of the "simple" full-text-search tokenizer.
151109*/
151110
151111/*
151112** The code in this file is only compiled if:
151113**
151114**     * The FTS3 module is being built as an extension
151115**       (in which case SQLITE_CORE is not defined), or
151116**
151117**     * The FTS3 module is being built into the core of
151118**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
151119*/
151120/* #include "fts3Int.h" */
151121#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151122
151123/* #include <assert.h> */
151124/* #include <stdlib.h> */
151125/* #include <stdio.h> */
151126/* #include <string.h> */
151127
151128/* #include "fts3_tokenizer.h" */
151129
151130typedef struct simple_tokenizer {
151131  sqlite3_tokenizer base;
151132  char delim[128];             /* flag ASCII delimiters */
151133} simple_tokenizer;
151134
151135typedef struct simple_tokenizer_cursor {
151136  sqlite3_tokenizer_cursor base;
151137  const char *pInput;          /* input we are tokenizing */
151138  int nBytes;                  /* size of the input */
151139  int iOffset;                 /* current position in pInput */
151140  int iToken;                  /* index of next token to be returned */
151141  char *pToken;                /* storage for current token */
151142  int nTokenAllocated;         /* space allocated to zToken buffer */
151143} simple_tokenizer_cursor;
151144
151145
151146static int simpleDelim(simple_tokenizer *t, unsigned char c){
151147  return c<0x80 && t->delim[c];
151148}
151149static int fts3_isalnum(int x){
151150  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
151151}
151152
151153/*
151154** Create a new tokenizer instance.
151155*/
151156static int simpleCreate(
151157  int argc, const char * const *argv,
151158  sqlite3_tokenizer **ppTokenizer
151159){
151160  simple_tokenizer *t;
151161
151162  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
151163  if( t==NULL ) return SQLITE_NOMEM;
151164  memset(t, 0, sizeof(*t));
151165
151166  /* TODO(shess) Delimiters need to remain the same from run to run,
151167  ** else we need to reindex.  One solution would be a meta-table to
151168  ** track such information in the database, then we'd only want this
151169  ** information on the initial create.
151170  */
151171  if( argc>1 ){
151172    int i, n = (int)strlen(argv[1]);
151173    for(i=0; i<n; i++){
151174      unsigned char ch = argv[1][i];
151175      /* We explicitly don't support UTF-8 delimiters for now. */
151176      if( ch>=0x80 ){
151177        sqlite3_free(t);
151178        return SQLITE_ERROR;
151179      }
151180      t->delim[ch] = 1;
151181    }
151182  } else {
151183    /* Mark non-alphanumeric ASCII characters as delimiters */
151184    int i;
151185    for(i=1; i<0x80; i++){
151186      t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
151187    }
151188  }
151189
151190  *ppTokenizer = &t->base;
151191  return SQLITE_OK;
151192}
151193
151194/*
151195** Destroy a tokenizer
151196*/
151197static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
151198  sqlite3_free(pTokenizer);
151199  return SQLITE_OK;
151200}
151201
151202/*
151203** Prepare to begin tokenizing a particular string.  The input
151204** string to be tokenized is pInput[0..nBytes-1].  A cursor
151205** used to incrementally tokenize this string is returned in
151206** *ppCursor.
151207*/
151208static int simpleOpen(
151209  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
151210  const char *pInput, int nBytes,        /* String to be tokenized */
151211  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
151212){
151213  simple_tokenizer_cursor *c;
151214
151215  UNUSED_PARAMETER(pTokenizer);
151216
151217  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
151218  if( c==NULL ) return SQLITE_NOMEM;
151219
151220  c->pInput = pInput;
151221  if( pInput==0 ){
151222    c->nBytes = 0;
151223  }else if( nBytes<0 ){
151224    c->nBytes = (int)strlen(pInput);
151225  }else{
151226    c->nBytes = nBytes;
151227  }
151228  c->iOffset = 0;                 /* start tokenizing at the beginning */
151229  c->iToken = 0;
151230  c->pToken = NULL;               /* no space allocated, yet. */
151231  c->nTokenAllocated = 0;
151232
151233  *ppCursor = &c->base;
151234  return SQLITE_OK;
151235}
151236
151237/*
151238** Close a tokenization cursor previously opened by a call to
151239** simpleOpen() above.
151240*/
151241static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
151242  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
151243  sqlite3_free(c->pToken);
151244  sqlite3_free(c);
151245  return SQLITE_OK;
151246}
151247
151248/*
151249** Extract the next token from a tokenization cursor.  The cursor must
151250** have been opened by a prior call to simpleOpen().
151251*/
151252static int simpleNext(
151253  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
151254  const char **ppToken,               /* OUT: *ppToken is the token text */
151255  int *pnBytes,                       /* OUT: Number of bytes in token */
151256  int *piStartOffset,                 /* OUT: Starting offset of token */
151257  int *piEndOffset,                   /* OUT: Ending offset of token */
151258  int *piPosition                     /* OUT: Position integer of token */
151259){
151260  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
151261  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
151262  unsigned char *p = (unsigned char *)c->pInput;
151263
151264  while( c->iOffset<c->nBytes ){
151265    int iStartOffset;
151266
151267    /* Scan past delimiter characters */
151268    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
151269      c->iOffset++;
151270    }
151271
151272    /* Count non-delimiter characters. */
151273    iStartOffset = c->iOffset;
151274    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
151275      c->iOffset++;
151276    }
151277
151278    if( c->iOffset>iStartOffset ){
151279      int i, n = c->iOffset-iStartOffset;
151280      if( n>c->nTokenAllocated ){
151281        char *pNew;
151282        c->nTokenAllocated = n+20;
151283        pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
151284        if( !pNew ) return SQLITE_NOMEM;
151285        c->pToken = pNew;
151286      }
151287      for(i=0; i<n; i++){
151288        /* TODO(shess) This needs expansion to handle UTF-8
151289        ** case-insensitivity.
151290        */
151291        unsigned char ch = p[iStartOffset+i];
151292        c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
151293      }
151294      *ppToken = c->pToken;
151295      *pnBytes = n;
151296      *piStartOffset = iStartOffset;
151297      *piEndOffset = c->iOffset;
151298      *piPosition = c->iToken++;
151299
151300      return SQLITE_OK;
151301    }
151302  }
151303  return SQLITE_DONE;
151304}
151305
151306/*
151307** The set of routines that implement the simple tokenizer
151308*/
151309static const sqlite3_tokenizer_module simpleTokenizerModule = {
151310  0,
151311  simpleCreate,
151312  simpleDestroy,
151313  simpleOpen,
151314  simpleClose,
151315  simpleNext,
151316  0,
151317};
151318
151319/*
151320** Allocate a new simple tokenizer.  Return a pointer to the new
151321** tokenizer in *ppModule
151322*/
151323SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
151324  sqlite3_tokenizer_module const**ppModule
151325){
151326  *ppModule = &simpleTokenizerModule;
151327}
151328
151329#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
151330
151331/************** End of fts3_tokenizer1.c *************************************/
151332/************** Begin file fts3_tokenize_vtab.c ******************************/
151333/*
151334** 2013 Apr 22
151335**
151336** The author disclaims copyright to this source code.  In place of
151337** a legal notice, here is a blessing:
151338**
151339**    May you do good and not evil.
151340**    May you find forgiveness for yourself and forgive others.
151341**    May you share freely, never taking more than you give.
151342**
151343******************************************************************************
151344**
151345** This file contains code for the "fts3tokenize" virtual table module.
151346** An fts3tokenize virtual table is created as follows:
151347**
151348**   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
151349**       <tokenizer-name>, <arg-1>, ...
151350**   );
151351**
151352** The table created has the following schema:
151353**
151354**   CREATE TABLE <tbl>(input, token, start, end, position)
151355**
151356** When queried, the query must include a WHERE clause of type:
151357**
151358**   input = <string>
151359**
151360** The virtual table module tokenizes this <string>, using the FTS3
151361** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
151362** statement and returns one row for each token in the result. With
151363** fields set as follows:
151364**
151365**   input:   Always set to a copy of <string>
151366**   token:   A token from the input.
151367**   start:   Byte offset of the token within the input <string>.
151368**   end:     Byte offset of the byte immediately following the end of the
151369**            token within the input string.
151370**   pos:     Token offset of token within input.
151371**
151372*/
151373/* #include "fts3Int.h" */
151374#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151375
151376/* #include <string.h> */
151377/* #include <assert.h> */
151378
151379typedef struct Fts3tokTable Fts3tokTable;
151380typedef struct Fts3tokCursor Fts3tokCursor;
151381
151382/*
151383** Virtual table structure.
151384*/
151385struct Fts3tokTable {
151386  sqlite3_vtab base;              /* Base class used by SQLite core */
151387  const sqlite3_tokenizer_module *pMod;
151388  sqlite3_tokenizer *pTok;
151389};
151390
151391/*
151392** Virtual table cursor structure.
151393*/
151394struct Fts3tokCursor {
151395  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
151396  char *zInput;                   /* Input string */
151397  sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
151398  int iRowid;                     /* Current 'rowid' value */
151399  const char *zToken;             /* Current 'token' value */
151400  int nToken;                     /* Size of zToken in bytes */
151401  int iStart;                     /* Current 'start' value */
151402  int iEnd;                       /* Current 'end' value */
151403  int iPos;                       /* Current 'pos' value */
151404};
151405
151406/*
151407** Query FTS for the tokenizer implementation named zName.
151408*/
151409static int fts3tokQueryTokenizer(
151410  Fts3Hash *pHash,
151411  const char *zName,
151412  const sqlite3_tokenizer_module **pp,
151413  char **pzErr
151414){
151415  sqlite3_tokenizer_module *p;
151416  int nName = (int)strlen(zName);
151417
151418  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
151419  if( !p ){
151420    sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
151421    return SQLITE_ERROR;
151422  }
151423
151424  *pp = p;
151425  return SQLITE_OK;
151426}
151427
151428/*
151429** The second argument, argv[], is an array of pointers to nul-terminated
151430** strings. This function makes a copy of the array and strings into a
151431** single block of memory. It then dequotes any of the strings that appear
151432** to be quoted.
151433**
151434** If successful, output parameter *pazDequote is set to point at the
151435** array of dequoted strings and SQLITE_OK is returned. The caller is
151436** responsible for eventually calling sqlite3_free() to free the array
151437** in this case. Or, if an error occurs, an SQLite error code is returned.
151438** The final value of *pazDequote is undefined in this case.
151439*/
151440static int fts3tokDequoteArray(
151441  int argc,                       /* Number of elements in argv[] */
151442  const char * const *argv,       /* Input array */
151443  char ***pazDequote              /* Output array */
151444){
151445  int rc = SQLITE_OK;             /* Return code */
151446  if( argc==0 ){
151447    *pazDequote = 0;
151448  }else{
151449    int i;
151450    int nByte = 0;
151451    char **azDequote;
151452
151453    for(i=0; i<argc; i++){
151454      nByte += (int)(strlen(argv[i]) + 1);
151455    }
151456
151457    *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
151458    if( azDequote==0 ){
151459      rc = SQLITE_NOMEM;
151460    }else{
151461      char *pSpace = (char *)&azDequote[argc];
151462      for(i=0; i<argc; i++){
151463        int n = (int)strlen(argv[i]);
151464        azDequote[i] = pSpace;
151465        memcpy(pSpace, argv[i], n+1);
151466        sqlite3Fts3Dequote(pSpace);
151467        pSpace += (n+1);
151468      }
151469    }
151470  }
151471
151472  return rc;
151473}
151474
151475/*
151476** Schema of the tokenizer table.
151477*/
151478#define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
151479
151480/*
151481** This function does all the work for both the xConnect and xCreate methods.
151482** These tables have no persistent representation of their own, so xConnect
151483** and xCreate are identical operations.
151484**
151485**   argv[0]: module name
151486**   argv[1]: database name
151487**   argv[2]: table name
151488**   argv[3]: first argument (tokenizer name)
151489*/
151490static int fts3tokConnectMethod(
151491  sqlite3 *db,                    /* Database connection */
151492  void *pHash,                    /* Hash table of tokenizers */
151493  int argc,                       /* Number of elements in argv array */
151494  const char * const *argv,       /* xCreate/xConnect argument array */
151495  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
151496  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
151497){
151498  Fts3tokTable *pTab = 0;
151499  const sqlite3_tokenizer_module *pMod = 0;
151500  sqlite3_tokenizer *pTok = 0;
151501  int rc;
151502  char **azDequote = 0;
151503  int nDequote;
151504
151505  rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
151506  if( rc!=SQLITE_OK ) return rc;
151507
151508  nDequote = argc-3;
151509  rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
151510
151511  if( rc==SQLITE_OK ){
151512    const char *zModule;
151513    if( nDequote<1 ){
151514      zModule = "simple";
151515    }else{
151516      zModule = azDequote[0];
151517    }
151518    rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
151519  }
151520
151521  assert( (rc==SQLITE_OK)==(pMod!=0) );
151522  if( rc==SQLITE_OK ){
151523    const char * const *azArg = (const char * const *)&azDequote[1];
151524    rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
151525  }
151526
151527  if( rc==SQLITE_OK ){
151528    pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
151529    if( pTab==0 ){
151530      rc = SQLITE_NOMEM;
151531    }
151532  }
151533
151534  if( rc==SQLITE_OK ){
151535    memset(pTab, 0, sizeof(Fts3tokTable));
151536    pTab->pMod = pMod;
151537    pTab->pTok = pTok;
151538    *ppVtab = &pTab->base;
151539  }else{
151540    if( pTok ){
151541      pMod->xDestroy(pTok);
151542    }
151543  }
151544
151545  sqlite3_free(azDequote);
151546  return rc;
151547}
151548
151549/*
151550** This function does the work for both the xDisconnect and xDestroy methods.
151551** These tables have no persistent representation of their own, so xDisconnect
151552** and xDestroy are identical operations.
151553*/
151554static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
151555  Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
151556
151557  pTab->pMod->xDestroy(pTab->pTok);
151558  sqlite3_free(pTab);
151559  return SQLITE_OK;
151560}
151561
151562/*
151563** xBestIndex - Analyze a WHERE and ORDER BY clause.
151564*/
151565static int fts3tokBestIndexMethod(
151566  sqlite3_vtab *pVTab,
151567  sqlite3_index_info *pInfo
151568){
151569  int i;
151570  UNUSED_PARAMETER(pVTab);
151571
151572  for(i=0; i<pInfo->nConstraint; i++){
151573    if( pInfo->aConstraint[i].usable
151574     && pInfo->aConstraint[i].iColumn==0
151575     && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
151576    ){
151577      pInfo->idxNum = 1;
151578      pInfo->aConstraintUsage[i].argvIndex = 1;
151579      pInfo->aConstraintUsage[i].omit = 1;
151580      pInfo->estimatedCost = 1;
151581      return SQLITE_OK;
151582    }
151583  }
151584
151585  pInfo->idxNum = 0;
151586  assert( pInfo->estimatedCost>1000000.0 );
151587
151588  return SQLITE_OK;
151589}
151590
151591/*
151592** xOpen - Open a cursor.
151593*/
151594static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
151595  Fts3tokCursor *pCsr;
151596  UNUSED_PARAMETER(pVTab);
151597
151598  pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
151599  if( pCsr==0 ){
151600    return SQLITE_NOMEM;
151601  }
151602  memset(pCsr, 0, sizeof(Fts3tokCursor));
151603
151604  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
151605  return SQLITE_OK;
151606}
151607
151608/*
151609** Reset the tokenizer cursor passed as the only argument. As if it had
151610** just been returned by fts3tokOpenMethod().
151611*/
151612static void fts3tokResetCursor(Fts3tokCursor *pCsr){
151613  if( pCsr->pCsr ){
151614    Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
151615    pTab->pMod->xClose(pCsr->pCsr);
151616    pCsr->pCsr = 0;
151617  }
151618  sqlite3_free(pCsr->zInput);
151619  pCsr->zInput = 0;
151620  pCsr->zToken = 0;
151621  pCsr->nToken = 0;
151622  pCsr->iStart = 0;
151623  pCsr->iEnd = 0;
151624  pCsr->iPos = 0;
151625  pCsr->iRowid = 0;
151626}
151627
151628/*
151629** xClose - Close a cursor.
151630*/
151631static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
151632  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151633
151634  fts3tokResetCursor(pCsr);
151635  sqlite3_free(pCsr);
151636  return SQLITE_OK;
151637}
151638
151639/*
151640** xNext - Advance the cursor to the next row, if any.
151641*/
151642static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
151643  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151644  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
151645  int rc;                         /* Return code */
151646
151647  pCsr->iRowid++;
151648  rc = pTab->pMod->xNext(pCsr->pCsr,
151649      &pCsr->zToken, &pCsr->nToken,
151650      &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
151651  );
151652
151653  if( rc!=SQLITE_OK ){
151654    fts3tokResetCursor(pCsr);
151655    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
151656  }
151657
151658  return rc;
151659}
151660
151661/*
151662** xFilter - Initialize a cursor to point at the start of its data.
151663*/
151664static int fts3tokFilterMethod(
151665  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
151666  int idxNum,                     /* Strategy index */
151667  const char *idxStr,             /* Unused */
151668  int nVal,                       /* Number of elements in apVal */
151669  sqlite3_value **apVal           /* Arguments for the indexing scheme */
151670){
151671  int rc = SQLITE_ERROR;
151672  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151673  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
151674  UNUSED_PARAMETER(idxStr);
151675  UNUSED_PARAMETER(nVal);
151676
151677  fts3tokResetCursor(pCsr);
151678  if( idxNum==1 ){
151679    const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
151680    int nByte = sqlite3_value_bytes(apVal[0]);
151681    pCsr->zInput = sqlite3_malloc(nByte+1);
151682    if( pCsr->zInput==0 ){
151683      rc = SQLITE_NOMEM;
151684    }else{
151685      memcpy(pCsr->zInput, zByte, nByte);
151686      pCsr->zInput[nByte] = 0;
151687      rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
151688      if( rc==SQLITE_OK ){
151689        pCsr->pCsr->pTokenizer = pTab->pTok;
151690      }
151691    }
151692  }
151693
151694  if( rc!=SQLITE_OK ) return rc;
151695  return fts3tokNextMethod(pCursor);
151696}
151697
151698/*
151699** xEof - Return true if the cursor is at EOF, or false otherwise.
151700*/
151701static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
151702  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151703  return (pCsr->zToken==0);
151704}
151705
151706/*
151707** xColumn - Return a column value.
151708*/
151709static int fts3tokColumnMethod(
151710  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
151711  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
151712  int iCol                        /* Index of column to read value from */
151713){
151714  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151715
151716  /* CREATE TABLE x(input, token, start, end, position) */
151717  switch( iCol ){
151718    case 0:
151719      sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
151720      break;
151721    case 1:
151722      sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
151723      break;
151724    case 2:
151725      sqlite3_result_int(pCtx, pCsr->iStart);
151726      break;
151727    case 3:
151728      sqlite3_result_int(pCtx, pCsr->iEnd);
151729      break;
151730    default:
151731      assert( iCol==4 );
151732      sqlite3_result_int(pCtx, pCsr->iPos);
151733      break;
151734  }
151735  return SQLITE_OK;
151736}
151737
151738/*
151739** xRowid - Return the current rowid for the cursor.
151740*/
151741static int fts3tokRowidMethod(
151742  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
151743  sqlite_int64 *pRowid            /* OUT: Rowid value */
151744){
151745  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151746  *pRowid = (sqlite3_int64)pCsr->iRowid;
151747  return SQLITE_OK;
151748}
151749
151750/*
151751** Register the fts3tok module with database connection db. Return SQLITE_OK
151752** if successful or an error code if sqlite3_create_module() fails.
151753*/
151754SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
151755  static const sqlite3_module fts3tok_module = {
151756     0,                           /* iVersion      */
151757     fts3tokConnectMethod,        /* xCreate       */
151758     fts3tokConnectMethod,        /* xConnect      */
151759     fts3tokBestIndexMethod,      /* xBestIndex    */
151760     fts3tokDisconnectMethod,     /* xDisconnect   */
151761     fts3tokDisconnectMethod,     /* xDestroy      */
151762     fts3tokOpenMethod,           /* xOpen         */
151763     fts3tokCloseMethod,          /* xClose        */
151764     fts3tokFilterMethod,         /* xFilter       */
151765     fts3tokNextMethod,           /* xNext         */
151766     fts3tokEofMethod,            /* xEof          */
151767     fts3tokColumnMethod,         /* xColumn       */
151768     fts3tokRowidMethod,          /* xRowid        */
151769     0,                           /* xUpdate       */
151770     0,                           /* xBegin        */
151771     0,                           /* xSync         */
151772     0,                           /* xCommit       */
151773     0,                           /* xRollback     */
151774     0,                           /* xFindFunction */
151775     0,                           /* xRename       */
151776     0,                           /* xSavepoint    */
151777     0,                           /* xRelease      */
151778     0                            /* xRollbackTo   */
151779  };
151780  int rc;                         /* Return code */
151781
151782  rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
151783  return rc;
151784}
151785
151786#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
151787
151788/************** End of fts3_tokenize_vtab.c **********************************/
151789/************** Begin file fts3_write.c **************************************/
151790/*
151791** 2009 Oct 23
151792**
151793** The author disclaims copyright to this source code.  In place of
151794** a legal notice, here is a blessing:
151795**
151796**    May you do good and not evil.
151797**    May you find forgiveness for yourself and forgive others.
151798**    May you share freely, never taking more than you give.
151799**
151800******************************************************************************
151801**
151802** This file is part of the SQLite FTS3 extension module. Specifically,
151803** this file contains code to insert, update and delete rows from FTS3
151804** tables. It also contains code to merge FTS3 b-tree segments. Some
151805** of the sub-routines used to merge segments are also used by the query
151806** code in fts3.c.
151807*/
151808
151809/* #include "fts3Int.h" */
151810#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151811
151812/* #include <string.h> */
151813/* #include <assert.h> */
151814/* #include <stdlib.h> */
151815
151816
151817#define FTS_MAX_APPENDABLE_HEIGHT 16
151818
151819/*
151820** When full-text index nodes are loaded from disk, the buffer that they
151821** are loaded into has the following number of bytes of padding at the end
151822** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
151823** of 920 bytes is allocated for it.
151824**
151825** This means that if we have a pointer into a buffer containing node data,
151826** it is always safe to read up to two varints from it without risking an
151827** overread, even if the node data is corrupted.
151828*/
151829#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
151830
151831/*
151832** Under certain circumstances, b-tree nodes (doclists) can be loaded into
151833** memory incrementally instead of all at once. This can be a big performance
151834** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
151835** method before retrieving all query results (as may happen, for example,
151836** if a query has a LIMIT clause).
151837**
151838** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
151839** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
151840** The code is written so that the hard lower-limit for each of these values
151841** is 1. Clearly such small values would be inefficient, but can be useful
151842** for testing purposes.
151843**
151844** If this module is built with SQLITE_TEST defined, these constants may
151845** be overridden at runtime for testing purposes. File fts3_test.c contains
151846** a Tcl interface to read and write the values.
151847*/
151848#ifdef SQLITE_TEST
151849int test_fts3_node_chunksize = (4*1024);
151850int test_fts3_node_chunk_threshold = (4*1024)*4;
151851# define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
151852# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
151853#else
151854# define FTS3_NODE_CHUNKSIZE (4*1024)
151855# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
151856#endif
151857
151858/*
151859** The two values that may be meaningfully bound to the :1 parameter in
151860** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
151861*/
151862#define FTS_STAT_DOCTOTAL      0
151863#define FTS_STAT_INCRMERGEHINT 1
151864#define FTS_STAT_AUTOINCRMERGE 2
151865
151866/*
151867** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
151868** and incremental merge operation that takes place. This is used for
151869** debugging FTS only, it should not usually be turned on in production
151870** systems.
151871*/
151872#ifdef FTS3_LOG_MERGES
151873static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
151874  sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
151875}
151876#else
151877#define fts3LogMerge(x, y)
151878#endif
151879
151880
151881typedef struct PendingList PendingList;
151882typedef struct SegmentNode SegmentNode;
151883typedef struct SegmentWriter SegmentWriter;
151884
151885/*
151886** An instance of the following data structure is used to build doclists
151887** incrementally. See function fts3PendingListAppend() for details.
151888*/
151889struct PendingList {
151890  int nData;
151891  char *aData;
151892  int nSpace;
151893  sqlite3_int64 iLastDocid;
151894  sqlite3_int64 iLastCol;
151895  sqlite3_int64 iLastPos;
151896};
151897
151898
151899/*
151900** Each cursor has a (possibly empty) linked list of the following objects.
151901*/
151902struct Fts3DeferredToken {
151903  Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
151904  int iCol;                       /* Column token must occur in */
151905  Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
151906  PendingList *pList;             /* Doclist is assembled here */
151907};
151908
151909/*
151910** An instance of this structure is used to iterate through the terms on
151911** a contiguous set of segment b-tree leaf nodes. Although the details of
151912** this structure are only manipulated by code in this file, opaque handles
151913** of type Fts3SegReader* are also used by code in fts3.c to iterate through
151914** terms when querying the full-text index. See functions:
151915**
151916**   sqlite3Fts3SegReaderNew()
151917**   sqlite3Fts3SegReaderFree()
151918**   sqlite3Fts3SegReaderIterate()
151919**
151920** Methods used to manipulate Fts3SegReader structures:
151921**
151922**   fts3SegReaderNext()
151923**   fts3SegReaderFirstDocid()
151924**   fts3SegReaderNextDocid()
151925*/
151926struct Fts3SegReader {
151927  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
151928  u8 bLookup;                     /* True for a lookup only */
151929  u8 rootOnly;                    /* True for a root-only reader */
151930
151931  sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
151932  sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
151933  sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
151934  sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
151935
151936  char *aNode;                    /* Pointer to node data (or NULL) */
151937  int nNode;                      /* Size of buffer at aNode (or 0) */
151938  int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
151939  sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
151940
151941  Fts3HashElem **ppNextElem;
151942
151943  /* Variables set by fts3SegReaderNext(). These may be read directly
151944  ** by the caller. They are valid from the time SegmentReaderNew() returns
151945  ** until SegmentReaderNext() returns something other than SQLITE_OK
151946  ** (i.e. SQLITE_DONE).
151947  */
151948  int nTerm;                      /* Number of bytes in current term */
151949  char *zTerm;                    /* Pointer to current term */
151950  int nTermAlloc;                 /* Allocated size of zTerm buffer */
151951  char *aDoclist;                 /* Pointer to doclist of current entry */
151952  int nDoclist;                   /* Size of doclist in current entry */
151953
151954  /* The following variables are used by fts3SegReaderNextDocid() to iterate
151955  ** through the current doclist (aDoclist/nDoclist).
151956  */
151957  char *pOffsetList;
151958  int nOffsetList;                /* For descending pending seg-readers only */
151959  sqlite3_int64 iDocid;
151960};
151961
151962#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
151963#define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
151964
151965/*
151966** An instance of this structure is used to create a segment b-tree in the
151967** database. The internal details of this type are only accessed by the
151968** following functions:
151969**
151970**   fts3SegWriterAdd()
151971**   fts3SegWriterFlush()
151972**   fts3SegWriterFree()
151973*/
151974struct SegmentWriter {
151975  SegmentNode *pTree;             /* Pointer to interior tree structure */
151976  sqlite3_int64 iFirst;           /* First slot in %_segments written */
151977  sqlite3_int64 iFree;            /* Next free slot in %_segments */
151978  char *zTerm;                    /* Pointer to previous term buffer */
151979  int nTerm;                      /* Number of bytes in zTerm */
151980  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
151981  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
151982  int nSize;                      /* Size of allocation at aData */
151983  int nData;                      /* Bytes of data in aData */
151984  char *aData;                    /* Pointer to block from malloc() */
151985  i64 nLeafData;                  /* Number of bytes of leaf data written */
151986};
151987
151988/*
151989** Type SegmentNode is used by the following three functions to create
151990** the interior part of the segment b+-tree structures (everything except
151991** the leaf nodes). These functions and type are only ever used by code
151992** within the fts3SegWriterXXX() family of functions described above.
151993**
151994**   fts3NodeAddTerm()
151995**   fts3NodeWrite()
151996**   fts3NodeFree()
151997**
151998** When a b+tree is written to the database (either as a result of a merge
151999** or the pending-terms table being flushed), leaves are written into the
152000** database file as soon as they are completely populated. The interior of
152001** the tree is assembled in memory and written out only once all leaves have
152002** been populated and stored. This is Ok, as the b+-tree fanout is usually
152003** very large, meaning that the interior of the tree consumes relatively
152004** little memory.
152005*/
152006struct SegmentNode {
152007  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
152008  SegmentNode *pRight;            /* Pointer to right-sibling */
152009  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
152010  int nEntry;                     /* Number of terms written to node so far */
152011  char *zTerm;                    /* Pointer to previous term buffer */
152012  int nTerm;                      /* Number of bytes in zTerm */
152013  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
152014  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
152015  int nData;                      /* Bytes of valid data so far */
152016  char *aData;                    /* Node data */
152017};
152018
152019/*
152020** Valid values for the second argument to fts3SqlStmt().
152021*/
152022#define SQL_DELETE_CONTENT             0
152023#define SQL_IS_EMPTY                   1
152024#define SQL_DELETE_ALL_CONTENT         2
152025#define SQL_DELETE_ALL_SEGMENTS        3
152026#define SQL_DELETE_ALL_SEGDIR          4
152027#define SQL_DELETE_ALL_DOCSIZE         5
152028#define SQL_DELETE_ALL_STAT            6
152029#define SQL_SELECT_CONTENT_BY_ROWID    7
152030#define SQL_NEXT_SEGMENT_INDEX         8
152031#define SQL_INSERT_SEGMENTS            9
152032#define SQL_NEXT_SEGMENTS_ID          10
152033#define SQL_INSERT_SEGDIR             11
152034#define SQL_SELECT_LEVEL              12
152035#define SQL_SELECT_LEVEL_RANGE        13
152036#define SQL_SELECT_LEVEL_COUNT        14
152037#define SQL_SELECT_SEGDIR_MAX_LEVEL   15
152038#define SQL_DELETE_SEGDIR_LEVEL       16
152039#define SQL_DELETE_SEGMENTS_RANGE     17
152040#define SQL_CONTENT_INSERT            18
152041#define SQL_DELETE_DOCSIZE            19
152042#define SQL_REPLACE_DOCSIZE           20
152043#define SQL_SELECT_DOCSIZE            21
152044#define SQL_SELECT_STAT               22
152045#define SQL_REPLACE_STAT              23
152046
152047#define SQL_SELECT_ALL_PREFIX_LEVEL   24
152048#define SQL_DELETE_ALL_TERMS_SEGDIR   25
152049#define SQL_DELETE_SEGDIR_RANGE       26
152050#define SQL_SELECT_ALL_LANGID         27
152051#define SQL_FIND_MERGE_LEVEL          28
152052#define SQL_MAX_LEAF_NODE_ESTIMATE    29
152053#define SQL_DELETE_SEGDIR_ENTRY       30
152054#define SQL_SHIFT_SEGDIR_ENTRY        31
152055#define SQL_SELECT_SEGDIR             32
152056#define SQL_CHOMP_SEGDIR              33
152057#define SQL_SEGMENT_IS_APPENDABLE     34
152058#define SQL_SELECT_INDEXES            35
152059#define SQL_SELECT_MXLEVEL            36
152060
152061#define SQL_SELECT_LEVEL_RANGE2       37
152062#define SQL_UPDATE_LEVEL_IDX          38
152063#define SQL_UPDATE_LEVEL              39
152064
152065/*
152066** This function is used to obtain an SQLite prepared statement handle
152067** for the statement identified by the second argument. If successful,
152068** *pp is set to the requested statement handle and SQLITE_OK returned.
152069** Otherwise, an SQLite error code is returned and *pp is set to 0.
152070**
152071** If argument apVal is not NULL, then it must point to an array with
152072** at least as many entries as the requested statement has bound
152073** parameters. The values are bound to the statements parameters before
152074** returning.
152075*/
152076static int fts3SqlStmt(
152077  Fts3Table *p,                   /* Virtual table handle */
152078  int eStmt,                      /* One of the SQL_XXX constants above */
152079  sqlite3_stmt **pp,              /* OUT: Statement handle */
152080  sqlite3_value **apVal           /* Values to bind to statement */
152081){
152082  const char *azSql[] = {
152083/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
152084/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
152085/* 2  */  "DELETE FROM %Q.'%q_content'",
152086/* 3  */  "DELETE FROM %Q.'%q_segments'",
152087/* 4  */  "DELETE FROM %Q.'%q_segdir'",
152088/* 5  */  "DELETE FROM %Q.'%q_docsize'",
152089/* 6  */  "DELETE FROM %Q.'%q_stat'",
152090/* 7  */  "SELECT %s WHERE rowid=?",
152091/* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
152092/* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
152093/* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
152094/* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
152095
152096          /* Return segments in order from oldest to newest.*/
152097/* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
152098            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
152099/* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
152100            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
152101            "ORDER BY level DESC, idx ASC",
152102
152103/* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
152104/* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
152105
152106/* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
152107/* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
152108/* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
152109/* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
152110/* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
152111/* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
152112/* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
152113/* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
152114/* 24 */  "",
152115/* 25 */  "",
152116
152117/* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
152118/* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
152119
152120/* This statement is used to determine which level to read the input from
152121** when performing an incremental merge. It returns the absolute level number
152122** of the oldest level in the db that contains at least ? segments. Or,
152123** if no level in the FTS index contains more than ? segments, the statement
152124** returns zero rows.  */
152125/* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
152126         "  GROUP BY level HAVING cnt>=?"
152127         "  ORDER BY (level %% 1024) ASC LIMIT 1",
152128
152129/* Estimate the upper limit on the number of leaf nodes in a new segment
152130** created by merging the oldest :2 segments from absolute level :1. See
152131** function sqlite3Fts3Incrmerge() for details.  */
152132/* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
152133         "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
152134
152135/* SQL_DELETE_SEGDIR_ENTRY
152136**   Delete the %_segdir entry on absolute level :1 with index :2.  */
152137/* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
152138
152139/* SQL_SHIFT_SEGDIR_ENTRY
152140**   Modify the idx value for the segment with idx=:3 on absolute level :2
152141**   to :1.  */
152142/* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
152143
152144/* SQL_SELECT_SEGDIR
152145**   Read a single entry from the %_segdir table. The entry from absolute
152146**   level :1 with index value :2.  */
152147/* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
152148            "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
152149
152150/* SQL_CHOMP_SEGDIR
152151**   Update the start_block (:1) and root (:2) fields of the %_segdir
152152**   entry located on absolute level :3 with index :4.  */
152153/* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
152154            "WHERE level = ? AND idx = ?",
152155
152156/* SQL_SEGMENT_IS_APPENDABLE
152157**   Return a single row if the segment with end_block=? is appendable. Or
152158**   no rows otherwise.  */
152159/* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
152160
152161/* SQL_SELECT_INDEXES
152162**   Return the list of valid segment indexes for absolute level ?  */
152163/* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
152164
152165/* SQL_SELECT_MXLEVEL
152166**   Return the largest relative level in the FTS index or indexes.  */
152167/* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
152168
152169          /* Return segments in order from oldest to newest.*/
152170/* 37 */  "SELECT level, idx, end_block "
152171            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
152172            "ORDER BY level DESC, idx ASC",
152173
152174          /* Update statements used while promoting segments */
152175/* 38 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
152176            "WHERE level=? AND idx=?",
152177/* 39 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
152178
152179  };
152180  int rc = SQLITE_OK;
152181  sqlite3_stmt *pStmt;
152182
152183  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
152184  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
152185
152186  pStmt = p->aStmt[eStmt];
152187  if( !pStmt ){
152188    char *zSql;
152189    if( eStmt==SQL_CONTENT_INSERT ){
152190      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
152191    }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
152192      zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
152193    }else{
152194      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
152195    }
152196    if( !zSql ){
152197      rc = SQLITE_NOMEM;
152198    }else{
152199      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
152200      sqlite3_free(zSql);
152201      assert( rc==SQLITE_OK || pStmt==0 );
152202      p->aStmt[eStmt] = pStmt;
152203    }
152204  }
152205  if( apVal ){
152206    int i;
152207    int nParam = sqlite3_bind_parameter_count(pStmt);
152208    for(i=0; rc==SQLITE_OK && i<nParam; i++){
152209      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
152210    }
152211  }
152212  *pp = pStmt;
152213  return rc;
152214}
152215
152216
152217static int fts3SelectDocsize(
152218  Fts3Table *pTab,                /* FTS3 table handle */
152219  sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
152220  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
152221){
152222  sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
152223  int rc;                         /* Return code */
152224
152225  rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
152226  if( rc==SQLITE_OK ){
152227    sqlite3_bind_int64(pStmt, 1, iDocid);
152228    rc = sqlite3_step(pStmt);
152229    if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
152230      rc = sqlite3_reset(pStmt);
152231      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
152232      pStmt = 0;
152233    }else{
152234      rc = SQLITE_OK;
152235    }
152236  }
152237
152238  *ppStmt = pStmt;
152239  return rc;
152240}
152241
152242SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
152243  Fts3Table *pTab,                /* Fts3 table handle */
152244  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
152245){
152246  sqlite3_stmt *pStmt = 0;
152247  int rc;
152248  rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
152249  if( rc==SQLITE_OK ){
152250    sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
152251    if( sqlite3_step(pStmt)!=SQLITE_ROW
152252     || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
152253    ){
152254      rc = sqlite3_reset(pStmt);
152255      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
152256      pStmt = 0;
152257    }
152258  }
152259  *ppStmt = pStmt;
152260  return rc;
152261}
152262
152263SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
152264  Fts3Table *pTab,                /* Fts3 table handle */
152265  sqlite3_int64 iDocid,           /* Docid to read size data for */
152266  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
152267){
152268  return fts3SelectDocsize(pTab, iDocid, ppStmt);
152269}
152270
152271/*
152272** Similar to fts3SqlStmt(). Except, after binding the parameters in
152273** array apVal[] to the SQL statement identified by eStmt, the statement
152274** is executed.
152275**
152276** Returns SQLITE_OK if the statement is successfully executed, or an
152277** SQLite error code otherwise.
152278*/
152279static void fts3SqlExec(
152280  int *pRC,                /* Result code */
152281  Fts3Table *p,            /* The FTS3 table */
152282  int eStmt,               /* Index of statement to evaluate */
152283  sqlite3_value **apVal    /* Parameters to bind */
152284){
152285  sqlite3_stmt *pStmt;
152286  int rc;
152287  if( *pRC ) return;
152288  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
152289  if( rc==SQLITE_OK ){
152290    sqlite3_step(pStmt);
152291    rc = sqlite3_reset(pStmt);
152292  }
152293  *pRC = rc;
152294}
152295
152296
152297/*
152298** This function ensures that the caller has obtained an exclusive
152299** shared-cache table-lock on the %_segdir table. This is required before
152300** writing data to the fts3 table. If this lock is not acquired first, then
152301** the caller may end up attempting to take this lock as part of committing
152302** a transaction, causing SQLite to return SQLITE_LOCKED or
152303** LOCKED_SHAREDCACHEto a COMMIT command.
152304**
152305** It is best to avoid this because if FTS3 returns any error when
152306** committing a transaction, the whole transaction will be rolled back.
152307** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
152308** It can still happen if the user locks the underlying tables directly
152309** instead of accessing them via FTS.
152310*/
152311static int fts3Writelock(Fts3Table *p){
152312  int rc = SQLITE_OK;
152313
152314  if( p->nPendingData==0 ){
152315    sqlite3_stmt *pStmt;
152316    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
152317    if( rc==SQLITE_OK ){
152318      sqlite3_bind_null(pStmt, 1);
152319      sqlite3_step(pStmt);
152320      rc = sqlite3_reset(pStmt);
152321    }
152322  }
152323
152324  return rc;
152325}
152326
152327/*
152328** FTS maintains a separate indexes for each language-id (a 32-bit integer).
152329** Within each language id, a separate index is maintained to store the
152330** document terms, and each configured prefix size (configured the FTS
152331** "prefix=" option). And each index consists of multiple levels ("relative
152332** levels").
152333**
152334** All three of these values (the language id, the specific index and the
152335** level within the index) are encoded in 64-bit integer values stored
152336** in the %_segdir table on disk. This function is used to convert three
152337** separate component values into the single 64-bit integer value that
152338** can be used to query the %_segdir table.
152339**
152340** Specifically, each language-id/index combination is allocated 1024
152341** 64-bit integer level values ("absolute levels"). The main terms index
152342** for language-id 0 is allocate values 0-1023. The first prefix index
152343** (if any) for language-id 0 is allocated values 1024-2047. And so on.
152344** Language 1 indexes are allocated immediately following language 0.
152345**
152346** So, for a system with nPrefix prefix indexes configured, the block of
152347** absolute levels that corresponds to language-id iLangid and index
152348** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
152349*/
152350static sqlite3_int64 getAbsoluteLevel(
152351  Fts3Table *p,                   /* FTS3 table handle */
152352  int iLangid,                    /* Language id */
152353  int iIndex,                     /* Index in p->aIndex[] */
152354  int iLevel                      /* Level of segments */
152355){
152356  sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
152357  assert( iLangid>=0 );
152358  assert( p->nIndex>0 );
152359  assert( iIndex>=0 && iIndex<p->nIndex );
152360
152361  iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
152362  return iBase + iLevel;
152363}
152364
152365/*
152366** Set *ppStmt to a statement handle that may be used to iterate through
152367** all rows in the %_segdir table, from oldest to newest. If successful,
152368** return SQLITE_OK. If an error occurs while preparing the statement,
152369** return an SQLite error code.
152370**
152371** There is only ever one instance of this SQL statement compiled for
152372** each FTS3 table.
152373**
152374** The statement returns the following columns from the %_segdir table:
152375**
152376**   0: idx
152377**   1: start_block
152378**   2: leaves_end_block
152379**   3: end_block
152380**   4: root
152381*/
152382SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
152383  Fts3Table *p,                   /* FTS3 table */
152384  int iLangid,                    /* Language being queried */
152385  int iIndex,                     /* Index for p->aIndex[] */
152386  int iLevel,                     /* Level to select (relative level) */
152387  sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
152388){
152389  int rc;
152390  sqlite3_stmt *pStmt = 0;
152391
152392  assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
152393  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
152394  assert( iIndex>=0 && iIndex<p->nIndex );
152395
152396  if( iLevel<0 ){
152397    /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
152398    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
152399    if( rc==SQLITE_OK ){
152400      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
152401      sqlite3_bind_int64(pStmt, 2,
152402          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
152403      );
152404    }
152405  }else{
152406    /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
152407    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
152408    if( rc==SQLITE_OK ){
152409      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
152410    }
152411  }
152412  *ppStmt = pStmt;
152413  return rc;
152414}
152415
152416
152417/*
152418** Append a single varint to a PendingList buffer. SQLITE_OK is returned
152419** if successful, or an SQLite error code otherwise.
152420**
152421** This function also serves to allocate the PendingList structure itself.
152422** For example, to create a new PendingList structure containing two
152423** varints:
152424**
152425**   PendingList *p = 0;
152426**   fts3PendingListAppendVarint(&p, 1);
152427**   fts3PendingListAppendVarint(&p, 2);
152428*/
152429static int fts3PendingListAppendVarint(
152430  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
152431  sqlite3_int64 i                 /* Value to append to data */
152432){
152433  PendingList *p = *pp;
152434
152435  /* Allocate or grow the PendingList as required. */
152436  if( !p ){
152437    p = sqlite3_malloc(sizeof(*p) + 100);
152438    if( !p ){
152439      return SQLITE_NOMEM;
152440    }
152441    p->nSpace = 100;
152442    p->aData = (char *)&p[1];
152443    p->nData = 0;
152444  }
152445  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
152446    int nNew = p->nSpace * 2;
152447    p = sqlite3_realloc(p, sizeof(*p) + nNew);
152448    if( !p ){
152449      sqlite3_free(*pp);
152450      *pp = 0;
152451      return SQLITE_NOMEM;
152452    }
152453    p->nSpace = nNew;
152454    p->aData = (char *)&p[1];
152455  }
152456
152457  /* Append the new serialized varint to the end of the list. */
152458  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
152459  p->aData[p->nData] = '\0';
152460  *pp = p;
152461  return SQLITE_OK;
152462}
152463
152464/*
152465** Add a docid/column/position entry to a PendingList structure. Non-zero
152466** is returned if the structure is sqlite3_realloced as part of adding
152467** the entry. Otherwise, zero.
152468**
152469** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
152470** Zero is always returned in this case. Otherwise, if no OOM error occurs,
152471** it is set to SQLITE_OK.
152472*/
152473static int fts3PendingListAppend(
152474  PendingList **pp,               /* IN/OUT: PendingList structure */
152475  sqlite3_int64 iDocid,           /* Docid for entry to add */
152476  sqlite3_int64 iCol,             /* Column for entry to add */
152477  sqlite3_int64 iPos,             /* Position of term for entry to add */
152478  int *pRc                        /* OUT: Return code */
152479){
152480  PendingList *p = *pp;
152481  int rc = SQLITE_OK;
152482
152483  assert( !p || p->iLastDocid<=iDocid );
152484
152485  if( !p || p->iLastDocid!=iDocid ){
152486    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
152487    if( p ){
152488      assert( p->nData<p->nSpace );
152489      assert( p->aData[p->nData]==0 );
152490      p->nData++;
152491    }
152492    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
152493      goto pendinglistappend_out;
152494    }
152495    p->iLastCol = -1;
152496    p->iLastPos = 0;
152497    p->iLastDocid = iDocid;
152498  }
152499  if( iCol>0 && p->iLastCol!=iCol ){
152500    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
152501     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
152502    ){
152503      goto pendinglistappend_out;
152504    }
152505    p->iLastCol = iCol;
152506    p->iLastPos = 0;
152507  }
152508  if( iCol>=0 ){
152509    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
152510    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
152511    if( rc==SQLITE_OK ){
152512      p->iLastPos = iPos;
152513    }
152514  }
152515
152516 pendinglistappend_out:
152517  *pRc = rc;
152518  if( p!=*pp ){
152519    *pp = p;
152520    return 1;
152521  }
152522  return 0;
152523}
152524
152525/*
152526** Free a PendingList object allocated by fts3PendingListAppend().
152527*/
152528static void fts3PendingListDelete(PendingList *pList){
152529  sqlite3_free(pList);
152530}
152531
152532/*
152533** Add an entry to one of the pending-terms hash tables.
152534*/
152535static int fts3PendingTermsAddOne(
152536  Fts3Table *p,
152537  int iCol,
152538  int iPos,
152539  Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
152540  const char *zToken,
152541  int nToken
152542){
152543  PendingList *pList;
152544  int rc = SQLITE_OK;
152545
152546  pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
152547  if( pList ){
152548    p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
152549  }
152550  if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
152551    if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
152552      /* Malloc failed while inserting the new entry. This can only
152553      ** happen if there was no previous entry for this token.
152554      */
152555      assert( 0==fts3HashFind(pHash, zToken, nToken) );
152556      sqlite3_free(pList);
152557      rc = SQLITE_NOMEM;
152558    }
152559  }
152560  if( rc==SQLITE_OK ){
152561    p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
152562  }
152563  return rc;
152564}
152565
152566/*
152567** Tokenize the nul-terminated string zText and add all tokens to the
152568** pending-terms hash-table. The docid used is that currently stored in
152569** p->iPrevDocid, and the column is specified by argument iCol.
152570**
152571** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
152572*/
152573static int fts3PendingTermsAdd(
152574  Fts3Table *p,                   /* Table into which text will be inserted */
152575  int iLangid,                    /* Language id to use */
152576  const char *zText,              /* Text of document to be inserted */
152577  int iCol,                       /* Column into which text is being inserted */
152578  u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
152579){
152580  int rc;
152581  int iStart = 0;
152582  int iEnd = 0;
152583  int iPos = 0;
152584  int nWord = 0;
152585
152586  char const *zToken;
152587  int nToken = 0;
152588
152589  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
152590  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
152591  sqlite3_tokenizer_cursor *pCsr;
152592  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
152593      const char**,int*,int*,int*,int*);
152594
152595  assert( pTokenizer && pModule );
152596
152597  /* If the user has inserted a NULL value, this function may be called with
152598  ** zText==0. In this case, add zero token entries to the hash table and
152599  ** return early. */
152600  if( zText==0 ){
152601    *pnWord = 0;
152602    return SQLITE_OK;
152603  }
152604
152605  rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
152606  if( rc!=SQLITE_OK ){
152607    return rc;
152608  }
152609
152610  xNext = pModule->xNext;
152611  while( SQLITE_OK==rc
152612      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
152613  ){
152614    int i;
152615    if( iPos>=nWord ) nWord = iPos+1;
152616
152617    /* Positions cannot be negative; we use -1 as a terminator internally.
152618    ** Tokens must have a non-zero length.
152619    */
152620    if( iPos<0 || !zToken || nToken<=0 ){
152621      rc = SQLITE_ERROR;
152622      break;
152623    }
152624
152625    /* Add the term to the terms index */
152626    rc = fts3PendingTermsAddOne(
152627        p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
152628    );
152629
152630    /* Add the term to each of the prefix indexes that it is not too
152631    ** short for. */
152632    for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
152633      struct Fts3Index *pIndex = &p->aIndex[i];
152634      if( nToken<pIndex->nPrefix ) continue;
152635      rc = fts3PendingTermsAddOne(
152636          p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
152637      );
152638    }
152639  }
152640
152641  pModule->xClose(pCsr);
152642  *pnWord += nWord;
152643  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
152644}
152645
152646/*
152647** Calling this function indicates that subsequent calls to
152648** fts3PendingTermsAdd() are to add term/position-list pairs for the
152649** contents of the document with docid iDocid.
152650*/
152651static int fts3PendingTermsDocid(
152652  Fts3Table *p,                   /* Full-text table handle */
152653  int bDelete,                    /* True if this op is a delete */
152654  int iLangid,                    /* Language id of row being written */
152655  sqlite_int64 iDocid             /* Docid of row being written */
152656){
152657  assert( iLangid>=0 );
152658  assert( bDelete==1 || bDelete==0 );
152659
152660  /* TODO(shess) Explore whether partially flushing the buffer on
152661  ** forced-flush would provide better performance.  I suspect that if
152662  ** we ordered the doclists by size and flushed the largest until the
152663  ** buffer was half empty, that would let the less frequent terms
152664  ** generate longer doclists.
152665  */
152666  if( iDocid<p->iPrevDocid
152667   || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
152668   || p->iPrevLangid!=iLangid
152669   || p->nPendingData>p->nMaxPendingData
152670  ){
152671    int rc = sqlite3Fts3PendingTermsFlush(p);
152672    if( rc!=SQLITE_OK ) return rc;
152673  }
152674  p->iPrevDocid = iDocid;
152675  p->iPrevLangid = iLangid;
152676  p->bPrevDelete = bDelete;
152677  return SQLITE_OK;
152678}
152679
152680/*
152681** Discard the contents of the pending-terms hash tables.
152682*/
152683SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
152684  int i;
152685  for(i=0; i<p->nIndex; i++){
152686    Fts3HashElem *pElem;
152687    Fts3Hash *pHash = &p->aIndex[i].hPending;
152688    for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
152689      PendingList *pList = (PendingList *)fts3HashData(pElem);
152690      fts3PendingListDelete(pList);
152691    }
152692    fts3HashClear(pHash);
152693  }
152694  p->nPendingData = 0;
152695}
152696
152697/*
152698** This function is called by the xUpdate() method as part of an INSERT
152699** operation. It adds entries for each term in the new record to the
152700** pendingTerms hash table.
152701**
152702** Argument apVal is the same as the similarly named argument passed to
152703** fts3InsertData(). Parameter iDocid is the docid of the new row.
152704*/
152705static int fts3InsertTerms(
152706  Fts3Table *p,
152707  int iLangid,
152708  sqlite3_value **apVal,
152709  u32 *aSz
152710){
152711  int i;                          /* Iterator variable */
152712  for(i=2; i<p->nColumn+2; i++){
152713    int iCol = i-2;
152714    if( p->abNotindexed[iCol]==0 ){
152715      const char *zText = (const char *)sqlite3_value_text(apVal[i]);
152716      int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
152717      if( rc!=SQLITE_OK ){
152718        return rc;
152719      }
152720      aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
152721    }
152722  }
152723  return SQLITE_OK;
152724}
152725
152726/*
152727** This function is called by the xUpdate() method for an INSERT operation.
152728** The apVal parameter is passed a copy of the apVal argument passed by
152729** SQLite to the xUpdate() method. i.e:
152730**
152731**   apVal[0]                Not used for INSERT.
152732**   apVal[1]                rowid
152733**   apVal[2]                Left-most user-defined column
152734**   ...
152735**   apVal[p->nColumn+1]     Right-most user-defined column
152736**   apVal[p->nColumn+2]     Hidden column with same name as table
152737**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
152738**   apVal[p->nColumn+4]     Hidden languageid column
152739*/
152740static int fts3InsertData(
152741  Fts3Table *p,                   /* Full-text table */
152742  sqlite3_value **apVal,          /* Array of values to insert */
152743  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
152744){
152745  int rc;                         /* Return code */
152746  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
152747
152748  if( p->zContentTbl ){
152749    sqlite3_value *pRowid = apVal[p->nColumn+3];
152750    if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
152751      pRowid = apVal[1];
152752    }
152753    if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
152754      return SQLITE_CONSTRAINT;
152755    }
152756    *piDocid = sqlite3_value_int64(pRowid);
152757    return SQLITE_OK;
152758  }
152759
152760  /* Locate the statement handle used to insert data into the %_content
152761  ** table. The SQL for this statement is:
152762  **
152763  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
152764  **
152765  ** The statement features N '?' variables, where N is the number of user
152766  ** defined columns in the FTS3 table, plus one for the docid field.
152767  */
152768  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
152769  if( rc==SQLITE_OK && p->zLanguageid ){
152770    rc = sqlite3_bind_int(
152771        pContentInsert, p->nColumn+2,
152772        sqlite3_value_int(apVal[p->nColumn+4])
152773    );
152774  }
152775  if( rc!=SQLITE_OK ) return rc;
152776
152777  /* There is a quirk here. The users INSERT statement may have specified
152778  ** a value for the "rowid" field, for the "docid" field, or for both.
152779  ** Which is a problem, since "rowid" and "docid" are aliases for the
152780  ** same value. For example:
152781  **
152782  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
152783  **
152784  ** In FTS3, this is an error. It is an error to specify non-NULL values
152785  ** for both docid and some other rowid alias.
152786  */
152787  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
152788    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
152789     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
152790    ){
152791      /* A rowid/docid conflict. */
152792      return SQLITE_ERROR;
152793    }
152794    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
152795    if( rc!=SQLITE_OK ) return rc;
152796  }
152797
152798  /* Execute the statement to insert the record. Set *piDocid to the
152799  ** new docid value.
152800  */
152801  sqlite3_step(pContentInsert);
152802  rc = sqlite3_reset(pContentInsert);
152803
152804  *piDocid = sqlite3_last_insert_rowid(p->db);
152805  return rc;
152806}
152807
152808
152809
152810/*
152811** Remove all data from the FTS3 table. Clear the hash table containing
152812** pending terms.
152813*/
152814static int fts3DeleteAll(Fts3Table *p, int bContent){
152815  int rc = SQLITE_OK;             /* Return code */
152816
152817  /* Discard the contents of the pending-terms hash table. */
152818  sqlite3Fts3PendingTermsClear(p);
152819
152820  /* Delete everything from the shadow tables. Except, leave %_content as
152821  ** is if bContent is false.  */
152822  assert( p->zContentTbl==0 || bContent==0 );
152823  if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
152824  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
152825  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
152826  if( p->bHasDocsize ){
152827    fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
152828  }
152829  if( p->bHasStat ){
152830    fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
152831  }
152832  return rc;
152833}
152834
152835/*
152836**
152837*/
152838static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
152839  int iLangid = 0;
152840  if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
152841  return iLangid;
152842}
152843
152844/*
152845** The first element in the apVal[] array is assumed to contain the docid
152846** (an integer) of a row about to be deleted. Remove all terms from the
152847** full-text index.
152848*/
152849static void fts3DeleteTerms(
152850  int *pRC,               /* Result code */
152851  Fts3Table *p,           /* The FTS table to delete from */
152852  sqlite3_value *pRowid,  /* The docid to be deleted */
152853  u32 *aSz,               /* Sizes of deleted document written here */
152854  int *pbFound            /* OUT: Set to true if row really does exist */
152855){
152856  int rc;
152857  sqlite3_stmt *pSelect;
152858
152859  assert( *pbFound==0 );
152860  if( *pRC ) return;
152861  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
152862  if( rc==SQLITE_OK ){
152863    if( SQLITE_ROW==sqlite3_step(pSelect) ){
152864      int i;
152865      int iLangid = langidFromSelect(p, pSelect);
152866      i64 iDocid = sqlite3_column_int64(pSelect, 0);
152867      rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
152868      for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
152869        int iCol = i-1;
152870        if( p->abNotindexed[iCol]==0 ){
152871          const char *zText = (const char *)sqlite3_column_text(pSelect, i);
152872          rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
152873          aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
152874        }
152875      }
152876      if( rc!=SQLITE_OK ){
152877        sqlite3_reset(pSelect);
152878        *pRC = rc;
152879        return;
152880      }
152881      *pbFound = 1;
152882    }
152883    rc = sqlite3_reset(pSelect);
152884  }else{
152885    sqlite3_reset(pSelect);
152886  }
152887  *pRC = rc;
152888}
152889
152890/*
152891** Forward declaration to account for the circular dependency between
152892** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
152893*/
152894static int fts3SegmentMerge(Fts3Table *, int, int, int);
152895
152896/*
152897** This function allocates a new level iLevel index in the segdir table.
152898** Usually, indexes are allocated within a level sequentially starting
152899** with 0, so the allocated index is one greater than the value returned
152900** by:
152901**
152902**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
152903**
152904** However, if there are already FTS3_MERGE_COUNT indexes at the requested
152905** level, they are merged into a single level (iLevel+1) segment and the
152906** allocated index is 0.
152907**
152908** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
152909** returned. Otherwise, an SQLite error code is returned.
152910*/
152911static int fts3AllocateSegdirIdx(
152912  Fts3Table *p,
152913  int iLangid,                    /* Language id */
152914  int iIndex,                     /* Index for p->aIndex */
152915  int iLevel,
152916  int *piIdx
152917){
152918  int rc;                         /* Return Code */
152919  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
152920  int iNext = 0;                  /* Result of query pNextIdx */
152921
152922  assert( iLangid>=0 );
152923  assert( p->nIndex>=1 );
152924
152925  /* Set variable iNext to the next available segdir index at level iLevel. */
152926  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
152927  if( rc==SQLITE_OK ){
152928    sqlite3_bind_int64(
152929        pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
152930    );
152931    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
152932      iNext = sqlite3_column_int(pNextIdx, 0);
152933    }
152934    rc = sqlite3_reset(pNextIdx);
152935  }
152936
152937  if( rc==SQLITE_OK ){
152938    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
152939    ** full, merge all segments in level iLevel into a single iLevel+1
152940    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
152941    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
152942    */
152943    if( iNext>=FTS3_MERGE_COUNT ){
152944      fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
152945      rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
152946      *piIdx = 0;
152947    }else{
152948      *piIdx = iNext;
152949    }
152950  }
152951
152952  return rc;
152953}
152954
152955/*
152956** The %_segments table is declared as follows:
152957**
152958**   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
152959**
152960** This function reads data from a single row of the %_segments table. The
152961** specific row is identified by the iBlockid parameter. If paBlob is not
152962** NULL, then a buffer is allocated using sqlite3_malloc() and populated
152963** with the contents of the blob stored in the "block" column of the
152964** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
152965** to the size of the blob in bytes before returning.
152966**
152967** If an error occurs, or the table does not contain the specified row,
152968** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
152969** paBlob is non-NULL, then it is the responsibility of the caller to
152970** eventually free the returned buffer.
152971**
152972** This function may leave an open sqlite3_blob* handle in the
152973** Fts3Table.pSegments variable. This handle is reused by subsequent calls
152974** to this function. The handle may be closed by calling the
152975** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
152976** performance improvement, but the blob handle should always be closed
152977** before control is returned to the user (to prevent a lock being held
152978** on the database file for longer than necessary). Thus, any virtual table
152979** method (xFilter etc.) that may directly or indirectly call this function
152980** must call sqlite3Fts3SegmentsClose() before returning.
152981*/
152982SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
152983  Fts3Table *p,                   /* FTS3 table handle */
152984  sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
152985  char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
152986  int *pnBlob,                    /* OUT: Size of blob data */
152987  int *pnLoad                     /* OUT: Bytes actually loaded */
152988){
152989  int rc;                         /* Return code */
152990
152991  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
152992  assert( pnBlob );
152993
152994  if( p->pSegments ){
152995    rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
152996  }else{
152997    if( 0==p->zSegmentsTbl ){
152998      p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
152999      if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
153000    }
153001    rc = sqlite3_blob_open(
153002       p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
153003    );
153004  }
153005
153006  if( rc==SQLITE_OK ){
153007    int nByte = sqlite3_blob_bytes(p->pSegments);
153008    *pnBlob = nByte;
153009    if( paBlob ){
153010      char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
153011      if( !aByte ){
153012        rc = SQLITE_NOMEM;
153013      }else{
153014        if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
153015          nByte = FTS3_NODE_CHUNKSIZE;
153016          *pnLoad = nByte;
153017        }
153018        rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
153019        memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
153020        if( rc!=SQLITE_OK ){
153021          sqlite3_free(aByte);
153022          aByte = 0;
153023        }
153024      }
153025      *paBlob = aByte;
153026    }
153027  }
153028
153029  return rc;
153030}
153031
153032/*
153033** Close the blob handle at p->pSegments, if it is open. See comments above
153034** the sqlite3Fts3ReadBlock() function for details.
153035*/
153036SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
153037  sqlite3_blob_close(p->pSegments);
153038  p->pSegments = 0;
153039}
153040
153041static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
153042  int nRead;                      /* Number of bytes to read */
153043  int rc;                         /* Return code */
153044
153045  nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
153046  rc = sqlite3_blob_read(
153047      pReader->pBlob,
153048      &pReader->aNode[pReader->nPopulate],
153049      nRead,
153050      pReader->nPopulate
153051  );
153052
153053  if( rc==SQLITE_OK ){
153054    pReader->nPopulate += nRead;
153055    memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
153056    if( pReader->nPopulate==pReader->nNode ){
153057      sqlite3_blob_close(pReader->pBlob);
153058      pReader->pBlob = 0;
153059      pReader->nPopulate = 0;
153060    }
153061  }
153062  return rc;
153063}
153064
153065static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
153066  int rc = SQLITE_OK;
153067  assert( !pReader->pBlob
153068       || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
153069  );
153070  while( pReader->pBlob && rc==SQLITE_OK
153071     &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
153072  ){
153073    rc = fts3SegReaderIncrRead(pReader);
153074  }
153075  return rc;
153076}
153077
153078/*
153079** Set an Fts3SegReader cursor to point at EOF.
153080*/
153081static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
153082  if( !fts3SegReaderIsRootOnly(pSeg) ){
153083    sqlite3_free(pSeg->aNode);
153084    sqlite3_blob_close(pSeg->pBlob);
153085    pSeg->pBlob = 0;
153086  }
153087  pSeg->aNode = 0;
153088}
153089
153090/*
153091** Move the iterator passed as the first argument to the next term in the
153092** segment. If successful, SQLITE_OK is returned. If there is no next term,
153093** SQLITE_DONE. Otherwise, an SQLite error code.
153094*/
153095static int fts3SegReaderNext(
153096  Fts3Table *p,
153097  Fts3SegReader *pReader,
153098  int bIncr
153099){
153100  int rc;                         /* Return code of various sub-routines */
153101  char *pNext;                    /* Cursor variable */
153102  int nPrefix;                    /* Number of bytes in term prefix */
153103  int nSuffix;                    /* Number of bytes in term suffix */
153104
153105  if( !pReader->aDoclist ){
153106    pNext = pReader->aNode;
153107  }else{
153108    pNext = &pReader->aDoclist[pReader->nDoclist];
153109  }
153110
153111  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
153112
153113    if( fts3SegReaderIsPending(pReader) ){
153114      Fts3HashElem *pElem = *(pReader->ppNextElem);
153115      sqlite3_free(pReader->aNode);
153116      pReader->aNode = 0;
153117      if( pElem ){
153118        char *aCopy;
153119        PendingList *pList = (PendingList *)fts3HashData(pElem);
153120        int nCopy = pList->nData+1;
153121        pReader->zTerm = (char *)fts3HashKey(pElem);
153122        pReader->nTerm = fts3HashKeysize(pElem);
153123        aCopy = (char*)sqlite3_malloc(nCopy);
153124        if( !aCopy ) return SQLITE_NOMEM;
153125        memcpy(aCopy, pList->aData, nCopy);
153126        pReader->nNode = pReader->nDoclist = nCopy;
153127        pReader->aNode = pReader->aDoclist = aCopy;
153128        pReader->ppNextElem++;
153129        assert( pReader->aNode );
153130      }
153131      return SQLITE_OK;
153132    }
153133
153134    fts3SegReaderSetEof(pReader);
153135
153136    /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
153137    ** blocks have already been traversed.  */
153138    assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
153139    if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
153140      return SQLITE_OK;
153141    }
153142
153143    rc = sqlite3Fts3ReadBlock(
153144        p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
153145        (bIncr ? &pReader->nPopulate : 0)
153146    );
153147    if( rc!=SQLITE_OK ) return rc;
153148    assert( pReader->pBlob==0 );
153149    if( bIncr && pReader->nPopulate<pReader->nNode ){
153150      pReader->pBlob = p->pSegments;
153151      p->pSegments = 0;
153152    }
153153    pNext = pReader->aNode;
153154  }
153155
153156  assert( !fts3SegReaderIsPending(pReader) );
153157
153158  rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
153159  if( rc!=SQLITE_OK ) return rc;
153160
153161  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
153162  ** safe (no risk of overread) even if the node data is corrupted. */
153163  pNext += fts3GetVarint32(pNext, &nPrefix);
153164  pNext += fts3GetVarint32(pNext, &nSuffix);
153165  if( nPrefix<0 || nSuffix<=0
153166   || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
153167  ){
153168    return FTS_CORRUPT_VTAB;
153169  }
153170
153171  if( nPrefix+nSuffix>pReader->nTermAlloc ){
153172    int nNew = (nPrefix+nSuffix)*2;
153173    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
153174    if( !zNew ){
153175      return SQLITE_NOMEM;
153176    }
153177    pReader->zTerm = zNew;
153178    pReader->nTermAlloc = nNew;
153179  }
153180
153181  rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
153182  if( rc!=SQLITE_OK ) return rc;
153183
153184  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
153185  pReader->nTerm = nPrefix+nSuffix;
153186  pNext += nSuffix;
153187  pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
153188  pReader->aDoclist = pNext;
153189  pReader->pOffsetList = 0;
153190
153191  /* Check that the doclist does not appear to extend past the end of the
153192  ** b-tree node. And that the final byte of the doclist is 0x00. If either
153193  ** of these statements is untrue, then the data structure is corrupt.
153194  */
153195  if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
153196   || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
153197  ){
153198    return FTS_CORRUPT_VTAB;
153199  }
153200  return SQLITE_OK;
153201}
153202
153203/*
153204** Set the SegReader to point to the first docid in the doclist associated
153205** with the current term.
153206*/
153207static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
153208  int rc = SQLITE_OK;
153209  assert( pReader->aDoclist );
153210  assert( !pReader->pOffsetList );
153211  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
153212    u8 bEof = 0;
153213    pReader->iDocid = 0;
153214    pReader->nOffsetList = 0;
153215    sqlite3Fts3DoclistPrev(0,
153216        pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
153217        &pReader->iDocid, &pReader->nOffsetList, &bEof
153218    );
153219  }else{
153220    rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
153221    if( rc==SQLITE_OK ){
153222      int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
153223      pReader->pOffsetList = &pReader->aDoclist[n];
153224    }
153225  }
153226  return rc;
153227}
153228
153229/*
153230** Advance the SegReader to point to the next docid in the doclist
153231** associated with the current term.
153232**
153233** If arguments ppOffsetList and pnOffsetList are not NULL, then
153234** *ppOffsetList is set to point to the first column-offset list
153235** in the doclist entry (i.e. immediately past the docid varint).
153236** *pnOffsetList is set to the length of the set of column-offset
153237** lists, not including the nul-terminator byte. For example:
153238*/
153239static int fts3SegReaderNextDocid(
153240  Fts3Table *pTab,
153241  Fts3SegReader *pReader,         /* Reader to advance to next docid */
153242  char **ppOffsetList,            /* OUT: Pointer to current position-list */
153243  int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
153244){
153245  int rc = SQLITE_OK;
153246  char *p = pReader->pOffsetList;
153247  char c = 0;
153248
153249  assert( p );
153250
153251  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
153252    /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
153253    ** Pending-terms doclists are always built up in ascending order, so
153254    ** we have to iterate through them backwards here. */
153255    u8 bEof = 0;
153256    if( ppOffsetList ){
153257      *ppOffsetList = pReader->pOffsetList;
153258      *pnOffsetList = pReader->nOffsetList - 1;
153259    }
153260    sqlite3Fts3DoclistPrev(0,
153261        pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
153262        &pReader->nOffsetList, &bEof
153263    );
153264    if( bEof ){
153265      pReader->pOffsetList = 0;
153266    }else{
153267      pReader->pOffsetList = p;
153268    }
153269  }else{
153270    char *pEnd = &pReader->aDoclist[pReader->nDoclist];
153271
153272    /* Pointer p currently points at the first byte of an offset list. The
153273    ** following block advances it to point one byte past the end of
153274    ** the same offset list. */
153275    while( 1 ){
153276
153277      /* The following line of code (and the "p++" below the while() loop) is
153278      ** normally all that is required to move pointer p to the desired
153279      ** position. The exception is if this node is being loaded from disk
153280      ** incrementally and pointer "p" now points to the first byte past
153281      ** the populated part of pReader->aNode[].
153282      */
153283      while( *p | c ) c = *p++ & 0x80;
153284      assert( *p==0 );
153285
153286      if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
153287      rc = fts3SegReaderIncrRead(pReader);
153288      if( rc!=SQLITE_OK ) return rc;
153289    }
153290    p++;
153291
153292    /* If required, populate the output variables with a pointer to and the
153293    ** size of the previous offset-list.
153294    */
153295    if( ppOffsetList ){
153296      *ppOffsetList = pReader->pOffsetList;
153297      *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
153298    }
153299
153300    /* List may have been edited in place by fts3EvalNearTrim() */
153301    while( p<pEnd && *p==0 ) p++;
153302
153303    /* If there are no more entries in the doclist, set pOffsetList to
153304    ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
153305    ** Fts3SegReader.pOffsetList to point to the next offset list before
153306    ** returning.
153307    */
153308    if( p>=pEnd ){
153309      pReader->pOffsetList = 0;
153310    }else{
153311      rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
153312      if( rc==SQLITE_OK ){
153313        sqlite3_int64 iDelta;
153314        pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
153315        if( pTab->bDescIdx ){
153316          pReader->iDocid -= iDelta;
153317        }else{
153318          pReader->iDocid += iDelta;
153319        }
153320      }
153321    }
153322  }
153323
153324  return SQLITE_OK;
153325}
153326
153327
153328SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
153329  Fts3Cursor *pCsr,
153330  Fts3MultiSegReader *pMsr,
153331  int *pnOvfl
153332){
153333  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
153334  int nOvfl = 0;
153335  int ii;
153336  int rc = SQLITE_OK;
153337  int pgsz = p->nPgsz;
153338
153339  assert( p->bFts4 );
153340  assert( pgsz>0 );
153341
153342  for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
153343    Fts3SegReader *pReader = pMsr->apSegment[ii];
153344    if( !fts3SegReaderIsPending(pReader)
153345     && !fts3SegReaderIsRootOnly(pReader)
153346    ){
153347      sqlite3_int64 jj;
153348      for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
153349        int nBlob;
153350        rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
153351        if( rc!=SQLITE_OK ) break;
153352        if( (nBlob+35)>pgsz ){
153353          nOvfl += (nBlob + 34)/pgsz;
153354        }
153355      }
153356    }
153357  }
153358  *pnOvfl = nOvfl;
153359  return rc;
153360}
153361
153362/*
153363** Free all allocations associated with the iterator passed as the
153364** second argument.
153365*/
153366SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
153367  if( pReader ){
153368    if( !fts3SegReaderIsPending(pReader) ){
153369      sqlite3_free(pReader->zTerm);
153370    }
153371    if( !fts3SegReaderIsRootOnly(pReader) ){
153372      sqlite3_free(pReader->aNode);
153373    }
153374    sqlite3_blob_close(pReader->pBlob);
153375  }
153376  sqlite3_free(pReader);
153377}
153378
153379/*
153380** Allocate a new SegReader object.
153381*/
153382SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
153383  int iAge,                       /* Segment "age". */
153384  int bLookup,                    /* True for a lookup only */
153385  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
153386  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
153387  sqlite3_int64 iEndBlock,        /* Final block of segment */
153388  const char *zRoot,              /* Buffer containing root node */
153389  int nRoot,                      /* Size of buffer containing root node */
153390  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
153391){
153392  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
153393  int nExtra = 0;                 /* Bytes to allocate segment root node */
153394
153395  assert( iStartLeaf<=iEndLeaf );
153396  if( iStartLeaf==0 ){
153397    nExtra = nRoot + FTS3_NODE_PADDING;
153398  }
153399
153400  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
153401  if( !pReader ){
153402    return SQLITE_NOMEM;
153403  }
153404  memset(pReader, 0, sizeof(Fts3SegReader));
153405  pReader->iIdx = iAge;
153406  pReader->bLookup = bLookup!=0;
153407  pReader->iStartBlock = iStartLeaf;
153408  pReader->iLeafEndBlock = iEndLeaf;
153409  pReader->iEndBlock = iEndBlock;
153410
153411  if( nExtra ){
153412    /* The entire segment is stored in the root node. */
153413    pReader->aNode = (char *)&pReader[1];
153414    pReader->rootOnly = 1;
153415    pReader->nNode = nRoot;
153416    memcpy(pReader->aNode, zRoot, nRoot);
153417    memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
153418  }else{
153419    pReader->iCurrentBlock = iStartLeaf-1;
153420  }
153421  *ppReader = pReader;
153422  return SQLITE_OK;
153423}
153424
153425/*
153426** This is a comparison function used as a qsort() callback when sorting
153427** an array of pending terms by term. This occurs as part of flushing
153428** the contents of the pending-terms hash table to the database.
153429*/
153430static int SQLITE_CDECL fts3CompareElemByTerm(
153431  const void *lhs,
153432  const void *rhs
153433){
153434  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
153435  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
153436  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
153437  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
153438
153439  int n = (n1<n2 ? n1 : n2);
153440  int c = memcmp(z1, z2, n);
153441  if( c==0 ){
153442    c = n1 - n2;
153443  }
153444  return c;
153445}
153446
153447/*
153448** This function is used to allocate an Fts3SegReader that iterates through
153449** a subset of the terms stored in the Fts3Table.pendingTerms array.
153450**
153451** If the isPrefixIter parameter is zero, then the returned SegReader iterates
153452** through each term in the pending-terms table. Or, if isPrefixIter is
153453** non-zero, it iterates through each term and its prefixes. For example, if
153454** the pending terms hash table contains the terms "sqlite", "mysql" and
153455** "firebird", then the iterator visits the following 'terms' (in the order
153456** shown):
153457**
153458**   f fi fir fire fireb firebi firebir firebird
153459**   m my mys mysq mysql
153460**   s sq sql sqli sqlit sqlite
153461**
153462** Whereas if isPrefixIter is zero, the terms visited are:
153463**
153464**   firebird mysql sqlite
153465*/
153466SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
153467  Fts3Table *p,                   /* Virtual table handle */
153468  int iIndex,                     /* Index for p->aIndex */
153469  const char *zTerm,              /* Term to search for */
153470  int nTerm,                      /* Size of buffer zTerm */
153471  int bPrefix,                    /* True for a prefix iterator */
153472  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
153473){
153474  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
153475  Fts3HashElem *pE;               /* Iterator variable */
153476  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
153477  int nElem = 0;                  /* Size of array at aElem */
153478  int rc = SQLITE_OK;             /* Return Code */
153479  Fts3Hash *pHash;
153480
153481  pHash = &p->aIndex[iIndex].hPending;
153482  if( bPrefix ){
153483    int nAlloc = 0;               /* Size of allocated array at aElem */
153484
153485    for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
153486      char *zKey = (char *)fts3HashKey(pE);
153487      int nKey = fts3HashKeysize(pE);
153488      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
153489        if( nElem==nAlloc ){
153490          Fts3HashElem **aElem2;
153491          nAlloc += 16;
153492          aElem2 = (Fts3HashElem **)sqlite3_realloc(
153493              aElem, nAlloc*sizeof(Fts3HashElem *)
153494          );
153495          if( !aElem2 ){
153496            rc = SQLITE_NOMEM;
153497            nElem = 0;
153498            break;
153499          }
153500          aElem = aElem2;
153501        }
153502
153503        aElem[nElem++] = pE;
153504      }
153505    }
153506
153507    /* If more than one term matches the prefix, sort the Fts3HashElem
153508    ** objects in term order using qsort(). This uses the same comparison
153509    ** callback as is used when flushing terms to disk.
153510    */
153511    if( nElem>1 ){
153512      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
153513    }
153514
153515  }else{
153516    /* The query is a simple term lookup that matches at most one term in
153517    ** the index. All that is required is a straight hash-lookup.
153518    **
153519    ** Because the stack address of pE may be accessed via the aElem pointer
153520    ** below, the "Fts3HashElem *pE" must be declared so that it is valid
153521    ** within this entire function, not just this "else{...}" block.
153522    */
153523    pE = fts3HashFindElem(pHash, zTerm, nTerm);
153524    if( pE ){
153525      aElem = &pE;
153526      nElem = 1;
153527    }
153528  }
153529
153530  if( nElem>0 ){
153531    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
153532    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
153533    if( !pReader ){
153534      rc = SQLITE_NOMEM;
153535    }else{
153536      memset(pReader, 0, nByte);
153537      pReader->iIdx = 0x7FFFFFFF;
153538      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
153539      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
153540    }
153541  }
153542
153543  if( bPrefix ){
153544    sqlite3_free(aElem);
153545  }
153546  *ppReader = pReader;
153547  return rc;
153548}
153549
153550/*
153551** Compare the entries pointed to by two Fts3SegReader structures.
153552** Comparison is as follows:
153553**
153554**   1) EOF is greater than not EOF.
153555**
153556**   2) The current terms (if any) are compared using memcmp(). If one
153557**      term is a prefix of another, the longer term is considered the
153558**      larger.
153559**
153560**   3) By segment age. An older segment is considered larger.
153561*/
153562static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
153563  int rc;
153564  if( pLhs->aNode && pRhs->aNode ){
153565    int rc2 = pLhs->nTerm - pRhs->nTerm;
153566    if( rc2<0 ){
153567      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
153568    }else{
153569      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
153570    }
153571    if( rc==0 ){
153572      rc = rc2;
153573    }
153574  }else{
153575    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
153576  }
153577  if( rc==0 ){
153578    rc = pRhs->iIdx - pLhs->iIdx;
153579  }
153580  assert( rc!=0 );
153581  return rc;
153582}
153583
153584/*
153585** A different comparison function for SegReader structures. In this
153586** version, it is assumed that each SegReader points to an entry in
153587** a doclist for identical terms. Comparison is made as follows:
153588**
153589**   1) EOF (end of doclist in this case) is greater than not EOF.
153590**
153591**   2) By current docid.
153592**
153593**   3) By segment age. An older segment is considered larger.
153594*/
153595static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
153596  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
153597  if( rc==0 ){
153598    if( pLhs->iDocid==pRhs->iDocid ){
153599      rc = pRhs->iIdx - pLhs->iIdx;
153600    }else{
153601      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
153602    }
153603  }
153604  assert( pLhs->aNode && pRhs->aNode );
153605  return rc;
153606}
153607static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
153608  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
153609  if( rc==0 ){
153610    if( pLhs->iDocid==pRhs->iDocid ){
153611      rc = pRhs->iIdx - pLhs->iIdx;
153612    }else{
153613      rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
153614    }
153615  }
153616  assert( pLhs->aNode && pRhs->aNode );
153617  return rc;
153618}
153619
153620/*
153621** Compare the term that the Fts3SegReader object passed as the first argument
153622** points to with the term specified by arguments zTerm and nTerm.
153623**
153624** If the pSeg iterator is already at EOF, return 0. Otherwise, return
153625** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
153626** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
153627*/
153628static int fts3SegReaderTermCmp(
153629  Fts3SegReader *pSeg,            /* Segment reader object */
153630  const char *zTerm,              /* Term to compare to */
153631  int nTerm                       /* Size of term zTerm in bytes */
153632){
153633  int res = 0;
153634  if( pSeg->aNode ){
153635    if( pSeg->nTerm>nTerm ){
153636      res = memcmp(pSeg->zTerm, zTerm, nTerm);
153637    }else{
153638      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
153639    }
153640    if( res==0 ){
153641      res = pSeg->nTerm-nTerm;
153642    }
153643  }
153644  return res;
153645}
153646
153647/*
153648** Argument apSegment is an array of nSegment elements. It is known that
153649** the final (nSegment-nSuspect) members are already in sorted order
153650** (according to the comparison function provided). This function shuffles
153651** the array around until all entries are in sorted order.
153652*/
153653static void fts3SegReaderSort(
153654  Fts3SegReader **apSegment,                     /* Array to sort entries of */
153655  int nSegment,                                  /* Size of apSegment array */
153656  int nSuspect,                                  /* Unsorted entry count */
153657  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
153658){
153659  int i;                          /* Iterator variable */
153660
153661  assert( nSuspect<=nSegment );
153662
153663  if( nSuspect==nSegment ) nSuspect--;
153664  for(i=nSuspect-1; i>=0; i--){
153665    int j;
153666    for(j=i; j<(nSegment-1); j++){
153667      Fts3SegReader *pTmp;
153668      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
153669      pTmp = apSegment[j+1];
153670      apSegment[j+1] = apSegment[j];
153671      apSegment[j] = pTmp;
153672    }
153673  }
153674
153675#ifndef NDEBUG
153676  /* Check that the list really is sorted now. */
153677  for(i=0; i<(nSuspect-1); i++){
153678    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
153679  }
153680#endif
153681}
153682
153683/*
153684** Insert a record into the %_segments table.
153685*/
153686static int fts3WriteSegment(
153687  Fts3Table *p,                   /* Virtual table handle */
153688  sqlite3_int64 iBlock,           /* Block id for new block */
153689  char *z,                        /* Pointer to buffer containing block data */
153690  int n                           /* Size of buffer z in bytes */
153691){
153692  sqlite3_stmt *pStmt;
153693  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
153694  if( rc==SQLITE_OK ){
153695    sqlite3_bind_int64(pStmt, 1, iBlock);
153696    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
153697    sqlite3_step(pStmt);
153698    rc = sqlite3_reset(pStmt);
153699  }
153700  return rc;
153701}
153702
153703/*
153704** Find the largest relative level number in the table. If successful, set
153705** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
153706** set *pnMax to zero and return an SQLite error code.
153707*/
153708SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
153709  int rc;
153710  int mxLevel = 0;
153711  sqlite3_stmt *pStmt = 0;
153712
153713  rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
153714  if( rc==SQLITE_OK ){
153715    if( SQLITE_ROW==sqlite3_step(pStmt) ){
153716      mxLevel = sqlite3_column_int(pStmt, 0);
153717    }
153718    rc = sqlite3_reset(pStmt);
153719  }
153720  *pnMax = mxLevel;
153721  return rc;
153722}
153723
153724/*
153725** Insert a record into the %_segdir table.
153726*/
153727static int fts3WriteSegdir(
153728  Fts3Table *p,                   /* Virtual table handle */
153729  sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
153730  int iIdx,                       /* Value for "idx" field */
153731  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
153732  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
153733  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
153734  sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */
153735  char *zRoot,                    /* Blob value for "root" field */
153736  int nRoot                       /* Number of bytes in buffer zRoot */
153737){
153738  sqlite3_stmt *pStmt;
153739  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
153740  if( rc==SQLITE_OK ){
153741    sqlite3_bind_int64(pStmt, 1, iLevel);
153742    sqlite3_bind_int(pStmt, 2, iIdx);
153743    sqlite3_bind_int64(pStmt, 3, iStartBlock);
153744    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
153745    if( nLeafData==0 ){
153746      sqlite3_bind_int64(pStmt, 5, iEndBlock);
153747    }else{
153748      char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
153749      if( !zEnd ) return SQLITE_NOMEM;
153750      sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
153751    }
153752    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
153753    sqlite3_step(pStmt);
153754    rc = sqlite3_reset(pStmt);
153755  }
153756  return rc;
153757}
153758
153759/*
153760** Return the size of the common prefix (if any) shared by zPrev and
153761** zNext, in bytes. For example,
153762**
153763**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
153764**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
153765**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
153766*/
153767static int fts3PrefixCompress(
153768  const char *zPrev,              /* Buffer containing previous term */
153769  int nPrev,                      /* Size of buffer zPrev in bytes */
153770  const char *zNext,              /* Buffer containing next term */
153771  int nNext                       /* Size of buffer zNext in bytes */
153772){
153773  int n;
153774  UNUSED_PARAMETER(nNext);
153775  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
153776  return n;
153777}
153778
153779/*
153780** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
153781** (according to memcmp) than the previous term.
153782*/
153783static int fts3NodeAddTerm(
153784  Fts3Table *p,                   /* Virtual table handle */
153785  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
153786  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
153787  const char *zTerm,              /* Pointer to buffer containing term */
153788  int nTerm                       /* Size of term in bytes */
153789){
153790  SegmentNode *pTree = *ppTree;
153791  int rc;
153792  SegmentNode *pNew;
153793
153794  /* First try to append the term to the current node. Return early if
153795  ** this is possible.
153796  */
153797  if( pTree ){
153798    int nData = pTree->nData;     /* Current size of node in bytes */
153799    int nReq = nData;             /* Required space after adding zTerm */
153800    int nPrefix;                  /* Number of bytes of prefix compression */
153801    int nSuffix;                  /* Suffix length */
153802
153803    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
153804    nSuffix = nTerm-nPrefix;
153805
153806    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
153807    if( nReq<=p->nNodeSize || !pTree->zTerm ){
153808
153809      if( nReq>p->nNodeSize ){
153810        /* An unusual case: this is the first term to be added to the node
153811        ** and the static node buffer (p->nNodeSize bytes) is not large
153812        ** enough. Use a separately malloced buffer instead This wastes
153813        ** p->nNodeSize bytes, but since this scenario only comes about when
153814        ** the database contain two terms that share a prefix of almost 2KB,
153815        ** this is not expected to be a serious problem.
153816        */
153817        assert( pTree->aData==(char *)&pTree[1] );
153818        pTree->aData = (char *)sqlite3_malloc(nReq);
153819        if( !pTree->aData ){
153820          return SQLITE_NOMEM;
153821        }
153822      }
153823
153824      if( pTree->zTerm ){
153825        /* There is no prefix-length field for first term in a node */
153826        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
153827      }
153828
153829      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
153830      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
153831      pTree->nData = nData + nSuffix;
153832      pTree->nEntry++;
153833
153834      if( isCopyTerm ){
153835        if( pTree->nMalloc<nTerm ){
153836          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
153837          if( !zNew ){
153838            return SQLITE_NOMEM;
153839          }
153840          pTree->nMalloc = nTerm*2;
153841          pTree->zMalloc = zNew;
153842        }
153843        pTree->zTerm = pTree->zMalloc;
153844        memcpy(pTree->zTerm, zTerm, nTerm);
153845        pTree->nTerm = nTerm;
153846      }else{
153847        pTree->zTerm = (char *)zTerm;
153848        pTree->nTerm = nTerm;
153849      }
153850      return SQLITE_OK;
153851    }
153852  }
153853
153854  /* If control flows to here, it was not possible to append zTerm to the
153855  ** current node. Create a new node (a right-sibling of the current node).
153856  ** If this is the first node in the tree, the term is added to it.
153857  **
153858  ** Otherwise, the term is not added to the new node, it is left empty for
153859  ** now. Instead, the term is inserted into the parent of pTree. If pTree
153860  ** has no parent, one is created here.
153861  */
153862  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
153863  if( !pNew ){
153864    return SQLITE_NOMEM;
153865  }
153866  memset(pNew, 0, sizeof(SegmentNode));
153867  pNew->nData = 1 + FTS3_VARINT_MAX;
153868  pNew->aData = (char *)&pNew[1];
153869
153870  if( pTree ){
153871    SegmentNode *pParent = pTree->pParent;
153872    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
153873    if( pTree->pParent==0 ){
153874      pTree->pParent = pParent;
153875    }
153876    pTree->pRight = pNew;
153877    pNew->pLeftmost = pTree->pLeftmost;
153878    pNew->pParent = pParent;
153879    pNew->zMalloc = pTree->zMalloc;
153880    pNew->nMalloc = pTree->nMalloc;
153881    pTree->zMalloc = 0;
153882  }else{
153883    pNew->pLeftmost = pNew;
153884    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
153885  }
153886
153887  *ppTree = pNew;
153888  return rc;
153889}
153890
153891/*
153892** Helper function for fts3NodeWrite().
153893*/
153894static int fts3TreeFinishNode(
153895  SegmentNode *pTree,
153896  int iHeight,
153897  sqlite3_int64 iLeftChild
153898){
153899  int nStart;
153900  assert( iHeight>=1 && iHeight<128 );
153901  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
153902  pTree->aData[nStart] = (char)iHeight;
153903  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
153904  return nStart;
153905}
153906
153907/*
153908** Write the buffer for the segment node pTree and all of its peers to the
153909** database. Then call this function recursively to write the parent of
153910** pTree and its peers to the database.
153911**
153912** Except, if pTree is a root node, do not write it to the database. Instead,
153913** set output variables *paRoot and *pnRoot to contain the root node.
153914**
153915** If successful, SQLITE_OK is returned and output variable *piLast is
153916** set to the largest blockid written to the database (or zero if no
153917** blocks were written to the db). Otherwise, an SQLite error code is
153918** returned.
153919*/
153920static int fts3NodeWrite(
153921  Fts3Table *p,                   /* Virtual table handle */
153922  SegmentNode *pTree,             /* SegmentNode handle */
153923  int iHeight,                    /* Height of this node in tree */
153924  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
153925  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
153926  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
153927  char **paRoot,                  /* OUT: Data for root node */
153928  int *pnRoot                     /* OUT: Size of root node in bytes */
153929){
153930  int rc = SQLITE_OK;
153931
153932  if( !pTree->pParent ){
153933    /* Root node of the tree. */
153934    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
153935    *piLast = iFree-1;
153936    *pnRoot = pTree->nData - nStart;
153937    *paRoot = &pTree->aData[nStart];
153938  }else{
153939    SegmentNode *pIter;
153940    sqlite3_int64 iNextFree = iFree;
153941    sqlite3_int64 iNextLeaf = iLeaf;
153942    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
153943      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
153944      int nWrite = pIter->nData - nStart;
153945
153946      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
153947      iNextFree++;
153948      iNextLeaf += (pIter->nEntry+1);
153949    }
153950    if( rc==SQLITE_OK ){
153951      assert( iNextLeaf==iFree );
153952      rc = fts3NodeWrite(
153953          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
153954      );
153955    }
153956  }
153957
153958  return rc;
153959}
153960
153961/*
153962** Free all memory allocations associated with the tree pTree.
153963*/
153964static void fts3NodeFree(SegmentNode *pTree){
153965  if( pTree ){
153966    SegmentNode *p = pTree->pLeftmost;
153967    fts3NodeFree(p->pParent);
153968    while( p ){
153969      SegmentNode *pRight = p->pRight;
153970      if( p->aData!=(char *)&p[1] ){
153971        sqlite3_free(p->aData);
153972      }
153973      assert( pRight==0 || p->zMalloc==0 );
153974      sqlite3_free(p->zMalloc);
153975      sqlite3_free(p);
153976      p = pRight;
153977    }
153978  }
153979}
153980
153981/*
153982** Add a term to the segment being constructed by the SegmentWriter object
153983** *ppWriter. When adding the first term to a segment, *ppWriter should
153984** be passed NULL. This function will allocate a new SegmentWriter object
153985** and return it via the input/output variable *ppWriter in this case.
153986**
153987** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
153988*/
153989static int fts3SegWriterAdd(
153990  Fts3Table *p,                   /* Virtual table handle */
153991  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
153992  int isCopyTerm,                 /* True if buffer zTerm must be copied */
153993  const char *zTerm,              /* Pointer to buffer containing term */
153994  int nTerm,                      /* Size of term in bytes */
153995  const char *aDoclist,           /* Pointer to buffer containing doclist */
153996  int nDoclist                    /* Size of doclist in bytes */
153997){
153998  int nPrefix;                    /* Size of term prefix in bytes */
153999  int nSuffix;                    /* Size of term suffix in bytes */
154000  int nReq;                       /* Number of bytes required on leaf page */
154001  int nData;
154002  SegmentWriter *pWriter = *ppWriter;
154003
154004  if( !pWriter ){
154005    int rc;
154006    sqlite3_stmt *pStmt;
154007
154008    /* Allocate the SegmentWriter structure */
154009    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
154010    if( !pWriter ) return SQLITE_NOMEM;
154011    memset(pWriter, 0, sizeof(SegmentWriter));
154012    *ppWriter = pWriter;
154013
154014    /* Allocate a buffer in which to accumulate data */
154015    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
154016    if( !pWriter->aData ) return SQLITE_NOMEM;
154017    pWriter->nSize = p->nNodeSize;
154018
154019    /* Find the next free blockid in the %_segments table */
154020    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
154021    if( rc!=SQLITE_OK ) return rc;
154022    if( SQLITE_ROW==sqlite3_step(pStmt) ){
154023      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
154024      pWriter->iFirst = pWriter->iFree;
154025    }
154026    rc = sqlite3_reset(pStmt);
154027    if( rc!=SQLITE_OK ) return rc;
154028  }
154029  nData = pWriter->nData;
154030
154031  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
154032  nSuffix = nTerm-nPrefix;
154033
154034  /* Figure out how many bytes are required by this new entry */
154035  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
154036    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
154037    nSuffix +                               /* Term suffix */
154038    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
154039    nDoclist;                               /* Doclist data */
154040
154041  if( nData>0 && nData+nReq>p->nNodeSize ){
154042    int rc;
154043
154044    /* The current leaf node is full. Write it out to the database. */
154045    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
154046    if( rc!=SQLITE_OK ) return rc;
154047    p->nLeafAdd++;
154048
154049    /* Add the current term to the interior node tree. The term added to
154050    ** the interior tree must:
154051    **
154052    **   a) be greater than the largest term on the leaf node just written
154053    **      to the database (still available in pWriter->zTerm), and
154054    **
154055    **   b) be less than or equal to the term about to be added to the new
154056    **      leaf node (zTerm/nTerm).
154057    **
154058    ** In other words, it must be the prefix of zTerm 1 byte longer than
154059    ** the common prefix (if any) of zTerm and pWriter->zTerm.
154060    */
154061    assert( nPrefix<nTerm );
154062    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
154063    if( rc!=SQLITE_OK ) return rc;
154064
154065    nData = 0;
154066    pWriter->nTerm = 0;
154067
154068    nPrefix = 0;
154069    nSuffix = nTerm;
154070    nReq = 1 +                              /* varint containing prefix size */
154071      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
154072      nTerm +                               /* Term suffix */
154073      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
154074      nDoclist;                             /* Doclist data */
154075  }
154076
154077  /* Increase the total number of bytes written to account for the new entry. */
154078  pWriter->nLeafData += nReq;
154079
154080  /* If the buffer currently allocated is too small for this entry, realloc
154081  ** the buffer to make it large enough.
154082  */
154083  if( nReq>pWriter->nSize ){
154084    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
154085    if( !aNew ) return SQLITE_NOMEM;
154086    pWriter->aData = aNew;
154087    pWriter->nSize = nReq;
154088  }
154089  assert( nData+nReq<=pWriter->nSize );
154090
154091  /* Append the prefix-compressed term and doclist to the buffer. */
154092  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
154093  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
154094  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
154095  nData += nSuffix;
154096  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
154097  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
154098  pWriter->nData = nData + nDoclist;
154099
154100  /* Save the current term so that it can be used to prefix-compress the next.
154101  ** If the isCopyTerm parameter is true, then the buffer pointed to by
154102  ** zTerm is transient, so take a copy of the term data. Otherwise, just
154103  ** store a copy of the pointer.
154104  */
154105  if( isCopyTerm ){
154106    if( nTerm>pWriter->nMalloc ){
154107      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
154108      if( !zNew ){
154109        return SQLITE_NOMEM;
154110      }
154111      pWriter->nMalloc = nTerm*2;
154112      pWriter->zMalloc = zNew;
154113      pWriter->zTerm = zNew;
154114    }
154115    assert( pWriter->zTerm==pWriter->zMalloc );
154116    memcpy(pWriter->zTerm, zTerm, nTerm);
154117  }else{
154118    pWriter->zTerm = (char *)zTerm;
154119  }
154120  pWriter->nTerm = nTerm;
154121
154122  return SQLITE_OK;
154123}
154124
154125/*
154126** Flush all data associated with the SegmentWriter object pWriter to the
154127** database. This function must be called after all terms have been added
154128** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
154129** returned. Otherwise, an SQLite error code.
154130*/
154131static int fts3SegWriterFlush(
154132  Fts3Table *p,                   /* Virtual table handle */
154133  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
154134  sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
154135  int iIdx                        /* Value for 'idx' column of %_segdir */
154136){
154137  int rc;                         /* Return code */
154138  if( pWriter->pTree ){
154139    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
154140    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
154141    char *zRoot = NULL;           /* Pointer to buffer containing root node */
154142    int nRoot = 0;                /* Size of buffer zRoot */
154143
154144    iLastLeaf = pWriter->iFree;
154145    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
154146    if( rc==SQLITE_OK ){
154147      rc = fts3NodeWrite(p, pWriter->pTree, 1,
154148          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
154149    }
154150    if( rc==SQLITE_OK ){
154151      rc = fts3WriteSegdir(p, iLevel, iIdx,
154152          pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
154153    }
154154  }else{
154155    /* The entire tree fits on the root node. Write it to the segdir table. */
154156    rc = fts3WriteSegdir(p, iLevel, iIdx,
154157        0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
154158  }
154159  p->nLeafAdd++;
154160  return rc;
154161}
154162
154163/*
154164** Release all memory held by the SegmentWriter object passed as the
154165** first argument.
154166*/
154167static void fts3SegWriterFree(SegmentWriter *pWriter){
154168  if( pWriter ){
154169    sqlite3_free(pWriter->aData);
154170    sqlite3_free(pWriter->zMalloc);
154171    fts3NodeFree(pWriter->pTree);
154172    sqlite3_free(pWriter);
154173  }
154174}
154175
154176/*
154177** The first value in the apVal[] array is assumed to contain an integer.
154178** This function tests if there exist any documents with docid values that
154179** are different from that integer. i.e. if deleting the document with docid
154180** pRowid would mean the FTS3 table were empty.
154181**
154182** If successful, *pisEmpty is set to true if the table is empty except for
154183** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
154184** error occurs, an SQLite error code is returned.
154185*/
154186static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
154187  sqlite3_stmt *pStmt;
154188  int rc;
154189  if( p->zContentTbl ){
154190    /* If using the content=xxx option, assume the table is never empty */
154191    *pisEmpty = 0;
154192    rc = SQLITE_OK;
154193  }else{
154194    rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
154195    if( rc==SQLITE_OK ){
154196      if( SQLITE_ROW==sqlite3_step(pStmt) ){
154197        *pisEmpty = sqlite3_column_int(pStmt, 0);
154198      }
154199      rc = sqlite3_reset(pStmt);
154200    }
154201  }
154202  return rc;
154203}
154204
154205/*
154206** Set *pnMax to the largest segment level in the database for the index
154207** iIndex.
154208**
154209** Segment levels are stored in the 'level' column of the %_segdir table.
154210**
154211** Return SQLITE_OK if successful, or an SQLite error code if not.
154212*/
154213static int fts3SegmentMaxLevel(
154214  Fts3Table *p,
154215  int iLangid,
154216  int iIndex,
154217  sqlite3_int64 *pnMax
154218){
154219  sqlite3_stmt *pStmt;
154220  int rc;
154221  assert( iIndex>=0 && iIndex<p->nIndex );
154222
154223  /* Set pStmt to the compiled version of:
154224  **
154225  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
154226  **
154227  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
154228  */
154229  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
154230  if( rc!=SQLITE_OK ) return rc;
154231  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
154232  sqlite3_bind_int64(pStmt, 2,
154233      getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
154234  );
154235  if( SQLITE_ROW==sqlite3_step(pStmt) ){
154236    *pnMax = sqlite3_column_int64(pStmt, 0);
154237  }
154238  return sqlite3_reset(pStmt);
154239}
154240
154241/*
154242** iAbsLevel is an absolute level that may be assumed to exist within
154243** the database. This function checks if it is the largest level number
154244** within its index. Assuming no error occurs, *pbMax is set to 1 if
154245** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
154246** is returned. If an error occurs, an error code is returned and the
154247** final value of *pbMax is undefined.
154248*/
154249static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
154250
154251  /* Set pStmt to the compiled version of:
154252  **
154253  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
154254  **
154255  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
154256  */
154257  sqlite3_stmt *pStmt;
154258  int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
154259  if( rc!=SQLITE_OK ) return rc;
154260  sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
154261  sqlite3_bind_int64(pStmt, 2,
154262      ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
154263  );
154264
154265  *pbMax = 0;
154266  if( SQLITE_ROW==sqlite3_step(pStmt) ){
154267    *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
154268  }
154269  return sqlite3_reset(pStmt);
154270}
154271
154272/*
154273** Delete all entries in the %_segments table associated with the segment
154274** opened with seg-reader pSeg. This function does not affect the contents
154275** of the %_segdir table.
154276*/
154277static int fts3DeleteSegment(
154278  Fts3Table *p,                   /* FTS table handle */
154279  Fts3SegReader *pSeg             /* Segment to delete */
154280){
154281  int rc = SQLITE_OK;             /* Return code */
154282  if( pSeg->iStartBlock ){
154283    sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
154284    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
154285    if( rc==SQLITE_OK ){
154286      sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
154287      sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
154288      sqlite3_step(pDelete);
154289      rc = sqlite3_reset(pDelete);
154290    }
154291  }
154292  return rc;
154293}
154294
154295/*
154296** This function is used after merging multiple segments into a single large
154297** segment to delete the old, now redundant, segment b-trees. Specifically,
154298** it:
154299**
154300**   1) Deletes all %_segments entries for the segments associated with
154301**      each of the SegReader objects in the array passed as the third
154302**      argument, and
154303**
154304**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
154305**      entries regardless of level if (iLevel<0).
154306**
154307** SQLITE_OK is returned if successful, otherwise an SQLite error code.
154308*/
154309static int fts3DeleteSegdir(
154310  Fts3Table *p,                   /* Virtual table handle */
154311  int iLangid,                    /* Language id */
154312  int iIndex,                     /* Index for p->aIndex */
154313  int iLevel,                     /* Level of %_segdir entries to delete */
154314  Fts3SegReader **apSegment,      /* Array of SegReader objects */
154315  int nReader                     /* Size of array apSegment */
154316){
154317  int rc = SQLITE_OK;             /* Return Code */
154318  int i;                          /* Iterator variable */
154319  sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
154320
154321  for(i=0; rc==SQLITE_OK && i<nReader; i++){
154322    rc = fts3DeleteSegment(p, apSegment[i]);
154323  }
154324  if( rc!=SQLITE_OK ){
154325    return rc;
154326  }
154327
154328  assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
154329  if( iLevel==FTS3_SEGCURSOR_ALL ){
154330    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
154331    if( rc==SQLITE_OK ){
154332      sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
154333      sqlite3_bind_int64(pDelete, 2,
154334          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
154335      );
154336    }
154337  }else{
154338    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
154339    if( rc==SQLITE_OK ){
154340      sqlite3_bind_int64(
154341          pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
154342      );
154343    }
154344  }
154345
154346  if( rc==SQLITE_OK ){
154347    sqlite3_step(pDelete);
154348    rc = sqlite3_reset(pDelete);
154349  }
154350
154351  return rc;
154352}
154353
154354/*
154355** When this function is called, buffer *ppList (size *pnList bytes) contains
154356** a position list that may (or may not) feature multiple columns. This
154357** function adjusts the pointer *ppList and the length *pnList so that they
154358** identify the subset of the position list that corresponds to column iCol.
154359**
154360** If there are no entries in the input position list for column iCol, then
154361** *pnList is set to zero before returning.
154362**
154363** If parameter bZero is non-zero, then any part of the input list following
154364** the end of the output list is zeroed before returning.
154365*/
154366static void fts3ColumnFilter(
154367  int iCol,                       /* Column to filter on */
154368  int bZero,                      /* Zero out anything following *ppList */
154369  char **ppList,                  /* IN/OUT: Pointer to position list */
154370  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
154371){
154372  char *pList = *ppList;
154373  int nList = *pnList;
154374  char *pEnd = &pList[nList];
154375  int iCurrent = 0;
154376  char *p = pList;
154377
154378  assert( iCol>=0 );
154379  while( 1 ){
154380    char c = 0;
154381    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
154382
154383    if( iCol==iCurrent ){
154384      nList = (int)(p - pList);
154385      break;
154386    }
154387
154388    nList -= (int)(p - pList);
154389    pList = p;
154390    if( nList==0 ){
154391      break;
154392    }
154393    p = &pList[1];
154394    p += fts3GetVarint32(p, &iCurrent);
154395  }
154396
154397  if( bZero && &pList[nList]!=pEnd ){
154398    memset(&pList[nList], 0, pEnd - &pList[nList]);
154399  }
154400  *ppList = pList;
154401  *pnList = nList;
154402}
154403
154404/*
154405** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
154406** existing data). Grow the buffer if required.
154407**
154408** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
154409** trying to resize the buffer, return SQLITE_NOMEM.
154410*/
154411static int fts3MsrBufferData(
154412  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
154413  char *pList,
154414  int nList
154415){
154416  if( nList>pMsr->nBuffer ){
154417    char *pNew;
154418    pMsr->nBuffer = nList*2;
154419    pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
154420    if( !pNew ) return SQLITE_NOMEM;
154421    pMsr->aBuffer = pNew;
154422  }
154423
154424  memcpy(pMsr->aBuffer, pList, nList);
154425  return SQLITE_OK;
154426}
154427
154428SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
154429  Fts3Table *p,                   /* Virtual table handle */
154430  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
154431  sqlite3_int64 *piDocid,         /* OUT: Docid value */
154432  char **paPoslist,               /* OUT: Pointer to position list */
154433  int *pnPoslist                  /* OUT: Size of position list in bytes */
154434){
154435  int nMerge = pMsr->nAdvance;
154436  Fts3SegReader **apSegment = pMsr->apSegment;
154437  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
154438    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
154439  );
154440
154441  if( nMerge==0 ){
154442    *paPoslist = 0;
154443    return SQLITE_OK;
154444  }
154445
154446  while( 1 ){
154447    Fts3SegReader *pSeg;
154448    pSeg = pMsr->apSegment[0];
154449
154450    if( pSeg->pOffsetList==0 ){
154451      *paPoslist = 0;
154452      break;
154453    }else{
154454      int rc;
154455      char *pList;
154456      int nList;
154457      int j;
154458      sqlite3_int64 iDocid = apSegment[0]->iDocid;
154459
154460      rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
154461      j = 1;
154462      while( rc==SQLITE_OK
154463        && j<nMerge
154464        && apSegment[j]->pOffsetList
154465        && apSegment[j]->iDocid==iDocid
154466      ){
154467        rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
154468        j++;
154469      }
154470      if( rc!=SQLITE_OK ) return rc;
154471      fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
154472
154473      if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
154474        rc = fts3MsrBufferData(pMsr, pList, nList+1);
154475        if( rc!=SQLITE_OK ) return rc;
154476        assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
154477        pList = pMsr->aBuffer;
154478      }
154479
154480      if( pMsr->iColFilter>=0 ){
154481        fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
154482      }
154483
154484      if( nList>0 ){
154485        *paPoslist = pList;
154486        *piDocid = iDocid;
154487        *pnPoslist = nList;
154488        break;
154489      }
154490    }
154491  }
154492
154493  return SQLITE_OK;
154494}
154495
154496static int fts3SegReaderStart(
154497  Fts3Table *p,                   /* Virtual table handle */
154498  Fts3MultiSegReader *pCsr,       /* Cursor object */
154499  const char *zTerm,              /* Term searched for (or NULL) */
154500  int nTerm                       /* Length of zTerm in bytes */
154501){
154502  int i;
154503  int nSeg = pCsr->nSegment;
154504
154505  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
154506  ** for, then advance each segment iterator until it points to a term of
154507  ** equal or greater value than the specified term. This prevents many
154508  ** unnecessary merge/sort operations for the case where single segment
154509  ** b-tree leaf nodes contain more than one term.
154510  */
154511  for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
154512    int res = 0;
154513    Fts3SegReader *pSeg = pCsr->apSegment[i];
154514    do {
154515      int rc = fts3SegReaderNext(p, pSeg, 0);
154516      if( rc!=SQLITE_OK ) return rc;
154517    }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
154518
154519    if( pSeg->bLookup && res!=0 ){
154520      fts3SegReaderSetEof(pSeg);
154521    }
154522  }
154523  fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
154524
154525  return SQLITE_OK;
154526}
154527
154528SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
154529  Fts3Table *p,                   /* Virtual table handle */
154530  Fts3MultiSegReader *pCsr,       /* Cursor object */
154531  Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
154532){
154533  pCsr->pFilter = pFilter;
154534  return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
154535}
154536
154537SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
154538  Fts3Table *p,                   /* Virtual table handle */
154539  Fts3MultiSegReader *pCsr,       /* Cursor object */
154540  int iCol,                       /* Column to match on. */
154541  const char *zTerm,              /* Term to iterate through a doclist for */
154542  int nTerm                       /* Number of bytes in zTerm */
154543){
154544  int i;
154545  int rc;
154546  int nSegment = pCsr->nSegment;
154547  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
154548    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
154549  );
154550
154551  assert( pCsr->pFilter==0 );
154552  assert( zTerm && nTerm>0 );
154553
154554  /* Advance each segment iterator until it points to the term zTerm/nTerm. */
154555  rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
154556  if( rc!=SQLITE_OK ) return rc;
154557
154558  /* Determine how many of the segments actually point to zTerm/nTerm. */
154559  for(i=0; i<nSegment; i++){
154560    Fts3SegReader *pSeg = pCsr->apSegment[i];
154561    if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
154562      break;
154563    }
154564  }
154565  pCsr->nAdvance = i;
154566
154567  /* Advance each of the segments to point to the first docid. */
154568  for(i=0; i<pCsr->nAdvance; i++){
154569    rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
154570    if( rc!=SQLITE_OK ) return rc;
154571  }
154572  fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
154573
154574  assert( iCol<0 || iCol<p->nColumn );
154575  pCsr->iColFilter = iCol;
154576
154577  return SQLITE_OK;
154578}
154579
154580/*
154581** This function is called on a MultiSegReader that has been started using
154582** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
154583** have been made. Calling this function puts the MultiSegReader in such
154584** a state that if the next two calls are:
154585**
154586**   sqlite3Fts3SegReaderStart()
154587**   sqlite3Fts3SegReaderStep()
154588**
154589** then the entire doclist for the term is available in
154590** MultiSegReader.aDoclist/nDoclist.
154591*/
154592SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
154593  int i;                          /* Used to iterate through segment-readers */
154594
154595  assert( pCsr->zTerm==0 );
154596  assert( pCsr->nTerm==0 );
154597  assert( pCsr->aDoclist==0 );
154598  assert( pCsr->nDoclist==0 );
154599
154600  pCsr->nAdvance = 0;
154601  pCsr->bRestart = 1;
154602  for(i=0; i<pCsr->nSegment; i++){
154603    pCsr->apSegment[i]->pOffsetList = 0;
154604    pCsr->apSegment[i]->nOffsetList = 0;
154605    pCsr->apSegment[i]->iDocid = 0;
154606  }
154607
154608  return SQLITE_OK;
154609}
154610
154611
154612SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
154613  Fts3Table *p,                   /* Virtual table handle */
154614  Fts3MultiSegReader *pCsr        /* Cursor object */
154615){
154616  int rc = SQLITE_OK;
154617
154618  int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
154619  int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
154620  int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
154621  int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
154622  int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
154623  int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
154624
154625  Fts3SegReader **apSegment = pCsr->apSegment;
154626  int nSegment = pCsr->nSegment;
154627  Fts3SegFilter *pFilter = pCsr->pFilter;
154628  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
154629    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
154630  );
154631
154632  if( pCsr->nSegment==0 ) return SQLITE_OK;
154633
154634  do {
154635    int nMerge;
154636    int i;
154637
154638    /* Advance the first pCsr->nAdvance entries in the apSegment[] array
154639    ** forward. Then sort the list in order of current term again.
154640    */
154641    for(i=0; i<pCsr->nAdvance; i++){
154642      Fts3SegReader *pSeg = apSegment[i];
154643      if( pSeg->bLookup ){
154644        fts3SegReaderSetEof(pSeg);
154645      }else{
154646        rc = fts3SegReaderNext(p, pSeg, 0);
154647      }
154648      if( rc!=SQLITE_OK ) return rc;
154649    }
154650    fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
154651    pCsr->nAdvance = 0;
154652
154653    /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
154654    assert( rc==SQLITE_OK );
154655    if( apSegment[0]->aNode==0 ) break;
154656
154657    pCsr->nTerm = apSegment[0]->nTerm;
154658    pCsr->zTerm = apSegment[0]->zTerm;
154659
154660    /* If this is a prefix-search, and if the term that apSegment[0] points
154661    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
154662    ** required callbacks have been made. In this case exit early.
154663    **
154664    ** Similarly, if this is a search for an exact match, and the first term
154665    ** of segment apSegment[0] is not a match, exit early.
154666    */
154667    if( pFilter->zTerm && !isScan ){
154668      if( pCsr->nTerm<pFilter->nTerm
154669       || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
154670       || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
154671      ){
154672        break;
154673      }
154674    }
154675
154676    nMerge = 1;
154677    while( nMerge<nSegment
154678        && apSegment[nMerge]->aNode
154679        && apSegment[nMerge]->nTerm==pCsr->nTerm
154680        && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
154681    ){
154682      nMerge++;
154683    }
154684
154685    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
154686    if( nMerge==1
154687     && !isIgnoreEmpty
154688     && !isFirst
154689     && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
154690    ){
154691      pCsr->nDoclist = apSegment[0]->nDoclist;
154692      if( fts3SegReaderIsPending(apSegment[0]) ){
154693        rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
154694        pCsr->aDoclist = pCsr->aBuffer;
154695      }else{
154696        pCsr->aDoclist = apSegment[0]->aDoclist;
154697      }
154698      if( rc==SQLITE_OK ) rc = SQLITE_ROW;
154699    }else{
154700      int nDoclist = 0;           /* Size of doclist */
154701      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
154702
154703      /* The current term of the first nMerge entries in the array
154704      ** of Fts3SegReader objects is the same. The doclists must be merged
154705      ** and a single term returned with the merged doclist.
154706      */
154707      for(i=0; i<nMerge; i++){
154708        fts3SegReaderFirstDocid(p, apSegment[i]);
154709      }
154710      fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
154711      while( apSegment[0]->pOffsetList ){
154712        int j;                    /* Number of segments that share a docid */
154713        char *pList = 0;
154714        int nList = 0;
154715        int nByte;
154716        sqlite3_int64 iDocid = apSegment[0]->iDocid;
154717        fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
154718        j = 1;
154719        while( j<nMerge
154720            && apSegment[j]->pOffsetList
154721            && apSegment[j]->iDocid==iDocid
154722        ){
154723          fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
154724          j++;
154725        }
154726
154727        if( isColFilter ){
154728          fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
154729        }
154730
154731        if( !isIgnoreEmpty || nList>0 ){
154732
154733          /* Calculate the 'docid' delta value to write into the merged
154734          ** doclist. */
154735          sqlite3_int64 iDelta;
154736          if( p->bDescIdx && nDoclist>0 ){
154737            iDelta = iPrev - iDocid;
154738          }else{
154739            iDelta = iDocid - iPrev;
154740          }
154741          assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
154742          assert( nDoclist>0 || iDelta==iDocid );
154743
154744          nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
154745          if( nDoclist+nByte>pCsr->nBuffer ){
154746            char *aNew;
154747            pCsr->nBuffer = (nDoclist+nByte)*2;
154748            aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
154749            if( !aNew ){
154750              return SQLITE_NOMEM;
154751            }
154752            pCsr->aBuffer = aNew;
154753          }
154754
154755          if( isFirst ){
154756            char *a = &pCsr->aBuffer[nDoclist];
154757            int nWrite;
154758
154759            nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
154760            if( nWrite ){
154761              iPrev = iDocid;
154762              nDoclist += nWrite;
154763            }
154764          }else{
154765            nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
154766            iPrev = iDocid;
154767            if( isRequirePos ){
154768              memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
154769              nDoclist += nList;
154770              pCsr->aBuffer[nDoclist++] = '\0';
154771            }
154772          }
154773        }
154774
154775        fts3SegReaderSort(apSegment, nMerge, j, xCmp);
154776      }
154777      if( nDoclist>0 ){
154778        pCsr->aDoclist = pCsr->aBuffer;
154779        pCsr->nDoclist = nDoclist;
154780        rc = SQLITE_ROW;
154781      }
154782    }
154783    pCsr->nAdvance = nMerge;
154784  }while( rc==SQLITE_OK );
154785
154786  return rc;
154787}
154788
154789
154790SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
154791  Fts3MultiSegReader *pCsr       /* Cursor object */
154792){
154793  if( pCsr ){
154794    int i;
154795    for(i=0; i<pCsr->nSegment; i++){
154796      sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
154797    }
154798    sqlite3_free(pCsr->apSegment);
154799    sqlite3_free(pCsr->aBuffer);
154800
154801    pCsr->nSegment = 0;
154802    pCsr->apSegment = 0;
154803    pCsr->aBuffer = 0;
154804  }
154805}
154806
154807/*
154808** Decode the "end_block" field, selected by column iCol of the SELECT
154809** statement passed as the first argument.
154810**
154811** The "end_block" field may contain either an integer, or a text field
154812** containing the text representation of two non-negative integers separated
154813** by one or more space (0x20) characters. In the first case, set *piEndBlock
154814** to the integer value and *pnByte to zero before returning. In the second,
154815** set *piEndBlock to the first value and *pnByte to the second.
154816*/
154817static void fts3ReadEndBlockField(
154818  sqlite3_stmt *pStmt,
154819  int iCol,
154820  i64 *piEndBlock,
154821  i64 *pnByte
154822){
154823  const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
154824  if( zText ){
154825    int i;
154826    int iMul = 1;
154827    i64 iVal = 0;
154828    for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
154829      iVal = iVal*10 + (zText[i] - '0');
154830    }
154831    *piEndBlock = iVal;
154832    while( zText[i]==' ' ) i++;
154833    iVal = 0;
154834    if( zText[i]=='-' ){
154835      i++;
154836      iMul = -1;
154837    }
154838    for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
154839      iVal = iVal*10 + (zText[i] - '0');
154840    }
154841    *pnByte = (iVal * (i64)iMul);
154842  }
154843}
154844
154845
154846/*
154847** A segment of size nByte bytes has just been written to absolute level
154848** iAbsLevel. Promote any segments that should be promoted as a result.
154849*/
154850static int fts3PromoteSegments(
154851  Fts3Table *p,                   /* FTS table handle */
154852  sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
154853  sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
154854){
154855  int rc = SQLITE_OK;
154856  sqlite3_stmt *pRange;
154857
154858  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
154859
154860  if( rc==SQLITE_OK ){
154861    int bOk = 0;
154862    i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
154863    i64 nLimit = (nByte*3)/2;
154864
154865    /* Loop through all entries in the %_segdir table corresponding to
154866    ** segments in this index on levels greater than iAbsLevel. If there is
154867    ** at least one such segment, and it is possible to determine that all
154868    ** such segments are smaller than nLimit bytes in size, they will be
154869    ** promoted to level iAbsLevel.  */
154870    sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
154871    sqlite3_bind_int64(pRange, 2, iLast);
154872    while( SQLITE_ROW==sqlite3_step(pRange) ){
154873      i64 nSize = 0, dummy;
154874      fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
154875      if( nSize<=0 || nSize>nLimit ){
154876        /* If nSize==0, then the %_segdir.end_block field does not not
154877        ** contain a size value. This happens if it was written by an
154878        ** old version of FTS. In this case it is not possible to determine
154879        ** the size of the segment, and so segment promotion does not
154880        ** take place.  */
154881        bOk = 0;
154882        break;
154883      }
154884      bOk = 1;
154885    }
154886    rc = sqlite3_reset(pRange);
154887
154888    if( bOk ){
154889      int iIdx = 0;
154890      sqlite3_stmt *pUpdate1 = 0;
154891      sqlite3_stmt *pUpdate2 = 0;
154892
154893      if( rc==SQLITE_OK ){
154894        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
154895      }
154896      if( rc==SQLITE_OK ){
154897        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
154898      }
154899
154900      if( rc==SQLITE_OK ){
154901
154902        /* Loop through all %_segdir entries for segments in this index with
154903        ** levels equal to or greater than iAbsLevel. As each entry is visited,
154904        ** updated it to set (level = -1) and (idx = N), where N is 0 for the
154905        ** oldest segment in the range, 1 for the next oldest, and so on.
154906        **
154907        ** In other words, move all segments being promoted to level -1,
154908        ** setting the "idx" fields as appropriate to keep them in the same
154909        ** order. The contents of level -1 (which is never used, except
154910        ** transiently here), will be moved back to level iAbsLevel below.  */
154911        sqlite3_bind_int64(pRange, 1, iAbsLevel);
154912        while( SQLITE_ROW==sqlite3_step(pRange) ){
154913          sqlite3_bind_int(pUpdate1, 1, iIdx++);
154914          sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
154915          sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
154916          sqlite3_step(pUpdate1);
154917          rc = sqlite3_reset(pUpdate1);
154918          if( rc!=SQLITE_OK ){
154919            sqlite3_reset(pRange);
154920            break;
154921          }
154922        }
154923      }
154924      if( rc==SQLITE_OK ){
154925        rc = sqlite3_reset(pRange);
154926      }
154927
154928      /* Move level -1 to level iAbsLevel */
154929      if( rc==SQLITE_OK ){
154930        sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
154931        sqlite3_step(pUpdate2);
154932        rc = sqlite3_reset(pUpdate2);
154933      }
154934    }
154935  }
154936
154937
154938  return rc;
154939}
154940
154941/*
154942** Merge all level iLevel segments in the database into a single
154943** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
154944** single segment with a level equal to the numerically largest level
154945** currently present in the database.
154946**
154947** If this function is called with iLevel<0, but there is only one
154948** segment in the database, SQLITE_DONE is returned immediately.
154949** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
154950** an SQLite error code is returned.
154951*/
154952static int fts3SegmentMerge(
154953  Fts3Table *p,
154954  int iLangid,                    /* Language id to merge */
154955  int iIndex,                     /* Index in p->aIndex[] to merge */
154956  int iLevel                      /* Level to merge */
154957){
154958  int rc;                         /* Return code */
154959  int iIdx = 0;                   /* Index of new segment */
154960  sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
154961  SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
154962  Fts3SegFilter filter;           /* Segment term filter condition */
154963  Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
154964  int bIgnoreEmpty = 0;           /* True to ignore empty segments */
154965  i64 iMaxLevel = 0;              /* Max level number for this index/langid */
154966
154967  assert( iLevel==FTS3_SEGCURSOR_ALL
154968       || iLevel==FTS3_SEGCURSOR_PENDING
154969       || iLevel>=0
154970  );
154971  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
154972  assert( iIndex>=0 && iIndex<p->nIndex );
154973
154974  rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
154975  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
154976
154977  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
154978    rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
154979    if( rc!=SQLITE_OK ) goto finished;
154980  }
154981
154982  if( iLevel==FTS3_SEGCURSOR_ALL ){
154983    /* This call is to merge all segments in the database to a single
154984    ** segment. The level of the new segment is equal to the numerically
154985    ** greatest segment level currently present in the database for this
154986    ** index. The idx of the new segment is always 0.  */
154987    if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
154988      rc = SQLITE_DONE;
154989      goto finished;
154990    }
154991    iNewLevel = iMaxLevel;
154992    bIgnoreEmpty = 1;
154993
154994  }else{
154995    /* This call is to merge all segments at level iLevel. find the next
154996    ** available segment index at level iLevel+1. The call to
154997    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
154998    ** a single iLevel+2 segment if necessary.  */
154999    assert( FTS3_SEGCURSOR_PENDING==-1 );
155000    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
155001    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
155002    bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
155003  }
155004  if( rc!=SQLITE_OK ) goto finished;
155005
155006  assert( csr.nSegment>0 );
155007  assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
155008  assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
155009
155010  memset(&filter, 0, sizeof(Fts3SegFilter));
155011  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
155012  filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
155013
155014  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
155015  while( SQLITE_OK==rc ){
155016    rc = sqlite3Fts3SegReaderStep(p, &csr);
155017    if( rc!=SQLITE_ROW ) break;
155018    rc = fts3SegWriterAdd(p, &pWriter, 1,
155019        csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
155020  }
155021  if( rc!=SQLITE_OK ) goto finished;
155022  assert( pWriter || bIgnoreEmpty );
155023
155024  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
155025    rc = fts3DeleteSegdir(
155026        p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
155027    );
155028    if( rc!=SQLITE_OK ) goto finished;
155029  }
155030  if( pWriter ){
155031    rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
155032    if( rc==SQLITE_OK ){
155033      if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
155034        rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
155035      }
155036    }
155037  }
155038
155039 finished:
155040  fts3SegWriterFree(pWriter);
155041  sqlite3Fts3SegReaderFinish(&csr);
155042  return rc;
155043}
155044
155045
155046/*
155047** Flush the contents of pendingTerms to level 0 segments.
155048*/
155049SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
155050  int rc = SQLITE_OK;
155051  int i;
155052
155053  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
155054    rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
155055    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
155056  }
155057  sqlite3Fts3PendingTermsClear(p);
155058
155059  /* Determine the auto-incr-merge setting if unknown.  If enabled,
155060  ** estimate the number of leaf blocks of content to be written
155061  */
155062  if( rc==SQLITE_OK && p->bHasStat
155063   && p->nAutoincrmerge==0xff && p->nLeafAdd>0
155064  ){
155065    sqlite3_stmt *pStmt = 0;
155066    rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
155067    if( rc==SQLITE_OK ){
155068      sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
155069      rc = sqlite3_step(pStmt);
155070      if( rc==SQLITE_ROW ){
155071        p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
155072        if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
155073      }else if( rc==SQLITE_DONE ){
155074        p->nAutoincrmerge = 0;
155075      }
155076      rc = sqlite3_reset(pStmt);
155077    }
155078  }
155079  return rc;
155080}
155081
155082/*
155083** Encode N integers as varints into a blob.
155084*/
155085static void fts3EncodeIntArray(
155086  int N,             /* The number of integers to encode */
155087  u32 *a,            /* The integer values */
155088  char *zBuf,        /* Write the BLOB here */
155089  int *pNBuf         /* Write number of bytes if zBuf[] used here */
155090){
155091  int i, j;
155092  for(i=j=0; i<N; i++){
155093    j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
155094  }
155095  *pNBuf = j;
155096}
155097
155098/*
155099** Decode a blob of varints into N integers
155100*/
155101static void fts3DecodeIntArray(
155102  int N,             /* The number of integers to decode */
155103  u32 *a,            /* Write the integer values */
155104  const char *zBuf,  /* The BLOB containing the varints */
155105  int nBuf           /* size of the BLOB */
155106){
155107  int i, j;
155108  UNUSED_PARAMETER(nBuf);
155109  for(i=j=0; i<N; i++){
155110    sqlite3_int64 x;
155111    j += sqlite3Fts3GetVarint(&zBuf[j], &x);
155112    assert(j<=nBuf);
155113    a[i] = (u32)(x & 0xffffffff);
155114  }
155115}
155116
155117/*
155118** Insert the sizes (in tokens) for each column of the document
155119** with docid equal to p->iPrevDocid.  The sizes are encoded as
155120** a blob of varints.
155121*/
155122static void fts3InsertDocsize(
155123  int *pRC,                       /* Result code */
155124  Fts3Table *p,                   /* Table into which to insert */
155125  u32 *aSz                        /* Sizes of each column, in tokens */
155126){
155127  char *pBlob;             /* The BLOB encoding of the document size */
155128  int nBlob;               /* Number of bytes in the BLOB */
155129  sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
155130  int rc;                  /* Result code from subfunctions */
155131
155132  if( *pRC ) return;
155133  pBlob = sqlite3_malloc( 10*p->nColumn );
155134  if( pBlob==0 ){
155135    *pRC = SQLITE_NOMEM;
155136    return;
155137  }
155138  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
155139  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
155140  if( rc ){
155141    sqlite3_free(pBlob);
155142    *pRC = rc;
155143    return;
155144  }
155145  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
155146  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
155147  sqlite3_step(pStmt);
155148  *pRC = sqlite3_reset(pStmt);
155149}
155150
155151/*
155152** Record 0 of the %_stat table contains a blob consisting of N varints,
155153** where N is the number of user defined columns in the fts3 table plus
155154** two. If nCol is the number of user defined columns, then values of the
155155** varints are set as follows:
155156**
155157**   Varint 0:       Total number of rows in the table.
155158**
155159**   Varint 1..nCol: For each column, the total number of tokens stored in
155160**                   the column for all rows of the table.
155161**
155162**   Varint 1+nCol:  The total size, in bytes, of all text values in all
155163**                   columns of all rows of the table.
155164**
155165*/
155166static void fts3UpdateDocTotals(
155167  int *pRC,                       /* The result code */
155168  Fts3Table *p,                   /* Table being updated */
155169  u32 *aSzIns,                    /* Size increases */
155170  u32 *aSzDel,                    /* Size decreases */
155171  int nChng                       /* Change in the number of documents */
155172){
155173  char *pBlob;             /* Storage for BLOB written into %_stat */
155174  int nBlob;               /* Size of BLOB written into %_stat */
155175  u32 *a;                  /* Array of integers that becomes the BLOB */
155176  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
155177  int i;                   /* Loop counter */
155178  int rc;                  /* Result code from subfunctions */
155179
155180  const int nStat = p->nColumn+2;
155181
155182  if( *pRC ) return;
155183  a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
155184  if( a==0 ){
155185    *pRC = SQLITE_NOMEM;
155186    return;
155187  }
155188  pBlob = (char*)&a[nStat];
155189  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
155190  if( rc ){
155191    sqlite3_free(a);
155192    *pRC = rc;
155193    return;
155194  }
155195  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
155196  if( sqlite3_step(pStmt)==SQLITE_ROW ){
155197    fts3DecodeIntArray(nStat, a,
155198         sqlite3_column_blob(pStmt, 0),
155199         sqlite3_column_bytes(pStmt, 0));
155200  }else{
155201    memset(a, 0, sizeof(u32)*(nStat) );
155202  }
155203  rc = sqlite3_reset(pStmt);
155204  if( rc!=SQLITE_OK ){
155205    sqlite3_free(a);
155206    *pRC = rc;
155207    return;
155208  }
155209  if( nChng<0 && a[0]<(u32)(-nChng) ){
155210    a[0] = 0;
155211  }else{
155212    a[0] += nChng;
155213  }
155214  for(i=0; i<p->nColumn+1; i++){
155215    u32 x = a[i+1];
155216    if( x+aSzIns[i] < aSzDel[i] ){
155217      x = 0;
155218    }else{
155219      x = x + aSzIns[i] - aSzDel[i];
155220    }
155221    a[i+1] = x;
155222  }
155223  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
155224  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
155225  if( rc ){
155226    sqlite3_free(a);
155227    *pRC = rc;
155228    return;
155229  }
155230  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
155231  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
155232  sqlite3_step(pStmt);
155233  *pRC = sqlite3_reset(pStmt);
155234  sqlite3_free(a);
155235}
155236
155237/*
155238** Merge the entire database so that there is one segment for each
155239** iIndex/iLangid combination.
155240*/
155241static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
155242  int bSeenDone = 0;
155243  int rc;
155244  sqlite3_stmt *pAllLangid = 0;
155245
155246  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
155247  if( rc==SQLITE_OK ){
155248    int rc2;
155249    sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
155250    sqlite3_bind_int(pAllLangid, 2, p->nIndex);
155251    while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
155252      int i;
155253      int iLangid = sqlite3_column_int(pAllLangid, 0);
155254      for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
155255        rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
155256        if( rc==SQLITE_DONE ){
155257          bSeenDone = 1;
155258          rc = SQLITE_OK;
155259        }
155260      }
155261    }
155262    rc2 = sqlite3_reset(pAllLangid);
155263    if( rc==SQLITE_OK ) rc = rc2;
155264  }
155265
155266  sqlite3Fts3SegmentsClose(p);
155267  sqlite3Fts3PendingTermsClear(p);
155268
155269  return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
155270}
155271
155272/*
155273** This function is called when the user executes the following statement:
155274**
155275**     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
155276**
155277** The entire FTS index is discarded and rebuilt. If the table is one
155278** created using the content=xxx option, then the new index is based on
155279** the current contents of the xxx table. Otherwise, it is rebuilt based
155280** on the contents of the %_content table.
155281*/
155282static int fts3DoRebuild(Fts3Table *p){
155283  int rc;                         /* Return Code */
155284
155285  rc = fts3DeleteAll(p, 0);
155286  if( rc==SQLITE_OK ){
155287    u32 *aSz = 0;
155288    u32 *aSzIns = 0;
155289    u32 *aSzDel = 0;
155290    sqlite3_stmt *pStmt = 0;
155291    int nEntry = 0;
155292
155293    /* Compose and prepare an SQL statement to loop through the content table */
155294    char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
155295    if( !zSql ){
155296      rc = SQLITE_NOMEM;
155297    }else{
155298      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
155299      sqlite3_free(zSql);
155300    }
155301
155302    if( rc==SQLITE_OK ){
155303      int nByte = sizeof(u32) * (p->nColumn+1)*3;
155304      aSz = (u32 *)sqlite3_malloc(nByte);
155305      if( aSz==0 ){
155306        rc = SQLITE_NOMEM;
155307      }else{
155308        memset(aSz, 0, nByte);
155309        aSzIns = &aSz[p->nColumn+1];
155310        aSzDel = &aSzIns[p->nColumn+1];
155311      }
155312    }
155313
155314    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
155315      int iCol;
155316      int iLangid = langidFromSelect(p, pStmt);
155317      rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
155318      memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
155319      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
155320        if( p->abNotindexed[iCol]==0 ){
155321          const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
155322          rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
155323          aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
155324        }
155325      }
155326      if( p->bHasDocsize ){
155327        fts3InsertDocsize(&rc, p, aSz);
155328      }
155329      if( rc!=SQLITE_OK ){
155330        sqlite3_finalize(pStmt);
155331        pStmt = 0;
155332      }else{
155333        nEntry++;
155334        for(iCol=0; iCol<=p->nColumn; iCol++){
155335          aSzIns[iCol] += aSz[iCol];
155336        }
155337      }
155338    }
155339    if( p->bFts4 ){
155340      fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
155341    }
155342    sqlite3_free(aSz);
155343
155344    if( pStmt ){
155345      int rc2 = sqlite3_finalize(pStmt);
155346      if( rc==SQLITE_OK ){
155347        rc = rc2;
155348      }
155349    }
155350  }
155351
155352  return rc;
155353}
155354
155355
155356/*
155357** This function opens a cursor used to read the input data for an
155358** incremental merge operation. Specifically, it opens a cursor to scan
155359** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
155360** level iAbsLevel.
155361*/
155362static int fts3IncrmergeCsr(
155363  Fts3Table *p,                   /* FTS3 table handle */
155364  sqlite3_int64 iAbsLevel,        /* Absolute level to open */
155365  int nSeg,                       /* Number of segments to merge */
155366  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
155367){
155368  int rc;                         /* Return Code */
155369  sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
155370  int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
155371
155372  /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
155373  memset(pCsr, 0, sizeof(*pCsr));
155374  nByte = sizeof(Fts3SegReader *) * nSeg;
155375  pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
155376
155377  if( pCsr->apSegment==0 ){
155378    rc = SQLITE_NOMEM;
155379  }else{
155380    memset(pCsr->apSegment, 0, nByte);
155381    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
155382  }
155383  if( rc==SQLITE_OK ){
155384    int i;
155385    int rc2;
155386    sqlite3_bind_int64(pStmt, 1, iAbsLevel);
155387    assert( pCsr->nSegment==0 );
155388    for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
155389      rc = sqlite3Fts3SegReaderNew(i, 0,
155390          sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
155391          sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
155392          sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
155393          sqlite3_column_blob(pStmt, 4),         /* segdir.root */
155394          sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
155395          &pCsr->apSegment[i]
155396      );
155397      pCsr->nSegment++;
155398    }
155399    rc2 = sqlite3_reset(pStmt);
155400    if( rc==SQLITE_OK ) rc = rc2;
155401  }
155402
155403  return rc;
155404}
155405
155406typedef struct IncrmergeWriter IncrmergeWriter;
155407typedef struct NodeWriter NodeWriter;
155408typedef struct Blob Blob;
155409typedef struct NodeReader NodeReader;
155410
155411/*
155412** An instance of the following structure is used as a dynamic buffer
155413** to build up nodes or other blobs of data in.
155414**
155415** The function blobGrowBuffer() is used to extend the allocation.
155416*/
155417struct Blob {
155418  char *a;                        /* Pointer to allocation */
155419  int n;                          /* Number of valid bytes of data in a[] */
155420  int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
155421};
155422
155423/*
155424** This structure is used to build up buffers containing segment b-tree
155425** nodes (blocks).
155426*/
155427struct NodeWriter {
155428  sqlite3_int64 iBlock;           /* Current block id */
155429  Blob key;                       /* Last key written to the current block */
155430  Blob block;                     /* Current block image */
155431};
155432
155433/*
155434** An object of this type contains the state required to create or append
155435** to an appendable b-tree segment.
155436*/
155437struct IncrmergeWriter {
155438  int nLeafEst;                   /* Space allocated for leaf blocks */
155439  int nWork;                      /* Number of leaf pages flushed */
155440  sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
155441  int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
155442  sqlite3_int64 iStart;           /* Block number of first allocated block */
155443  sqlite3_int64 iEnd;             /* Block number of last allocated block */
155444  sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
155445  u8 bNoLeafData;                 /* If true, store 0 for segment size */
155446  NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
155447};
155448
155449/*
155450** An object of the following type is used to read data from a single
155451** FTS segment node. See the following functions:
155452**
155453**     nodeReaderInit()
155454**     nodeReaderNext()
155455**     nodeReaderRelease()
155456*/
155457struct NodeReader {
155458  const char *aNode;
155459  int nNode;
155460  int iOff;                       /* Current offset within aNode[] */
155461
155462  /* Output variables. Containing the current node entry. */
155463  sqlite3_int64 iChild;           /* Pointer to child node */
155464  Blob term;                      /* Current term */
155465  const char *aDoclist;           /* Pointer to doclist */
155466  int nDoclist;                   /* Size of doclist in bytes */
155467};
155468
155469/*
155470** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
155471** Otherwise, if the allocation at pBlob->a is not already at least nMin
155472** bytes in size, extend (realloc) it to be so.
155473**
155474** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
155475** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
155476** to reflect the new size of the pBlob->a[] buffer.
155477*/
155478static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
155479  if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
155480    int nAlloc = nMin;
155481    char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
155482    if( a ){
155483      pBlob->nAlloc = nAlloc;
155484      pBlob->a = a;
155485    }else{
155486      *pRc = SQLITE_NOMEM;
155487    }
155488  }
155489}
155490
155491/*
155492** Attempt to advance the node-reader object passed as the first argument to
155493** the next entry on the node.
155494**
155495** Return an error code if an error occurs (SQLITE_NOMEM is possible).
155496** Otherwise return SQLITE_OK. If there is no next entry on the node
155497** (e.g. because the current entry is the last) set NodeReader->aNode to
155498** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
155499** variables for the new entry.
155500*/
155501static int nodeReaderNext(NodeReader *p){
155502  int bFirst = (p->term.n==0);    /* True for first term on the node */
155503  int nPrefix = 0;                /* Bytes to copy from previous term */
155504  int nSuffix = 0;                /* Bytes to append to the prefix */
155505  int rc = SQLITE_OK;             /* Return code */
155506
155507  assert( p->aNode );
155508  if( p->iChild && bFirst==0 ) p->iChild++;
155509  if( p->iOff>=p->nNode ){
155510    /* EOF */
155511    p->aNode = 0;
155512  }else{
155513    if( bFirst==0 ){
155514      p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
155515    }
155516    p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
155517
155518    blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
155519    if( rc==SQLITE_OK ){
155520      memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
155521      p->term.n = nPrefix+nSuffix;
155522      p->iOff += nSuffix;
155523      if( p->iChild==0 ){
155524        p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
155525        p->aDoclist = &p->aNode[p->iOff];
155526        p->iOff += p->nDoclist;
155527      }
155528    }
155529  }
155530
155531  assert( p->iOff<=p->nNode );
155532
155533  return rc;
155534}
155535
155536/*
155537** Release all dynamic resources held by node-reader object *p.
155538*/
155539static void nodeReaderRelease(NodeReader *p){
155540  sqlite3_free(p->term.a);
155541}
155542
155543/*
155544** Initialize a node-reader object to read the node in buffer aNode/nNode.
155545**
155546** If successful, SQLITE_OK is returned and the NodeReader object set to
155547** point to the first entry on the node (if any). Otherwise, an SQLite
155548** error code is returned.
155549*/
155550static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
155551  memset(p, 0, sizeof(NodeReader));
155552  p->aNode = aNode;
155553  p->nNode = nNode;
155554
155555  /* Figure out if this is a leaf or an internal node. */
155556  if( p->aNode[0] ){
155557    /* An internal node. */
155558    p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
155559  }else{
155560    p->iOff = 1;
155561  }
155562
155563  return nodeReaderNext(p);
155564}
155565
155566/*
155567** This function is called while writing an FTS segment each time a leaf o
155568** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
155569** to be greater than the largest key on the node just written, but smaller
155570** than or equal to the first key that will be written to the next leaf
155571** node.
155572**
155573** The block id of the leaf node just written to disk may be found in
155574** (pWriter->aNodeWriter[0].iBlock) when this function is called.
155575*/
155576static int fts3IncrmergePush(
155577  Fts3Table *p,                   /* Fts3 table handle */
155578  IncrmergeWriter *pWriter,       /* Writer object */
155579  const char *zTerm,              /* Term to write to internal node */
155580  int nTerm                       /* Bytes at zTerm */
155581){
155582  sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
155583  int iLayer;
155584
155585  assert( nTerm>0 );
155586  for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
155587    sqlite3_int64 iNextPtr = 0;
155588    NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
155589    int rc = SQLITE_OK;
155590    int nPrefix;
155591    int nSuffix;
155592    int nSpace;
155593
155594    /* Figure out how much space the key will consume if it is written to
155595    ** the current node of layer iLayer. Due to the prefix compression,
155596    ** the space required changes depending on which node the key is to
155597    ** be added to.  */
155598    nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
155599    nSuffix = nTerm - nPrefix;
155600    nSpace  = sqlite3Fts3VarintLen(nPrefix);
155601    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
155602
155603    if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
155604      /* If the current node of layer iLayer contains zero keys, or if adding
155605      ** the key to it will not cause it to grow to larger than nNodeSize
155606      ** bytes in size, write the key here.  */
155607
155608      Blob *pBlk = &pNode->block;
155609      if( pBlk->n==0 ){
155610        blobGrowBuffer(pBlk, p->nNodeSize, &rc);
155611        if( rc==SQLITE_OK ){
155612          pBlk->a[0] = (char)iLayer;
155613          pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
155614        }
155615      }
155616      blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
155617      blobGrowBuffer(&pNode->key, nTerm, &rc);
155618
155619      if( rc==SQLITE_OK ){
155620        if( pNode->key.n ){
155621          pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
155622        }
155623        pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
155624        memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
155625        pBlk->n += nSuffix;
155626
155627        memcpy(pNode->key.a, zTerm, nTerm);
155628        pNode->key.n = nTerm;
155629      }
155630    }else{
155631      /* Otherwise, flush the current node of layer iLayer to disk.
155632      ** Then allocate a new, empty sibling node. The key will be written
155633      ** into the parent of this node. */
155634      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
155635
155636      assert( pNode->block.nAlloc>=p->nNodeSize );
155637      pNode->block.a[0] = (char)iLayer;
155638      pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
155639
155640      iNextPtr = pNode->iBlock;
155641      pNode->iBlock++;
155642      pNode->key.n = 0;
155643    }
155644
155645    if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
155646    iPtr = iNextPtr;
155647  }
155648
155649  assert( 0 );
155650  return 0;
155651}
155652
155653/*
155654** Append a term and (optionally) doclist to the FTS segment node currently
155655** stored in blob *pNode. The node need not contain any terms, but the
155656** header must be written before this function is called.
155657**
155658** A node header is a single 0x00 byte for a leaf node, or a height varint
155659** followed by the left-hand-child varint for an internal node.
155660**
155661** The term to be appended is passed via arguments zTerm/nTerm. For a
155662** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
155663** node, both aDoclist and nDoclist must be passed 0.
155664**
155665** If the size of the value in blob pPrev is zero, then this is the first
155666** term written to the node. Otherwise, pPrev contains a copy of the
155667** previous term. Before this function returns, it is updated to contain a
155668** copy of zTerm/nTerm.
155669**
155670** It is assumed that the buffer associated with pNode is already large
155671** enough to accommodate the new entry. The buffer associated with pPrev
155672** is extended by this function if requrired.
155673**
155674** If an error (i.e. OOM condition) occurs, an SQLite error code is
155675** returned. Otherwise, SQLITE_OK.
155676*/
155677static int fts3AppendToNode(
155678  Blob *pNode,                    /* Current node image to append to */
155679  Blob *pPrev,                    /* Buffer containing previous term written */
155680  const char *zTerm,              /* New term to write */
155681  int nTerm,                      /* Size of zTerm in bytes */
155682  const char *aDoclist,           /* Doclist (or NULL) to write */
155683  int nDoclist                    /* Size of aDoclist in bytes */
155684){
155685  int rc = SQLITE_OK;             /* Return code */
155686  int bFirst = (pPrev->n==0);     /* True if this is the first term written */
155687  int nPrefix;                    /* Size of term prefix in bytes */
155688  int nSuffix;                    /* Size of term suffix in bytes */
155689
155690  /* Node must have already been started. There must be a doclist for a
155691  ** leaf node, and there must not be a doclist for an internal node.  */
155692  assert( pNode->n>0 );
155693  assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
155694
155695  blobGrowBuffer(pPrev, nTerm, &rc);
155696  if( rc!=SQLITE_OK ) return rc;
155697
155698  nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
155699  nSuffix = nTerm - nPrefix;
155700  memcpy(pPrev->a, zTerm, nTerm);
155701  pPrev->n = nTerm;
155702
155703  if( bFirst==0 ){
155704    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
155705  }
155706  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
155707  memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
155708  pNode->n += nSuffix;
155709
155710  if( aDoclist ){
155711    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
155712    memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
155713    pNode->n += nDoclist;
155714  }
155715
155716  assert( pNode->n<=pNode->nAlloc );
155717
155718  return SQLITE_OK;
155719}
155720
155721/*
155722** Append the current term and doclist pointed to by cursor pCsr to the
155723** appendable b-tree segment opened for writing by pWriter.
155724**
155725** Return SQLITE_OK if successful, or an SQLite error code otherwise.
155726*/
155727static int fts3IncrmergeAppend(
155728  Fts3Table *p,                   /* Fts3 table handle */
155729  IncrmergeWriter *pWriter,       /* Writer object */
155730  Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
155731){
155732  const char *zTerm = pCsr->zTerm;
155733  int nTerm = pCsr->nTerm;
155734  const char *aDoclist = pCsr->aDoclist;
155735  int nDoclist = pCsr->nDoclist;
155736  int rc = SQLITE_OK;           /* Return code */
155737  int nSpace;                   /* Total space in bytes required on leaf */
155738  int nPrefix;                  /* Size of prefix shared with previous term */
155739  int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
155740  NodeWriter *pLeaf;            /* Object used to write leaf nodes */
155741
155742  pLeaf = &pWriter->aNodeWriter[0];
155743  nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
155744  nSuffix = nTerm - nPrefix;
155745
155746  nSpace  = sqlite3Fts3VarintLen(nPrefix);
155747  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
155748  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
155749
155750  /* If the current block is not empty, and if adding this term/doclist
155751  ** to the current block would make it larger than Fts3Table.nNodeSize
155752  ** bytes, write this block out to the database. */
155753  if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
155754    rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
155755    pWriter->nWork++;
155756
155757    /* Add the current term to the parent node. The term added to the
155758    ** parent must:
155759    **
155760    **   a) be greater than the largest term on the leaf node just written
155761    **      to the database (still available in pLeaf->key), and
155762    **
155763    **   b) be less than or equal to the term about to be added to the new
155764    **      leaf node (zTerm/nTerm).
155765    **
155766    ** In other words, it must be the prefix of zTerm 1 byte longer than
155767    ** the common prefix (if any) of zTerm and pWriter->zTerm.
155768    */
155769    if( rc==SQLITE_OK ){
155770      rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
155771    }
155772
155773    /* Advance to the next output block */
155774    pLeaf->iBlock++;
155775    pLeaf->key.n = 0;
155776    pLeaf->block.n = 0;
155777
155778    nSuffix = nTerm;
155779    nSpace  = 1;
155780    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
155781    nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
155782  }
155783
155784  pWriter->nLeafData += nSpace;
155785  blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
155786  if( rc==SQLITE_OK ){
155787    if( pLeaf->block.n==0 ){
155788      pLeaf->block.n = 1;
155789      pLeaf->block.a[0] = '\0';
155790    }
155791    rc = fts3AppendToNode(
155792        &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
155793    );
155794  }
155795
155796  return rc;
155797}
155798
155799/*
155800** This function is called to release all dynamic resources held by the
155801** merge-writer object pWriter, and if no error has occurred, to flush
155802** all outstanding node buffers held by pWriter to disk.
155803**
155804** If *pRc is not SQLITE_OK when this function is called, then no attempt
155805** is made to write any data to disk. Instead, this function serves only
155806** to release outstanding resources.
155807**
155808** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
155809** flushing buffers to disk, *pRc is set to an SQLite error code before
155810** returning.
155811*/
155812static void fts3IncrmergeRelease(
155813  Fts3Table *p,                   /* FTS3 table handle */
155814  IncrmergeWriter *pWriter,       /* Merge-writer object */
155815  int *pRc                        /* IN/OUT: Error code */
155816){
155817  int i;                          /* Used to iterate through non-root layers */
155818  int iRoot;                      /* Index of root in pWriter->aNodeWriter */
155819  NodeWriter *pRoot;              /* NodeWriter for root node */
155820  int rc = *pRc;                  /* Error code */
155821
155822  /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
155823  ** root node. If the segment fits entirely on a single leaf node, iRoot
155824  ** will be set to 0. If the root node is the parent of the leaves, iRoot
155825  ** will be 1. And so on.  */
155826  for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
155827    NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
155828    if( pNode->block.n>0 ) break;
155829    assert( *pRc || pNode->block.nAlloc==0 );
155830    assert( *pRc || pNode->key.nAlloc==0 );
155831    sqlite3_free(pNode->block.a);
155832    sqlite3_free(pNode->key.a);
155833  }
155834
155835  /* Empty output segment. This is a no-op. */
155836  if( iRoot<0 ) return;
155837
155838  /* The entire output segment fits on a single node. Normally, this means
155839  ** the node would be stored as a blob in the "root" column of the %_segdir
155840  ** table. However, this is not permitted in this case. The problem is that
155841  ** space has already been reserved in the %_segments table, and so the
155842  ** start_block and end_block fields of the %_segdir table must be populated.
155843  ** And, by design or by accident, released versions of FTS cannot handle
155844  ** segments that fit entirely on the root node with start_block!=0.
155845  **
155846  ** Instead, create a synthetic root node that contains nothing but a
155847  ** pointer to the single content node. So that the segment consists of a
155848  ** single leaf and a single interior (root) node.
155849  **
155850  ** Todo: Better might be to defer allocating space in the %_segments
155851  ** table until we are sure it is needed.
155852  */
155853  if( iRoot==0 ){
155854    Blob *pBlock = &pWriter->aNodeWriter[1].block;
155855    blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
155856    if( rc==SQLITE_OK ){
155857      pBlock->a[0] = 0x01;
155858      pBlock->n = 1 + sqlite3Fts3PutVarint(
155859          &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
155860      );
155861    }
155862    iRoot = 1;
155863  }
155864  pRoot = &pWriter->aNodeWriter[iRoot];
155865
155866  /* Flush all currently outstanding nodes to disk. */
155867  for(i=0; i<iRoot; i++){
155868    NodeWriter *pNode = &pWriter->aNodeWriter[i];
155869    if( pNode->block.n>0 && rc==SQLITE_OK ){
155870      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
155871    }
155872    sqlite3_free(pNode->block.a);
155873    sqlite3_free(pNode->key.a);
155874  }
155875
155876  /* Write the %_segdir record. */
155877  if( rc==SQLITE_OK ){
155878    rc = fts3WriteSegdir(p,
155879        pWriter->iAbsLevel+1,               /* level */
155880        pWriter->iIdx,                      /* idx */
155881        pWriter->iStart,                    /* start_block */
155882        pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
155883        pWriter->iEnd,                      /* end_block */
155884        (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
155885        pRoot->block.a, pRoot->block.n      /* root */
155886    );
155887  }
155888  sqlite3_free(pRoot->block.a);
155889  sqlite3_free(pRoot->key.a);
155890
155891  *pRc = rc;
155892}
155893
155894/*
155895** Compare the term in buffer zLhs (size in bytes nLhs) with that in
155896** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
155897** the other, it is considered to be smaller than the other.
155898**
155899** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
155900** if it is greater.
155901*/
155902static int fts3TermCmp(
155903  const char *zLhs, int nLhs,     /* LHS of comparison */
155904  const char *zRhs, int nRhs      /* RHS of comparison */
155905){
155906  int nCmp = MIN(nLhs, nRhs);
155907  int res;
155908
155909  res = memcmp(zLhs, zRhs, nCmp);
155910  if( res==0 ) res = nLhs - nRhs;
155911
155912  return res;
155913}
155914
155915
155916/*
155917** Query to see if the entry in the %_segments table with blockid iEnd is
155918** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
155919** returning. Otherwise, set *pbRes to 0.
155920**
155921** Or, if an error occurs while querying the database, return an SQLite
155922** error code. The final value of *pbRes is undefined in this case.
155923**
155924** This is used to test if a segment is an "appendable" segment. If it
155925** is, then a NULL entry has been inserted into the %_segments table
155926** with blockid %_segdir.end_block.
155927*/
155928static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
155929  int bRes = 0;                   /* Result to set *pbRes to */
155930  sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
155931  int rc;                         /* Return code */
155932
155933  rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
155934  if( rc==SQLITE_OK ){
155935    sqlite3_bind_int64(pCheck, 1, iEnd);
155936    if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
155937    rc = sqlite3_reset(pCheck);
155938  }
155939
155940  *pbRes = bRes;
155941  return rc;
155942}
155943
155944/*
155945** This function is called when initializing an incremental-merge operation.
155946** It checks if the existing segment with index value iIdx at absolute level
155947** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
155948** merge-writer object *pWriter is initialized to write to it.
155949**
155950** An existing segment can be appended to by an incremental merge if:
155951**
155952**   * It was initially created as an appendable segment (with all required
155953**     space pre-allocated), and
155954**
155955**   * The first key read from the input (arguments zKey and nKey) is
155956**     greater than the largest key currently stored in the potential
155957**     output segment.
155958*/
155959static int fts3IncrmergeLoad(
155960  Fts3Table *p,                   /* Fts3 table handle */
155961  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
155962  int iIdx,                       /* Index of candidate output segment */
155963  const char *zKey,               /* First key to write */
155964  int nKey,                       /* Number of bytes in nKey */
155965  IncrmergeWriter *pWriter        /* Populate this object */
155966){
155967  int rc;                         /* Return code */
155968  sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
155969
155970  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
155971  if( rc==SQLITE_OK ){
155972    sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
155973    sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
155974    sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
155975    const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
155976    int nRoot = 0;                /* Size of aRoot[] in bytes */
155977    int rc2;                      /* Return code from sqlite3_reset() */
155978    int bAppendable = 0;          /* Set to true if segment is appendable */
155979
155980    /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
155981    sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
155982    sqlite3_bind_int(pSelect, 2, iIdx);
155983    if( sqlite3_step(pSelect)==SQLITE_ROW ){
155984      iStart = sqlite3_column_int64(pSelect, 1);
155985      iLeafEnd = sqlite3_column_int64(pSelect, 2);
155986      fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
155987      if( pWriter->nLeafData<0 ){
155988        pWriter->nLeafData = pWriter->nLeafData * -1;
155989      }
155990      pWriter->bNoLeafData = (pWriter->nLeafData==0);
155991      nRoot = sqlite3_column_bytes(pSelect, 4);
155992      aRoot = sqlite3_column_blob(pSelect, 4);
155993    }else{
155994      return sqlite3_reset(pSelect);
155995    }
155996
155997    /* Check for the zero-length marker in the %_segments table */
155998    rc = fts3IsAppendable(p, iEnd, &bAppendable);
155999
156000    /* Check that zKey/nKey is larger than the largest key the candidate */
156001    if( rc==SQLITE_OK && bAppendable ){
156002      char *aLeaf = 0;
156003      int nLeaf = 0;
156004
156005      rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
156006      if( rc==SQLITE_OK ){
156007        NodeReader reader;
156008        for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
156009            rc==SQLITE_OK && reader.aNode;
156010            rc = nodeReaderNext(&reader)
156011        ){
156012          assert( reader.aNode );
156013        }
156014        if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
156015          bAppendable = 0;
156016        }
156017        nodeReaderRelease(&reader);
156018      }
156019      sqlite3_free(aLeaf);
156020    }
156021
156022    if( rc==SQLITE_OK && bAppendable ){
156023      /* It is possible to append to this segment. Set up the IncrmergeWriter
156024      ** object to do so.  */
156025      int i;
156026      int nHeight = (int)aRoot[0];
156027      NodeWriter *pNode;
156028
156029      pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
156030      pWriter->iStart = iStart;
156031      pWriter->iEnd = iEnd;
156032      pWriter->iAbsLevel = iAbsLevel;
156033      pWriter->iIdx = iIdx;
156034
156035      for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
156036        pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
156037      }
156038
156039      pNode = &pWriter->aNodeWriter[nHeight];
156040      pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
156041      blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
156042      if( rc==SQLITE_OK ){
156043        memcpy(pNode->block.a, aRoot, nRoot);
156044        pNode->block.n = nRoot;
156045      }
156046
156047      for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
156048        NodeReader reader;
156049        pNode = &pWriter->aNodeWriter[i];
156050
156051        rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
156052        while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
156053        blobGrowBuffer(&pNode->key, reader.term.n, &rc);
156054        if( rc==SQLITE_OK ){
156055          memcpy(pNode->key.a, reader.term.a, reader.term.n);
156056          pNode->key.n = reader.term.n;
156057          if( i>0 ){
156058            char *aBlock = 0;
156059            int nBlock = 0;
156060            pNode = &pWriter->aNodeWriter[i-1];
156061            pNode->iBlock = reader.iChild;
156062            rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
156063            blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
156064            if( rc==SQLITE_OK ){
156065              memcpy(pNode->block.a, aBlock, nBlock);
156066              pNode->block.n = nBlock;
156067            }
156068            sqlite3_free(aBlock);
156069          }
156070        }
156071        nodeReaderRelease(&reader);
156072      }
156073    }
156074
156075    rc2 = sqlite3_reset(pSelect);
156076    if( rc==SQLITE_OK ) rc = rc2;
156077  }
156078
156079  return rc;
156080}
156081
156082/*
156083** Determine the largest segment index value that exists within absolute
156084** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
156085** one before returning SQLITE_OK. Or, if there are no segments at all
156086** within level iAbsLevel, set *piIdx to zero.
156087**
156088** If an error occurs, return an SQLite error code. The final value of
156089** *piIdx is undefined in this case.
156090*/
156091static int fts3IncrmergeOutputIdx(
156092  Fts3Table *p,                   /* FTS Table handle */
156093  sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
156094  int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
156095){
156096  int rc;
156097  sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
156098
156099  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
156100  if( rc==SQLITE_OK ){
156101    sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
156102    sqlite3_step(pOutputIdx);
156103    *piIdx = sqlite3_column_int(pOutputIdx, 0);
156104    rc = sqlite3_reset(pOutputIdx);
156105  }
156106
156107  return rc;
156108}
156109
156110/*
156111** Allocate an appendable output segment on absolute level iAbsLevel+1
156112** with idx value iIdx.
156113**
156114** In the %_segdir table, a segment is defined by the values in three
156115** columns:
156116**
156117**     start_block
156118**     leaves_end_block
156119**     end_block
156120**
156121** When an appendable segment is allocated, it is estimated that the
156122** maximum number of leaf blocks that may be required is the sum of the
156123** number of leaf blocks consumed by the input segments, plus the number
156124** of input segments, multiplied by two. This value is stored in stack
156125** variable nLeafEst.
156126**
156127** A total of 16*nLeafEst blocks are allocated when an appendable segment
156128** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
156129** array of leaf nodes starts at the first block allocated. The array
156130** of interior nodes that are parents of the leaf nodes start at block
156131** (start_block + (1 + end_block - start_block) / 16). And so on.
156132**
156133** In the actual code below, the value "16" is replaced with the
156134** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
156135*/
156136static int fts3IncrmergeWriter(
156137  Fts3Table *p,                   /* Fts3 table handle */
156138  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
156139  int iIdx,                       /* Index of new output segment */
156140  Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
156141  IncrmergeWriter *pWriter        /* Populate this object */
156142){
156143  int rc;                         /* Return Code */
156144  int i;                          /* Iterator variable */
156145  int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
156146  sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
156147  sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
156148
156149  /* Calculate nLeafEst. */
156150  rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
156151  if( rc==SQLITE_OK ){
156152    sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
156153    sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
156154    if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
156155      nLeafEst = sqlite3_column_int(pLeafEst, 0);
156156    }
156157    rc = sqlite3_reset(pLeafEst);
156158  }
156159  if( rc!=SQLITE_OK ) return rc;
156160
156161  /* Calculate the first block to use in the output segment */
156162  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
156163  if( rc==SQLITE_OK ){
156164    if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
156165      pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
156166      pWriter->iEnd = pWriter->iStart - 1;
156167      pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
156168    }
156169    rc = sqlite3_reset(pFirstBlock);
156170  }
156171  if( rc!=SQLITE_OK ) return rc;
156172
156173  /* Insert the marker in the %_segments table to make sure nobody tries
156174  ** to steal the space just allocated. This is also used to identify
156175  ** appendable segments.  */
156176  rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
156177  if( rc!=SQLITE_OK ) return rc;
156178
156179  pWriter->iAbsLevel = iAbsLevel;
156180  pWriter->nLeafEst = nLeafEst;
156181  pWriter->iIdx = iIdx;
156182
156183  /* Set up the array of NodeWriter objects */
156184  for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
156185    pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
156186  }
156187  return SQLITE_OK;
156188}
156189
156190/*
156191** Remove an entry from the %_segdir table. This involves running the
156192** following two statements:
156193**
156194**   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
156195**   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
156196**
156197** The DELETE statement removes the specific %_segdir level. The UPDATE
156198** statement ensures that the remaining segments have contiguously allocated
156199** idx values.
156200*/
156201static int fts3RemoveSegdirEntry(
156202  Fts3Table *p,                   /* FTS3 table handle */
156203  sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
156204  int iIdx                        /* Index of %_segdir entry to delete */
156205){
156206  int rc;                         /* Return code */
156207  sqlite3_stmt *pDelete = 0;      /* DELETE statement */
156208
156209  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
156210  if( rc==SQLITE_OK ){
156211    sqlite3_bind_int64(pDelete, 1, iAbsLevel);
156212    sqlite3_bind_int(pDelete, 2, iIdx);
156213    sqlite3_step(pDelete);
156214    rc = sqlite3_reset(pDelete);
156215  }
156216
156217  return rc;
156218}
156219
156220/*
156221** One or more segments have just been removed from absolute level iAbsLevel.
156222** Update the 'idx' values of the remaining segments in the level so that
156223** the idx values are a contiguous sequence starting from 0.
156224*/
156225static int fts3RepackSegdirLevel(
156226  Fts3Table *p,                   /* FTS3 table handle */
156227  sqlite3_int64 iAbsLevel         /* Absolute level to repack */
156228){
156229  int rc;                         /* Return code */
156230  int *aIdx = 0;                  /* Array of remaining idx values */
156231  int nIdx = 0;                   /* Valid entries in aIdx[] */
156232  int nAlloc = 0;                 /* Allocated size of aIdx[] */
156233  int i;                          /* Iterator variable */
156234  sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
156235  sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
156236
156237  rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
156238  if( rc==SQLITE_OK ){
156239    int rc2;
156240    sqlite3_bind_int64(pSelect, 1, iAbsLevel);
156241    while( SQLITE_ROW==sqlite3_step(pSelect) ){
156242      if( nIdx>=nAlloc ){
156243        int *aNew;
156244        nAlloc += 16;
156245        aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
156246        if( !aNew ){
156247          rc = SQLITE_NOMEM;
156248          break;
156249        }
156250        aIdx = aNew;
156251      }
156252      aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
156253    }
156254    rc2 = sqlite3_reset(pSelect);
156255    if( rc==SQLITE_OK ) rc = rc2;
156256  }
156257
156258  if( rc==SQLITE_OK ){
156259    rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
156260  }
156261  if( rc==SQLITE_OK ){
156262    sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
156263  }
156264
156265  assert( p->bIgnoreSavepoint==0 );
156266  p->bIgnoreSavepoint = 1;
156267  for(i=0; rc==SQLITE_OK && i<nIdx; i++){
156268    if( aIdx[i]!=i ){
156269      sqlite3_bind_int(pUpdate, 3, aIdx[i]);
156270      sqlite3_bind_int(pUpdate, 1, i);
156271      sqlite3_step(pUpdate);
156272      rc = sqlite3_reset(pUpdate);
156273    }
156274  }
156275  p->bIgnoreSavepoint = 0;
156276
156277  sqlite3_free(aIdx);
156278  return rc;
156279}
156280
156281static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
156282  pNode->a[0] = (char)iHeight;
156283  if( iChild ){
156284    assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
156285    pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
156286  }else{
156287    assert( pNode->nAlloc>=1 );
156288    pNode->n = 1;
156289  }
156290}
156291
156292/*
156293** The first two arguments are a pointer to and the size of a segment b-tree
156294** node. The node may be a leaf or an internal node.
156295**
156296** This function creates a new node image in blob object *pNew by copying
156297** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
156298** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
156299*/
156300static int fts3TruncateNode(
156301  const char *aNode,              /* Current node image */
156302  int nNode,                      /* Size of aNode in bytes */
156303  Blob *pNew,                     /* OUT: Write new node image here */
156304  const char *zTerm,              /* Omit all terms smaller than this */
156305  int nTerm,                      /* Size of zTerm in bytes */
156306  sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
156307){
156308  NodeReader reader;              /* Reader object */
156309  Blob prev = {0, 0, 0};          /* Previous term written to new node */
156310  int rc = SQLITE_OK;             /* Return code */
156311  int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
156312
156313  /* Allocate required output space */
156314  blobGrowBuffer(pNew, nNode, &rc);
156315  if( rc!=SQLITE_OK ) return rc;
156316  pNew->n = 0;
156317
156318  /* Populate new node buffer */
156319  for(rc = nodeReaderInit(&reader, aNode, nNode);
156320      rc==SQLITE_OK && reader.aNode;
156321      rc = nodeReaderNext(&reader)
156322  ){
156323    if( pNew->n==0 ){
156324      int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
156325      if( res<0 || (bLeaf==0 && res==0) ) continue;
156326      fts3StartNode(pNew, (int)aNode[0], reader.iChild);
156327      *piBlock = reader.iChild;
156328    }
156329    rc = fts3AppendToNode(
156330        pNew, &prev, reader.term.a, reader.term.n,
156331        reader.aDoclist, reader.nDoclist
156332    );
156333    if( rc!=SQLITE_OK ) break;
156334  }
156335  if( pNew->n==0 ){
156336    fts3StartNode(pNew, (int)aNode[0], reader.iChild);
156337    *piBlock = reader.iChild;
156338  }
156339  assert( pNew->n<=pNew->nAlloc );
156340
156341  nodeReaderRelease(&reader);
156342  sqlite3_free(prev.a);
156343  return rc;
156344}
156345
156346/*
156347** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
156348** level iAbsLevel. This may involve deleting entries from the %_segments
156349** table, and modifying existing entries in both the %_segments and %_segdir
156350** tables.
156351**
156352** SQLITE_OK is returned if the segment is updated successfully. Or an
156353** SQLite error code otherwise.
156354*/
156355static int fts3TruncateSegment(
156356  Fts3Table *p,                   /* FTS3 table handle */
156357  sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
156358  int iIdx,                       /* Index within level of segment to modify */
156359  const char *zTerm,              /* Remove terms smaller than this */
156360  int nTerm                      /* Number of bytes in buffer zTerm */
156361){
156362  int rc = SQLITE_OK;             /* Return code */
156363  Blob root = {0,0,0};            /* New root page image */
156364  Blob block = {0,0,0};           /* Buffer used for any other block */
156365  sqlite3_int64 iBlock = 0;       /* Block id */
156366  sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
156367  sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
156368  sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
156369
156370  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
156371  if( rc==SQLITE_OK ){
156372    int rc2;                      /* sqlite3_reset() return code */
156373    sqlite3_bind_int64(pFetch, 1, iAbsLevel);
156374    sqlite3_bind_int(pFetch, 2, iIdx);
156375    if( SQLITE_ROW==sqlite3_step(pFetch) ){
156376      const char *aRoot = sqlite3_column_blob(pFetch, 4);
156377      int nRoot = sqlite3_column_bytes(pFetch, 4);
156378      iOldStart = sqlite3_column_int64(pFetch, 1);
156379      rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
156380    }
156381    rc2 = sqlite3_reset(pFetch);
156382    if( rc==SQLITE_OK ) rc = rc2;
156383  }
156384
156385  while( rc==SQLITE_OK && iBlock ){
156386    char *aBlock = 0;
156387    int nBlock = 0;
156388    iNewStart = iBlock;
156389
156390    rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
156391    if( rc==SQLITE_OK ){
156392      rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
156393    }
156394    if( rc==SQLITE_OK ){
156395      rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
156396    }
156397    sqlite3_free(aBlock);
156398  }
156399
156400  /* Variable iNewStart now contains the first valid leaf node. */
156401  if( rc==SQLITE_OK && iNewStart ){
156402    sqlite3_stmt *pDel = 0;
156403    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
156404    if( rc==SQLITE_OK ){
156405      sqlite3_bind_int64(pDel, 1, iOldStart);
156406      sqlite3_bind_int64(pDel, 2, iNewStart-1);
156407      sqlite3_step(pDel);
156408      rc = sqlite3_reset(pDel);
156409    }
156410  }
156411
156412  if( rc==SQLITE_OK ){
156413    sqlite3_stmt *pChomp = 0;
156414    rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
156415    if( rc==SQLITE_OK ){
156416      sqlite3_bind_int64(pChomp, 1, iNewStart);
156417      sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
156418      sqlite3_bind_int64(pChomp, 3, iAbsLevel);
156419      sqlite3_bind_int(pChomp, 4, iIdx);
156420      sqlite3_step(pChomp);
156421      rc = sqlite3_reset(pChomp);
156422    }
156423  }
156424
156425  sqlite3_free(root.a);
156426  sqlite3_free(block.a);
156427  return rc;
156428}
156429
156430/*
156431** This function is called after an incrmental-merge operation has run to
156432** merge (or partially merge) two or more segments from absolute level
156433** iAbsLevel.
156434**
156435** Each input segment is either removed from the db completely (if all of
156436** its data was copied to the output segment by the incrmerge operation)
156437** or modified in place so that it no longer contains those entries that
156438** have been duplicated in the output segment.
156439*/
156440static int fts3IncrmergeChomp(
156441  Fts3Table *p,                   /* FTS table handle */
156442  sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
156443  Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
156444  int *pnRem                      /* Number of segments not deleted */
156445){
156446  int i;
156447  int nRem = 0;
156448  int rc = SQLITE_OK;
156449
156450  for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
156451    Fts3SegReader *pSeg = 0;
156452    int j;
156453
156454    /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
156455    ** somewhere in the pCsr->apSegment[] array.  */
156456    for(j=0; ALWAYS(j<pCsr->nSegment); j++){
156457      pSeg = pCsr->apSegment[j];
156458      if( pSeg->iIdx==i ) break;
156459    }
156460    assert( j<pCsr->nSegment && pSeg->iIdx==i );
156461
156462    if( pSeg->aNode==0 ){
156463      /* Seg-reader is at EOF. Remove the entire input segment. */
156464      rc = fts3DeleteSegment(p, pSeg);
156465      if( rc==SQLITE_OK ){
156466        rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
156467      }
156468      *pnRem = 0;
156469    }else{
156470      /* The incremental merge did not copy all the data from this
156471      ** segment to the upper level. The segment is modified in place
156472      ** so that it contains no keys smaller than zTerm/nTerm. */
156473      const char *zTerm = pSeg->zTerm;
156474      int nTerm = pSeg->nTerm;
156475      rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
156476      nRem++;
156477    }
156478  }
156479
156480  if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
156481    rc = fts3RepackSegdirLevel(p, iAbsLevel);
156482  }
156483
156484  *pnRem = nRem;
156485  return rc;
156486}
156487
156488/*
156489** Store an incr-merge hint in the database.
156490*/
156491static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
156492  sqlite3_stmt *pReplace = 0;
156493  int rc;                         /* Return code */
156494
156495  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
156496  if( rc==SQLITE_OK ){
156497    sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
156498    sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
156499    sqlite3_step(pReplace);
156500    rc = sqlite3_reset(pReplace);
156501  }
156502
156503  return rc;
156504}
156505
156506/*
156507** Load an incr-merge hint from the database. The incr-merge hint, if one
156508** exists, is stored in the rowid==1 row of the %_stat table.
156509**
156510** If successful, populate blob *pHint with the value read from the %_stat
156511** table and return SQLITE_OK. Otherwise, if an error occurs, return an
156512** SQLite error code.
156513*/
156514static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
156515  sqlite3_stmt *pSelect = 0;
156516  int rc;
156517
156518  pHint->n = 0;
156519  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
156520  if( rc==SQLITE_OK ){
156521    int rc2;
156522    sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
156523    if( SQLITE_ROW==sqlite3_step(pSelect) ){
156524      const char *aHint = sqlite3_column_blob(pSelect, 0);
156525      int nHint = sqlite3_column_bytes(pSelect, 0);
156526      if( aHint ){
156527        blobGrowBuffer(pHint, nHint, &rc);
156528        if( rc==SQLITE_OK ){
156529          memcpy(pHint->a, aHint, nHint);
156530          pHint->n = nHint;
156531        }
156532      }
156533    }
156534    rc2 = sqlite3_reset(pSelect);
156535    if( rc==SQLITE_OK ) rc = rc2;
156536  }
156537
156538  return rc;
156539}
156540
156541/*
156542** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
156543** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
156544** consists of two varints, the absolute level number of the input segments
156545** and the number of input segments.
156546**
156547** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
156548** set *pRc to an SQLite error code before returning.
156549*/
156550static void fts3IncrmergeHintPush(
156551  Blob *pHint,                    /* Hint blob to append to */
156552  i64 iAbsLevel,                  /* First varint to store in hint */
156553  int nInput,                     /* Second varint to store in hint */
156554  int *pRc                        /* IN/OUT: Error code */
156555){
156556  blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
156557  if( *pRc==SQLITE_OK ){
156558    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
156559    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
156560  }
156561}
156562
156563/*
156564** Read the last entry (most recently pushed) from the hint blob *pHint
156565** and then remove the entry. Write the two values read to *piAbsLevel and
156566** *pnInput before returning.
156567**
156568** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
156569** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
156570*/
156571static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
156572  const int nHint = pHint->n;
156573  int i;
156574
156575  i = pHint->n-2;
156576  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
156577  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
156578
156579  pHint->n = i;
156580  i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
156581  i += fts3GetVarint32(&pHint->a[i], pnInput);
156582  if( i!=nHint ) return FTS_CORRUPT_VTAB;
156583
156584  return SQLITE_OK;
156585}
156586
156587
156588/*
156589** Attempt an incremental merge that writes nMerge leaf blocks.
156590**
156591** Incremental merges happen nMin segments at a time. The segments
156592** to be merged are the nMin oldest segments (the ones with the smallest
156593** values for the _segdir.idx field) in the highest level that contains
156594** at least nMin segments. Multiple merges might occur in an attempt to
156595** write the quota of nMerge leaf blocks.
156596*/
156597SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
156598  int rc;                         /* Return code */
156599  int nRem = nMerge;              /* Number of leaf pages yet to  be written */
156600  Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
156601  Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
156602  IncrmergeWriter *pWriter;       /* Writer object */
156603  int nSeg = 0;                   /* Number of input segments */
156604  sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
156605  Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
156606  int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
156607
156608  /* Allocate space for the cursor, filter and writer objects */
156609  const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
156610  pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
156611  if( !pWriter ) return SQLITE_NOMEM;
156612  pFilter = (Fts3SegFilter *)&pWriter[1];
156613  pCsr = (Fts3MultiSegReader *)&pFilter[1];
156614
156615  rc = fts3IncrmergeHintLoad(p, &hint);
156616  while( rc==SQLITE_OK && nRem>0 ){
156617    const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
156618    sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
156619    int bUseHint = 0;             /* True if attempting to append */
156620    int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
156621
156622    /* Search the %_segdir table for the absolute level with the smallest
156623    ** relative level number that contains at least nMin segments, if any.
156624    ** If one is found, set iAbsLevel to the absolute level number and
156625    ** nSeg to nMin. If no level with at least nMin segments can be found,
156626    ** set nSeg to -1.
156627    */
156628    rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
156629    sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
156630    if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
156631      iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
156632      nSeg = sqlite3_column_int(pFindLevel, 1);
156633      assert( nSeg>=2 );
156634    }else{
156635      nSeg = -1;
156636    }
156637    rc = sqlite3_reset(pFindLevel);
156638
156639    /* If the hint read from the %_stat table is not empty, check if the
156640    ** last entry in it specifies a relative level smaller than or equal
156641    ** to the level identified by the block above (if any). If so, this
156642    ** iteration of the loop will work on merging at the hinted level.
156643    */
156644    if( rc==SQLITE_OK && hint.n ){
156645      int nHint = hint.n;
156646      sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
156647      int nHintSeg = 0;                     /* Hint number of segments */
156648
156649      rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
156650      if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
156651        iAbsLevel = iHintAbsLevel;
156652        nSeg = nHintSeg;
156653        bUseHint = 1;
156654        bDirtyHint = 1;
156655      }else{
156656        /* This undoes the effect of the HintPop() above - so that no entry
156657        ** is removed from the hint blob.  */
156658        hint.n = nHint;
156659      }
156660    }
156661
156662    /* If nSeg is less that zero, then there is no level with at least
156663    ** nMin segments and no hint in the %_stat table. No work to do.
156664    ** Exit early in this case.  */
156665    if( nSeg<0 ) break;
156666
156667    /* Open a cursor to iterate through the contents of the oldest nSeg
156668    ** indexes of absolute level iAbsLevel. If this cursor is opened using
156669    ** the 'hint' parameters, it is possible that there are less than nSeg
156670    ** segments available in level iAbsLevel. In this case, no work is
156671    ** done on iAbsLevel - fall through to the next iteration of the loop
156672    ** to start work on some other level.  */
156673    memset(pWriter, 0, nAlloc);
156674    pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
156675
156676    if( rc==SQLITE_OK ){
156677      rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
156678      assert( bUseHint==1 || bUseHint==0 );
156679      if( iIdx==0 || (bUseHint && iIdx==1) ){
156680        int bIgnore = 0;
156681        rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
156682        if( bIgnore ){
156683          pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
156684        }
156685      }
156686    }
156687
156688    if( rc==SQLITE_OK ){
156689      rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
156690    }
156691    if( SQLITE_OK==rc && pCsr->nSegment==nSeg
156692     && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
156693     && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
156694    ){
156695      if( bUseHint && iIdx>0 ){
156696        const char *zKey = pCsr->zTerm;
156697        int nKey = pCsr->nTerm;
156698        rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
156699      }else{
156700        rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
156701      }
156702
156703      if( rc==SQLITE_OK && pWriter->nLeafEst ){
156704        fts3LogMerge(nSeg, iAbsLevel);
156705        do {
156706          rc = fts3IncrmergeAppend(p, pWriter, pCsr);
156707          if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
156708          if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
156709        }while( rc==SQLITE_ROW );
156710
156711        /* Update or delete the input segments */
156712        if( rc==SQLITE_OK ){
156713          nRem -= (1 + pWriter->nWork);
156714          rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
156715          if( nSeg!=0 ){
156716            bDirtyHint = 1;
156717            fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
156718          }
156719        }
156720      }
156721
156722      if( nSeg!=0 ){
156723        pWriter->nLeafData = pWriter->nLeafData * -1;
156724      }
156725      fts3IncrmergeRelease(p, pWriter, &rc);
156726      if( nSeg==0 && pWriter->bNoLeafData==0 ){
156727        fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
156728      }
156729    }
156730
156731    sqlite3Fts3SegReaderFinish(pCsr);
156732  }
156733
156734  /* Write the hint values into the %_stat table for the next incr-merger */
156735  if( bDirtyHint && rc==SQLITE_OK ){
156736    rc = fts3IncrmergeHintStore(p, &hint);
156737  }
156738
156739  sqlite3_free(pWriter);
156740  sqlite3_free(hint.a);
156741  return rc;
156742}
156743
156744/*
156745** Convert the text beginning at *pz into an integer and return
156746** its value.  Advance *pz to point to the first character past
156747** the integer.
156748*/
156749static int fts3Getint(const char **pz){
156750  const char *z = *pz;
156751  int i = 0;
156752  while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
156753  *pz = z;
156754  return i;
156755}
156756
156757/*
156758** Process statements of the form:
156759**
156760**    INSERT INTO table(table) VALUES('merge=A,B');
156761**
156762** A and B are integers that decode to be the number of leaf pages
156763** written for the merge, and the minimum number of segments on a level
156764** before it will be selected for a merge, respectively.
156765*/
156766static int fts3DoIncrmerge(
156767  Fts3Table *p,                   /* FTS3 table handle */
156768  const char *zParam              /* Nul-terminated string containing "A,B" */
156769){
156770  int rc;
156771  int nMin = (FTS3_MERGE_COUNT / 2);
156772  int nMerge = 0;
156773  const char *z = zParam;
156774
156775  /* Read the first integer value */
156776  nMerge = fts3Getint(&z);
156777
156778  /* If the first integer value is followed by a ',',  read the second
156779  ** integer value. */
156780  if( z[0]==',' && z[1]!='\0' ){
156781    z++;
156782    nMin = fts3Getint(&z);
156783  }
156784
156785  if( z[0]!='\0' || nMin<2 ){
156786    rc = SQLITE_ERROR;
156787  }else{
156788    rc = SQLITE_OK;
156789    if( !p->bHasStat ){
156790      assert( p->bFts4==0 );
156791      sqlite3Fts3CreateStatTable(&rc, p);
156792    }
156793    if( rc==SQLITE_OK ){
156794      rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
156795    }
156796    sqlite3Fts3SegmentsClose(p);
156797  }
156798  return rc;
156799}
156800
156801/*
156802** Process statements of the form:
156803**
156804**    INSERT INTO table(table) VALUES('automerge=X');
156805**
156806** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
156807** turn it on.  The setting is persistent.
156808*/
156809static int fts3DoAutoincrmerge(
156810  Fts3Table *p,                   /* FTS3 table handle */
156811  const char *zParam              /* Nul-terminated string containing boolean */
156812){
156813  int rc = SQLITE_OK;
156814  sqlite3_stmt *pStmt = 0;
156815  p->nAutoincrmerge = fts3Getint(&zParam);
156816  if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
156817    p->nAutoincrmerge = 8;
156818  }
156819  if( !p->bHasStat ){
156820    assert( p->bFts4==0 );
156821    sqlite3Fts3CreateStatTable(&rc, p);
156822    if( rc ) return rc;
156823  }
156824  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
156825  if( rc ) return rc;
156826  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
156827  sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
156828  sqlite3_step(pStmt);
156829  rc = sqlite3_reset(pStmt);
156830  return rc;
156831}
156832
156833/*
156834** Return a 64-bit checksum for the FTS index entry specified by the
156835** arguments to this function.
156836*/
156837static u64 fts3ChecksumEntry(
156838  const char *zTerm,              /* Pointer to buffer containing term */
156839  int nTerm,                      /* Size of zTerm in bytes */
156840  int iLangid,                    /* Language id for current row */
156841  int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
156842  i64 iDocid,                     /* Docid for current row. */
156843  int iCol,                       /* Column number */
156844  int iPos                        /* Position */
156845){
156846  int i;
156847  u64 ret = (u64)iDocid;
156848
156849  ret += (ret<<3) + iLangid;
156850  ret += (ret<<3) + iIndex;
156851  ret += (ret<<3) + iCol;
156852  ret += (ret<<3) + iPos;
156853  for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
156854
156855  return ret;
156856}
156857
156858/*
156859** Return a checksum of all entries in the FTS index that correspond to
156860** language id iLangid. The checksum is calculated by XORing the checksums
156861** of each individual entry (see fts3ChecksumEntry()) together.
156862**
156863** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
156864** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
156865** return value is undefined in this case.
156866*/
156867static u64 fts3ChecksumIndex(
156868  Fts3Table *p,                   /* FTS3 table handle */
156869  int iLangid,                    /* Language id to return cksum for */
156870  int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
156871  int *pRc                        /* OUT: Return code */
156872){
156873  Fts3SegFilter filter;
156874  Fts3MultiSegReader csr;
156875  int rc;
156876  u64 cksum = 0;
156877
156878  assert( *pRc==SQLITE_OK );
156879
156880  memset(&filter, 0, sizeof(filter));
156881  memset(&csr, 0, sizeof(csr));
156882  filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
156883  filter.flags |= FTS3_SEGMENT_SCAN;
156884
156885  rc = sqlite3Fts3SegReaderCursor(
156886      p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
156887  );
156888  if( rc==SQLITE_OK ){
156889    rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
156890  }
156891
156892  if( rc==SQLITE_OK ){
156893    while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
156894      char *pCsr = csr.aDoclist;
156895      char *pEnd = &pCsr[csr.nDoclist];
156896
156897      i64 iDocid = 0;
156898      i64 iCol = 0;
156899      i64 iPos = 0;
156900
156901      pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
156902      while( pCsr<pEnd ){
156903        i64 iVal = 0;
156904        pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
156905        if( pCsr<pEnd ){
156906          if( iVal==0 || iVal==1 ){
156907            iCol = 0;
156908            iPos = 0;
156909            if( iVal ){
156910              pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
156911            }else{
156912              pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
156913              iDocid += iVal;
156914            }
156915          }else{
156916            iPos += (iVal - 2);
156917            cksum = cksum ^ fts3ChecksumEntry(
156918                csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
156919                (int)iCol, (int)iPos
156920            );
156921          }
156922        }
156923      }
156924    }
156925  }
156926  sqlite3Fts3SegReaderFinish(&csr);
156927
156928  *pRc = rc;
156929  return cksum;
156930}
156931
156932/*
156933** Check if the contents of the FTS index match the current contents of the
156934** content table. If no error occurs and the contents do match, set *pbOk
156935** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
156936** to false before returning.
156937**
156938** If an error occurs (e.g. an OOM or IO error), return an SQLite error
156939** code. The final value of *pbOk is undefined in this case.
156940*/
156941static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
156942  int rc = SQLITE_OK;             /* Return code */
156943  u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
156944  u64 cksum2 = 0;                 /* Checksum based on %_content contents */
156945  sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
156946
156947  /* This block calculates the checksum according to the FTS index. */
156948  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
156949  if( rc==SQLITE_OK ){
156950    int rc2;
156951    sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
156952    sqlite3_bind_int(pAllLangid, 2, p->nIndex);
156953    while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
156954      int iLangid = sqlite3_column_int(pAllLangid, 0);
156955      int i;
156956      for(i=0; i<p->nIndex; i++){
156957        cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
156958      }
156959    }
156960    rc2 = sqlite3_reset(pAllLangid);
156961    if( rc==SQLITE_OK ) rc = rc2;
156962  }
156963
156964  /* This block calculates the checksum according to the %_content table */
156965  if( rc==SQLITE_OK ){
156966    sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
156967    sqlite3_stmt *pStmt = 0;
156968    char *zSql;
156969
156970    zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
156971    if( !zSql ){
156972      rc = SQLITE_NOMEM;
156973    }else{
156974      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
156975      sqlite3_free(zSql);
156976    }
156977
156978    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
156979      i64 iDocid = sqlite3_column_int64(pStmt, 0);
156980      int iLang = langidFromSelect(p, pStmt);
156981      int iCol;
156982
156983      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
156984        if( p->abNotindexed[iCol]==0 ){
156985          const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
156986          int nText = sqlite3_column_bytes(pStmt, iCol+1);
156987          sqlite3_tokenizer_cursor *pT = 0;
156988
156989          rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
156990          while( rc==SQLITE_OK ){
156991            char const *zToken;       /* Buffer containing token */
156992            int nToken = 0;           /* Number of bytes in token */
156993            int iDum1 = 0, iDum2 = 0; /* Dummy variables */
156994            int iPos = 0;             /* Position of token in zText */
156995
156996            rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
156997            if( rc==SQLITE_OK ){
156998              int i;
156999              cksum2 = cksum2 ^ fts3ChecksumEntry(
157000                  zToken, nToken, iLang, 0, iDocid, iCol, iPos
157001              );
157002              for(i=1; i<p->nIndex; i++){
157003                if( p->aIndex[i].nPrefix<=nToken ){
157004                  cksum2 = cksum2 ^ fts3ChecksumEntry(
157005                      zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
157006                  );
157007                }
157008              }
157009            }
157010          }
157011          if( pT ) pModule->xClose(pT);
157012          if( rc==SQLITE_DONE ) rc = SQLITE_OK;
157013        }
157014      }
157015    }
157016
157017    sqlite3_finalize(pStmt);
157018  }
157019
157020  *pbOk = (cksum1==cksum2);
157021  return rc;
157022}
157023
157024/*
157025** Run the integrity-check. If no error occurs and the current contents of
157026** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
157027** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
157028**
157029** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
157030** error code.
157031**
157032** The integrity-check works as follows. For each token and indexed token
157033** prefix in the document set, a 64-bit checksum is calculated (by code
157034** in fts3ChecksumEntry()) based on the following:
157035**
157036**     + The index number (0 for the main index, 1 for the first prefix
157037**       index etc.),
157038**     + The token (or token prefix) text itself,
157039**     + The language-id of the row it appears in,
157040**     + The docid of the row it appears in,
157041**     + The column it appears in, and
157042**     + The tokens position within that column.
157043**
157044** The checksums for all entries in the index are XORed together to create
157045** a single checksum for the entire index.
157046**
157047** The integrity-check code calculates the same checksum in two ways:
157048**
157049**     1. By scanning the contents of the FTS index, and
157050**     2. By scanning and tokenizing the content table.
157051**
157052** If the two checksums are identical, the integrity-check is deemed to have
157053** passed.
157054*/
157055static int fts3DoIntegrityCheck(
157056  Fts3Table *p                    /* FTS3 table handle */
157057){
157058  int rc;
157059  int bOk = 0;
157060  rc = fts3IntegrityCheck(p, &bOk);
157061  if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
157062  return rc;
157063}
157064
157065/*
157066** Handle a 'special' INSERT of the form:
157067**
157068**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
157069**
157070** Argument pVal contains the result of <expr>. Currently the only
157071** meaningful value to insert is the text 'optimize'.
157072*/
157073static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
157074  int rc;                         /* Return Code */
157075  const char *zVal = (const char *)sqlite3_value_text(pVal);
157076  int nVal = sqlite3_value_bytes(pVal);
157077
157078  if( !zVal ){
157079    return SQLITE_NOMEM;
157080  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
157081    rc = fts3DoOptimize(p, 0);
157082  }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
157083    rc = fts3DoRebuild(p);
157084  }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
157085    rc = fts3DoIntegrityCheck(p);
157086  }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
157087    rc = fts3DoIncrmerge(p, &zVal[6]);
157088  }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
157089    rc = fts3DoAutoincrmerge(p, &zVal[10]);
157090#ifdef SQLITE_TEST
157091  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
157092    p->nNodeSize = atoi(&zVal[9]);
157093    rc = SQLITE_OK;
157094  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
157095    p->nMaxPendingData = atoi(&zVal[11]);
157096    rc = SQLITE_OK;
157097  }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
157098    p->bNoIncrDoclist = atoi(&zVal[21]);
157099    rc = SQLITE_OK;
157100#endif
157101  }else{
157102    rc = SQLITE_ERROR;
157103  }
157104
157105  return rc;
157106}
157107
157108#ifndef SQLITE_DISABLE_FTS4_DEFERRED
157109/*
157110** Delete all cached deferred doclists. Deferred doclists are cached
157111** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
157112*/
157113SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
157114  Fts3DeferredToken *pDef;
157115  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
157116    fts3PendingListDelete(pDef->pList);
157117    pDef->pList = 0;
157118  }
157119}
157120
157121/*
157122** Free all entries in the pCsr->pDeffered list. Entries are added to
157123** this list using sqlite3Fts3DeferToken().
157124*/
157125SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
157126  Fts3DeferredToken *pDef;
157127  Fts3DeferredToken *pNext;
157128  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
157129    pNext = pDef->pNext;
157130    fts3PendingListDelete(pDef->pList);
157131    sqlite3_free(pDef);
157132  }
157133  pCsr->pDeferred = 0;
157134}
157135
157136/*
157137** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
157138** based on the row that pCsr currently points to.
157139**
157140** A deferred-doclist is like any other doclist with position information
157141** included, except that it only contains entries for a single row of the
157142** table, not for all rows.
157143*/
157144SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
157145  int rc = SQLITE_OK;             /* Return code */
157146  if( pCsr->pDeferred ){
157147    int i;                        /* Used to iterate through table columns */
157148    sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
157149    Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
157150
157151    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
157152    sqlite3_tokenizer *pT = p->pTokenizer;
157153    sqlite3_tokenizer_module const *pModule = pT->pModule;
157154
157155    assert( pCsr->isRequireSeek==0 );
157156    iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
157157
157158    for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
157159      if( p->abNotindexed[i]==0 ){
157160        const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
157161        sqlite3_tokenizer_cursor *pTC = 0;
157162
157163        rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
157164        while( rc==SQLITE_OK ){
157165          char const *zToken;       /* Buffer containing token */
157166          int nToken = 0;           /* Number of bytes in token */
157167          int iDum1 = 0, iDum2 = 0; /* Dummy variables */
157168          int iPos = 0;             /* Position of token in zText */
157169
157170          rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
157171          for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
157172            Fts3PhraseToken *pPT = pDef->pToken;
157173            if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
157174                && (pPT->bFirst==0 || iPos==0)
157175                && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
157176                && (0==memcmp(zToken, pPT->z, pPT->n))
157177              ){
157178              fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
157179            }
157180          }
157181        }
157182        if( pTC ) pModule->xClose(pTC);
157183        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
157184      }
157185    }
157186
157187    for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
157188      if( pDef->pList ){
157189        rc = fts3PendingListAppendVarint(&pDef->pList, 0);
157190      }
157191    }
157192  }
157193
157194  return rc;
157195}
157196
157197SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
157198  Fts3DeferredToken *p,
157199  char **ppData,
157200  int *pnData
157201){
157202  char *pRet;
157203  int nSkip;
157204  sqlite3_int64 dummy;
157205
157206  *ppData = 0;
157207  *pnData = 0;
157208
157209  if( p->pList==0 ){
157210    return SQLITE_OK;
157211  }
157212
157213  pRet = (char *)sqlite3_malloc(p->pList->nData);
157214  if( !pRet ) return SQLITE_NOMEM;
157215
157216  nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
157217  *pnData = p->pList->nData - nSkip;
157218  *ppData = pRet;
157219
157220  memcpy(pRet, &p->pList->aData[nSkip], *pnData);
157221  return SQLITE_OK;
157222}
157223
157224/*
157225** Add an entry for token pToken to the pCsr->pDeferred list.
157226*/
157227SQLITE_PRIVATE int sqlite3Fts3DeferToken(
157228  Fts3Cursor *pCsr,               /* Fts3 table cursor */
157229  Fts3PhraseToken *pToken,        /* Token to defer */
157230  int iCol                        /* Column that token must appear in (or -1) */
157231){
157232  Fts3DeferredToken *pDeferred;
157233  pDeferred = sqlite3_malloc(sizeof(*pDeferred));
157234  if( !pDeferred ){
157235    return SQLITE_NOMEM;
157236  }
157237  memset(pDeferred, 0, sizeof(*pDeferred));
157238  pDeferred->pToken = pToken;
157239  pDeferred->pNext = pCsr->pDeferred;
157240  pDeferred->iCol = iCol;
157241  pCsr->pDeferred = pDeferred;
157242
157243  assert( pToken->pDeferred==0 );
157244  pToken->pDeferred = pDeferred;
157245
157246  return SQLITE_OK;
157247}
157248#endif
157249
157250/*
157251** SQLite value pRowid contains the rowid of a row that may or may not be
157252** present in the FTS3 table. If it is, delete it and adjust the contents
157253** of subsiduary data structures accordingly.
157254*/
157255static int fts3DeleteByRowid(
157256  Fts3Table *p,
157257  sqlite3_value *pRowid,
157258  int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
157259  u32 *aSzDel
157260){
157261  int rc = SQLITE_OK;             /* Return code */
157262  int bFound = 0;                 /* True if *pRowid really is in the table */
157263
157264  fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
157265  if( bFound && rc==SQLITE_OK ){
157266    int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
157267    rc = fts3IsEmpty(p, pRowid, &isEmpty);
157268    if( rc==SQLITE_OK ){
157269      if( isEmpty ){
157270        /* Deleting this row means the whole table is empty. In this case
157271        ** delete the contents of all three tables and throw away any
157272        ** data in the pendingTerms hash table.  */
157273        rc = fts3DeleteAll(p, 1);
157274        *pnChng = 0;
157275        memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
157276      }else{
157277        *pnChng = *pnChng - 1;
157278        if( p->zContentTbl==0 ){
157279          fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
157280        }
157281        if( p->bHasDocsize ){
157282          fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
157283        }
157284      }
157285    }
157286  }
157287
157288  return rc;
157289}
157290
157291/*
157292** This function does the work for the xUpdate method of FTS3 virtual
157293** tables. The schema of the virtual table being:
157294**
157295**     CREATE TABLE <table name>(
157296**       <user columns>,
157297**       <table name> HIDDEN,
157298**       docid HIDDEN,
157299**       <langid> HIDDEN
157300**     );
157301**
157302**
157303*/
157304SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
157305  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
157306  int nArg,                       /* Size of argument array */
157307  sqlite3_value **apVal,          /* Array of arguments */
157308  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
157309){
157310  Fts3Table *p = (Fts3Table *)pVtab;
157311  int rc = SQLITE_OK;             /* Return Code */
157312  int isRemove = 0;               /* True for an UPDATE or DELETE */
157313  u32 *aSzIns = 0;                /* Sizes of inserted documents */
157314  u32 *aSzDel = 0;                /* Sizes of deleted documents */
157315  int nChng = 0;                  /* Net change in number of documents */
157316  int bInsertDone = 0;
157317
157318  /* At this point it must be known if the %_stat table exists or not.
157319  ** So bHasStat may not be 2.  */
157320  assert( p->bHasStat==0 || p->bHasStat==1 );
157321
157322  assert( p->pSegments==0 );
157323  assert(
157324      nArg==1                     /* DELETE operations */
157325   || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
157326  );
157327
157328  /* Check for a "special" INSERT operation. One of the form:
157329  **
157330  **   INSERT INTO xyz(xyz) VALUES('command');
157331  */
157332  if( nArg>1
157333   && sqlite3_value_type(apVal[0])==SQLITE_NULL
157334   && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
157335  ){
157336    rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
157337    goto update_out;
157338  }
157339
157340  if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
157341    rc = SQLITE_CONSTRAINT;
157342    goto update_out;
157343  }
157344
157345  /* Allocate space to hold the change in document sizes */
157346  aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
157347  if( aSzDel==0 ){
157348    rc = SQLITE_NOMEM;
157349    goto update_out;
157350  }
157351  aSzIns = &aSzDel[p->nColumn+1];
157352  memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
157353
157354  rc = fts3Writelock(p);
157355  if( rc!=SQLITE_OK ) goto update_out;
157356
157357  /* If this is an INSERT operation, or an UPDATE that modifies the rowid
157358  ** value, then this operation requires constraint handling.
157359  **
157360  ** If the on-conflict mode is REPLACE, this means that the existing row
157361  ** should be deleted from the database before inserting the new row. Or,
157362  ** if the on-conflict mode is other than REPLACE, then this method must
157363  ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
157364  ** modify the database file.
157365  */
157366  if( nArg>1 && p->zContentTbl==0 ){
157367    /* Find the value object that holds the new rowid value. */
157368    sqlite3_value *pNewRowid = apVal[3+p->nColumn];
157369    if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
157370      pNewRowid = apVal[1];
157371    }
157372
157373    if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
157374        sqlite3_value_type(apVal[0])==SQLITE_NULL
157375     || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
157376    )){
157377      /* The new rowid is not NULL (in this case the rowid will be
157378      ** automatically assigned and there is no chance of a conflict), and
157379      ** the statement is either an INSERT or an UPDATE that modifies the
157380      ** rowid column. So if the conflict mode is REPLACE, then delete any
157381      ** existing row with rowid=pNewRowid.
157382      **
157383      ** Or, if the conflict mode is not REPLACE, insert the new record into
157384      ** the %_content table. If we hit the duplicate rowid constraint (or any
157385      ** other error) while doing so, return immediately.
157386      **
157387      ** This branch may also run if pNewRowid contains a value that cannot
157388      ** be losslessly converted to an integer. In this case, the eventual
157389      ** call to fts3InsertData() (either just below or further on in this
157390      ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
157391      ** invoked, it will delete zero rows (since no row will have
157392      ** docid=$pNewRowid if $pNewRowid is not an integer value).
157393      */
157394      if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
157395        rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
157396      }else{
157397        rc = fts3InsertData(p, apVal, pRowid);
157398        bInsertDone = 1;
157399      }
157400    }
157401  }
157402  if( rc!=SQLITE_OK ){
157403    goto update_out;
157404  }
157405
157406  /* If this is a DELETE or UPDATE operation, remove the old record. */
157407  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
157408    assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
157409    rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
157410    isRemove = 1;
157411  }
157412
157413  /* If this is an INSERT or UPDATE operation, insert the new record. */
157414  if( nArg>1 && rc==SQLITE_OK ){
157415    int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
157416    if( bInsertDone==0 ){
157417      rc = fts3InsertData(p, apVal, pRowid);
157418      if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
157419        rc = FTS_CORRUPT_VTAB;
157420      }
157421    }
157422    if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
157423      rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
157424    }
157425    if( rc==SQLITE_OK ){
157426      assert( p->iPrevDocid==*pRowid );
157427      rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
157428    }
157429    if( p->bHasDocsize ){
157430      fts3InsertDocsize(&rc, p, aSzIns);
157431    }
157432    nChng++;
157433  }
157434
157435  if( p->bFts4 ){
157436    fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
157437  }
157438
157439 update_out:
157440  sqlite3_free(aSzDel);
157441  sqlite3Fts3SegmentsClose(p);
157442  return rc;
157443}
157444
157445/*
157446** Flush any data in the pending-terms hash table to disk. If successful,
157447** merge all segments in the database (including the new segment, if
157448** there was any data to flush) into a single segment.
157449*/
157450SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
157451  int rc;
157452  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
157453  if( rc==SQLITE_OK ){
157454    rc = fts3DoOptimize(p, 1);
157455    if( rc==SQLITE_OK || rc==SQLITE_DONE ){
157456      int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
157457      if( rc2!=SQLITE_OK ) rc = rc2;
157458    }else{
157459      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
157460      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
157461    }
157462  }
157463  sqlite3Fts3SegmentsClose(p);
157464  return rc;
157465}
157466
157467#endif
157468
157469/************** End of fts3_write.c ******************************************/
157470/************** Begin file fts3_snippet.c ************************************/
157471/*
157472** 2009 Oct 23
157473**
157474** The author disclaims copyright to this source code.  In place of
157475** a legal notice, here is a blessing:
157476**
157477**    May you do good and not evil.
157478**    May you find forgiveness for yourself and forgive others.
157479**    May you share freely, never taking more than you give.
157480**
157481******************************************************************************
157482*/
157483
157484/* #include "fts3Int.h" */
157485#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
157486
157487/* #include <string.h> */
157488/* #include <assert.h> */
157489
157490/*
157491** Characters that may appear in the second argument to matchinfo().
157492*/
157493#define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
157494#define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
157495#define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
157496#define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
157497#define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
157498#define FTS3_MATCHINFO_LCS       's'        /* nCol values */
157499#define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
157500#define FTS3_MATCHINFO_LHITS     'y'        /* nCol*nPhrase values */
157501#define FTS3_MATCHINFO_LHITS_BM  'b'        /* nCol*nPhrase values */
157502
157503/*
157504** The default value for the second argument to matchinfo().
157505*/
157506#define FTS3_MATCHINFO_DEFAULT   "pcx"
157507
157508
157509/*
157510** Used as an fts3ExprIterate() context when loading phrase doclists to
157511** Fts3Expr.aDoclist[]/nDoclist.
157512*/
157513typedef struct LoadDoclistCtx LoadDoclistCtx;
157514struct LoadDoclistCtx {
157515  Fts3Cursor *pCsr;               /* FTS3 Cursor */
157516  int nPhrase;                    /* Number of phrases seen so far */
157517  int nToken;                     /* Number of tokens seen so far */
157518};
157519
157520/*
157521** The following types are used as part of the implementation of the
157522** fts3BestSnippet() routine.
157523*/
157524typedef struct SnippetIter SnippetIter;
157525typedef struct SnippetPhrase SnippetPhrase;
157526typedef struct SnippetFragment SnippetFragment;
157527
157528struct SnippetIter {
157529  Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
157530  int iCol;                       /* Extract snippet from this column */
157531  int nSnippet;                   /* Requested snippet length (in tokens) */
157532  int nPhrase;                    /* Number of phrases in query */
157533  SnippetPhrase *aPhrase;         /* Array of size nPhrase */
157534  int iCurrent;                   /* First token of current snippet */
157535};
157536
157537struct SnippetPhrase {
157538  int nToken;                     /* Number of tokens in phrase */
157539  char *pList;                    /* Pointer to start of phrase position list */
157540  int iHead;                      /* Next value in position list */
157541  char *pHead;                    /* Position list data following iHead */
157542  int iTail;                      /* Next value in trailing position list */
157543  char *pTail;                    /* Position list data following iTail */
157544};
157545
157546struct SnippetFragment {
157547  int iCol;                       /* Column snippet is extracted from */
157548  int iPos;                       /* Index of first token in snippet */
157549  u64 covered;                    /* Mask of query phrases covered */
157550  u64 hlmask;                     /* Mask of snippet terms to highlight */
157551};
157552
157553/*
157554** This type is used as an fts3ExprIterate() context object while
157555** accumulating the data returned by the matchinfo() function.
157556*/
157557typedef struct MatchInfo MatchInfo;
157558struct MatchInfo {
157559  Fts3Cursor *pCursor;            /* FTS3 Cursor */
157560  int nCol;                       /* Number of columns in table */
157561  int nPhrase;                    /* Number of matchable phrases in query */
157562  sqlite3_int64 nDoc;             /* Number of docs in database */
157563  char flag;
157564  u32 *aMatchinfo;                /* Pre-allocated buffer */
157565};
157566
157567/*
157568** An instance of this structure is used to manage a pair of buffers, each
157569** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
157570** for details.
157571*/
157572struct MatchinfoBuffer {
157573  u8 aRef[3];
157574  int nElem;
157575  int bGlobal;                    /* Set if global data is loaded */
157576  char *zMatchinfo;
157577  u32 aMatchinfo[1];
157578};
157579
157580
157581/*
157582** The snippet() and offsets() functions both return text values. An instance
157583** of the following structure is used to accumulate those values while the
157584** functions are running. See fts3StringAppend() for details.
157585*/
157586typedef struct StrBuffer StrBuffer;
157587struct StrBuffer {
157588  char *z;                        /* Pointer to buffer containing string */
157589  int n;                          /* Length of z in bytes (excl. nul-term) */
157590  int nAlloc;                     /* Allocated size of buffer z in bytes */
157591};
157592
157593
157594/*************************************************************************
157595** Start of MatchinfoBuffer code.
157596*/
157597
157598/*
157599** Allocate a two-slot MatchinfoBuffer object.
157600*/
157601static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
157602  MatchinfoBuffer *pRet;
157603  int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
157604  int nStr = (int)strlen(zMatchinfo);
157605
157606  pRet = sqlite3_malloc(nByte + nStr+1);
157607  if( pRet ){
157608    memset(pRet, 0, nByte);
157609    pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
157610    pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
157611    pRet->nElem = nElem;
157612    pRet->zMatchinfo = ((char*)pRet) + nByte;
157613    memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
157614    pRet->aRef[0] = 1;
157615  }
157616
157617  return pRet;
157618}
157619
157620static void fts3MIBufferFree(void *p){
157621  MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
157622
157623  assert( (u32*)p==&pBuf->aMatchinfo[1]
157624       || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
157625  );
157626  if( (u32*)p==&pBuf->aMatchinfo[1] ){
157627    pBuf->aRef[1] = 0;
157628  }else{
157629    pBuf->aRef[2] = 0;
157630  }
157631
157632  if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
157633    sqlite3_free(pBuf);
157634  }
157635}
157636
157637static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
157638  void (*xRet)(void*) = 0;
157639  u32 *aOut = 0;
157640
157641  if( p->aRef[1]==0 ){
157642    p->aRef[1] = 1;
157643    aOut = &p->aMatchinfo[1];
157644    xRet = fts3MIBufferFree;
157645  }
157646  else if( p->aRef[2]==0 ){
157647    p->aRef[2] = 1;
157648    aOut = &p->aMatchinfo[p->nElem+2];
157649    xRet = fts3MIBufferFree;
157650  }else{
157651    aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
157652    if( aOut ){
157653      xRet = sqlite3_free;
157654      if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
157655    }
157656  }
157657
157658  *paOut = aOut;
157659  return xRet;
157660}
157661
157662static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
157663  p->bGlobal = 1;
157664  memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
157665}
157666
157667/*
157668** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
157669*/
157670SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
157671  if( p ){
157672    assert( p->aRef[0]==1 );
157673    p->aRef[0] = 0;
157674    if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
157675      sqlite3_free(p);
157676    }
157677  }
157678}
157679
157680/*
157681** End of MatchinfoBuffer code.
157682*************************************************************************/
157683
157684
157685/*
157686** This function is used to help iterate through a position-list. A position
157687** list is a list of unique integers, sorted from smallest to largest. Each
157688** element of the list is represented by an FTS3 varint that takes the value
157689** of the difference between the current element and the previous one plus
157690** two. For example, to store the position-list:
157691**
157692**     4 9 113
157693**
157694** the three varints:
157695**
157696**     6 7 106
157697**
157698** are encoded.
157699**
157700** When this function is called, *pp points to the start of an element of
157701** the list. *piPos contains the value of the previous entry in the list.
157702** After it returns, *piPos contains the value of the next element of the
157703** list and *pp is advanced to the following varint.
157704*/
157705static void fts3GetDeltaPosition(char **pp, int *piPos){
157706  int iVal;
157707  *pp += fts3GetVarint32(*pp, &iVal);
157708  *piPos += (iVal-2);
157709}
157710
157711/*
157712** Helper function for fts3ExprIterate() (see below).
157713*/
157714static int fts3ExprIterate2(
157715  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
157716  int *piPhrase,                  /* Pointer to phrase counter */
157717  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
157718  void *pCtx                      /* Second argument to pass to callback */
157719){
157720  int rc;                         /* Return code */
157721  int eType = pExpr->eType;     /* Type of expression node pExpr */
157722
157723  if( eType!=FTSQUERY_PHRASE ){
157724    assert( pExpr->pLeft && pExpr->pRight );
157725    rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
157726    if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
157727      rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
157728    }
157729  }else{
157730    rc = x(pExpr, *piPhrase, pCtx);
157731    (*piPhrase)++;
157732  }
157733  return rc;
157734}
157735
157736/*
157737** Iterate through all phrase nodes in an FTS3 query, except those that
157738** are part of a sub-tree that is the right-hand-side of a NOT operator.
157739** For each phrase node found, the supplied callback function is invoked.
157740**
157741** If the callback function returns anything other than SQLITE_OK,
157742** the iteration is abandoned and the error code returned immediately.
157743** Otherwise, SQLITE_OK is returned after a callback has been made for
157744** all eligible phrase nodes.
157745*/
157746static int fts3ExprIterate(
157747  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
157748  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
157749  void *pCtx                      /* Second argument to pass to callback */
157750){
157751  int iPhrase = 0;                /* Variable used as the phrase counter */
157752  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
157753}
157754
157755
157756/*
157757** This is an fts3ExprIterate() callback used while loading the doclists
157758** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
157759** fts3ExprLoadDoclists().
157760*/
157761static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
157762  int rc = SQLITE_OK;
157763  Fts3Phrase *pPhrase = pExpr->pPhrase;
157764  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
157765
157766  UNUSED_PARAMETER(iPhrase);
157767
157768  p->nPhrase++;
157769  p->nToken += pPhrase->nToken;
157770
157771  return rc;
157772}
157773
157774/*
157775** Load the doclists for each phrase in the query associated with FTS3 cursor
157776** pCsr.
157777**
157778** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
157779** phrases in the expression (all phrases except those directly or
157780** indirectly descended from the right-hand-side of a NOT operator). If
157781** pnToken is not NULL, then it is set to the number of tokens in all
157782** matchable phrases of the expression.
157783*/
157784static int fts3ExprLoadDoclists(
157785  Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
157786  int *pnPhrase,                  /* OUT: Number of phrases in query */
157787  int *pnToken                    /* OUT: Number of tokens in query */
157788){
157789  int rc;                         /* Return Code */
157790  LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
157791  sCtx.pCsr = pCsr;
157792  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
157793  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
157794  if( pnToken ) *pnToken = sCtx.nToken;
157795  return rc;
157796}
157797
157798static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
157799  (*(int *)ctx)++;
157800  pExpr->iPhrase = iPhrase;
157801  return SQLITE_OK;
157802}
157803static int fts3ExprPhraseCount(Fts3Expr *pExpr){
157804  int nPhrase = 0;
157805  (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
157806  return nPhrase;
157807}
157808
157809/*
157810** Advance the position list iterator specified by the first two
157811** arguments so that it points to the first element with a value greater
157812** than or equal to parameter iNext.
157813*/
157814static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
157815  char *pIter = *ppIter;
157816  if( pIter ){
157817    int iIter = *piIter;
157818
157819    while( iIter<iNext ){
157820      if( 0==(*pIter & 0xFE) ){
157821        iIter = -1;
157822        pIter = 0;
157823        break;
157824      }
157825      fts3GetDeltaPosition(&pIter, &iIter);
157826    }
157827
157828    *piIter = iIter;
157829    *ppIter = pIter;
157830  }
157831}
157832
157833/*
157834** Advance the snippet iterator to the next candidate snippet.
157835*/
157836static int fts3SnippetNextCandidate(SnippetIter *pIter){
157837  int i;                          /* Loop counter */
157838
157839  if( pIter->iCurrent<0 ){
157840    /* The SnippetIter object has just been initialized. The first snippet
157841    ** candidate always starts at offset 0 (even if this candidate has a
157842    ** score of 0.0).
157843    */
157844    pIter->iCurrent = 0;
157845
157846    /* Advance the 'head' iterator of each phrase to the first offset that
157847    ** is greater than or equal to (iNext+nSnippet).
157848    */
157849    for(i=0; i<pIter->nPhrase; i++){
157850      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
157851      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
157852    }
157853  }else{
157854    int iStart;
157855    int iEnd = 0x7FFFFFFF;
157856
157857    for(i=0; i<pIter->nPhrase; i++){
157858      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
157859      if( pPhrase->pHead && pPhrase->iHead<iEnd ){
157860        iEnd = pPhrase->iHead;
157861      }
157862    }
157863    if( iEnd==0x7FFFFFFF ){
157864      return 1;
157865    }
157866
157867    pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
157868    for(i=0; i<pIter->nPhrase; i++){
157869      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
157870      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
157871      fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
157872    }
157873  }
157874
157875  return 0;
157876}
157877
157878/*
157879** Retrieve information about the current candidate snippet of snippet
157880** iterator pIter.
157881*/
157882static void fts3SnippetDetails(
157883  SnippetIter *pIter,             /* Snippet iterator */
157884  u64 mCovered,                   /* Bitmask of phrases already covered */
157885  int *piToken,                   /* OUT: First token of proposed snippet */
157886  int *piScore,                   /* OUT: "Score" for this snippet */
157887  u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
157888  u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
157889){
157890  int iStart = pIter->iCurrent;   /* First token of snippet */
157891  int iScore = 0;                 /* Score of this snippet */
157892  int i;                          /* Loop counter */
157893  u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
157894  u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
157895
157896  for(i=0; i<pIter->nPhrase; i++){
157897    SnippetPhrase *pPhrase = &pIter->aPhrase[i];
157898    if( pPhrase->pTail ){
157899      char *pCsr = pPhrase->pTail;
157900      int iCsr = pPhrase->iTail;
157901
157902      while( iCsr<(iStart+pIter->nSnippet) ){
157903        int j;
157904        u64 mPhrase = (u64)1 << i;
157905        u64 mPos = (u64)1 << (iCsr - iStart);
157906        assert( iCsr>=iStart );
157907        if( (mCover|mCovered)&mPhrase ){
157908          iScore++;
157909        }else{
157910          iScore += 1000;
157911        }
157912        mCover |= mPhrase;
157913
157914        for(j=0; j<pPhrase->nToken; j++){
157915          mHighlight |= (mPos>>j);
157916        }
157917
157918        if( 0==(*pCsr & 0x0FE) ) break;
157919        fts3GetDeltaPosition(&pCsr, &iCsr);
157920      }
157921    }
157922  }
157923
157924  /* Set the output variables before returning. */
157925  *piToken = iStart;
157926  *piScore = iScore;
157927  *pmCover = mCover;
157928  *pmHighlight = mHighlight;
157929}
157930
157931/*
157932** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
157933** Each invocation populates an element of the SnippetIter.aPhrase[] array.
157934*/
157935static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
157936  SnippetIter *p = (SnippetIter *)ctx;
157937  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
157938  char *pCsr;
157939  int rc;
157940
157941  pPhrase->nToken = pExpr->pPhrase->nToken;
157942  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
157943  assert( rc==SQLITE_OK || pCsr==0 );
157944  if( pCsr ){
157945    int iFirst = 0;
157946    pPhrase->pList = pCsr;
157947    fts3GetDeltaPosition(&pCsr, &iFirst);
157948    assert( iFirst>=0 );
157949    pPhrase->pHead = pCsr;
157950    pPhrase->pTail = pCsr;
157951    pPhrase->iHead = iFirst;
157952    pPhrase->iTail = iFirst;
157953  }else{
157954    assert( rc!=SQLITE_OK || (
157955       pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
157956    ));
157957  }
157958
157959  return rc;
157960}
157961
157962/*
157963** Select the fragment of text consisting of nFragment contiguous tokens
157964** from column iCol that represent the "best" snippet. The best snippet
157965** is the snippet with the highest score, where scores are calculated
157966** by adding:
157967**
157968**   (a) +1 point for each occurrence of a matchable phrase in the snippet.
157969**
157970**   (b) +1000 points for the first occurrence of each matchable phrase in
157971**       the snippet for which the corresponding mCovered bit is not set.
157972**
157973** The selected snippet parameters are stored in structure *pFragment before
157974** returning. The score of the selected snippet is stored in *piScore
157975** before returning.
157976*/
157977static int fts3BestSnippet(
157978  int nSnippet,                   /* Desired snippet length */
157979  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
157980  int iCol,                       /* Index of column to create snippet from */
157981  u64 mCovered,                   /* Mask of phrases already covered */
157982  u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
157983  SnippetFragment *pFragment,     /* OUT: Best snippet found */
157984  int *piScore                    /* OUT: Score of snippet pFragment */
157985){
157986  int rc;                         /* Return Code */
157987  int nList;                      /* Number of phrases in expression */
157988  SnippetIter sIter;              /* Iterates through snippet candidates */
157989  int nByte;                      /* Number of bytes of space to allocate */
157990  int iBestScore = -1;            /* Best snippet score found so far */
157991  int i;                          /* Loop counter */
157992
157993  memset(&sIter, 0, sizeof(sIter));
157994
157995  /* Iterate through the phrases in the expression to count them. The same
157996  ** callback makes sure the doclists are loaded for each phrase.
157997  */
157998  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
157999  if( rc!=SQLITE_OK ){
158000    return rc;
158001  }
158002
158003  /* Now that it is known how many phrases there are, allocate and zero
158004  ** the required space using malloc().
158005  */
158006  nByte = sizeof(SnippetPhrase) * nList;
158007  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
158008  if( !sIter.aPhrase ){
158009    return SQLITE_NOMEM;
158010  }
158011  memset(sIter.aPhrase, 0, nByte);
158012
158013  /* Initialize the contents of the SnippetIter object. Then iterate through
158014  ** the set of phrases in the expression to populate the aPhrase[] array.
158015  */
158016  sIter.pCsr = pCsr;
158017  sIter.iCol = iCol;
158018  sIter.nSnippet = nSnippet;
158019  sIter.nPhrase = nList;
158020  sIter.iCurrent = -1;
158021  rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
158022  if( rc==SQLITE_OK ){
158023
158024    /* Set the *pmSeen output variable. */
158025    for(i=0; i<nList; i++){
158026      if( sIter.aPhrase[i].pHead ){
158027        *pmSeen |= (u64)1 << i;
158028      }
158029    }
158030
158031    /* Loop through all candidate snippets. Store the best snippet in
158032     ** *pFragment. Store its associated 'score' in iBestScore.
158033     */
158034    pFragment->iCol = iCol;
158035    while( !fts3SnippetNextCandidate(&sIter) ){
158036      int iPos;
158037      int iScore;
158038      u64 mCover;
158039      u64 mHighlite;
158040      fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
158041      assert( iScore>=0 );
158042      if( iScore>iBestScore ){
158043        pFragment->iPos = iPos;
158044        pFragment->hlmask = mHighlite;
158045        pFragment->covered = mCover;
158046        iBestScore = iScore;
158047      }
158048    }
158049
158050    *piScore = iBestScore;
158051  }
158052  sqlite3_free(sIter.aPhrase);
158053  return rc;
158054}
158055
158056
158057/*
158058** Append a string to the string-buffer passed as the first argument.
158059**
158060** If nAppend is negative, then the length of the string zAppend is
158061** determined using strlen().
158062*/
158063static int fts3StringAppend(
158064  StrBuffer *pStr,                /* Buffer to append to */
158065  const char *zAppend,            /* Pointer to data to append to buffer */
158066  int nAppend                     /* Size of zAppend in bytes (or -1) */
158067){
158068  if( nAppend<0 ){
158069    nAppend = (int)strlen(zAppend);
158070  }
158071
158072  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
158073  ** to grow the buffer until so that it is big enough to accomadate the
158074  ** appended data.
158075  */
158076  if( pStr->n+nAppend+1>=pStr->nAlloc ){
158077    int nAlloc = pStr->nAlloc+nAppend+100;
158078    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
158079    if( !zNew ){
158080      return SQLITE_NOMEM;
158081    }
158082    pStr->z = zNew;
158083    pStr->nAlloc = nAlloc;
158084  }
158085  assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
158086
158087  /* Append the data to the string buffer. */
158088  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
158089  pStr->n += nAppend;
158090  pStr->z[pStr->n] = '\0';
158091
158092  return SQLITE_OK;
158093}
158094
158095/*
158096** The fts3BestSnippet() function often selects snippets that end with a
158097** query term. That is, the final term of the snippet is always a term
158098** that requires highlighting. For example, if 'X' is a highlighted term
158099** and '.' is a non-highlighted term, BestSnippet() may select:
158100**
158101**     ........X.....X
158102**
158103** This function "shifts" the beginning of the snippet forward in the
158104** document so that there are approximately the same number of
158105** non-highlighted terms to the right of the final highlighted term as there
158106** are to the left of the first highlighted term. For example, to this:
158107**
158108**     ....X.....X....
158109**
158110** This is done as part of extracting the snippet text, not when selecting
158111** the snippet. Snippet selection is done based on doclists only, so there
158112** is no way for fts3BestSnippet() to know whether or not the document
158113** actually contains terms that follow the final highlighted term.
158114*/
158115static int fts3SnippetShift(
158116  Fts3Table *pTab,                /* FTS3 table snippet comes from */
158117  int iLangid,                    /* Language id to use in tokenizing */
158118  int nSnippet,                   /* Number of tokens desired for snippet */
158119  const char *zDoc,               /* Document text to extract snippet from */
158120  int nDoc,                       /* Size of buffer zDoc in bytes */
158121  int *piPos,                     /* IN/OUT: First token of snippet */
158122  u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
158123){
158124  u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
158125
158126  if( hlmask ){
158127    int nLeft;                    /* Tokens to the left of first highlight */
158128    int nRight;                   /* Tokens to the right of last highlight */
158129    int nDesired;                 /* Ideal number of tokens to shift forward */
158130
158131    for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
158132    for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
158133    nDesired = (nLeft-nRight)/2;
158134
158135    /* Ideally, the start of the snippet should be pushed forward in the
158136    ** document nDesired tokens. This block checks if there are actually
158137    ** nDesired tokens to the right of the snippet. If so, *piPos and
158138    ** *pHlMask are updated to shift the snippet nDesired tokens to the
158139    ** right. Otherwise, the snippet is shifted by the number of tokens
158140    ** available.
158141    */
158142    if( nDesired>0 ){
158143      int nShift;                 /* Number of tokens to shift snippet by */
158144      int iCurrent = 0;           /* Token counter */
158145      int rc;                     /* Return Code */
158146      sqlite3_tokenizer_module *pMod;
158147      sqlite3_tokenizer_cursor *pC;
158148      pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
158149
158150      /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
158151      ** or more tokens in zDoc/nDoc.
158152      */
158153      rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
158154      if( rc!=SQLITE_OK ){
158155        return rc;
158156      }
158157      while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
158158        const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
158159        rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
158160      }
158161      pMod->xClose(pC);
158162      if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
158163
158164      nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
158165      assert( nShift<=nDesired );
158166      if( nShift>0 ){
158167        *piPos += nShift;
158168        *pHlmask = hlmask >> nShift;
158169      }
158170    }
158171  }
158172  return SQLITE_OK;
158173}
158174
158175/*
158176** Extract the snippet text for fragment pFragment from cursor pCsr and
158177** append it to string buffer pOut.
158178*/
158179static int fts3SnippetText(
158180  Fts3Cursor *pCsr,               /* FTS3 Cursor */
158181  SnippetFragment *pFragment,     /* Snippet to extract */
158182  int iFragment,                  /* Fragment number */
158183  int isLast,                     /* True for final fragment in snippet */
158184  int nSnippet,                   /* Number of tokens in extracted snippet */
158185  const char *zOpen,              /* String inserted before highlighted term */
158186  const char *zClose,             /* String inserted after highlighted term */
158187  const char *zEllipsis,          /* String inserted between snippets */
158188  StrBuffer *pOut                 /* Write output here */
158189){
158190  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
158191  int rc;                         /* Return code */
158192  const char *zDoc;               /* Document text to extract snippet from */
158193  int nDoc;                       /* Size of zDoc in bytes */
158194  int iCurrent = 0;               /* Current token number of document */
158195  int iEnd = 0;                   /* Byte offset of end of current token */
158196  int isShiftDone = 0;            /* True after snippet is shifted */
158197  int iPos = pFragment->iPos;     /* First token of snippet */
158198  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
158199  int iCol = pFragment->iCol+1;   /* Query column to extract text from */
158200  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
158201  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
158202
158203  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
158204  if( zDoc==0 ){
158205    if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
158206      return SQLITE_NOMEM;
158207    }
158208    return SQLITE_OK;
158209  }
158210  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
158211
158212  /* Open a token cursor on the document. */
158213  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
158214  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
158215  if( rc!=SQLITE_OK ){
158216    return rc;
158217  }
158218
158219  while( rc==SQLITE_OK ){
158220    const char *ZDUMMY;           /* Dummy argument used with tokenizer */
158221    int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
158222    int iBegin = 0;               /* Offset in zDoc of start of token */
158223    int iFin = 0;                 /* Offset in zDoc of end of token */
158224    int isHighlight = 0;          /* True for highlighted terms */
158225
158226    /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
158227    ** in the FTS code the variable that the third argument to xNext points to
158228    ** is initialized to zero before the first (*but not necessarily
158229    ** subsequent*) call to xNext(). This is done for a particular application
158230    ** that needs to know whether or not the tokenizer is being used for
158231    ** snippet generation or for some other purpose.
158232    **
158233    ** Extreme care is required when writing code to depend on this
158234    ** initialization. It is not a documented part of the tokenizer interface.
158235    ** If a tokenizer is used directly by any code outside of FTS, this
158236    ** convention might not be respected.  */
158237    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
158238    if( rc!=SQLITE_OK ){
158239      if( rc==SQLITE_DONE ){
158240        /* Special case - the last token of the snippet is also the last token
158241        ** of the column. Append any punctuation that occurred between the end
158242        ** of the previous token and the end of the document to the output.
158243        ** Then break out of the loop. */
158244        rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
158245      }
158246      break;
158247    }
158248    if( iCurrent<iPos ){ continue; }
158249
158250    if( !isShiftDone ){
158251      int n = nDoc - iBegin;
158252      rc = fts3SnippetShift(
158253          pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
158254      );
158255      isShiftDone = 1;
158256
158257      /* Now that the shift has been done, check if the initial "..." are
158258      ** required. They are required if (a) this is not the first fragment,
158259      ** or (b) this fragment does not begin at position 0 of its column.
158260      */
158261      if( rc==SQLITE_OK ){
158262        if( iPos>0 || iFragment>0 ){
158263          rc = fts3StringAppend(pOut, zEllipsis, -1);
158264        }else if( iBegin ){
158265          rc = fts3StringAppend(pOut, zDoc, iBegin);
158266        }
158267      }
158268      if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
158269    }
158270
158271    if( iCurrent>=(iPos+nSnippet) ){
158272      if( isLast ){
158273        rc = fts3StringAppend(pOut, zEllipsis, -1);
158274      }
158275      break;
158276    }
158277
158278    /* Set isHighlight to true if this term should be highlighted. */
158279    isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
158280
158281    if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
158282    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
158283    if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
158284    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
158285
158286    iEnd = iFin;
158287  }
158288
158289  pMod->xClose(pC);
158290  return rc;
158291}
158292
158293
158294/*
158295** This function is used to count the entries in a column-list (a
158296** delta-encoded list of term offsets within a single column of a single
158297** row). When this function is called, *ppCollist should point to the
158298** beginning of the first varint in the column-list (the varint that
158299** contains the position of the first matching term in the column data).
158300** Before returning, *ppCollist is set to point to the first byte after
158301** the last varint in the column-list (either the 0x00 signifying the end
158302** of the position-list, or the 0x01 that precedes the column number of
158303** the next column in the position-list).
158304**
158305** The number of elements in the column-list is returned.
158306*/
158307static int fts3ColumnlistCount(char **ppCollist){
158308  char *pEnd = *ppCollist;
158309  char c = 0;
158310  int nEntry = 0;
158311
158312  /* A column-list is terminated by either a 0x01 or 0x00. */
158313  while( 0xFE & (*pEnd | c) ){
158314    c = *pEnd++ & 0x80;
158315    if( !c ) nEntry++;
158316  }
158317
158318  *ppCollist = pEnd;
158319  return nEntry;
158320}
158321
158322/*
158323** This function gathers 'y' or 'b' data for a single phrase.
158324*/
158325static void fts3ExprLHits(
158326  Fts3Expr *pExpr,                /* Phrase expression node */
158327  MatchInfo *p                    /* Matchinfo context */
158328){
158329  Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
158330  int iStart;
158331  Fts3Phrase *pPhrase = pExpr->pPhrase;
158332  char *pIter = pPhrase->doclist.pList;
158333  int iCol = 0;
158334
158335  assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
158336  if( p->flag==FTS3_MATCHINFO_LHITS ){
158337    iStart = pExpr->iPhrase * p->nCol;
158338  }else{
158339    iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
158340  }
158341
158342  while( 1 ){
158343    int nHit = fts3ColumnlistCount(&pIter);
158344    if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
158345      if( p->flag==FTS3_MATCHINFO_LHITS ){
158346        p->aMatchinfo[iStart + iCol] = (u32)nHit;
158347      }else if( nHit ){
158348        p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
158349      }
158350    }
158351    assert( *pIter==0x00 || *pIter==0x01 );
158352    if( *pIter!=0x01 ) break;
158353    pIter++;
158354    pIter += fts3GetVarint32(pIter, &iCol);
158355  }
158356}
158357
158358/*
158359** Gather the results for matchinfo directives 'y' and 'b'.
158360*/
158361static void fts3ExprLHitGather(
158362  Fts3Expr *pExpr,
158363  MatchInfo *p
158364){
158365  assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
158366  if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
158367    if( pExpr->pLeft ){
158368      fts3ExprLHitGather(pExpr->pLeft, p);
158369      fts3ExprLHitGather(pExpr->pRight, p);
158370    }else{
158371      fts3ExprLHits(pExpr, p);
158372    }
158373  }
158374}
158375
158376/*
158377** fts3ExprIterate() callback used to collect the "global" matchinfo stats
158378** for a single query.
158379**
158380** fts3ExprIterate() callback to load the 'global' elements of a
158381** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
158382** of the matchinfo array that are constant for all rows returned by the
158383** current query.
158384**
158385** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
158386** function populates Matchinfo.aMatchinfo[] as follows:
158387**
158388**   for(iCol=0; iCol<nCol; iCol++){
158389**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
158390**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
158391**   }
158392**
158393** where X is the number of matches for phrase iPhrase is column iCol of all
158394** rows of the table. Y is the number of rows for which column iCol contains
158395** at least one instance of phrase iPhrase.
158396**
158397** If the phrase pExpr consists entirely of deferred tokens, then all X and
158398** Y values are set to nDoc, where nDoc is the number of documents in the
158399** file system. This is done because the full-text index doclist is required
158400** to calculate these values properly, and the full-text index doclist is
158401** not available for deferred tokens.
158402*/
158403static int fts3ExprGlobalHitsCb(
158404  Fts3Expr *pExpr,                /* Phrase expression node */
158405  int iPhrase,                    /* Phrase number (numbered from zero) */
158406  void *pCtx                      /* Pointer to MatchInfo structure */
158407){
158408  MatchInfo *p = (MatchInfo *)pCtx;
158409  return sqlite3Fts3EvalPhraseStats(
158410      p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
158411  );
158412}
158413
158414/*
158415** fts3ExprIterate() callback used to collect the "local" part of the
158416** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
158417** array that are different for each row returned by the query.
158418*/
158419static int fts3ExprLocalHitsCb(
158420  Fts3Expr *pExpr,                /* Phrase expression node */
158421  int iPhrase,                    /* Phrase number */
158422  void *pCtx                      /* Pointer to MatchInfo structure */
158423){
158424  int rc = SQLITE_OK;
158425  MatchInfo *p = (MatchInfo *)pCtx;
158426  int iStart = iPhrase * p->nCol * 3;
158427  int i;
158428
158429  for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
158430    char *pCsr;
158431    rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
158432    if( pCsr ){
158433      p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
158434    }else{
158435      p->aMatchinfo[iStart+i*3] = 0;
158436    }
158437  }
158438
158439  return rc;
158440}
158441
158442static int fts3MatchinfoCheck(
158443  Fts3Table *pTab,
158444  char cArg,
158445  char **pzErr
158446){
158447  if( (cArg==FTS3_MATCHINFO_NPHRASE)
158448   || (cArg==FTS3_MATCHINFO_NCOL)
158449   || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
158450   || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
158451   || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
158452   || (cArg==FTS3_MATCHINFO_LCS)
158453   || (cArg==FTS3_MATCHINFO_HITS)
158454   || (cArg==FTS3_MATCHINFO_LHITS)
158455   || (cArg==FTS3_MATCHINFO_LHITS_BM)
158456  ){
158457    return SQLITE_OK;
158458  }
158459  sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
158460  return SQLITE_ERROR;
158461}
158462
158463static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
158464  int nVal;                       /* Number of integers output by cArg */
158465
158466  switch( cArg ){
158467    case FTS3_MATCHINFO_NDOC:
158468    case FTS3_MATCHINFO_NPHRASE:
158469    case FTS3_MATCHINFO_NCOL:
158470      nVal = 1;
158471      break;
158472
158473    case FTS3_MATCHINFO_AVGLENGTH:
158474    case FTS3_MATCHINFO_LENGTH:
158475    case FTS3_MATCHINFO_LCS:
158476      nVal = pInfo->nCol;
158477      break;
158478
158479    case FTS3_MATCHINFO_LHITS:
158480      nVal = pInfo->nCol * pInfo->nPhrase;
158481      break;
158482
158483    case FTS3_MATCHINFO_LHITS_BM:
158484      nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
158485      break;
158486
158487    default:
158488      assert( cArg==FTS3_MATCHINFO_HITS );
158489      nVal = pInfo->nCol * pInfo->nPhrase * 3;
158490      break;
158491  }
158492
158493  return nVal;
158494}
158495
158496static int fts3MatchinfoSelectDoctotal(
158497  Fts3Table *pTab,
158498  sqlite3_stmt **ppStmt,
158499  sqlite3_int64 *pnDoc,
158500  const char **paLen
158501){
158502  sqlite3_stmt *pStmt;
158503  const char *a;
158504  sqlite3_int64 nDoc;
158505
158506  if( !*ppStmt ){
158507    int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
158508    if( rc!=SQLITE_OK ) return rc;
158509  }
158510  pStmt = *ppStmt;
158511  assert( sqlite3_data_count(pStmt)==1 );
158512
158513  a = sqlite3_column_blob(pStmt, 0);
158514  a += sqlite3Fts3GetVarint(a, &nDoc);
158515  if( nDoc==0 ) return FTS_CORRUPT_VTAB;
158516  *pnDoc = (u32)nDoc;
158517
158518  if( paLen ) *paLen = a;
158519  return SQLITE_OK;
158520}
158521
158522/*
158523** An instance of the following structure is used to store state while
158524** iterating through a multi-column position-list corresponding to the
158525** hits for a single phrase on a single row in order to calculate the
158526** values for a matchinfo() FTS3_MATCHINFO_LCS request.
158527*/
158528typedef struct LcsIterator LcsIterator;
158529struct LcsIterator {
158530  Fts3Expr *pExpr;                /* Pointer to phrase expression */
158531  int iPosOffset;                 /* Tokens count up to end of this phrase */
158532  char *pRead;                    /* Cursor used to iterate through aDoclist */
158533  int iPos;                       /* Current position */
158534};
158535
158536/*
158537** If LcsIterator.iCol is set to the following value, the iterator has
158538** finished iterating through all offsets for all columns.
158539*/
158540#define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
158541
158542static int fts3MatchinfoLcsCb(
158543  Fts3Expr *pExpr,                /* Phrase expression node */
158544  int iPhrase,                    /* Phrase number (numbered from zero) */
158545  void *pCtx                      /* Pointer to MatchInfo structure */
158546){
158547  LcsIterator *aIter = (LcsIterator *)pCtx;
158548  aIter[iPhrase].pExpr = pExpr;
158549  return SQLITE_OK;
158550}
158551
158552/*
158553** Advance the iterator passed as an argument to the next position. Return
158554** 1 if the iterator is at EOF or if it now points to the start of the
158555** position list for the next column.
158556*/
158557static int fts3LcsIteratorAdvance(LcsIterator *pIter){
158558  char *pRead = pIter->pRead;
158559  sqlite3_int64 iRead;
158560  int rc = 0;
158561
158562  pRead += sqlite3Fts3GetVarint(pRead, &iRead);
158563  if( iRead==0 || iRead==1 ){
158564    pRead = 0;
158565    rc = 1;
158566  }else{
158567    pIter->iPos += (int)(iRead-2);
158568  }
158569
158570  pIter->pRead = pRead;
158571  return rc;
158572}
158573
158574/*
158575** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
158576**
158577** If the call is successful, the longest-common-substring lengths for each
158578** column are written into the first nCol elements of the pInfo->aMatchinfo[]
158579** array before returning. SQLITE_OK is returned in this case.
158580**
158581** Otherwise, if an error occurs, an SQLite error code is returned and the
158582** data written to the first nCol elements of pInfo->aMatchinfo[] is
158583** undefined.
158584*/
158585static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
158586  LcsIterator *aIter;
158587  int i;
158588  int iCol;
158589  int nToken = 0;
158590
158591  /* Allocate and populate the array of LcsIterator objects. The array
158592  ** contains one element for each matchable phrase in the query.
158593  **/
158594  aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
158595  if( !aIter ) return SQLITE_NOMEM;
158596  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
158597  (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
158598
158599  for(i=0; i<pInfo->nPhrase; i++){
158600    LcsIterator *pIter = &aIter[i];
158601    nToken -= pIter->pExpr->pPhrase->nToken;
158602    pIter->iPosOffset = nToken;
158603  }
158604
158605  for(iCol=0; iCol<pInfo->nCol; iCol++){
158606    int nLcs = 0;                 /* LCS value for this column */
158607    int nLive = 0;                /* Number of iterators in aIter not at EOF */
158608
158609    for(i=0; i<pInfo->nPhrase; i++){
158610      int rc;
158611      LcsIterator *pIt = &aIter[i];
158612      rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
158613      if( rc!=SQLITE_OK ) return rc;
158614      if( pIt->pRead ){
158615        pIt->iPos = pIt->iPosOffset;
158616        fts3LcsIteratorAdvance(&aIter[i]);
158617        nLive++;
158618      }
158619    }
158620
158621    while( nLive>0 ){
158622      LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
158623      int nThisLcs = 0;           /* LCS for the current iterator positions */
158624
158625      for(i=0; i<pInfo->nPhrase; i++){
158626        LcsIterator *pIter = &aIter[i];
158627        if( pIter->pRead==0 ){
158628          /* This iterator is already at EOF for this column. */
158629          nThisLcs = 0;
158630        }else{
158631          if( pAdv==0 || pIter->iPos<pAdv->iPos ){
158632            pAdv = pIter;
158633          }
158634          if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
158635            nThisLcs++;
158636          }else{
158637            nThisLcs = 1;
158638          }
158639          if( nThisLcs>nLcs ) nLcs = nThisLcs;
158640        }
158641      }
158642      if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
158643    }
158644
158645    pInfo->aMatchinfo[iCol] = nLcs;
158646  }
158647
158648  sqlite3_free(aIter);
158649  return SQLITE_OK;
158650}
158651
158652/*
158653** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
158654** be returned by the matchinfo() function. Argument zArg contains the
158655** format string passed as the second argument to matchinfo (or the
158656** default value "pcx" if no second argument was specified). The format
158657** string has already been validated and the pInfo->aMatchinfo[] array
158658** is guaranteed to be large enough for the output.
158659**
158660** If bGlobal is true, then populate all fields of the matchinfo() output.
158661** If it is false, then assume that those fields that do not change between
158662** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
158663** have already been populated.
158664**
158665** Return SQLITE_OK if successful, or an SQLite error code if an error
158666** occurs. If a value other than SQLITE_OK is returned, the state the
158667** pInfo->aMatchinfo[] buffer is left in is undefined.
158668*/
158669static int fts3MatchinfoValues(
158670  Fts3Cursor *pCsr,               /* FTS3 cursor object */
158671  int bGlobal,                    /* True to grab the global stats */
158672  MatchInfo *pInfo,               /* Matchinfo context object */
158673  const char *zArg                /* Matchinfo format string */
158674){
158675  int rc = SQLITE_OK;
158676  int i;
158677  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
158678  sqlite3_stmt *pSelect = 0;
158679
158680  for(i=0; rc==SQLITE_OK && zArg[i]; i++){
158681    pInfo->flag = zArg[i];
158682    switch( zArg[i] ){
158683      case FTS3_MATCHINFO_NPHRASE:
158684        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
158685        break;
158686
158687      case FTS3_MATCHINFO_NCOL:
158688        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
158689        break;
158690
158691      case FTS3_MATCHINFO_NDOC:
158692        if( bGlobal ){
158693          sqlite3_int64 nDoc = 0;
158694          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
158695          pInfo->aMatchinfo[0] = (u32)nDoc;
158696        }
158697        break;
158698
158699      case FTS3_MATCHINFO_AVGLENGTH:
158700        if( bGlobal ){
158701          sqlite3_int64 nDoc;     /* Number of rows in table */
158702          const char *a;          /* Aggregate column length array */
158703
158704          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
158705          if( rc==SQLITE_OK ){
158706            int iCol;
158707            for(iCol=0; iCol<pInfo->nCol; iCol++){
158708              u32 iVal;
158709              sqlite3_int64 nToken;
158710              a += sqlite3Fts3GetVarint(a, &nToken);
158711              iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
158712              pInfo->aMatchinfo[iCol] = iVal;
158713            }
158714          }
158715        }
158716        break;
158717
158718      case FTS3_MATCHINFO_LENGTH: {
158719        sqlite3_stmt *pSelectDocsize = 0;
158720        rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
158721        if( rc==SQLITE_OK ){
158722          int iCol;
158723          const char *a = sqlite3_column_blob(pSelectDocsize, 0);
158724          for(iCol=0; iCol<pInfo->nCol; iCol++){
158725            sqlite3_int64 nToken;
158726            a += sqlite3Fts3GetVarint(a, &nToken);
158727            pInfo->aMatchinfo[iCol] = (u32)nToken;
158728          }
158729        }
158730        sqlite3_reset(pSelectDocsize);
158731        break;
158732      }
158733
158734      case FTS3_MATCHINFO_LCS:
158735        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
158736        if( rc==SQLITE_OK ){
158737          rc = fts3MatchinfoLcs(pCsr, pInfo);
158738        }
158739        break;
158740
158741      case FTS3_MATCHINFO_LHITS_BM:
158742      case FTS3_MATCHINFO_LHITS: {
158743        int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
158744        memset(pInfo->aMatchinfo, 0, nZero);
158745        fts3ExprLHitGather(pCsr->pExpr, pInfo);
158746        break;
158747      }
158748
158749      default: {
158750        Fts3Expr *pExpr;
158751        assert( zArg[i]==FTS3_MATCHINFO_HITS );
158752        pExpr = pCsr->pExpr;
158753        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
158754        if( rc!=SQLITE_OK ) break;
158755        if( bGlobal ){
158756          if( pCsr->pDeferred ){
158757            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
158758            if( rc!=SQLITE_OK ) break;
158759          }
158760          rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
158761          sqlite3Fts3EvalTestDeferred(pCsr, &rc);
158762          if( rc!=SQLITE_OK ) break;
158763        }
158764        (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
158765        break;
158766      }
158767    }
158768
158769    pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
158770  }
158771
158772  sqlite3_reset(pSelect);
158773  return rc;
158774}
158775
158776
158777/*
158778** Populate pCsr->aMatchinfo[] with data for the current row. The
158779** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
158780*/
158781static void fts3GetMatchinfo(
158782  sqlite3_context *pCtx,        /* Return results here */
158783  Fts3Cursor *pCsr,               /* FTS3 Cursor object */
158784  const char *zArg                /* Second argument to matchinfo() function */
158785){
158786  MatchInfo sInfo;
158787  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
158788  int rc = SQLITE_OK;
158789  int bGlobal = 0;                /* Collect 'global' stats as well as local */
158790
158791  u32 *aOut = 0;
158792  void (*xDestroyOut)(void*) = 0;
158793
158794  memset(&sInfo, 0, sizeof(MatchInfo));
158795  sInfo.pCursor = pCsr;
158796  sInfo.nCol = pTab->nColumn;
158797
158798  /* If there is cached matchinfo() data, but the format string for the
158799  ** cache does not match the format string for this request, discard
158800  ** the cached data. */
158801  if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
158802    sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
158803    pCsr->pMIBuffer = 0;
158804  }
158805
158806  /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
158807  ** matchinfo function has been called for this query. In this case
158808  ** allocate the array used to accumulate the matchinfo data and
158809  ** initialize those elements that are constant for every row.
158810  */
158811  if( pCsr->pMIBuffer==0 ){
158812    int nMatchinfo = 0;           /* Number of u32 elements in match-info */
158813    int i;                        /* Used to iterate through zArg */
158814
158815    /* Determine the number of phrases in the query */
158816    pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
158817    sInfo.nPhrase = pCsr->nPhrase;
158818
158819    /* Determine the number of integers in the buffer returned by this call. */
158820    for(i=0; zArg[i]; i++){
158821      char *zErr = 0;
158822      if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
158823        sqlite3_result_error(pCtx, zErr, -1);
158824        sqlite3_free(zErr);
158825        return;
158826      }
158827      nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
158828    }
158829
158830    /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
158831    pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
158832    if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
158833
158834    pCsr->isMatchinfoNeeded = 1;
158835    bGlobal = 1;
158836  }
158837
158838  if( rc==SQLITE_OK ){
158839    xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
158840    if( xDestroyOut==0 ){
158841      rc = SQLITE_NOMEM;
158842    }
158843  }
158844
158845  if( rc==SQLITE_OK ){
158846    sInfo.aMatchinfo = aOut;
158847    sInfo.nPhrase = pCsr->nPhrase;
158848    rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
158849    if( bGlobal ){
158850      fts3MIBufferSetGlobal(pCsr->pMIBuffer);
158851    }
158852  }
158853
158854  if( rc!=SQLITE_OK ){
158855    sqlite3_result_error_code(pCtx, rc);
158856    if( xDestroyOut ) xDestroyOut(aOut);
158857  }else{
158858    int n = pCsr->pMIBuffer->nElem * sizeof(u32);
158859    sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
158860  }
158861}
158862
158863/*
158864** Implementation of snippet() function.
158865*/
158866SQLITE_PRIVATE void sqlite3Fts3Snippet(
158867  sqlite3_context *pCtx,          /* SQLite function call context */
158868  Fts3Cursor *pCsr,               /* Cursor object */
158869  const char *zStart,             /* Snippet start text - "<b>" */
158870  const char *zEnd,               /* Snippet end text - "</b>" */
158871  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
158872  int iCol,                       /* Extract snippet from this column */
158873  int nToken                      /* Approximate number of tokens in snippet */
158874){
158875  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
158876  int rc = SQLITE_OK;
158877  int i;
158878  StrBuffer res = {0, 0, 0};
158879
158880  /* The returned text includes up to four fragments of text extracted from
158881  ** the data in the current row. The first iteration of the for(...) loop
158882  ** below attempts to locate a single fragment of text nToken tokens in
158883  ** size that contains at least one instance of all phrases in the query
158884  ** expression that appear in the current row. If such a fragment of text
158885  ** cannot be found, the second iteration of the loop attempts to locate
158886  ** a pair of fragments, and so on.
158887  */
158888  int nSnippet = 0;               /* Number of fragments in this snippet */
158889  SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
158890  int nFToken = -1;               /* Number of tokens in each fragment */
158891
158892  if( !pCsr->pExpr ){
158893    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
158894    return;
158895  }
158896
158897  for(nSnippet=1; 1; nSnippet++){
158898
158899    int iSnip;                    /* Loop counter 0..nSnippet-1 */
158900    u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
158901    u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
158902
158903    if( nToken>=0 ){
158904      nFToken = (nToken+nSnippet-1) / nSnippet;
158905    }else{
158906      nFToken = -1 * nToken;
158907    }
158908
158909    for(iSnip=0; iSnip<nSnippet; iSnip++){
158910      int iBestScore = -1;        /* Best score of columns checked so far */
158911      int iRead;                  /* Used to iterate through columns */
158912      SnippetFragment *pFragment = &aSnippet[iSnip];
158913
158914      memset(pFragment, 0, sizeof(*pFragment));
158915
158916      /* Loop through all columns of the table being considered for snippets.
158917      ** If the iCol argument to this function was negative, this means all
158918      ** columns of the FTS3 table. Otherwise, only column iCol is considered.
158919      */
158920      for(iRead=0; iRead<pTab->nColumn; iRead++){
158921        SnippetFragment sF = {0, 0, 0, 0};
158922        int iS = 0;
158923        if( iCol>=0 && iRead!=iCol ) continue;
158924
158925        /* Find the best snippet of nFToken tokens in column iRead. */
158926        rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
158927        if( rc!=SQLITE_OK ){
158928          goto snippet_out;
158929        }
158930        if( iS>iBestScore ){
158931          *pFragment = sF;
158932          iBestScore = iS;
158933        }
158934      }
158935
158936      mCovered |= pFragment->covered;
158937    }
158938
158939    /* If all query phrases seen by fts3BestSnippet() are present in at least
158940    ** one of the nSnippet snippet fragments, break out of the loop.
158941    */
158942    assert( (mCovered&mSeen)==mCovered );
158943    if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
158944  }
158945
158946  assert( nFToken>0 );
158947
158948  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
158949    rc = fts3SnippetText(pCsr, &aSnippet[i],
158950        i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
158951    );
158952  }
158953
158954 snippet_out:
158955  sqlite3Fts3SegmentsClose(pTab);
158956  if( rc!=SQLITE_OK ){
158957    sqlite3_result_error_code(pCtx, rc);
158958    sqlite3_free(res.z);
158959  }else{
158960    sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
158961  }
158962}
158963
158964
158965typedef struct TermOffset TermOffset;
158966typedef struct TermOffsetCtx TermOffsetCtx;
158967
158968struct TermOffset {
158969  char *pList;                    /* Position-list */
158970  int iPos;                       /* Position just read from pList */
158971  int iOff;                       /* Offset of this term from read positions */
158972};
158973
158974struct TermOffsetCtx {
158975  Fts3Cursor *pCsr;
158976  int iCol;                       /* Column of table to populate aTerm for */
158977  int iTerm;
158978  sqlite3_int64 iDocid;
158979  TermOffset *aTerm;
158980};
158981
158982/*
158983** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
158984*/
158985static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
158986  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
158987  int nTerm;                      /* Number of tokens in phrase */
158988  int iTerm;                      /* For looping through nTerm phrase terms */
158989  char *pList;                    /* Pointer to position list for phrase */
158990  int iPos = 0;                   /* First position in position-list */
158991  int rc;
158992
158993  UNUSED_PARAMETER(iPhrase);
158994  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
158995  nTerm = pExpr->pPhrase->nToken;
158996  if( pList ){
158997    fts3GetDeltaPosition(&pList, &iPos);
158998    assert( iPos>=0 );
158999  }
159000
159001  for(iTerm=0; iTerm<nTerm; iTerm++){
159002    TermOffset *pT = &p->aTerm[p->iTerm++];
159003    pT->iOff = nTerm-iTerm-1;
159004    pT->pList = pList;
159005    pT->iPos = iPos;
159006  }
159007
159008  return rc;
159009}
159010
159011/*
159012** Implementation of offsets() function.
159013*/
159014SQLITE_PRIVATE void sqlite3Fts3Offsets(
159015  sqlite3_context *pCtx,          /* SQLite function call context */
159016  Fts3Cursor *pCsr                /* Cursor object */
159017){
159018  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
159019  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
159020  int rc;                         /* Return Code */
159021  int nToken;                     /* Number of tokens in query */
159022  int iCol;                       /* Column currently being processed */
159023  StrBuffer res = {0, 0, 0};      /* Result string */
159024  TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
159025
159026  if( !pCsr->pExpr ){
159027    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
159028    return;
159029  }
159030
159031  memset(&sCtx, 0, sizeof(sCtx));
159032  assert( pCsr->isRequireSeek==0 );
159033
159034  /* Count the number of terms in the query */
159035  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
159036  if( rc!=SQLITE_OK ) goto offsets_out;
159037
159038  /* Allocate the array of TermOffset iterators. */
159039  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
159040  if( 0==sCtx.aTerm ){
159041    rc = SQLITE_NOMEM;
159042    goto offsets_out;
159043  }
159044  sCtx.iDocid = pCsr->iPrevId;
159045  sCtx.pCsr = pCsr;
159046
159047  /* Loop through the table columns, appending offset information to
159048  ** string-buffer res for each column.
159049  */
159050  for(iCol=0; iCol<pTab->nColumn; iCol++){
159051    sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
159052    const char *ZDUMMY;           /* Dummy argument used with xNext() */
159053    int NDUMMY = 0;               /* Dummy argument used with xNext() */
159054    int iStart = 0;
159055    int iEnd = 0;
159056    int iCurrent = 0;
159057    const char *zDoc;
159058    int nDoc;
159059
159060    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
159061    ** no way that this operation can fail, so the return code from
159062    ** fts3ExprIterate() can be discarded.
159063    */
159064    sCtx.iCol = iCol;
159065    sCtx.iTerm = 0;
159066    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
159067
159068    /* Retreive the text stored in column iCol. If an SQL NULL is stored
159069    ** in column iCol, jump immediately to the next iteration of the loop.
159070    ** If an OOM occurs while retrieving the data (this can happen if SQLite
159071    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
159072    ** to the caller.
159073    */
159074    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
159075    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
159076    if( zDoc==0 ){
159077      if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
159078        continue;
159079      }
159080      rc = SQLITE_NOMEM;
159081      goto offsets_out;
159082    }
159083
159084    /* Initialize a tokenizer iterator to iterate through column iCol. */
159085    rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
159086        zDoc, nDoc, &pC
159087    );
159088    if( rc!=SQLITE_OK ) goto offsets_out;
159089
159090    rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
159091    while( rc==SQLITE_OK ){
159092      int i;                      /* Used to loop through terms */
159093      int iMinPos = 0x7FFFFFFF;   /* Position of next token */
159094      TermOffset *pTerm = 0;      /* TermOffset associated with next token */
159095
159096      for(i=0; i<nToken; i++){
159097        TermOffset *pT = &sCtx.aTerm[i];
159098        if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
159099          iMinPos = pT->iPos-pT->iOff;
159100          pTerm = pT;
159101        }
159102      }
159103
159104      if( !pTerm ){
159105        /* All offsets for this column have been gathered. */
159106        rc = SQLITE_DONE;
159107      }else{
159108        assert( iCurrent<=iMinPos );
159109        if( 0==(0xFE&*pTerm->pList) ){
159110          pTerm->pList = 0;
159111        }else{
159112          fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
159113        }
159114        while( rc==SQLITE_OK && iCurrent<iMinPos ){
159115          rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
159116        }
159117        if( rc==SQLITE_OK ){
159118          char aBuffer[64];
159119          sqlite3_snprintf(sizeof(aBuffer), aBuffer,
159120              "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
159121          );
159122          rc = fts3StringAppend(&res, aBuffer, -1);
159123        }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
159124          rc = FTS_CORRUPT_VTAB;
159125        }
159126      }
159127    }
159128    if( rc==SQLITE_DONE ){
159129      rc = SQLITE_OK;
159130    }
159131
159132    pMod->xClose(pC);
159133    if( rc!=SQLITE_OK ) goto offsets_out;
159134  }
159135
159136 offsets_out:
159137  sqlite3_free(sCtx.aTerm);
159138  assert( rc!=SQLITE_DONE );
159139  sqlite3Fts3SegmentsClose(pTab);
159140  if( rc!=SQLITE_OK ){
159141    sqlite3_result_error_code(pCtx,  rc);
159142    sqlite3_free(res.z);
159143  }else{
159144    sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
159145  }
159146  return;
159147}
159148
159149/*
159150** Implementation of matchinfo() function.
159151*/
159152SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
159153  sqlite3_context *pContext,      /* Function call context */
159154  Fts3Cursor *pCsr,               /* FTS3 table cursor */
159155  const char *zArg                /* Second arg to matchinfo() function */
159156){
159157  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
159158  const char *zFormat;
159159
159160  if( zArg ){
159161    zFormat = zArg;
159162  }else{
159163    zFormat = FTS3_MATCHINFO_DEFAULT;
159164  }
159165
159166  if( !pCsr->pExpr ){
159167    sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
159168    return;
159169  }else{
159170    /* Retrieve matchinfo() data. */
159171    fts3GetMatchinfo(pContext, pCsr, zFormat);
159172    sqlite3Fts3SegmentsClose(pTab);
159173  }
159174}
159175
159176#endif
159177
159178/************** End of fts3_snippet.c ****************************************/
159179/************** Begin file fts3_unicode.c ************************************/
159180/*
159181** 2012 May 24
159182**
159183** The author disclaims copyright to this source code.  In place of
159184** a legal notice, here is a blessing:
159185**
159186**    May you do good and not evil.
159187**    May you find forgiveness for yourself and forgive others.
159188**    May you share freely, never taking more than you give.
159189**
159190******************************************************************************
159191**
159192** Implementation of the "unicode" full-text-search tokenizer.
159193*/
159194
159195#ifndef SQLITE_DISABLE_FTS3_UNICODE
159196
159197/* #include "fts3Int.h" */
159198#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
159199
159200/* #include <assert.h> */
159201/* #include <stdlib.h> */
159202/* #include <stdio.h> */
159203/* #include <string.h> */
159204
159205/* #include "fts3_tokenizer.h" */
159206
159207/*
159208** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
159209** from the sqlite3 source file utf.c. If this file is compiled as part
159210** of the amalgamation, they are not required.
159211*/
159212#ifndef SQLITE_AMALGAMATION
159213
159214static const unsigned char sqlite3Utf8Trans1[] = {
159215  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
159216  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
159217  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
159218  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
159219  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
159220  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
159221  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
159222  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
159223};
159224
159225#define READ_UTF8(zIn, zTerm, c)                           \
159226  c = *(zIn++);                                            \
159227  if( c>=0xc0 ){                                           \
159228    c = sqlite3Utf8Trans1[c-0xc0];                         \
159229    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
159230      c = (c<<6) + (0x3f & *(zIn++));                      \
159231    }                                                      \
159232    if( c<0x80                                             \
159233        || (c&0xFFFFF800)==0xD800                          \
159234        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
159235  }
159236
159237#define WRITE_UTF8(zOut, c) {                          \
159238  if( c<0x00080 ){                                     \
159239    *zOut++ = (u8)(c&0xFF);                            \
159240  }                                                    \
159241  else if( c<0x00800 ){                                \
159242    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
159243    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
159244  }                                                    \
159245  else if( c<0x10000 ){                                \
159246    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
159247    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
159248    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
159249  }else{                                               \
159250    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
159251    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
159252    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
159253    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
159254  }                                                    \
159255}
159256
159257#endif /* ifndef SQLITE_AMALGAMATION */
159258
159259typedef struct unicode_tokenizer unicode_tokenizer;
159260typedef struct unicode_cursor unicode_cursor;
159261
159262struct unicode_tokenizer {
159263  sqlite3_tokenizer base;
159264  int bRemoveDiacritic;
159265  int nException;
159266  int *aiException;
159267};
159268
159269struct unicode_cursor {
159270  sqlite3_tokenizer_cursor base;
159271  const unsigned char *aInput;    /* Input text being tokenized */
159272  int nInput;                     /* Size of aInput[] in bytes */
159273  int iOff;                       /* Current offset within aInput[] */
159274  int iToken;                     /* Index of next token to be returned */
159275  char *zToken;                   /* storage for current token */
159276  int nAlloc;                     /* space allocated at zToken */
159277};
159278
159279
159280/*
159281** Destroy a tokenizer allocated by unicodeCreate().
159282*/
159283static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
159284  if( pTokenizer ){
159285    unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
159286    sqlite3_free(p->aiException);
159287    sqlite3_free(p);
159288  }
159289  return SQLITE_OK;
159290}
159291
159292/*
159293** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
159294** statement has specified that the tokenizer for this table shall consider
159295** all characters in string zIn/nIn to be separators (if bAlnum==0) or
159296** token characters (if bAlnum==1).
159297**
159298** For each codepoint in the zIn/nIn string, this function checks if the
159299** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
159300** If so, no action is taken. Otherwise, the codepoint is added to the
159301** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
159302** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
159303** codepoints in the aiException[] array.
159304**
159305** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
159306** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
159307** It is not possible to change the behavior of the tokenizer with respect
159308** to these codepoints.
159309*/
159310static int unicodeAddExceptions(
159311  unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
159312  int bAlnum,                     /* Replace Isalnum() return value with this */
159313  const char *zIn,                /* Array of characters to make exceptions */
159314  int nIn                         /* Length of z in bytes */
159315){
159316  const unsigned char *z = (const unsigned char *)zIn;
159317  const unsigned char *zTerm = &z[nIn];
159318  int iCode;
159319  int nEntry = 0;
159320
159321  assert( bAlnum==0 || bAlnum==1 );
159322
159323  while( z<zTerm ){
159324    READ_UTF8(z, zTerm, iCode);
159325    assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
159326    if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
159327     && sqlite3FtsUnicodeIsdiacritic(iCode)==0
159328    ){
159329      nEntry++;
159330    }
159331  }
159332
159333  if( nEntry ){
159334    int *aNew;                    /* New aiException[] array */
159335    int nNew;                     /* Number of valid entries in array aNew[] */
159336
159337    aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
159338    if( aNew==0 ) return SQLITE_NOMEM;
159339    nNew = p->nException;
159340
159341    z = (const unsigned char *)zIn;
159342    while( z<zTerm ){
159343      READ_UTF8(z, zTerm, iCode);
159344      if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
159345       && sqlite3FtsUnicodeIsdiacritic(iCode)==0
159346      ){
159347        int i, j;
159348        for(i=0; i<nNew && aNew[i]<iCode; i++);
159349        for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
159350        aNew[i] = iCode;
159351        nNew++;
159352      }
159353    }
159354    p->aiException = aNew;
159355    p->nException = nNew;
159356  }
159357
159358  return SQLITE_OK;
159359}
159360
159361/*
159362** Return true if the p->aiException[] array contains the value iCode.
159363*/
159364static int unicodeIsException(unicode_tokenizer *p, int iCode){
159365  if( p->nException>0 ){
159366    int *a = p->aiException;
159367    int iLo = 0;
159368    int iHi = p->nException-1;
159369
159370    while( iHi>=iLo ){
159371      int iTest = (iHi + iLo) / 2;
159372      if( iCode==a[iTest] ){
159373        return 1;
159374      }else if( iCode>a[iTest] ){
159375        iLo = iTest+1;
159376      }else{
159377        iHi = iTest-1;
159378      }
159379    }
159380  }
159381
159382  return 0;
159383}
159384
159385/*
159386** Return true if, for the purposes of tokenization, codepoint iCode is
159387** considered a token character (not a separator).
159388*/
159389static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
159390  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
159391  return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
159392}
159393
159394/*
159395** Create a new tokenizer instance.
159396*/
159397static int unicodeCreate(
159398  int nArg,                       /* Size of array argv[] */
159399  const char * const *azArg,      /* Tokenizer creation arguments */
159400  sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
159401){
159402  unicode_tokenizer *pNew;        /* New tokenizer object */
159403  int i;
159404  int rc = SQLITE_OK;
159405
159406  pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
159407  if( pNew==NULL ) return SQLITE_NOMEM;
159408  memset(pNew, 0, sizeof(unicode_tokenizer));
159409  pNew->bRemoveDiacritic = 1;
159410
159411  for(i=0; rc==SQLITE_OK && i<nArg; i++){
159412    const char *z = azArg[i];
159413    int n = (int)strlen(z);
159414
159415    if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
159416      pNew->bRemoveDiacritic = 1;
159417    }
159418    else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
159419      pNew->bRemoveDiacritic = 0;
159420    }
159421    else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
159422      rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
159423    }
159424    else if( n>=11 && memcmp("separators=", z, 11)==0 ){
159425      rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
159426    }
159427    else{
159428      /* Unrecognized argument */
159429      rc  = SQLITE_ERROR;
159430    }
159431  }
159432
159433  if( rc!=SQLITE_OK ){
159434    unicodeDestroy((sqlite3_tokenizer *)pNew);
159435    pNew = 0;
159436  }
159437  *pp = (sqlite3_tokenizer *)pNew;
159438  return rc;
159439}
159440
159441/*
159442** Prepare to begin tokenizing a particular string.  The input
159443** string to be tokenized is pInput[0..nBytes-1].  A cursor
159444** used to incrementally tokenize this string is returned in
159445** *ppCursor.
159446*/
159447static int unicodeOpen(
159448  sqlite3_tokenizer *p,           /* The tokenizer */
159449  const char *aInput,             /* Input string */
159450  int nInput,                     /* Size of string aInput in bytes */
159451  sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
159452){
159453  unicode_cursor *pCsr;
159454
159455  pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
159456  if( pCsr==0 ){
159457    return SQLITE_NOMEM;
159458  }
159459  memset(pCsr, 0, sizeof(unicode_cursor));
159460
159461  pCsr->aInput = (const unsigned char *)aInput;
159462  if( aInput==0 ){
159463    pCsr->nInput = 0;
159464  }else if( nInput<0 ){
159465    pCsr->nInput = (int)strlen(aInput);
159466  }else{
159467    pCsr->nInput = nInput;
159468  }
159469
159470  *pp = &pCsr->base;
159471  UNUSED_PARAMETER(p);
159472  return SQLITE_OK;
159473}
159474
159475/*
159476** Close a tokenization cursor previously opened by a call to
159477** simpleOpen() above.
159478*/
159479static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
159480  unicode_cursor *pCsr = (unicode_cursor *) pCursor;
159481  sqlite3_free(pCsr->zToken);
159482  sqlite3_free(pCsr);
159483  return SQLITE_OK;
159484}
159485
159486/*
159487** Extract the next token from a tokenization cursor.  The cursor must
159488** have been opened by a prior call to simpleOpen().
159489*/
159490static int unicodeNext(
159491  sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
159492  const char **paToken,           /* OUT: Token text */
159493  int *pnToken,                   /* OUT: Number of bytes at *paToken */
159494  int *piStart,                   /* OUT: Starting offset of token */
159495  int *piEnd,                     /* OUT: Ending offset of token */
159496  int *piPos                      /* OUT: Position integer of token */
159497){
159498  unicode_cursor *pCsr = (unicode_cursor *)pC;
159499  unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
159500  int iCode = 0;
159501  char *zOut;
159502  const unsigned char *z = &pCsr->aInput[pCsr->iOff];
159503  const unsigned char *zStart = z;
159504  const unsigned char *zEnd;
159505  const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
159506
159507  /* Scan past any delimiter characters before the start of the next token.
159508  ** Return SQLITE_DONE early if this takes us all the way to the end of
159509  ** the input.  */
159510  while( z<zTerm ){
159511    READ_UTF8(z, zTerm, iCode);
159512    if( unicodeIsAlnum(p, iCode) ) break;
159513    zStart = z;
159514  }
159515  if( zStart>=zTerm ) return SQLITE_DONE;
159516
159517  zOut = pCsr->zToken;
159518  do {
159519    int iOut;
159520
159521    /* Grow the output buffer if required. */
159522    if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
159523      char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
159524      if( !zNew ) return SQLITE_NOMEM;
159525      zOut = &zNew[zOut - pCsr->zToken];
159526      pCsr->zToken = zNew;
159527      pCsr->nAlloc += 64;
159528    }
159529
159530    /* Write the folded case of the last character read to the output */
159531    zEnd = z;
159532    iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
159533    if( iOut ){
159534      WRITE_UTF8(zOut, iOut);
159535    }
159536
159537    /* If the cursor is not at EOF, read the next character */
159538    if( z>=zTerm ) break;
159539    READ_UTF8(z, zTerm, iCode);
159540  }while( unicodeIsAlnum(p, iCode)
159541       || sqlite3FtsUnicodeIsdiacritic(iCode)
159542  );
159543
159544  /* Set the output variables and return. */
159545  pCsr->iOff = (int)(z - pCsr->aInput);
159546  *paToken = pCsr->zToken;
159547  *pnToken = (int)(zOut - pCsr->zToken);
159548  *piStart = (int)(zStart - pCsr->aInput);
159549  *piEnd = (int)(zEnd - pCsr->aInput);
159550  *piPos = pCsr->iToken++;
159551  return SQLITE_OK;
159552}
159553
159554/*
159555** Set *ppModule to a pointer to the sqlite3_tokenizer_module
159556** structure for the unicode tokenizer.
159557*/
159558SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
159559  static const sqlite3_tokenizer_module module = {
159560    0,
159561    unicodeCreate,
159562    unicodeDestroy,
159563    unicodeOpen,
159564    unicodeClose,
159565    unicodeNext,
159566    0,
159567  };
159568  *ppModule = &module;
159569}
159570
159571#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
159572#endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
159573
159574/************** End of fts3_unicode.c ****************************************/
159575/************** Begin file fts3_unicode2.c ***********************************/
159576/*
159577** 2012 May 25
159578**
159579** The author disclaims copyright to this source code.  In place of
159580** a legal notice, here is a blessing:
159581**
159582**    May you do good and not evil.
159583**    May you find forgiveness for yourself and forgive others.
159584**    May you share freely, never taking more than you give.
159585**
159586******************************************************************************
159587*/
159588
159589/*
159590** DO NOT EDIT THIS MACHINE GENERATED FILE.
159591*/
159592
159593#ifndef SQLITE_DISABLE_FTS3_UNICODE
159594#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
159595
159596/* #include <assert.h> */
159597
159598/*
159599** Return true if the argument corresponds to a unicode codepoint
159600** classified as either a letter or a number. Otherwise false.
159601**
159602** The results are undefined if the value passed to this function
159603** is less than zero.
159604*/
159605SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
159606  /* Each unsigned integer in the following array corresponds to a contiguous
159607  ** range of unicode codepoints that are not either letters or numbers (i.e.
159608  ** codepoints for which this function should return 0).
159609  **
159610  ** The most significant 22 bits in each 32-bit value contain the first
159611  ** codepoint in the range. The least significant 10 bits are used to store
159612  ** the size of the range (always at least 1). In other words, the value
159613  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
159614  ** C. It is not possible to represent a range larger than 1023 codepoints
159615  ** using this format.
159616  */
159617  static const unsigned int aEntry[] = {
159618    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
159619    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
159620    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
159621    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
159622    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
159623    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
159624    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
159625    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
159626    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
159627    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
159628    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
159629    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
159630    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
159631    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
159632    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
159633    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
159634    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
159635    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
159636    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
159637    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
159638    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
159639    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
159640    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
159641    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
159642    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
159643    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
159644    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
159645    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
159646    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
159647    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
159648    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
159649    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
159650    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
159651    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
159652    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
159653    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
159654    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
159655    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
159656    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
159657    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
159658    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
159659    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
159660    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
159661    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
159662    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
159663    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
159664    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
159665    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
159666    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
159667    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
159668    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
159669    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
159670    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
159671    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
159672    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
159673    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
159674    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
159675    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
159676    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
159677    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
159678    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
159679    0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
159680    0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
159681    0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
159682    0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
159683    0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
159684    0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
159685    0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
159686    0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
159687    0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
159688    0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
159689    0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
159690    0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
159691    0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
159692    0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
159693    0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
159694    0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
159695    0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
159696    0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
159697    0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
159698    0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
159699    0x380400F0,
159700  };
159701  static const unsigned int aAscii[4] = {
159702    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
159703  };
159704
159705  if( c<128 ){
159706    return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
159707  }else if( c<(1<<22) ){
159708    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
159709    int iRes = 0;
159710    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
159711    int iLo = 0;
159712    while( iHi>=iLo ){
159713      int iTest = (iHi + iLo) / 2;
159714      if( key >= aEntry[iTest] ){
159715        iRes = iTest;
159716        iLo = iTest+1;
159717      }else{
159718        iHi = iTest-1;
159719      }
159720    }
159721    assert( aEntry[0]<key );
159722    assert( key>=aEntry[iRes] );
159723    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
159724  }
159725  return 1;
159726}
159727
159728
159729/*
159730** If the argument is a codepoint corresponding to a lowercase letter
159731** in the ASCII range with a diacritic added, return the codepoint
159732** of the ASCII letter only. For example, if passed 235 - "LATIN
159733** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
159734** E"). The resuls of passing a codepoint that corresponds to an
159735** uppercase letter are undefined.
159736*/
159737static int remove_diacritic(int c){
159738  unsigned short aDia[] = {
159739        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
159740     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
159741     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
159742     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
159743     3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
159744     3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
159745     4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
159746     6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
159747    61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
159748    61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
159749    62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
159750    62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
159751    62924, 63050, 63082, 63274, 63390,
159752  };
159753  char aChar[] = {
159754    '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
159755    'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
159756    's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
159757    'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
159758    'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
159759    '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
159760    'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
159761    'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
159762    'e',  'i',  'o',  'u',  'y',
159763  };
159764
159765  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
159766  int iRes = 0;
159767  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
159768  int iLo = 0;
159769  while( iHi>=iLo ){
159770    int iTest = (iHi + iLo) / 2;
159771    if( key >= aDia[iTest] ){
159772      iRes = iTest;
159773      iLo = iTest+1;
159774    }else{
159775      iHi = iTest-1;
159776    }
159777  }
159778  assert( key>=aDia[iRes] );
159779  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
159780}
159781
159782
159783/*
159784** Return true if the argument interpreted as a unicode codepoint
159785** is a diacritical modifier character.
159786*/
159787SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
159788  unsigned int mask0 = 0x08029FDF;
159789  unsigned int mask1 = 0x000361F8;
159790  if( c<768 || c>817 ) return 0;
159791  return (c < 768+32) ?
159792      (mask0 & (1 << (c-768))) :
159793      (mask1 & (1 << (c-768-32)));
159794}
159795
159796
159797/*
159798** Interpret the argument as a unicode codepoint. If the codepoint
159799** is an upper case character that has a lower case equivalent,
159800** return the codepoint corresponding to the lower case version.
159801** Otherwise, return a copy of the argument.
159802**
159803** The results are undefined if the value passed to this function
159804** is less than zero.
159805*/
159806SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
159807  /* Each entry in the following array defines a rule for folding a range
159808  ** of codepoints to lower case. The rule applies to a range of nRange
159809  ** codepoints starting at codepoint iCode.
159810  **
159811  ** If the least significant bit in flags is clear, then the rule applies
159812  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
159813  ** need to be folded). Or, if it is set, then the rule only applies to
159814  ** every second codepoint in the range, starting with codepoint C.
159815  **
159816  ** The 7 most significant bits in flags are an index into the aiOff[]
159817  ** array. If a specific codepoint C does require folding, then its lower
159818  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
159819  **
159820  ** The contents of this array are generated by parsing the CaseFolding.txt
159821  ** file distributed as part of the "Unicode Character Database". See
159822  ** http://www.unicode.org for details.
159823  */
159824  static const struct TableEntry {
159825    unsigned short iCode;
159826    unsigned char flags;
159827    unsigned char nRange;
159828  } aEntry[] = {
159829    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
159830    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
159831    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
159832    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
159833    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
159834    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
159835    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
159836    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
159837    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
159838    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
159839    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
159840    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
159841    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
159842    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
159843    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
159844    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
159845    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
159846    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
159847    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
159848    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
159849    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
159850    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
159851    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
159852    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
159853    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
159854    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
159855    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
159856    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
159857    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
159858    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
159859    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
159860    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
159861    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
159862    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
159863    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
159864    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
159865    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
159866    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
159867    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
159868    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
159869    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
159870    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
159871    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
159872    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
159873    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
159874    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
159875    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
159876    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
159877    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
159878    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
159879    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
159880    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
159881    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
159882    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
159883    {65313, 14, 26},
159884  };
159885  static const unsigned short aiOff[] = {
159886   1,     2,     8,     15,    16,    26,    28,    32,
159887   37,    38,    40,    48,    63,    64,    69,    71,
159888   79,    80,    116,   202,   203,   205,   206,   207,
159889   209,   210,   211,   213,   214,   217,   218,   219,
159890   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
159891   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
159892   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
159893   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
159894   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
159895   65514, 65521, 65527, 65528, 65529,
159896  };
159897
159898  int ret = c;
159899
159900  assert( c>=0 );
159901  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
159902
159903  if( c<128 ){
159904    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
159905  }else if( c<65536 ){
159906    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
159907    int iLo = 0;
159908    int iRes = -1;
159909
159910    while( iHi>=iLo ){
159911      int iTest = (iHi + iLo) / 2;
159912      int cmp = (c - aEntry[iTest].iCode);
159913      if( cmp>=0 ){
159914        iRes = iTest;
159915        iLo = iTest+1;
159916      }else{
159917        iHi = iTest-1;
159918      }
159919    }
159920    assert( iRes<0 || c>=aEntry[iRes].iCode );
159921
159922    if( iRes>=0 ){
159923      const struct TableEntry *p = &aEntry[iRes];
159924      if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
159925        ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
159926        assert( ret>0 );
159927      }
159928    }
159929
159930    if( bRemoveDiacritic ) ret = remove_diacritic(ret);
159931  }
159932
159933  else if( c>=66560 && c<66600 ){
159934    ret = c + 40;
159935  }
159936
159937  return ret;
159938}
159939#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
159940#endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
159941
159942/************** End of fts3_unicode2.c ***************************************/
159943/************** Begin file rtree.c *******************************************/
159944/*
159945** 2001 September 15
159946**
159947** The author disclaims copyright to this source code.  In place of
159948** a legal notice, here is a blessing:
159949**
159950**    May you do good and not evil.
159951**    May you find forgiveness for yourself and forgive others.
159952**    May you share freely, never taking more than you give.
159953**
159954*************************************************************************
159955** This file contains code for implementations of the r-tree and r*-tree
159956** algorithms packaged as an SQLite virtual table module.
159957*/
159958
159959/*
159960** Database Format of R-Tree Tables
159961** --------------------------------
159962**
159963** The data structure for a single virtual r-tree table is stored in three
159964** native SQLite tables declared as follows. In each case, the '%' character
159965** in the table name is replaced with the user-supplied name of the r-tree
159966** table.
159967**
159968**   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
159969**   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
159970**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
159971**
159972** The data for each node of the r-tree structure is stored in the %_node
159973** table. For each node that is not the root node of the r-tree, there is
159974** an entry in the %_parent table associating the node with its parent.
159975** And for each row of data in the table, there is an entry in the %_rowid
159976** table that maps from the entries rowid to the id of the node that it
159977** is stored on.
159978**
159979** The root node of an r-tree always exists, even if the r-tree table is
159980** empty. The nodeno of the root node is always 1. All other nodes in the
159981** table must be the same size as the root node. The content of each node
159982** is formatted as follows:
159983**
159984**   1. If the node is the root node (node 1), then the first 2 bytes
159985**      of the node contain the tree depth as a big-endian integer.
159986**      For non-root nodes, the first 2 bytes are left unused.
159987**
159988**   2. The next 2 bytes contain the number of entries currently
159989**      stored in the node.
159990**
159991**   3. The remainder of the node contains the node entries. Each entry
159992**      consists of a single 8-byte integer followed by an even number
159993**      of 4-byte coordinates. For leaf nodes the integer is the rowid
159994**      of a record. For internal nodes it is the node number of a
159995**      child page.
159996*/
159997
159998#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
159999
160000#ifndef SQLITE_CORE
160001/*   #include "sqlite3ext.h" */
160002  SQLITE_EXTENSION_INIT1
160003#else
160004/*   #include "sqlite3.h" */
160005#endif
160006
160007/* #include <string.h> */
160008/* #include <assert.h> */
160009/* #include <stdio.h> */
160010
160011#ifndef SQLITE_AMALGAMATION
160012#include "sqlite3rtree.h"
160013typedef sqlite3_int64 i64;
160014typedef unsigned char u8;
160015typedef unsigned short u16;
160016typedef unsigned int u32;
160017#endif
160018
160019/*  The following macro is used to suppress compiler warnings.
160020*/
160021#ifndef UNUSED_PARAMETER
160022# define UNUSED_PARAMETER(x) (void)(x)
160023#endif
160024
160025typedef struct Rtree Rtree;
160026typedef struct RtreeCursor RtreeCursor;
160027typedef struct RtreeNode RtreeNode;
160028typedef struct RtreeCell RtreeCell;
160029typedef struct RtreeConstraint RtreeConstraint;
160030typedef struct RtreeMatchArg RtreeMatchArg;
160031typedef struct RtreeGeomCallback RtreeGeomCallback;
160032typedef union RtreeCoord RtreeCoord;
160033typedef struct RtreeSearchPoint RtreeSearchPoint;
160034
160035/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
160036#define RTREE_MAX_DIMENSIONS 5
160037
160038/* Size of hash table Rtree.aHash. This hash table is not expected to
160039** ever contain very many entries, so a fixed number of buckets is
160040** used.
160041*/
160042#define HASHSIZE 97
160043
160044/* The xBestIndex method of this virtual table requires an estimate of
160045** the number of rows in the virtual table to calculate the costs of
160046** various strategies. If possible, this estimate is loaded from the
160047** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
160048** Otherwise, if no sqlite_stat1 entry is available, use
160049** RTREE_DEFAULT_ROWEST.
160050*/
160051#define RTREE_DEFAULT_ROWEST 1048576
160052#define RTREE_MIN_ROWEST         100
160053
160054/*
160055** An rtree virtual-table object.
160056*/
160057struct Rtree {
160058  sqlite3_vtab base;          /* Base class.  Must be first */
160059  sqlite3 *db;                /* Host database connection */
160060  int iNodeSize;              /* Size in bytes of each node in the node table */
160061  u8 nDim;                    /* Number of dimensions */
160062  u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
160063  u8 nBytesPerCell;           /* Bytes consumed per cell */
160064  int iDepth;                 /* Current depth of the r-tree structure */
160065  char *zDb;                  /* Name of database containing r-tree table */
160066  char *zName;                /* Name of r-tree table */
160067  int nBusy;                  /* Current number of users of this structure */
160068  i64 nRowEst;                /* Estimated number of rows in this table */
160069
160070  /* List of nodes removed during a CondenseTree operation. List is
160071  ** linked together via the pointer normally used for hash chains -
160072  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
160073  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
160074  */
160075  RtreeNode *pDeleted;
160076  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
160077
160078  /* Statements to read/write/delete a record from xxx_node */
160079  sqlite3_stmt *pReadNode;
160080  sqlite3_stmt *pWriteNode;
160081  sqlite3_stmt *pDeleteNode;
160082
160083  /* Statements to read/write/delete a record from xxx_rowid */
160084  sqlite3_stmt *pReadRowid;
160085  sqlite3_stmt *pWriteRowid;
160086  sqlite3_stmt *pDeleteRowid;
160087
160088  /* Statements to read/write/delete a record from xxx_parent */
160089  sqlite3_stmt *pReadParent;
160090  sqlite3_stmt *pWriteParent;
160091  sqlite3_stmt *pDeleteParent;
160092
160093  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
160094};
160095
160096/* Possible values for Rtree.eCoordType: */
160097#define RTREE_COORD_REAL32 0
160098#define RTREE_COORD_INT32  1
160099
160100/*
160101** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
160102** only deal with integer coordinates.  No floating point operations
160103** will be done.
160104*/
160105#ifdef SQLITE_RTREE_INT_ONLY
160106  typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
160107  typedef int RtreeValue;                  /* Low accuracy coordinate */
160108# define RTREE_ZERO 0
160109#else
160110  typedef double RtreeDValue;              /* High accuracy coordinate */
160111  typedef float RtreeValue;                /* Low accuracy coordinate */
160112# define RTREE_ZERO 0.0
160113#endif
160114
160115/*
160116** When doing a search of an r-tree, instances of the following structure
160117** record intermediate results from the tree walk.
160118**
160119** The id is always a node-id.  For iLevel>=1 the id is the node-id of
160120** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
160121** the id is of the parent node and the cell that RtreeSearchPoint
160122** represents is the iCell-th entry in the parent node.
160123*/
160124struct RtreeSearchPoint {
160125  RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
160126  sqlite3_int64 id;      /* Node ID */
160127  u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
160128  u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
160129  u8 iCell;              /* Cell index within the node */
160130};
160131
160132/*
160133** The minimum number of cells allowed for a node is a third of the
160134** maximum. In Gutman's notation:
160135**
160136**     m = M/3
160137**
160138** If an R*-tree "Reinsert" operation is required, the same number of
160139** cells are removed from the overfull node and reinserted into the tree.
160140*/
160141#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
160142#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
160143#define RTREE_MAXCELLS 51
160144
160145/*
160146** The smallest possible node-size is (512-64)==448 bytes. And the largest
160147** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
160148** Therefore all non-root nodes must contain at least 3 entries. Since
160149** 2^40 is greater than 2^64, an r-tree structure always has a depth of
160150** 40 or less.
160151*/
160152#define RTREE_MAX_DEPTH 40
160153
160154
160155/*
160156** Number of entries in the cursor RtreeNode cache.  The first entry is
160157** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
160158** entries cache the RtreeNode for the first elements of the priority queue.
160159*/
160160#define RTREE_CACHE_SZ  5
160161
160162/*
160163** An rtree cursor object.
160164*/
160165struct RtreeCursor {
160166  sqlite3_vtab_cursor base;         /* Base class.  Must be first */
160167  u8 atEOF;                         /* True if at end of search */
160168  u8 bPoint;                        /* True if sPoint is valid */
160169  int iStrategy;                    /* Copy of idxNum search parameter */
160170  int nConstraint;                  /* Number of entries in aConstraint */
160171  RtreeConstraint *aConstraint;     /* Search constraints. */
160172  int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
160173  int nPoint;                       /* Number of slots used in aPoint[] */
160174  int mxLevel;                      /* iLevel value for root of the tree */
160175  RtreeSearchPoint *aPoint;         /* Priority queue for search points */
160176  RtreeSearchPoint sPoint;          /* Cached next search point */
160177  RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
160178  u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
160179};
160180
160181/* Return the Rtree of a RtreeCursor */
160182#define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
160183
160184/*
160185** A coordinate can be either a floating point number or a integer.  All
160186** coordinates within a single R-Tree are always of the same time.
160187*/
160188union RtreeCoord {
160189  RtreeValue f;      /* Floating point value */
160190  int i;             /* Integer value */
160191  u32 u;             /* Unsigned for byte-order conversions */
160192};
160193
160194/*
160195** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
160196** formatted as a RtreeDValue (double or int64). This macro assumes that local
160197** variable pRtree points to the Rtree structure associated with the
160198** RtreeCoord.
160199*/
160200#ifdef SQLITE_RTREE_INT_ONLY
160201# define DCOORD(coord) ((RtreeDValue)coord.i)
160202#else
160203# define DCOORD(coord) (                           \
160204    (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
160205      ((double)coord.f) :                           \
160206      ((double)coord.i)                             \
160207  )
160208#endif
160209
160210/*
160211** A search constraint.
160212*/
160213struct RtreeConstraint {
160214  int iCoord;                     /* Index of constrained coordinate */
160215  int op;                         /* Constraining operation */
160216  union {
160217    RtreeDValue rValue;             /* Constraint value. */
160218    int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
160219    int (*xQueryFunc)(sqlite3_rtree_query_info*);
160220  } u;
160221  sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
160222};
160223
160224/* Possible values for RtreeConstraint.op */
160225#define RTREE_EQ    0x41  /* A */
160226#define RTREE_LE    0x42  /* B */
160227#define RTREE_LT    0x43  /* C */
160228#define RTREE_GE    0x44  /* D */
160229#define RTREE_GT    0x45  /* E */
160230#define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
160231#define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
160232
160233
160234/*
160235** An rtree structure node.
160236*/
160237struct RtreeNode {
160238  RtreeNode *pParent;         /* Parent node */
160239  i64 iNode;                  /* The node number */
160240  int nRef;                   /* Number of references to this node */
160241  int isDirty;                /* True if the node needs to be written to disk */
160242  u8 *zData;                  /* Content of the node, as should be on disk */
160243  RtreeNode *pNext;           /* Next node in this hash collision chain */
160244};
160245
160246/* Return the number of cells in a node  */
160247#define NCELL(pNode) readInt16(&(pNode)->zData[2])
160248
160249/*
160250** A single cell from a node, deserialized
160251*/
160252struct RtreeCell {
160253  i64 iRowid;                                 /* Node or entry ID */
160254  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
160255};
160256
160257
160258/*
160259** This object becomes the sqlite3_user_data() for the SQL functions
160260** that are created by sqlite3_rtree_geometry_callback() and
160261** sqlite3_rtree_query_callback() and which appear on the right of MATCH
160262** operators in order to constrain a search.
160263**
160264** xGeom and xQueryFunc are the callback functions.  Exactly one of
160265** xGeom and xQueryFunc fields is non-NULL, depending on whether the
160266** SQL function was created using sqlite3_rtree_geometry_callback() or
160267** sqlite3_rtree_query_callback().
160268**
160269** This object is deleted automatically by the destructor mechanism in
160270** sqlite3_create_function_v2().
160271*/
160272struct RtreeGeomCallback {
160273  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
160274  int (*xQueryFunc)(sqlite3_rtree_query_info*);
160275  void (*xDestructor)(void*);
160276  void *pContext;
160277};
160278
160279
160280/*
160281** Value for the first field of every RtreeMatchArg object. The MATCH
160282** operator tests that the first field of a blob operand matches this
160283** value to avoid operating on invalid blobs (which could cause a segfault).
160284*/
160285#define RTREE_GEOMETRY_MAGIC 0x891245AB
160286
160287/*
160288** An instance of this structure (in the form of a BLOB) is returned by
160289** the SQL functions that sqlite3_rtree_geometry_callback() and
160290** sqlite3_rtree_query_callback() create, and is read as the right-hand
160291** operand to the MATCH operator of an R-Tree.
160292*/
160293struct RtreeMatchArg {
160294  u32 magic;                  /* Always RTREE_GEOMETRY_MAGIC */
160295  RtreeGeomCallback cb;       /* Info about the callback functions */
160296  int nParam;                 /* Number of parameters to the SQL function */
160297  sqlite3_value **apSqlParam; /* Original SQL parameter values */
160298  RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
160299};
160300
160301#ifndef MAX
160302# define MAX(x,y) ((x) < (y) ? (y) : (x))
160303#endif
160304#ifndef MIN
160305# define MIN(x,y) ((x) > (y) ? (y) : (x))
160306#endif
160307
160308/*
160309** Functions to deserialize a 16 bit integer, 32 bit real number and
160310** 64 bit integer. The deserialized value is returned.
160311*/
160312static int readInt16(u8 *p){
160313  return (p[0]<<8) + p[1];
160314}
160315static void readCoord(u8 *p, RtreeCoord *pCoord){
160316  pCoord->u = (
160317    (((u32)p[0]) << 24) +
160318    (((u32)p[1]) << 16) +
160319    (((u32)p[2]) <<  8) +
160320    (((u32)p[3]) <<  0)
160321  );
160322}
160323static i64 readInt64(u8 *p){
160324  return (
160325    (((i64)p[0]) << 56) +
160326    (((i64)p[1]) << 48) +
160327    (((i64)p[2]) << 40) +
160328    (((i64)p[3]) << 32) +
160329    (((i64)p[4]) << 24) +
160330    (((i64)p[5]) << 16) +
160331    (((i64)p[6]) <<  8) +
160332    (((i64)p[7]) <<  0)
160333  );
160334}
160335
160336/*
160337** Functions to serialize a 16 bit integer, 32 bit real number and
160338** 64 bit integer. The value returned is the number of bytes written
160339** to the argument buffer (always 2, 4 and 8 respectively).
160340*/
160341static int writeInt16(u8 *p, int i){
160342  p[0] = (i>> 8)&0xFF;
160343  p[1] = (i>> 0)&0xFF;
160344  return 2;
160345}
160346static int writeCoord(u8 *p, RtreeCoord *pCoord){
160347  u32 i;
160348  assert( sizeof(RtreeCoord)==4 );
160349  assert( sizeof(u32)==4 );
160350  i = pCoord->u;
160351  p[0] = (i>>24)&0xFF;
160352  p[1] = (i>>16)&0xFF;
160353  p[2] = (i>> 8)&0xFF;
160354  p[3] = (i>> 0)&0xFF;
160355  return 4;
160356}
160357static int writeInt64(u8 *p, i64 i){
160358  p[0] = (i>>56)&0xFF;
160359  p[1] = (i>>48)&0xFF;
160360  p[2] = (i>>40)&0xFF;
160361  p[3] = (i>>32)&0xFF;
160362  p[4] = (i>>24)&0xFF;
160363  p[5] = (i>>16)&0xFF;
160364  p[6] = (i>> 8)&0xFF;
160365  p[7] = (i>> 0)&0xFF;
160366  return 8;
160367}
160368
160369/*
160370** Increment the reference count of node p.
160371*/
160372static void nodeReference(RtreeNode *p){
160373  if( p ){
160374    p->nRef++;
160375  }
160376}
160377
160378/*
160379** Clear the content of node p (set all bytes to 0x00).
160380*/
160381static void nodeZero(Rtree *pRtree, RtreeNode *p){
160382  memset(&p->zData[2], 0, pRtree->iNodeSize-2);
160383  p->isDirty = 1;
160384}
160385
160386/*
160387** Given a node number iNode, return the corresponding key to use
160388** in the Rtree.aHash table.
160389*/
160390static int nodeHash(i64 iNode){
160391  return iNode % HASHSIZE;
160392}
160393
160394/*
160395** Search the node hash table for node iNode. If found, return a pointer
160396** to it. Otherwise, return 0.
160397*/
160398static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
160399  RtreeNode *p;
160400  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
160401  return p;
160402}
160403
160404/*
160405** Add node pNode to the node hash table.
160406*/
160407static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
160408  int iHash;
160409  assert( pNode->pNext==0 );
160410  iHash = nodeHash(pNode->iNode);
160411  pNode->pNext = pRtree->aHash[iHash];
160412  pRtree->aHash[iHash] = pNode;
160413}
160414
160415/*
160416** Remove node pNode from the node hash table.
160417*/
160418static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
160419  RtreeNode **pp;
160420  if( pNode->iNode!=0 ){
160421    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
160422    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
160423    *pp = pNode->pNext;
160424    pNode->pNext = 0;
160425  }
160426}
160427
160428/*
160429** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
160430** indicating that node has not yet been assigned a node number. It is
160431** assigned a node number when nodeWrite() is called to write the
160432** node contents out to the database.
160433*/
160434static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
160435  RtreeNode *pNode;
160436  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
160437  if( pNode ){
160438    memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
160439    pNode->zData = (u8 *)&pNode[1];
160440    pNode->nRef = 1;
160441    pNode->pParent = pParent;
160442    pNode->isDirty = 1;
160443    nodeReference(pParent);
160444  }
160445  return pNode;
160446}
160447
160448/*
160449** Obtain a reference to an r-tree node.
160450*/
160451static int nodeAcquire(
160452  Rtree *pRtree,             /* R-tree structure */
160453  i64 iNode,                 /* Node number to load */
160454  RtreeNode *pParent,        /* Either the parent node or NULL */
160455  RtreeNode **ppNode         /* OUT: Acquired node */
160456){
160457  int rc;
160458  int rc2 = SQLITE_OK;
160459  RtreeNode *pNode;
160460
160461  /* Check if the requested node is already in the hash table. If so,
160462  ** increase its reference count and return it.
160463  */
160464  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
160465    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
160466    if( pParent && !pNode->pParent ){
160467      nodeReference(pParent);
160468      pNode->pParent = pParent;
160469    }
160470    pNode->nRef++;
160471    *ppNode = pNode;
160472    return SQLITE_OK;
160473  }
160474
160475  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
160476  rc = sqlite3_step(pRtree->pReadNode);
160477  if( rc==SQLITE_ROW ){
160478    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
160479    if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
160480      pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
160481      if( !pNode ){
160482        rc2 = SQLITE_NOMEM;
160483      }else{
160484        pNode->pParent = pParent;
160485        pNode->zData = (u8 *)&pNode[1];
160486        pNode->nRef = 1;
160487        pNode->iNode = iNode;
160488        pNode->isDirty = 0;
160489        pNode->pNext = 0;
160490        memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
160491        nodeReference(pParent);
160492      }
160493    }
160494  }
160495  rc = sqlite3_reset(pRtree->pReadNode);
160496  if( rc==SQLITE_OK ) rc = rc2;
160497
160498  /* If the root node was just loaded, set pRtree->iDepth to the height
160499  ** of the r-tree structure. A height of zero means all data is stored on
160500  ** the root node. A height of one means the children of the root node
160501  ** are the leaves, and so on. If the depth as specified on the root node
160502  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
160503  */
160504  if( pNode && iNode==1 ){
160505    pRtree->iDepth = readInt16(pNode->zData);
160506    if( pRtree->iDepth>RTREE_MAX_DEPTH ){
160507      rc = SQLITE_CORRUPT_VTAB;
160508    }
160509  }
160510
160511  /* If no error has occurred so far, check if the "number of entries"
160512  ** field on the node is too large. If so, set the return code to
160513  ** SQLITE_CORRUPT_VTAB.
160514  */
160515  if( pNode && rc==SQLITE_OK ){
160516    if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
160517      rc = SQLITE_CORRUPT_VTAB;
160518    }
160519  }
160520
160521  if( rc==SQLITE_OK ){
160522    if( pNode!=0 ){
160523      nodeHashInsert(pRtree, pNode);
160524    }else{
160525      rc = SQLITE_CORRUPT_VTAB;
160526    }
160527    *ppNode = pNode;
160528  }else{
160529    sqlite3_free(pNode);
160530    *ppNode = 0;
160531  }
160532
160533  return rc;
160534}
160535
160536/*
160537** Overwrite cell iCell of node pNode with the contents of pCell.
160538*/
160539static void nodeOverwriteCell(
160540  Rtree *pRtree,             /* The overall R-Tree */
160541  RtreeNode *pNode,          /* The node into which the cell is to be written */
160542  RtreeCell *pCell,          /* The cell to write */
160543  int iCell                  /* Index into pNode into which pCell is written */
160544){
160545  int ii;
160546  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
160547  p += writeInt64(p, pCell->iRowid);
160548  for(ii=0; ii<(pRtree->nDim*2); ii++){
160549    p += writeCoord(p, &pCell->aCoord[ii]);
160550  }
160551  pNode->isDirty = 1;
160552}
160553
160554/*
160555** Remove the cell with index iCell from node pNode.
160556*/
160557static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
160558  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
160559  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
160560  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
160561  memmove(pDst, pSrc, nByte);
160562  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
160563  pNode->isDirty = 1;
160564}
160565
160566/*
160567** Insert the contents of cell pCell into node pNode. If the insert
160568** is successful, return SQLITE_OK.
160569**
160570** If there is not enough free space in pNode, return SQLITE_FULL.
160571*/
160572static int nodeInsertCell(
160573  Rtree *pRtree,                /* The overall R-Tree */
160574  RtreeNode *pNode,             /* Write new cell into this node */
160575  RtreeCell *pCell              /* The cell to be inserted */
160576){
160577  int nCell;                    /* Current number of cells in pNode */
160578  int nMaxCell;                 /* Maximum number of cells for pNode */
160579
160580  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
160581  nCell = NCELL(pNode);
160582
160583  assert( nCell<=nMaxCell );
160584  if( nCell<nMaxCell ){
160585    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
160586    writeInt16(&pNode->zData[2], nCell+1);
160587    pNode->isDirty = 1;
160588  }
160589
160590  return (nCell==nMaxCell);
160591}
160592
160593/*
160594** If the node is dirty, write it out to the database.
160595*/
160596static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
160597  int rc = SQLITE_OK;
160598  if( pNode->isDirty ){
160599    sqlite3_stmt *p = pRtree->pWriteNode;
160600    if( pNode->iNode ){
160601      sqlite3_bind_int64(p, 1, pNode->iNode);
160602    }else{
160603      sqlite3_bind_null(p, 1);
160604    }
160605    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
160606    sqlite3_step(p);
160607    pNode->isDirty = 0;
160608    rc = sqlite3_reset(p);
160609    if( pNode->iNode==0 && rc==SQLITE_OK ){
160610      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
160611      nodeHashInsert(pRtree, pNode);
160612    }
160613  }
160614  return rc;
160615}
160616
160617/*
160618** Release a reference to a node. If the node is dirty and the reference
160619** count drops to zero, the node data is written to the database.
160620*/
160621static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
160622  int rc = SQLITE_OK;
160623  if( pNode ){
160624    assert( pNode->nRef>0 );
160625    pNode->nRef--;
160626    if( pNode->nRef==0 ){
160627      if( pNode->iNode==1 ){
160628        pRtree->iDepth = -1;
160629      }
160630      if( pNode->pParent ){
160631        rc = nodeRelease(pRtree, pNode->pParent);
160632      }
160633      if( rc==SQLITE_OK ){
160634        rc = nodeWrite(pRtree, pNode);
160635      }
160636      nodeHashDelete(pRtree, pNode);
160637      sqlite3_free(pNode);
160638    }
160639  }
160640  return rc;
160641}
160642
160643/*
160644** Return the 64-bit integer value associated with cell iCell of
160645** node pNode. If pNode is a leaf node, this is a rowid. If it is
160646** an internal node, then the 64-bit integer is a child page number.
160647*/
160648static i64 nodeGetRowid(
160649  Rtree *pRtree,       /* The overall R-Tree */
160650  RtreeNode *pNode,    /* The node from which to extract the ID */
160651  int iCell            /* The cell index from which to extract the ID */
160652){
160653  assert( iCell<NCELL(pNode) );
160654  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
160655}
160656
160657/*
160658** Return coordinate iCoord from cell iCell in node pNode.
160659*/
160660static void nodeGetCoord(
160661  Rtree *pRtree,               /* The overall R-Tree */
160662  RtreeNode *pNode,            /* The node from which to extract a coordinate */
160663  int iCell,                   /* The index of the cell within the node */
160664  int iCoord,                  /* Which coordinate to extract */
160665  RtreeCoord *pCoord           /* OUT: Space to write result to */
160666){
160667  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
160668}
160669
160670/*
160671** Deserialize cell iCell of node pNode. Populate the structure pointed
160672** to by pCell with the results.
160673*/
160674static void nodeGetCell(
160675  Rtree *pRtree,               /* The overall R-Tree */
160676  RtreeNode *pNode,            /* The node containing the cell to be read */
160677  int iCell,                   /* Index of the cell within the node */
160678  RtreeCell *pCell             /* OUT: Write the cell contents here */
160679){
160680  u8 *pData;
160681  RtreeCoord *pCoord;
160682  int ii;
160683  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
160684  pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
160685  pCoord = pCell->aCoord;
160686  for(ii=0; ii<pRtree->nDim*2; ii++){
160687    readCoord(&pData[ii*4], &pCoord[ii]);
160688  }
160689}
160690
160691
160692/* Forward declaration for the function that does the work of
160693** the virtual table module xCreate() and xConnect() methods.
160694*/
160695static int rtreeInit(
160696  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
160697);
160698
160699/*
160700** Rtree virtual table module xCreate method.
160701*/
160702static int rtreeCreate(
160703  sqlite3 *db,
160704  void *pAux,
160705  int argc, const char *const*argv,
160706  sqlite3_vtab **ppVtab,
160707  char **pzErr
160708){
160709  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
160710}
160711
160712/*
160713** Rtree virtual table module xConnect method.
160714*/
160715static int rtreeConnect(
160716  sqlite3 *db,
160717  void *pAux,
160718  int argc, const char *const*argv,
160719  sqlite3_vtab **ppVtab,
160720  char **pzErr
160721){
160722  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
160723}
160724
160725/*
160726** Increment the r-tree reference count.
160727*/
160728static void rtreeReference(Rtree *pRtree){
160729  pRtree->nBusy++;
160730}
160731
160732/*
160733** Decrement the r-tree reference count. When the reference count reaches
160734** zero the structure is deleted.
160735*/
160736static void rtreeRelease(Rtree *pRtree){
160737  pRtree->nBusy--;
160738  if( pRtree->nBusy==0 ){
160739    sqlite3_finalize(pRtree->pReadNode);
160740    sqlite3_finalize(pRtree->pWriteNode);
160741    sqlite3_finalize(pRtree->pDeleteNode);
160742    sqlite3_finalize(pRtree->pReadRowid);
160743    sqlite3_finalize(pRtree->pWriteRowid);
160744    sqlite3_finalize(pRtree->pDeleteRowid);
160745    sqlite3_finalize(pRtree->pReadParent);
160746    sqlite3_finalize(pRtree->pWriteParent);
160747    sqlite3_finalize(pRtree->pDeleteParent);
160748    sqlite3_free(pRtree);
160749  }
160750}
160751
160752/*
160753** Rtree virtual table module xDisconnect method.
160754*/
160755static int rtreeDisconnect(sqlite3_vtab *pVtab){
160756  rtreeRelease((Rtree *)pVtab);
160757  return SQLITE_OK;
160758}
160759
160760/*
160761** Rtree virtual table module xDestroy method.
160762*/
160763static int rtreeDestroy(sqlite3_vtab *pVtab){
160764  Rtree *pRtree = (Rtree *)pVtab;
160765  int rc;
160766  char *zCreate = sqlite3_mprintf(
160767    "DROP TABLE '%q'.'%q_node';"
160768    "DROP TABLE '%q'.'%q_rowid';"
160769    "DROP TABLE '%q'.'%q_parent';",
160770    pRtree->zDb, pRtree->zName,
160771    pRtree->zDb, pRtree->zName,
160772    pRtree->zDb, pRtree->zName
160773  );
160774  if( !zCreate ){
160775    rc = SQLITE_NOMEM;
160776  }else{
160777    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
160778    sqlite3_free(zCreate);
160779  }
160780  if( rc==SQLITE_OK ){
160781    rtreeRelease(pRtree);
160782  }
160783
160784  return rc;
160785}
160786
160787/*
160788** Rtree virtual table module xOpen method.
160789*/
160790static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
160791  int rc = SQLITE_NOMEM;
160792  RtreeCursor *pCsr;
160793
160794  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
160795  if( pCsr ){
160796    memset(pCsr, 0, sizeof(RtreeCursor));
160797    pCsr->base.pVtab = pVTab;
160798    rc = SQLITE_OK;
160799  }
160800  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
160801
160802  return rc;
160803}
160804
160805
160806/*
160807** Free the RtreeCursor.aConstraint[] array and its contents.
160808*/
160809static void freeCursorConstraints(RtreeCursor *pCsr){
160810  if( pCsr->aConstraint ){
160811    int i;                        /* Used to iterate through constraint array */
160812    for(i=0; i<pCsr->nConstraint; i++){
160813      sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
160814      if( pInfo ){
160815        if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
160816        sqlite3_free(pInfo);
160817      }
160818    }
160819    sqlite3_free(pCsr->aConstraint);
160820    pCsr->aConstraint = 0;
160821  }
160822}
160823
160824/*
160825** Rtree virtual table module xClose method.
160826*/
160827static int rtreeClose(sqlite3_vtab_cursor *cur){
160828  Rtree *pRtree = (Rtree *)(cur->pVtab);
160829  int ii;
160830  RtreeCursor *pCsr = (RtreeCursor *)cur;
160831  freeCursorConstraints(pCsr);
160832  sqlite3_free(pCsr->aPoint);
160833  for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
160834  sqlite3_free(pCsr);
160835  return SQLITE_OK;
160836}
160837
160838/*
160839** Rtree virtual table module xEof method.
160840**
160841** Return non-zero if the cursor does not currently point to a valid
160842** record (i.e if the scan has finished), or zero otherwise.
160843*/
160844static int rtreeEof(sqlite3_vtab_cursor *cur){
160845  RtreeCursor *pCsr = (RtreeCursor *)cur;
160846  return pCsr->atEOF;
160847}
160848
160849/*
160850** Convert raw bits from the on-disk RTree record into a coordinate value.
160851** The on-disk format is big-endian and needs to be converted for little-
160852** endian platforms.  The on-disk record stores integer coordinates if
160853** eInt is true and it stores 32-bit floating point records if eInt is
160854** false.  a[] is the four bytes of the on-disk record to be decoded.
160855** Store the results in "r".
160856**
160857** There are three versions of this macro, one each for little-endian and
160858** big-endian processors and a third generic implementation.  The endian-
160859** specific implementations are much faster and are preferred if the
160860** processor endianness is known at compile-time.  The SQLITE_BYTEORDER
160861** macro is part of sqliteInt.h and hence the endian-specific
160862** implementation will only be used if this module is compiled as part
160863** of the amalgamation.
160864*/
160865#if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
160866#define RTREE_DECODE_COORD(eInt, a, r) {                        \
160867    RtreeCoord c;    /* Coordinate decoded */                   \
160868    memcpy(&c.u,a,4);                                           \
160869    c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
160870          ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
160871    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
160872}
160873#elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
160874#define RTREE_DECODE_COORD(eInt, a, r) {                        \
160875    RtreeCoord c;    /* Coordinate decoded */                   \
160876    memcpy(&c.u,a,4);                                           \
160877    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
160878}
160879#else
160880#define RTREE_DECODE_COORD(eInt, a, r) {                        \
160881    RtreeCoord c;    /* Coordinate decoded */                   \
160882    c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
160883           +((u32)a[2]<<8) + a[3];                              \
160884    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
160885}
160886#endif
160887
160888/*
160889** Check the RTree node or entry given by pCellData and p against the MATCH
160890** constraint pConstraint.
160891*/
160892static int rtreeCallbackConstraint(
160893  RtreeConstraint *pConstraint,  /* The constraint to test */
160894  int eInt,                      /* True if RTree holding integer coordinates */
160895  u8 *pCellData,                 /* Raw cell content */
160896  RtreeSearchPoint *pSearch,     /* Container of this cell */
160897  sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
160898  int *peWithin                  /* OUT: visibility of the cell */
160899){
160900  int i;                                                /* Loop counter */
160901  sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
160902  int nCoord = pInfo->nCoord;                           /* No. of coordinates */
160903  int rc;                                             /* Callback return code */
160904  sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
160905
160906  assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
160907  assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
160908
160909  if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
160910    pInfo->iRowid = readInt64(pCellData);
160911  }
160912  pCellData += 8;
160913  for(i=0; i<nCoord; i++, pCellData += 4){
160914    RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
160915  }
160916  if( pConstraint->op==RTREE_MATCH ){
160917    rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
160918                              nCoord, aCoord, &i);
160919    if( i==0 ) *peWithin = NOT_WITHIN;
160920    *prScore = RTREE_ZERO;
160921  }else{
160922    pInfo->aCoord = aCoord;
160923    pInfo->iLevel = pSearch->iLevel - 1;
160924    pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
160925    pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
160926    rc = pConstraint->u.xQueryFunc(pInfo);
160927    if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
160928    if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
160929      *prScore = pInfo->rScore;
160930    }
160931  }
160932  return rc;
160933}
160934
160935/*
160936** Check the internal RTree node given by pCellData against constraint p.
160937** If this constraint cannot be satisfied by any child within the node,
160938** set *peWithin to NOT_WITHIN.
160939*/
160940static void rtreeNonleafConstraint(
160941  RtreeConstraint *p,        /* The constraint to test */
160942  int eInt,                  /* True if RTree holds integer coordinates */
160943  u8 *pCellData,             /* Raw cell content as appears on disk */
160944  int *peWithin              /* Adjust downward, as appropriate */
160945){
160946  sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
160947
160948  /* p->iCoord might point to either a lower or upper bound coordinate
160949  ** in a coordinate pair.  But make pCellData point to the lower bound.
160950  */
160951  pCellData += 8 + 4*(p->iCoord&0xfe);
160952
160953  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
160954      || p->op==RTREE_GT || p->op==RTREE_EQ );
160955  switch( p->op ){
160956    case RTREE_LE:
160957    case RTREE_LT:
160958    case RTREE_EQ:
160959      RTREE_DECODE_COORD(eInt, pCellData, val);
160960      /* val now holds the lower bound of the coordinate pair */
160961      if( p->u.rValue>=val ) return;
160962      if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
160963      /* Fall through for the RTREE_EQ case */
160964
160965    default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
160966      pCellData += 4;
160967      RTREE_DECODE_COORD(eInt, pCellData, val);
160968      /* val now holds the upper bound of the coordinate pair */
160969      if( p->u.rValue<=val ) return;
160970  }
160971  *peWithin = NOT_WITHIN;
160972}
160973
160974/*
160975** Check the leaf RTree cell given by pCellData against constraint p.
160976** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
160977** If the constraint is satisfied, leave *peWithin unchanged.
160978**
160979** The constraint is of the form:  xN op $val
160980**
160981** The op is given by p->op.  The xN is p->iCoord-th coordinate in
160982** pCellData.  $val is given by p->u.rValue.
160983*/
160984static void rtreeLeafConstraint(
160985  RtreeConstraint *p,        /* The constraint to test */
160986  int eInt,                  /* True if RTree holds integer coordinates */
160987  u8 *pCellData,             /* Raw cell content as appears on disk */
160988  int *peWithin              /* Adjust downward, as appropriate */
160989){
160990  RtreeDValue xN;      /* Coordinate value converted to a double */
160991
160992  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
160993      || p->op==RTREE_GT || p->op==RTREE_EQ );
160994  pCellData += 8 + p->iCoord*4;
160995  RTREE_DECODE_COORD(eInt, pCellData, xN);
160996  switch( p->op ){
160997    case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
160998    case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
160999    case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
161000    case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
161001    default:       if( xN == p->u.rValue ) return;  break;
161002  }
161003  *peWithin = NOT_WITHIN;
161004}
161005
161006/*
161007** One of the cells in node pNode is guaranteed to have a 64-bit
161008** integer value equal to iRowid. Return the index of this cell.
161009*/
161010static int nodeRowidIndex(
161011  Rtree *pRtree,
161012  RtreeNode *pNode,
161013  i64 iRowid,
161014  int *piIndex
161015){
161016  int ii;
161017  int nCell = NCELL(pNode);
161018  assert( nCell<200 );
161019  for(ii=0; ii<nCell; ii++){
161020    if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
161021      *piIndex = ii;
161022      return SQLITE_OK;
161023    }
161024  }
161025  return SQLITE_CORRUPT_VTAB;
161026}
161027
161028/*
161029** Return the index of the cell containing a pointer to node pNode
161030** in its parent. If pNode is the root node, return -1.
161031*/
161032static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
161033  RtreeNode *pParent = pNode->pParent;
161034  if( pParent ){
161035    return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
161036  }
161037  *piIndex = -1;
161038  return SQLITE_OK;
161039}
161040
161041/*
161042** Compare two search points.  Return negative, zero, or positive if the first
161043** is less than, equal to, or greater than the second.
161044**
161045** The rScore is the primary key.  Smaller rScore values come first.
161046** If the rScore is a tie, then use iLevel as the tie breaker with smaller
161047** iLevel values coming first.  In this way, if rScore is the same for all
161048** SearchPoints, then iLevel becomes the deciding factor and the result
161049** is a depth-first search, which is the desired default behavior.
161050*/
161051static int rtreeSearchPointCompare(
161052  const RtreeSearchPoint *pA,
161053  const RtreeSearchPoint *pB
161054){
161055  if( pA->rScore<pB->rScore ) return -1;
161056  if( pA->rScore>pB->rScore ) return +1;
161057  if( pA->iLevel<pB->iLevel ) return -1;
161058  if( pA->iLevel>pB->iLevel ) return +1;
161059  return 0;
161060}
161061
161062/*
161063** Interchange to search points in a cursor.
161064*/
161065static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
161066  RtreeSearchPoint t = p->aPoint[i];
161067  assert( i<j );
161068  p->aPoint[i] = p->aPoint[j];
161069  p->aPoint[j] = t;
161070  i++; j++;
161071  if( i<RTREE_CACHE_SZ ){
161072    if( j>=RTREE_CACHE_SZ ){
161073      nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
161074      p->aNode[i] = 0;
161075    }else{
161076      RtreeNode *pTemp = p->aNode[i];
161077      p->aNode[i] = p->aNode[j];
161078      p->aNode[j] = pTemp;
161079    }
161080  }
161081}
161082
161083/*
161084** Return the search point with the lowest current score.
161085*/
161086static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
161087  return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
161088}
161089
161090/*
161091** Get the RtreeNode for the search point with the lowest score.
161092*/
161093static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
161094  sqlite3_int64 id;
161095  int ii = 1 - pCur->bPoint;
161096  assert( ii==0 || ii==1 );
161097  assert( pCur->bPoint || pCur->nPoint );
161098  if( pCur->aNode[ii]==0 ){
161099    assert( pRC!=0 );
161100    id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
161101    *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
161102  }
161103  return pCur->aNode[ii];
161104}
161105
161106/*
161107** Push a new element onto the priority queue
161108*/
161109static RtreeSearchPoint *rtreeEnqueue(
161110  RtreeCursor *pCur,    /* The cursor */
161111  RtreeDValue rScore,   /* Score for the new search point */
161112  u8 iLevel             /* Level for the new search point */
161113){
161114  int i, j;
161115  RtreeSearchPoint *pNew;
161116  if( pCur->nPoint>=pCur->nPointAlloc ){
161117    int nNew = pCur->nPointAlloc*2 + 8;
161118    pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
161119    if( pNew==0 ) return 0;
161120    pCur->aPoint = pNew;
161121    pCur->nPointAlloc = nNew;
161122  }
161123  i = pCur->nPoint++;
161124  pNew = pCur->aPoint + i;
161125  pNew->rScore = rScore;
161126  pNew->iLevel = iLevel;
161127  assert( iLevel<=RTREE_MAX_DEPTH );
161128  while( i>0 ){
161129    RtreeSearchPoint *pParent;
161130    j = (i-1)/2;
161131    pParent = pCur->aPoint + j;
161132    if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
161133    rtreeSearchPointSwap(pCur, j, i);
161134    i = j;
161135    pNew = pParent;
161136  }
161137  return pNew;
161138}
161139
161140/*
161141** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
161142** NULL if malloc fails.
161143*/
161144static RtreeSearchPoint *rtreeSearchPointNew(
161145  RtreeCursor *pCur,    /* The cursor */
161146  RtreeDValue rScore,   /* Score for the new search point */
161147  u8 iLevel             /* Level for the new search point */
161148){
161149  RtreeSearchPoint *pNew, *pFirst;
161150  pFirst = rtreeSearchPointFirst(pCur);
161151  pCur->anQueue[iLevel]++;
161152  if( pFirst==0
161153   || pFirst->rScore>rScore
161154   || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
161155  ){
161156    if( pCur->bPoint ){
161157      int ii;
161158      pNew = rtreeEnqueue(pCur, rScore, iLevel);
161159      if( pNew==0 ) return 0;
161160      ii = (int)(pNew - pCur->aPoint) + 1;
161161      if( ii<RTREE_CACHE_SZ ){
161162        assert( pCur->aNode[ii]==0 );
161163        pCur->aNode[ii] = pCur->aNode[0];
161164       }else{
161165        nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
161166      }
161167      pCur->aNode[0] = 0;
161168      *pNew = pCur->sPoint;
161169    }
161170    pCur->sPoint.rScore = rScore;
161171    pCur->sPoint.iLevel = iLevel;
161172    pCur->bPoint = 1;
161173    return &pCur->sPoint;
161174  }else{
161175    return rtreeEnqueue(pCur, rScore, iLevel);
161176  }
161177}
161178
161179#if 0
161180/* Tracing routines for the RtreeSearchPoint queue */
161181static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
161182  if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
161183  printf(" %d.%05lld.%02d %g %d",
161184    p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
161185  );
161186  idx++;
161187  if( idx<RTREE_CACHE_SZ ){
161188    printf(" %p\n", pCur->aNode[idx]);
161189  }else{
161190    printf("\n");
161191  }
161192}
161193static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
161194  int ii;
161195  printf("=== %9s ", zPrefix);
161196  if( pCur->bPoint ){
161197    tracePoint(&pCur->sPoint, -1, pCur);
161198  }
161199  for(ii=0; ii<pCur->nPoint; ii++){
161200    if( ii>0 || pCur->bPoint ) printf("              ");
161201    tracePoint(&pCur->aPoint[ii], ii, pCur);
161202  }
161203}
161204# define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
161205#else
161206# define RTREE_QUEUE_TRACE(A,B)   /* no-op */
161207#endif
161208
161209/* Remove the search point with the lowest current score.
161210*/
161211static void rtreeSearchPointPop(RtreeCursor *p){
161212  int i, j, k, n;
161213  i = 1 - p->bPoint;
161214  assert( i==0 || i==1 );
161215  if( p->aNode[i] ){
161216    nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
161217    p->aNode[i] = 0;
161218  }
161219  if( p->bPoint ){
161220    p->anQueue[p->sPoint.iLevel]--;
161221    p->bPoint = 0;
161222  }else if( p->nPoint ){
161223    p->anQueue[p->aPoint[0].iLevel]--;
161224    n = --p->nPoint;
161225    p->aPoint[0] = p->aPoint[n];
161226    if( n<RTREE_CACHE_SZ-1 ){
161227      p->aNode[1] = p->aNode[n+1];
161228      p->aNode[n+1] = 0;
161229    }
161230    i = 0;
161231    while( (j = i*2+1)<n ){
161232      k = j+1;
161233      if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
161234        if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
161235          rtreeSearchPointSwap(p, i, k);
161236          i = k;
161237        }else{
161238          break;
161239        }
161240      }else{
161241        if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
161242          rtreeSearchPointSwap(p, i, j);
161243          i = j;
161244        }else{
161245          break;
161246        }
161247      }
161248    }
161249  }
161250}
161251
161252
161253/*
161254** Continue the search on cursor pCur until the front of the queue
161255** contains an entry suitable for returning as a result-set row,
161256** or until the RtreeSearchPoint queue is empty, indicating that the
161257** query has completed.
161258*/
161259static int rtreeStepToLeaf(RtreeCursor *pCur){
161260  RtreeSearchPoint *p;
161261  Rtree *pRtree = RTREE_OF_CURSOR(pCur);
161262  RtreeNode *pNode;
161263  int eWithin;
161264  int rc = SQLITE_OK;
161265  int nCell;
161266  int nConstraint = pCur->nConstraint;
161267  int ii;
161268  int eInt;
161269  RtreeSearchPoint x;
161270
161271  eInt = pRtree->eCoordType==RTREE_COORD_INT32;
161272  while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
161273    pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
161274    if( rc ) return rc;
161275    nCell = NCELL(pNode);
161276    assert( nCell<200 );
161277    while( p->iCell<nCell ){
161278      sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
161279      u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
161280      eWithin = FULLY_WITHIN;
161281      for(ii=0; ii<nConstraint; ii++){
161282        RtreeConstraint *pConstraint = pCur->aConstraint + ii;
161283        if( pConstraint->op>=RTREE_MATCH ){
161284          rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
161285                                       &rScore, &eWithin);
161286          if( rc ) return rc;
161287        }else if( p->iLevel==1 ){
161288          rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
161289        }else{
161290          rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
161291        }
161292        if( eWithin==NOT_WITHIN ) break;
161293      }
161294      p->iCell++;
161295      if( eWithin==NOT_WITHIN ) continue;
161296      x.iLevel = p->iLevel - 1;
161297      if( x.iLevel ){
161298        x.id = readInt64(pCellData);
161299        x.iCell = 0;
161300      }else{
161301        x.id = p->id;
161302        x.iCell = p->iCell - 1;
161303      }
161304      if( p->iCell>=nCell ){
161305        RTREE_QUEUE_TRACE(pCur, "POP-S:");
161306        rtreeSearchPointPop(pCur);
161307      }
161308      if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
161309      p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
161310      if( p==0 ) return SQLITE_NOMEM;
161311      p->eWithin = eWithin;
161312      p->id = x.id;
161313      p->iCell = x.iCell;
161314      RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
161315      break;
161316    }
161317    if( p->iCell>=nCell ){
161318      RTREE_QUEUE_TRACE(pCur, "POP-Se:");
161319      rtreeSearchPointPop(pCur);
161320    }
161321  }
161322  pCur->atEOF = p==0;
161323  return SQLITE_OK;
161324}
161325
161326/*
161327** Rtree virtual table module xNext method.
161328*/
161329static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
161330  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
161331  int rc = SQLITE_OK;
161332
161333  /* Move to the next entry that matches the configured constraints. */
161334  RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
161335  rtreeSearchPointPop(pCsr);
161336  rc = rtreeStepToLeaf(pCsr);
161337  return rc;
161338}
161339
161340/*
161341** Rtree virtual table module xRowid method.
161342*/
161343static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
161344  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
161345  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
161346  int rc = SQLITE_OK;
161347  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
161348  if( rc==SQLITE_OK && p ){
161349    *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
161350  }
161351  return rc;
161352}
161353
161354/*
161355** Rtree virtual table module xColumn method.
161356*/
161357static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
161358  Rtree *pRtree = (Rtree *)cur->pVtab;
161359  RtreeCursor *pCsr = (RtreeCursor *)cur;
161360  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
161361  RtreeCoord c;
161362  int rc = SQLITE_OK;
161363  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
161364
161365  if( rc ) return rc;
161366  if( p==0 ) return SQLITE_OK;
161367  if( i==0 ){
161368    sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
161369  }else{
161370    if( rc ) return rc;
161371    nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
161372#ifndef SQLITE_RTREE_INT_ONLY
161373    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
161374      sqlite3_result_double(ctx, c.f);
161375    }else
161376#endif
161377    {
161378      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
161379      sqlite3_result_int(ctx, c.i);
161380    }
161381  }
161382  return SQLITE_OK;
161383}
161384
161385/*
161386** Use nodeAcquire() to obtain the leaf node containing the record with
161387** rowid iRowid. If successful, set *ppLeaf to point to the node and
161388** return SQLITE_OK. If there is no such record in the table, set
161389** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
161390** to zero and return an SQLite error code.
161391*/
161392static int findLeafNode(
161393  Rtree *pRtree,              /* RTree to search */
161394  i64 iRowid,                 /* The rowid searching for */
161395  RtreeNode **ppLeaf,         /* Write the node here */
161396  sqlite3_int64 *piNode       /* Write the node-id here */
161397){
161398  int rc;
161399  *ppLeaf = 0;
161400  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
161401  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
161402    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
161403    if( piNode ) *piNode = iNode;
161404    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
161405    sqlite3_reset(pRtree->pReadRowid);
161406  }else{
161407    rc = sqlite3_reset(pRtree->pReadRowid);
161408  }
161409  return rc;
161410}
161411
161412/*
161413** This function is called to configure the RtreeConstraint object passed
161414** as the second argument for a MATCH constraint. The value passed as the
161415** first argument to this function is the right-hand operand to the MATCH
161416** operator.
161417*/
161418static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
161419  RtreeMatchArg *pBlob;              /* BLOB returned by geometry function */
161420  sqlite3_rtree_query_info *pInfo;   /* Callback information */
161421  int nBlob;                         /* Size of the geometry function blob */
161422  int nExpected;                     /* Expected size of the BLOB */
161423
161424  /* Check that value is actually a blob. */
161425  if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
161426
161427  /* Check that the blob is roughly the right size. */
161428  nBlob = sqlite3_value_bytes(pValue);
161429  if( nBlob<(int)sizeof(RtreeMatchArg) ){
161430    return SQLITE_ERROR;
161431  }
161432
161433  pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
161434  if( !pInfo ) return SQLITE_NOMEM;
161435  memset(pInfo, 0, sizeof(*pInfo));
161436  pBlob = (RtreeMatchArg*)&pInfo[1];
161437
161438  memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
161439  nExpected = (int)(sizeof(RtreeMatchArg) +
161440                    pBlob->nParam*sizeof(sqlite3_value*) +
161441                    (pBlob->nParam-1)*sizeof(RtreeDValue));
161442  if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
161443    sqlite3_free(pInfo);
161444    return SQLITE_ERROR;
161445  }
161446  pInfo->pContext = pBlob->cb.pContext;
161447  pInfo->nParam = pBlob->nParam;
161448  pInfo->aParam = pBlob->aParam;
161449  pInfo->apSqlParam = pBlob->apSqlParam;
161450
161451  if( pBlob->cb.xGeom ){
161452    pCons->u.xGeom = pBlob->cb.xGeom;
161453  }else{
161454    pCons->op = RTREE_QUERY;
161455    pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
161456  }
161457  pCons->pInfo = pInfo;
161458  return SQLITE_OK;
161459}
161460
161461/*
161462** Rtree virtual table module xFilter method.
161463*/
161464static int rtreeFilter(
161465  sqlite3_vtab_cursor *pVtabCursor,
161466  int idxNum, const char *idxStr,
161467  int argc, sqlite3_value **argv
161468){
161469  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
161470  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
161471  RtreeNode *pRoot = 0;
161472  int ii;
161473  int rc = SQLITE_OK;
161474  int iCell = 0;
161475
161476  rtreeReference(pRtree);
161477
161478  /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
161479  freeCursorConstraints(pCsr);
161480  sqlite3_free(pCsr->aPoint);
161481  memset(pCsr, 0, sizeof(RtreeCursor));
161482  pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
161483
161484  pCsr->iStrategy = idxNum;
161485  if( idxNum==1 ){
161486    /* Special case - lookup by rowid. */
161487    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
161488    RtreeSearchPoint *p;     /* Search point for the the leaf */
161489    i64 iRowid = sqlite3_value_int64(argv[0]);
161490    i64 iNode = 0;
161491    rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
161492    if( rc==SQLITE_OK && pLeaf!=0 ){
161493      p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
161494      assert( p!=0 );  /* Always returns pCsr->sPoint */
161495      pCsr->aNode[0] = pLeaf;
161496      p->id = iNode;
161497      p->eWithin = PARTLY_WITHIN;
161498      rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
161499      p->iCell = iCell;
161500      RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
161501    }else{
161502      pCsr->atEOF = 1;
161503    }
161504  }else{
161505    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
161506    ** with the configured constraints.
161507    */
161508    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
161509    if( rc==SQLITE_OK && argc>0 ){
161510      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
161511      pCsr->nConstraint = argc;
161512      if( !pCsr->aConstraint ){
161513        rc = SQLITE_NOMEM;
161514      }else{
161515        memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
161516        memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
161517        assert( (idxStr==0 && argc==0)
161518                || (idxStr && (int)strlen(idxStr)==argc*2) );
161519        for(ii=0; ii<argc; ii++){
161520          RtreeConstraint *p = &pCsr->aConstraint[ii];
161521          p->op = idxStr[ii*2];
161522          p->iCoord = idxStr[ii*2+1]-'0';
161523          if( p->op>=RTREE_MATCH ){
161524            /* A MATCH operator. The right-hand-side must be a blob that
161525            ** can be cast into an RtreeMatchArg object. One created using
161526            ** an sqlite3_rtree_geometry_callback() SQL user function.
161527            */
161528            rc = deserializeGeometry(argv[ii], p);
161529            if( rc!=SQLITE_OK ){
161530              break;
161531            }
161532            p->pInfo->nCoord = pRtree->nDim*2;
161533            p->pInfo->anQueue = pCsr->anQueue;
161534            p->pInfo->mxLevel = pRtree->iDepth + 1;
161535          }else{
161536#ifdef SQLITE_RTREE_INT_ONLY
161537            p->u.rValue = sqlite3_value_int64(argv[ii]);
161538#else
161539            p->u.rValue = sqlite3_value_double(argv[ii]);
161540#endif
161541          }
161542        }
161543      }
161544    }
161545    if( rc==SQLITE_OK ){
161546      RtreeSearchPoint *pNew;
161547      pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
161548      if( pNew==0 ) return SQLITE_NOMEM;
161549      pNew->id = 1;
161550      pNew->iCell = 0;
161551      pNew->eWithin = PARTLY_WITHIN;
161552      assert( pCsr->bPoint==1 );
161553      pCsr->aNode[0] = pRoot;
161554      pRoot = 0;
161555      RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
161556      rc = rtreeStepToLeaf(pCsr);
161557    }
161558  }
161559
161560  nodeRelease(pRtree, pRoot);
161561  rtreeRelease(pRtree);
161562  return rc;
161563}
161564
161565/*
161566** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
161567** extension is currently being used by a version of SQLite too old to
161568** support estimatedRows. In that case this function is a no-op.
161569*/
161570static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
161571#if SQLITE_VERSION_NUMBER>=3008002
161572  if( sqlite3_libversion_number()>=3008002 ){
161573    pIdxInfo->estimatedRows = nRow;
161574  }
161575#endif
161576}
161577
161578/*
161579** Rtree virtual table module xBestIndex method. There are three
161580** table scan strategies to choose from (in order from most to
161581** least desirable):
161582**
161583**   idxNum     idxStr        Strategy
161584**   ------------------------------------------------
161585**     1        Unused        Direct lookup by rowid.
161586**     2        See below     R-tree query or full-table scan.
161587**   ------------------------------------------------
161588**
161589** If strategy 1 is used, then idxStr is not meaningful. If strategy
161590** 2 is used, idxStr is formatted to contain 2 bytes for each
161591** constraint used. The first two bytes of idxStr correspond to
161592** the constraint in sqlite3_index_info.aConstraintUsage[] with
161593** (argvIndex==1) etc.
161594**
161595** The first of each pair of bytes in idxStr identifies the constraint
161596** operator as follows:
161597**
161598**   Operator    Byte Value
161599**   ----------------------
161600**      =        0x41 ('A')
161601**     <=        0x42 ('B')
161602**      <        0x43 ('C')
161603**     >=        0x44 ('D')
161604**      >        0x45 ('E')
161605**   MATCH       0x46 ('F')
161606**   ----------------------
161607**
161608** The second of each pair of bytes identifies the coordinate column
161609** to which the constraint applies. The leftmost coordinate column
161610** is 'a', the second from the left 'b' etc.
161611*/
161612static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
161613  Rtree *pRtree = (Rtree*)tab;
161614  int rc = SQLITE_OK;
161615  int ii;
161616  int bMatch = 0;                 /* True if there exists a MATCH constraint */
161617  i64 nRow;                       /* Estimated rows returned by this scan */
161618
161619  int iIdx = 0;
161620  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
161621  memset(zIdxStr, 0, sizeof(zIdxStr));
161622
161623  /* Check if there exists a MATCH constraint - even an unusable one. If there
161624  ** is, do not consider the lookup-by-rowid plan as using such a plan would
161625  ** require the VDBE to evaluate the MATCH constraint, which is not currently
161626  ** possible. */
161627  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
161628    if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
161629      bMatch = 1;
161630    }
161631  }
161632
161633  assert( pIdxInfo->idxStr==0 );
161634  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
161635    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
161636
161637    if( bMatch==0 && p->usable
161638     && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
161639    ){
161640      /* We have an equality constraint on the rowid. Use strategy 1. */
161641      int jj;
161642      for(jj=0; jj<ii; jj++){
161643        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
161644        pIdxInfo->aConstraintUsage[jj].omit = 0;
161645      }
161646      pIdxInfo->idxNum = 1;
161647      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
161648      pIdxInfo->aConstraintUsage[jj].omit = 1;
161649
161650      /* This strategy involves a two rowid lookups on an B-Tree structures
161651      ** and then a linear search of an R-Tree node. This should be
161652      ** considered almost as quick as a direct rowid lookup (for which
161653      ** sqlite uses an internal cost of 0.0). It is expected to return
161654      ** a single row.
161655      */
161656      pIdxInfo->estimatedCost = 30.0;
161657      setEstimatedRows(pIdxInfo, 1);
161658      return SQLITE_OK;
161659    }
161660
161661    if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
161662      u8 op;
161663      switch( p->op ){
161664        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
161665        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
161666        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
161667        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
161668        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
161669        default:
161670          assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
161671          op = RTREE_MATCH;
161672          break;
161673      }
161674      zIdxStr[iIdx++] = op;
161675      zIdxStr[iIdx++] = p->iColumn - 1 + '0';
161676      pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
161677      pIdxInfo->aConstraintUsage[ii].omit = 1;
161678    }
161679  }
161680
161681  pIdxInfo->idxNum = 2;
161682  pIdxInfo->needToFreeIdxStr = 1;
161683  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
161684    return SQLITE_NOMEM;
161685  }
161686
161687  nRow = pRtree->nRowEst >> (iIdx/2);
161688  pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
161689  setEstimatedRows(pIdxInfo, nRow);
161690
161691  return rc;
161692}
161693
161694/*
161695** Return the N-dimensional volumn of the cell stored in *p.
161696*/
161697static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
161698  RtreeDValue area = (RtreeDValue)1;
161699  int ii;
161700  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
161701    area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
161702  }
161703  return area;
161704}
161705
161706/*
161707** Return the margin length of cell p. The margin length is the sum
161708** of the objects size in each dimension.
161709*/
161710static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
161711  RtreeDValue margin = (RtreeDValue)0;
161712  int ii;
161713  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
161714    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
161715  }
161716  return margin;
161717}
161718
161719/*
161720** Store the union of cells p1 and p2 in p1.
161721*/
161722static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
161723  int ii;
161724  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
161725    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
161726      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
161727      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
161728    }
161729  }else{
161730    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
161731      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
161732      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
161733    }
161734  }
161735}
161736
161737/*
161738** Return true if the area covered by p2 is a subset of the area covered
161739** by p1. False otherwise.
161740*/
161741static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
161742  int ii;
161743  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
161744  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
161745    RtreeCoord *a1 = &p1->aCoord[ii];
161746    RtreeCoord *a2 = &p2->aCoord[ii];
161747    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
161748     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
161749    ){
161750      return 0;
161751    }
161752  }
161753  return 1;
161754}
161755
161756/*
161757** Return the amount cell p would grow by if it were unioned with pCell.
161758*/
161759static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
161760  RtreeDValue area;
161761  RtreeCell cell;
161762  memcpy(&cell, p, sizeof(RtreeCell));
161763  area = cellArea(pRtree, &cell);
161764  cellUnion(pRtree, &cell, pCell);
161765  return (cellArea(pRtree, &cell)-area);
161766}
161767
161768static RtreeDValue cellOverlap(
161769  Rtree *pRtree,
161770  RtreeCell *p,
161771  RtreeCell *aCell,
161772  int nCell
161773){
161774  int ii;
161775  RtreeDValue overlap = RTREE_ZERO;
161776  for(ii=0; ii<nCell; ii++){
161777    int jj;
161778    RtreeDValue o = (RtreeDValue)1;
161779    for(jj=0; jj<(pRtree->nDim*2); jj+=2){
161780      RtreeDValue x1, x2;
161781      x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
161782      x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
161783      if( x2<x1 ){
161784        o = (RtreeDValue)0;
161785        break;
161786      }else{
161787        o = o * (x2-x1);
161788      }
161789    }
161790    overlap += o;
161791  }
161792  return overlap;
161793}
161794
161795
161796/*
161797** This function implements the ChooseLeaf algorithm from Gutman[84].
161798** ChooseSubTree in r*tree terminology.
161799*/
161800static int ChooseLeaf(
161801  Rtree *pRtree,               /* Rtree table */
161802  RtreeCell *pCell,            /* Cell to insert into rtree */
161803  int iHeight,                 /* Height of sub-tree rooted at pCell */
161804  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
161805){
161806  int rc;
161807  int ii;
161808  RtreeNode *pNode;
161809  rc = nodeAcquire(pRtree, 1, 0, &pNode);
161810
161811  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
161812    int iCell;
161813    sqlite3_int64 iBest = 0;
161814
161815    RtreeDValue fMinGrowth = RTREE_ZERO;
161816    RtreeDValue fMinArea = RTREE_ZERO;
161817
161818    int nCell = NCELL(pNode);
161819    RtreeCell cell;
161820    RtreeNode *pChild;
161821
161822    RtreeCell *aCell = 0;
161823
161824    /* Select the child node which will be enlarged the least if pCell
161825    ** is inserted into it. Resolve ties by choosing the entry with
161826    ** the smallest area.
161827    */
161828    for(iCell=0; iCell<nCell; iCell++){
161829      int bBest = 0;
161830      RtreeDValue growth;
161831      RtreeDValue area;
161832      nodeGetCell(pRtree, pNode, iCell, &cell);
161833      growth = cellGrowth(pRtree, &cell, pCell);
161834      area = cellArea(pRtree, &cell);
161835      if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
161836        bBest = 1;
161837      }
161838      if( bBest ){
161839        fMinGrowth = growth;
161840        fMinArea = area;
161841        iBest = cell.iRowid;
161842      }
161843    }
161844
161845    sqlite3_free(aCell);
161846    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
161847    nodeRelease(pRtree, pNode);
161848    pNode = pChild;
161849  }
161850
161851  *ppLeaf = pNode;
161852  return rc;
161853}
161854
161855/*
161856** A cell with the same content as pCell has just been inserted into
161857** the node pNode. This function updates the bounding box cells in
161858** all ancestor elements.
161859*/
161860static int AdjustTree(
161861  Rtree *pRtree,                    /* Rtree table */
161862  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
161863  RtreeCell *pCell                  /* This cell was just inserted */
161864){
161865  RtreeNode *p = pNode;
161866  while( p->pParent ){
161867    RtreeNode *pParent = p->pParent;
161868    RtreeCell cell;
161869    int iCell;
161870
161871    if( nodeParentIndex(pRtree, p, &iCell) ){
161872      return SQLITE_CORRUPT_VTAB;
161873    }
161874
161875    nodeGetCell(pRtree, pParent, iCell, &cell);
161876    if( !cellContains(pRtree, &cell, pCell) ){
161877      cellUnion(pRtree, &cell, pCell);
161878      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
161879    }
161880
161881    p = pParent;
161882  }
161883  return SQLITE_OK;
161884}
161885
161886/*
161887** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
161888*/
161889static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
161890  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
161891  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
161892  sqlite3_step(pRtree->pWriteRowid);
161893  return sqlite3_reset(pRtree->pWriteRowid);
161894}
161895
161896/*
161897** Write mapping (iNode->iPar) to the <rtree>_parent table.
161898*/
161899static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
161900  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
161901  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
161902  sqlite3_step(pRtree->pWriteParent);
161903  return sqlite3_reset(pRtree->pWriteParent);
161904}
161905
161906static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
161907
161908
161909/*
161910** Arguments aIdx, aDistance and aSpare all point to arrays of size
161911** nIdx. The aIdx array contains the set of integers from 0 to
161912** (nIdx-1) in no particular order. This function sorts the values
161913** in aIdx according to the indexed values in aDistance. For
161914** example, assuming the inputs:
161915**
161916**   aIdx      = { 0,   1,   2,   3 }
161917**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
161918**
161919** this function sets the aIdx array to contain:
161920**
161921**   aIdx      = { 0,   1,   2,   3 }
161922**
161923** The aSpare array is used as temporary working space by the
161924** sorting algorithm.
161925*/
161926static void SortByDistance(
161927  int *aIdx,
161928  int nIdx,
161929  RtreeDValue *aDistance,
161930  int *aSpare
161931){
161932  if( nIdx>1 ){
161933    int iLeft = 0;
161934    int iRight = 0;
161935
161936    int nLeft = nIdx/2;
161937    int nRight = nIdx-nLeft;
161938    int *aLeft = aIdx;
161939    int *aRight = &aIdx[nLeft];
161940
161941    SortByDistance(aLeft, nLeft, aDistance, aSpare);
161942    SortByDistance(aRight, nRight, aDistance, aSpare);
161943
161944    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
161945    aLeft = aSpare;
161946
161947    while( iLeft<nLeft || iRight<nRight ){
161948      if( iLeft==nLeft ){
161949        aIdx[iLeft+iRight] = aRight[iRight];
161950        iRight++;
161951      }else if( iRight==nRight ){
161952        aIdx[iLeft+iRight] = aLeft[iLeft];
161953        iLeft++;
161954      }else{
161955        RtreeDValue fLeft = aDistance[aLeft[iLeft]];
161956        RtreeDValue fRight = aDistance[aRight[iRight]];
161957        if( fLeft<fRight ){
161958          aIdx[iLeft+iRight] = aLeft[iLeft];
161959          iLeft++;
161960        }else{
161961          aIdx[iLeft+iRight] = aRight[iRight];
161962          iRight++;
161963        }
161964      }
161965    }
161966
161967#if 0
161968    /* Check that the sort worked */
161969    {
161970      int jj;
161971      for(jj=1; jj<nIdx; jj++){
161972        RtreeDValue left = aDistance[aIdx[jj-1]];
161973        RtreeDValue right = aDistance[aIdx[jj]];
161974        assert( left<=right );
161975      }
161976    }
161977#endif
161978  }
161979}
161980
161981/*
161982** Arguments aIdx, aCell and aSpare all point to arrays of size
161983** nIdx. The aIdx array contains the set of integers from 0 to
161984** (nIdx-1) in no particular order. This function sorts the values
161985** in aIdx according to dimension iDim of the cells in aCell. The
161986** minimum value of dimension iDim is considered first, the
161987** maximum used to break ties.
161988**
161989** The aSpare array is used as temporary working space by the
161990** sorting algorithm.
161991*/
161992static void SortByDimension(
161993  Rtree *pRtree,
161994  int *aIdx,
161995  int nIdx,
161996  int iDim,
161997  RtreeCell *aCell,
161998  int *aSpare
161999){
162000  if( nIdx>1 ){
162001
162002    int iLeft = 0;
162003    int iRight = 0;
162004
162005    int nLeft = nIdx/2;
162006    int nRight = nIdx-nLeft;
162007    int *aLeft = aIdx;
162008    int *aRight = &aIdx[nLeft];
162009
162010    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
162011    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
162012
162013    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
162014    aLeft = aSpare;
162015    while( iLeft<nLeft || iRight<nRight ){
162016      RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
162017      RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
162018      RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
162019      RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
162020      if( (iLeft!=nLeft) && ((iRight==nRight)
162021       || (xleft1<xright1)
162022       || (xleft1==xright1 && xleft2<xright2)
162023      )){
162024        aIdx[iLeft+iRight] = aLeft[iLeft];
162025        iLeft++;
162026      }else{
162027        aIdx[iLeft+iRight] = aRight[iRight];
162028        iRight++;
162029      }
162030    }
162031
162032#if 0
162033    /* Check that the sort worked */
162034    {
162035      int jj;
162036      for(jj=1; jj<nIdx; jj++){
162037        RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
162038        RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
162039        RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
162040        RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
162041        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
162042      }
162043    }
162044#endif
162045  }
162046}
162047
162048/*
162049** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
162050*/
162051static int splitNodeStartree(
162052  Rtree *pRtree,
162053  RtreeCell *aCell,
162054  int nCell,
162055  RtreeNode *pLeft,
162056  RtreeNode *pRight,
162057  RtreeCell *pBboxLeft,
162058  RtreeCell *pBboxRight
162059){
162060  int **aaSorted;
162061  int *aSpare;
162062  int ii;
162063
162064  int iBestDim = 0;
162065  int iBestSplit = 0;
162066  RtreeDValue fBestMargin = RTREE_ZERO;
162067
162068  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
162069
162070  aaSorted = (int **)sqlite3_malloc(nByte);
162071  if( !aaSorted ){
162072    return SQLITE_NOMEM;
162073  }
162074
162075  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
162076  memset(aaSorted, 0, nByte);
162077  for(ii=0; ii<pRtree->nDim; ii++){
162078    int jj;
162079    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
162080    for(jj=0; jj<nCell; jj++){
162081      aaSorted[ii][jj] = jj;
162082    }
162083    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
162084  }
162085
162086  for(ii=0; ii<pRtree->nDim; ii++){
162087    RtreeDValue margin = RTREE_ZERO;
162088    RtreeDValue fBestOverlap = RTREE_ZERO;
162089    RtreeDValue fBestArea = RTREE_ZERO;
162090    int iBestLeft = 0;
162091    int nLeft;
162092
162093    for(
162094      nLeft=RTREE_MINCELLS(pRtree);
162095      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
162096      nLeft++
162097    ){
162098      RtreeCell left;
162099      RtreeCell right;
162100      int kk;
162101      RtreeDValue overlap;
162102      RtreeDValue area;
162103
162104      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
162105      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
162106      for(kk=1; kk<(nCell-1); kk++){
162107        if( kk<nLeft ){
162108          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
162109        }else{
162110          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
162111        }
162112      }
162113      margin += cellMargin(pRtree, &left);
162114      margin += cellMargin(pRtree, &right);
162115      overlap = cellOverlap(pRtree, &left, &right, 1);
162116      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
162117      if( (nLeft==RTREE_MINCELLS(pRtree))
162118       || (overlap<fBestOverlap)
162119       || (overlap==fBestOverlap && area<fBestArea)
162120      ){
162121        iBestLeft = nLeft;
162122        fBestOverlap = overlap;
162123        fBestArea = area;
162124      }
162125    }
162126
162127    if( ii==0 || margin<fBestMargin ){
162128      iBestDim = ii;
162129      fBestMargin = margin;
162130      iBestSplit = iBestLeft;
162131    }
162132  }
162133
162134  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
162135  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
162136  for(ii=0; ii<nCell; ii++){
162137    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
162138    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
162139    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
162140    nodeInsertCell(pRtree, pTarget, pCell);
162141    cellUnion(pRtree, pBbox, pCell);
162142  }
162143
162144  sqlite3_free(aaSorted);
162145  return SQLITE_OK;
162146}
162147
162148
162149static int updateMapping(
162150  Rtree *pRtree,
162151  i64 iRowid,
162152  RtreeNode *pNode,
162153  int iHeight
162154){
162155  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
162156  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
162157  if( iHeight>0 ){
162158    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
162159    if( pChild ){
162160      nodeRelease(pRtree, pChild->pParent);
162161      nodeReference(pNode);
162162      pChild->pParent = pNode;
162163    }
162164  }
162165  return xSetMapping(pRtree, iRowid, pNode->iNode);
162166}
162167
162168static int SplitNode(
162169  Rtree *pRtree,
162170  RtreeNode *pNode,
162171  RtreeCell *pCell,
162172  int iHeight
162173){
162174  int i;
162175  int newCellIsRight = 0;
162176
162177  int rc = SQLITE_OK;
162178  int nCell = NCELL(pNode);
162179  RtreeCell *aCell;
162180  int *aiUsed;
162181
162182  RtreeNode *pLeft = 0;
162183  RtreeNode *pRight = 0;
162184
162185  RtreeCell leftbbox;
162186  RtreeCell rightbbox;
162187
162188  /* Allocate an array and populate it with a copy of pCell and
162189  ** all cells from node pLeft. Then zero the original node.
162190  */
162191  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
162192  if( !aCell ){
162193    rc = SQLITE_NOMEM;
162194    goto splitnode_out;
162195  }
162196  aiUsed = (int *)&aCell[nCell+1];
162197  memset(aiUsed, 0, sizeof(int)*(nCell+1));
162198  for(i=0; i<nCell; i++){
162199    nodeGetCell(pRtree, pNode, i, &aCell[i]);
162200  }
162201  nodeZero(pRtree, pNode);
162202  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
162203  nCell++;
162204
162205  if( pNode->iNode==1 ){
162206    pRight = nodeNew(pRtree, pNode);
162207    pLeft = nodeNew(pRtree, pNode);
162208    pRtree->iDepth++;
162209    pNode->isDirty = 1;
162210    writeInt16(pNode->zData, pRtree->iDepth);
162211  }else{
162212    pLeft = pNode;
162213    pRight = nodeNew(pRtree, pLeft->pParent);
162214    nodeReference(pLeft);
162215  }
162216
162217  if( !pLeft || !pRight ){
162218    rc = SQLITE_NOMEM;
162219    goto splitnode_out;
162220  }
162221
162222  memset(pLeft->zData, 0, pRtree->iNodeSize);
162223  memset(pRight->zData, 0, pRtree->iNodeSize);
162224
162225  rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
162226                         &leftbbox, &rightbbox);
162227  if( rc!=SQLITE_OK ){
162228    goto splitnode_out;
162229  }
162230
162231  /* Ensure both child nodes have node numbers assigned to them by calling
162232  ** nodeWrite(). Node pRight always needs a node number, as it was created
162233  ** by nodeNew() above. But node pLeft sometimes already has a node number.
162234  ** In this case avoid the all to nodeWrite().
162235  */
162236  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
162237   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
162238  ){
162239    goto splitnode_out;
162240  }
162241
162242  rightbbox.iRowid = pRight->iNode;
162243  leftbbox.iRowid = pLeft->iNode;
162244
162245  if( pNode->iNode==1 ){
162246    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
162247    if( rc!=SQLITE_OK ){
162248      goto splitnode_out;
162249    }
162250  }else{
162251    RtreeNode *pParent = pLeft->pParent;
162252    int iCell;
162253    rc = nodeParentIndex(pRtree, pLeft, &iCell);
162254    if( rc==SQLITE_OK ){
162255      nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
162256      rc = AdjustTree(pRtree, pParent, &leftbbox);
162257    }
162258    if( rc!=SQLITE_OK ){
162259      goto splitnode_out;
162260    }
162261  }
162262  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
162263    goto splitnode_out;
162264  }
162265
162266  for(i=0; i<NCELL(pRight); i++){
162267    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
162268    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
162269    if( iRowid==pCell->iRowid ){
162270      newCellIsRight = 1;
162271    }
162272    if( rc!=SQLITE_OK ){
162273      goto splitnode_out;
162274    }
162275  }
162276  if( pNode->iNode==1 ){
162277    for(i=0; i<NCELL(pLeft); i++){
162278      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
162279      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
162280      if( rc!=SQLITE_OK ){
162281        goto splitnode_out;
162282      }
162283    }
162284  }else if( newCellIsRight==0 ){
162285    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
162286  }
162287
162288  if( rc==SQLITE_OK ){
162289    rc = nodeRelease(pRtree, pRight);
162290    pRight = 0;
162291  }
162292  if( rc==SQLITE_OK ){
162293    rc = nodeRelease(pRtree, pLeft);
162294    pLeft = 0;
162295  }
162296
162297splitnode_out:
162298  nodeRelease(pRtree, pRight);
162299  nodeRelease(pRtree, pLeft);
162300  sqlite3_free(aCell);
162301  return rc;
162302}
162303
162304/*
162305** If node pLeaf is not the root of the r-tree and its pParent pointer is
162306** still NULL, load all ancestor nodes of pLeaf into memory and populate
162307** the pLeaf->pParent chain all the way up to the root node.
162308**
162309** This operation is required when a row is deleted (or updated - an update
162310** is implemented as a delete followed by an insert). SQLite provides the
162311** rowid of the row to delete, which can be used to find the leaf on which
162312** the entry resides (argument pLeaf). Once the leaf is located, this
162313** function is called to determine its ancestry.
162314*/
162315static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
162316  int rc = SQLITE_OK;
162317  RtreeNode *pChild = pLeaf;
162318  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
162319    int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
162320    sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
162321    rc = sqlite3_step(pRtree->pReadParent);
162322    if( rc==SQLITE_ROW ){
162323      RtreeNode *pTest;           /* Used to test for reference loops */
162324      i64 iNode;                  /* Node number of parent node */
162325
162326      /* Before setting pChild->pParent, test that we are not creating a
162327      ** loop of references (as we would if, say, pChild==pParent). We don't
162328      ** want to do this as it leads to a memory leak when trying to delete
162329      ** the referenced counted node structures.
162330      */
162331      iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
162332      for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
162333      if( !pTest ){
162334        rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
162335      }
162336    }
162337    rc = sqlite3_reset(pRtree->pReadParent);
162338    if( rc==SQLITE_OK ) rc = rc2;
162339    if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
162340    pChild = pChild->pParent;
162341  }
162342  return rc;
162343}
162344
162345static int deleteCell(Rtree *, RtreeNode *, int, int);
162346
162347static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
162348  int rc;
162349  int rc2;
162350  RtreeNode *pParent = 0;
162351  int iCell;
162352
162353  assert( pNode->nRef==1 );
162354
162355  /* Remove the entry in the parent cell. */
162356  rc = nodeParentIndex(pRtree, pNode, &iCell);
162357  if( rc==SQLITE_OK ){
162358    pParent = pNode->pParent;
162359    pNode->pParent = 0;
162360    rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
162361  }
162362  rc2 = nodeRelease(pRtree, pParent);
162363  if( rc==SQLITE_OK ){
162364    rc = rc2;
162365  }
162366  if( rc!=SQLITE_OK ){
162367    return rc;
162368  }
162369
162370  /* Remove the xxx_node entry. */
162371  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
162372  sqlite3_step(pRtree->pDeleteNode);
162373  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
162374    return rc;
162375  }
162376
162377  /* Remove the xxx_parent entry. */
162378  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
162379  sqlite3_step(pRtree->pDeleteParent);
162380  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
162381    return rc;
162382  }
162383
162384  /* Remove the node from the in-memory hash table and link it into
162385  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
162386  */
162387  nodeHashDelete(pRtree, pNode);
162388  pNode->iNode = iHeight;
162389  pNode->pNext = pRtree->pDeleted;
162390  pNode->nRef++;
162391  pRtree->pDeleted = pNode;
162392
162393  return SQLITE_OK;
162394}
162395
162396static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
162397  RtreeNode *pParent = pNode->pParent;
162398  int rc = SQLITE_OK;
162399  if( pParent ){
162400    int ii;
162401    int nCell = NCELL(pNode);
162402    RtreeCell box;                            /* Bounding box for pNode */
162403    nodeGetCell(pRtree, pNode, 0, &box);
162404    for(ii=1; ii<nCell; ii++){
162405      RtreeCell cell;
162406      nodeGetCell(pRtree, pNode, ii, &cell);
162407      cellUnion(pRtree, &box, &cell);
162408    }
162409    box.iRowid = pNode->iNode;
162410    rc = nodeParentIndex(pRtree, pNode, &ii);
162411    if( rc==SQLITE_OK ){
162412      nodeOverwriteCell(pRtree, pParent, &box, ii);
162413      rc = fixBoundingBox(pRtree, pParent);
162414    }
162415  }
162416  return rc;
162417}
162418
162419/*
162420** Delete the cell at index iCell of node pNode. After removing the
162421** cell, adjust the r-tree data structure if required.
162422*/
162423static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
162424  RtreeNode *pParent;
162425  int rc;
162426
162427  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
162428    return rc;
162429  }
162430
162431  /* Remove the cell from the node. This call just moves bytes around
162432  ** the in-memory node image, so it cannot fail.
162433  */
162434  nodeDeleteCell(pRtree, pNode, iCell);
162435
162436  /* If the node is not the tree root and now has less than the minimum
162437  ** number of cells, remove it from the tree. Otherwise, update the
162438  ** cell in the parent node so that it tightly contains the updated
162439  ** node.
162440  */
162441  pParent = pNode->pParent;
162442  assert( pParent || pNode->iNode==1 );
162443  if( pParent ){
162444    if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
162445      rc = removeNode(pRtree, pNode, iHeight);
162446    }else{
162447      rc = fixBoundingBox(pRtree, pNode);
162448    }
162449  }
162450
162451  return rc;
162452}
162453
162454static int Reinsert(
162455  Rtree *pRtree,
162456  RtreeNode *pNode,
162457  RtreeCell *pCell,
162458  int iHeight
162459){
162460  int *aOrder;
162461  int *aSpare;
162462  RtreeCell *aCell;
162463  RtreeDValue *aDistance;
162464  int nCell;
162465  RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
162466  int iDim;
162467  int ii;
162468  int rc = SQLITE_OK;
162469  int n;
162470
162471  memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
162472
162473  nCell = NCELL(pNode)+1;
162474  n = (nCell+1)&(~1);
162475
162476  /* Allocate the buffers used by this operation. The allocation is
162477  ** relinquished before this function returns.
162478  */
162479  aCell = (RtreeCell *)sqlite3_malloc(n * (
162480    sizeof(RtreeCell)     +         /* aCell array */
162481    sizeof(int)           +         /* aOrder array */
162482    sizeof(int)           +         /* aSpare array */
162483    sizeof(RtreeDValue)             /* aDistance array */
162484  ));
162485  if( !aCell ){
162486    return SQLITE_NOMEM;
162487  }
162488  aOrder    = (int *)&aCell[n];
162489  aSpare    = (int *)&aOrder[n];
162490  aDistance = (RtreeDValue *)&aSpare[n];
162491
162492  for(ii=0; ii<nCell; ii++){
162493    if( ii==(nCell-1) ){
162494      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
162495    }else{
162496      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
162497    }
162498    aOrder[ii] = ii;
162499    for(iDim=0; iDim<pRtree->nDim; iDim++){
162500      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
162501      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
162502    }
162503  }
162504  for(iDim=0; iDim<pRtree->nDim; iDim++){
162505    aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
162506  }
162507
162508  for(ii=0; ii<nCell; ii++){
162509    aDistance[ii] = RTREE_ZERO;
162510    for(iDim=0; iDim<pRtree->nDim; iDim++){
162511      RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
162512                               DCOORD(aCell[ii].aCoord[iDim*2]));
162513      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
162514    }
162515  }
162516
162517  SortByDistance(aOrder, nCell, aDistance, aSpare);
162518  nodeZero(pRtree, pNode);
162519
162520  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
162521    RtreeCell *p = &aCell[aOrder[ii]];
162522    nodeInsertCell(pRtree, pNode, p);
162523    if( p->iRowid==pCell->iRowid ){
162524      if( iHeight==0 ){
162525        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
162526      }else{
162527        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
162528      }
162529    }
162530  }
162531  if( rc==SQLITE_OK ){
162532    rc = fixBoundingBox(pRtree, pNode);
162533  }
162534  for(; rc==SQLITE_OK && ii<nCell; ii++){
162535    /* Find a node to store this cell in. pNode->iNode currently contains
162536    ** the height of the sub-tree headed by the cell.
162537    */
162538    RtreeNode *pInsert;
162539    RtreeCell *p = &aCell[aOrder[ii]];
162540    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
162541    if( rc==SQLITE_OK ){
162542      int rc2;
162543      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
162544      rc2 = nodeRelease(pRtree, pInsert);
162545      if( rc==SQLITE_OK ){
162546        rc = rc2;
162547      }
162548    }
162549  }
162550
162551  sqlite3_free(aCell);
162552  return rc;
162553}
162554
162555/*
162556** Insert cell pCell into node pNode. Node pNode is the head of a
162557** subtree iHeight high (leaf nodes have iHeight==0).
162558*/
162559static int rtreeInsertCell(
162560  Rtree *pRtree,
162561  RtreeNode *pNode,
162562  RtreeCell *pCell,
162563  int iHeight
162564){
162565  int rc = SQLITE_OK;
162566  if( iHeight>0 ){
162567    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
162568    if( pChild ){
162569      nodeRelease(pRtree, pChild->pParent);
162570      nodeReference(pNode);
162571      pChild->pParent = pNode;
162572    }
162573  }
162574  if( nodeInsertCell(pRtree, pNode, pCell) ){
162575    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
162576      rc = SplitNode(pRtree, pNode, pCell, iHeight);
162577    }else{
162578      pRtree->iReinsertHeight = iHeight;
162579      rc = Reinsert(pRtree, pNode, pCell, iHeight);
162580    }
162581  }else{
162582    rc = AdjustTree(pRtree, pNode, pCell);
162583    if( rc==SQLITE_OK ){
162584      if( iHeight==0 ){
162585        rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
162586      }else{
162587        rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
162588      }
162589    }
162590  }
162591  return rc;
162592}
162593
162594static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
162595  int ii;
162596  int rc = SQLITE_OK;
162597  int nCell = NCELL(pNode);
162598
162599  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
162600    RtreeNode *pInsert;
162601    RtreeCell cell;
162602    nodeGetCell(pRtree, pNode, ii, &cell);
162603
162604    /* Find a node to store this cell in. pNode->iNode currently contains
162605    ** the height of the sub-tree headed by the cell.
162606    */
162607    rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
162608    if( rc==SQLITE_OK ){
162609      int rc2;
162610      rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
162611      rc2 = nodeRelease(pRtree, pInsert);
162612      if( rc==SQLITE_OK ){
162613        rc = rc2;
162614      }
162615    }
162616  }
162617  return rc;
162618}
162619
162620/*
162621** Select a currently unused rowid for a new r-tree record.
162622*/
162623static int newRowid(Rtree *pRtree, i64 *piRowid){
162624  int rc;
162625  sqlite3_bind_null(pRtree->pWriteRowid, 1);
162626  sqlite3_bind_null(pRtree->pWriteRowid, 2);
162627  sqlite3_step(pRtree->pWriteRowid);
162628  rc = sqlite3_reset(pRtree->pWriteRowid);
162629  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
162630  return rc;
162631}
162632
162633/*
162634** Remove the entry with rowid=iDelete from the r-tree structure.
162635*/
162636static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
162637  int rc;                         /* Return code */
162638  RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
162639  int iCell;                      /* Index of iDelete cell in pLeaf */
162640  RtreeNode *pRoot;               /* Root node of rtree structure */
162641
162642
162643  /* Obtain a reference to the root node to initialize Rtree.iDepth */
162644  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
162645
162646  /* Obtain a reference to the leaf node that contains the entry
162647  ** about to be deleted.
162648  */
162649  if( rc==SQLITE_OK ){
162650    rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
162651  }
162652
162653  /* Delete the cell in question from the leaf node. */
162654  if( rc==SQLITE_OK ){
162655    int rc2;
162656    rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
162657    if( rc==SQLITE_OK ){
162658      rc = deleteCell(pRtree, pLeaf, iCell, 0);
162659    }
162660    rc2 = nodeRelease(pRtree, pLeaf);
162661    if( rc==SQLITE_OK ){
162662      rc = rc2;
162663    }
162664  }
162665
162666  /* Delete the corresponding entry in the <rtree>_rowid table. */
162667  if( rc==SQLITE_OK ){
162668    sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
162669    sqlite3_step(pRtree->pDeleteRowid);
162670    rc = sqlite3_reset(pRtree->pDeleteRowid);
162671  }
162672
162673  /* Check if the root node now has exactly one child. If so, remove
162674  ** it, schedule the contents of the child for reinsertion and
162675  ** reduce the tree height by one.
162676  **
162677  ** This is equivalent to copying the contents of the child into
162678  ** the root node (the operation that Gutman's paper says to perform
162679  ** in this scenario).
162680  */
162681  if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
162682    int rc2;
162683    RtreeNode *pChild;
162684    i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
162685    rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
162686    if( rc==SQLITE_OK ){
162687      rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
162688    }
162689    rc2 = nodeRelease(pRtree, pChild);
162690    if( rc==SQLITE_OK ) rc = rc2;
162691    if( rc==SQLITE_OK ){
162692      pRtree->iDepth--;
162693      writeInt16(pRoot->zData, pRtree->iDepth);
162694      pRoot->isDirty = 1;
162695    }
162696  }
162697
162698  /* Re-insert the contents of any underfull nodes removed from the tree. */
162699  for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
162700    if( rc==SQLITE_OK ){
162701      rc = reinsertNodeContent(pRtree, pLeaf);
162702    }
162703    pRtree->pDeleted = pLeaf->pNext;
162704    sqlite3_free(pLeaf);
162705  }
162706
162707  /* Release the reference to the root node. */
162708  if( rc==SQLITE_OK ){
162709    rc = nodeRelease(pRtree, pRoot);
162710  }else{
162711    nodeRelease(pRtree, pRoot);
162712  }
162713
162714  return rc;
162715}
162716
162717/*
162718** Rounding constants for float->double conversion.
162719*/
162720#define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
162721#define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
162722
162723#if !defined(SQLITE_RTREE_INT_ONLY)
162724/*
162725** Convert an sqlite3_value into an RtreeValue (presumably a float)
162726** while taking care to round toward negative or positive, respectively.
162727*/
162728static RtreeValue rtreeValueDown(sqlite3_value *v){
162729  double d = sqlite3_value_double(v);
162730  float f = (float)d;
162731  if( f>d ){
162732    f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
162733  }
162734  return f;
162735}
162736static RtreeValue rtreeValueUp(sqlite3_value *v){
162737  double d = sqlite3_value_double(v);
162738  float f = (float)d;
162739  if( f<d ){
162740    f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
162741  }
162742  return f;
162743}
162744#endif /* !defined(SQLITE_RTREE_INT_ONLY) */
162745
162746/*
162747** A constraint has failed while inserting a row into an rtree table.
162748** Assuming no OOM error occurs, this function sets the error message
162749** (at pRtree->base.zErrMsg) to an appropriate value and returns
162750** SQLITE_CONSTRAINT.
162751**
162752** Parameter iCol is the index of the leftmost column involved in the
162753** constraint failure. If it is 0, then the constraint that failed is
162754** the unique constraint on the id column. Otherwise, it is the rtree
162755** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
162756**
162757** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
162758*/
162759static int rtreeConstraintError(Rtree *pRtree, int iCol){
162760  sqlite3_stmt *pStmt = 0;
162761  char *zSql;
162762  int rc;
162763
162764  assert( iCol==0 || iCol%2 );
162765  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
162766  if( zSql ){
162767    rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
162768  }else{
162769    rc = SQLITE_NOMEM;
162770  }
162771  sqlite3_free(zSql);
162772
162773  if( rc==SQLITE_OK ){
162774    if( iCol==0 ){
162775      const char *zCol = sqlite3_column_name(pStmt, 0);
162776      pRtree->base.zErrMsg = sqlite3_mprintf(
162777          "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
162778      );
162779    }else{
162780      const char *zCol1 = sqlite3_column_name(pStmt, iCol);
162781      const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
162782      pRtree->base.zErrMsg = sqlite3_mprintf(
162783          "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
162784      );
162785    }
162786  }
162787
162788  sqlite3_finalize(pStmt);
162789  return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
162790}
162791
162792
162793
162794/*
162795** The xUpdate method for rtree module virtual tables.
162796*/
162797static int rtreeUpdate(
162798  sqlite3_vtab *pVtab,
162799  int nData,
162800  sqlite3_value **azData,
162801  sqlite_int64 *pRowid
162802){
162803  Rtree *pRtree = (Rtree *)pVtab;
162804  int rc = SQLITE_OK;
162805  RtreeCell cell;                 /* New cell to insert if nData>1 */
162806  int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
162807
162808  rtreeReference(pRtree);
162809  assert(nData>=1);
162810
162811  cell.iRowid = 0;  /* Used only to suppress a compiler warning */
162812
162813  /* Constraint handling. A write operation on an r-tree table may return
162814  ** SQLITE_CONSTRAINT for two reasons:
162815  **
162816  **   1. A duplicate rowid value, or
162817  **   2. The supplied data violates the "x2>=x1" constraint.
162818  **
162819  ** In the first case, if the conflict-handling mode is REPLACE, then
162820  ** the conflicting row can be removed before proceeding. In the second
162821  ** case, SQLITE_CONSTRAINT must be returned regardless of the
162822  ** conflict-handling mode specified by the user.
162823  */
162824  if( nData>1 ){
162825    int ii;
162826
162827    /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
162828    **
162829    ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
162830    ** with "column" that are interpreted as table constraints.
162831    ** Example:  CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
162832    ** This problem was discovered after years of use, so we silently ignore
162833    ** these kinds of misdeclared tables to avoid breaking any legacy.
162834    */
162835    assert( nData<=(pRtree->nDim*2 + 3) );
162836
162837#ifndef SQLITE_RTREE_INT_ONLY
162838    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
162839      for(ii=0; ii<nData-4; ii+=2){
162840        cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
162841        cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
162842        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
162843          rc = rtreeConstraintError(pRtree, ii+1);
162844          goto constraint;
162845        }
162846      }
162847    }else
162848#endif
162849    {
162850      for(ii=0; ii<nData-4; ii+=2){
162851        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
162852        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
162853        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
162854          rc = rtreeConstraintError(pRtree, ii+1);
162855          goto constraint;
162856        }
162857      }
162858    }
162859
162860    /* If a rowid value was supplied, check if it is already present in
162861    ** the table. If so, the constraint has failed. */
162862    if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
162863      cell.iRowid = sqlite3_value_int64(azData[2]);
162864      if( sqlite3_value_type(azData[0])==SQLITE_NULL
162865       || sqlite3_value_int64(azData[0])!=cell.iRowid
162866      ){
162867        int steprc;
162868        sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
162869        steprc = sqlite3_step(pRtree->pReadRowid);
162870        rc = sqlite3_reset(pRtree->pReadRowid);
162871        if( SQLITE_ROW==steprc ){
162872          if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
162873            rc = rtreeDeleteRowid(pRtree, cell.iRowid);
162874          }else{
162875            rc = rtreeConstraintError(pRtree, 0);
162876            goto constraint;
162877          }
162878        }
162879      }
162880      bHaveRowid = 1;
162881    }
162882  }
162883
162884  /* If azData[0] is not an SQL NULL value, it is the rowid of a
162885  ** record to delete from the r-tree table. The following block does
162886  ** just that.
162887  */
162888  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
162889    rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
162890  }
162891
162892  /* If the azData[] array contains more than one element, elements
162893  ** (azData[2]..azData[argc-1]) contain a new record to insert into
162894  ** the r-tree structure.
162895  */
162896  if( rc==SQLITE_OK && nData>1 ){
162897    /* Insert the new record into the r-tree */
162898    RtreeNode *pLeaf = 0;
162899
162900    /* Figure out the rowid of the new row. */
162901    if( bHaveRowid==0 ){
162902      rc = newRowid(pRtree, &cell.iRowid);
162903    }
162904    *pRowid = cell.iRowid;
162905
162906    if( rc==SQLITE_OK ){
162907      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
162908    }
162909    if( rc==SQLITE_OK ){
162910      int rc2;
162911      pRtree->iReinsertHeight = -1;
162912      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
162913      rc2 = nodeRelease(pRtree, pLeaf);
162914      if( rc==SQLITE_OK ){
162915        rc = rc2;
162916      }
162917    }
162918  }
162919
162920constraint:
162921  rtreeRelease(pRtree);
162922  return rc;
162923}
162924
162925/*
162926** The xRename method for rtree module virtual tables.
162927*/
162928static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
162929  Rtree *pRtree = (Rtree *)pVtab;
162930  int rc = SQLITE_NOMEM;
162931  char *zSql = sqlite3_mprintf(
162932    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
162933    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
162934    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
162935    , pRtree->zDb, pRtree->zName, zNewName
162936    , pRtree->zDb, pRtree->zName, zNewName
162937    , pRtree->zDb, pRtree->zName, zNewName
162938  );
162939  if( zSql ){
162940    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
162941    sqlite3_free(zSql);
162942  }
162943  return rc;
162944}
162945
162946/*
162947** This function populates the pRtree->nRowEst variable with an estimate
162948** of the number of rows in the virtual table. If possible, this is based
162949** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
162950*/
162951static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
162952  const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
162953  char *zSql;
162954  sqlite3_stmt *p;
162955  int rc;
162956  i64 nRow = 0;
162957
162958  if( sqlite3_table_column_metadata(db,pRtree->zDb,"sqlite_stat1",
162959          0,0,0,0,0,0)==SQLITE_ERROR ){
162960    pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
162961    return SQLITE_OK;
162962  }
162963  zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
162964  if( zSql==0 ){
162965    rc = SQLITE_NOMEM;
162966  }else{
162967    rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
162968    if( rc==SQLITE_OK ){
162969      if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
162970      rc = sqlite3_finalize(p);
162971    }else if( rc!=SQLITE_NOMEM ){
162972      rc = SQLITE_OK;
162973    }
162974
162975    if( rc==SQLITE_OK ){
162976      if( nRow==0 ){
162977        pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
162978      }else{
162979        pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
162980      }
162981    }
162982    sqlite3_free(zSql);
162983  }
162984
162985  return rc;
162986}
162987
162988static sqlite3_module rtreeModule = {
162989  0,                          /* iVersion */
162990  rtreeCreate,                /* xCreate - create a table */
162991  rtreeConnect,               /* xConnect - connect to an existing table */
162992  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
162993  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
162994  rtreeDestroy,               /* xDestroy - Drop a table */
162995  rtreeOpen,                  /* xOpen - open a cursor */
162996  rtreeClose,                 /* xClose - close a cursor */
162997  rtreeFilter,                /* xFilter - configure scan constraints */
162998  rtreeNext,                  /* xNext - advance a cursor */
162999  rtreeEof,                   /* xEof */
163000  rtreeColumn,                /* xColumn - read data */
163001  rtreeRowid,                 /* xRowid - read data */
163002  rtreeUpdate,                /* xUpdate - write data */
163003  0,                          /* xBegin - begin transaction */
163004  0,                          /* xSync - sync transaction */
163005  0,                          /* xCommit - commit transaction */
163006  0,                          /* xRollback - rollback transaction */
163007  0,                          /* xFindFunction - function overloading */
163008  rtreeRename,                /* xRename - rename the table */
163009  0,                          /* xSavepoint */
163010  0,                          /* xRelease */
163011  0                           /* xRollbackTo */
163012};
163013
163014static int rtreeSqlInit(
163015  Rtree *pRtree,
163016  sqlite3 *db,
163017  const char *zDb,
163018  const char *zPrefix,
163019  int isCreate
163020){
163021  int rc = SQLITE_OK;
163022
163023  #define N_STATEMENT 9
163024  static const char *azSql[N_STATEMENT] = {
163025    /* Read and write the xxx_node table */
163026    "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
163027    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
163028    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
163029
163030    /* Read and write the xxx_rowid table */
163031    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
163032    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
163033    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
163034
163035    /* Read and write the xxx_parent table */
163036    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
163037    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
163038    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
163039  };
163040  sqlite3_stmt **appStmt[N_STATEMENT];
163041  int i;
163042
163043  pRtree->db = db;
163044
163045  if( isCreate ){
163046    char *zCreate = sqlite3_mprintf(
163047"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
163048"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
163049"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
163050                                  " parentnode INTEGER);"
163051"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
163052      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
163053    );
163054    if( !zCreate ){
163055      return SQLITE_NOMEM;
163056    }
163057    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
163058    sqlite3_free(zCreate);
163059    if( rc!=SQLITE_OK ){
163060      return rc;
163061    }
163062  }
163063
163064  appStmt[0] = &pRtree->pReadNode;
163065  appStmt[1] = &pRtree->pWriteNode;
163066  appStmt[2] = &pRtree->pDeleteNode;
163067  appStmt[3] = &pRtree->pReadRowid;
163068  appStmt[4] = &pRtree->pWriteRowid;
163069  appStmt[5] = &pRtree->pDeleteRowid;
163070  appStmt[6] = &pRtree->pReadParent;
163071  appStmt[7] = &pRtree->pWriteParent;
163072  appStmt[8] = &pRtree->pDeleteParent;
163073
163074  rc = rtreeQueryStat1(db, pRtree);
163075  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
163076    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
163077    if( zSql ){
163078      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
163079    }else{
163080      rc = SQLITE_NOMEM;
163081    }
163082    sqlite3_free(zSql);
163083  }
163084
163085  return rc;
163086}
163087
163088/*
163089** The second argument to this function contains the text of an SQL statement
163090** that returns a single integer value. The statement is compiled and executed
163091** using database connection db. If successful, the integer value returned
163092** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
163093** code is returned and the value of *piVal after returning is not defined.
163094*/
163095static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
163096  int rc = SQLITE_NOMEM;
163097  if( zSql ){
163098    sqlite3_stmt *pStmt = 0;
163099    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
163100    if( rc==SQLITE_OK ){
163101      if( SQLITE_ROW==sqlite3_step(pStmt) ){
163102        *piVal = sqlite3_column_int(pStmt, 0);
163103      }
163104      rc = sqlite3_finalize(pStmt);
163105    }
163106  }
163107  return rc;
163108}
163109
163110/*
163111** This function is called from within the xConnect() or xCreate() method to
163112** determine the node-size used by the rtree table being created or connected
163113** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
163114** Otherwise, an SQLite error code is returned.
163115**
163116** If this function is being called as part of an xConnect(), then the rtree
163117** table already exists. In this case the node-size is determined by inspecting
163118** the root node of the tree.
163119**
163120** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
163121** This ensures that each node is stored on a single database page. If the
163122** database page-size is so large that more than RTREE_MAXCELLS entries
163123** would fit in a single node, use a smaller node-size.
163124*/
163125static int getNodeSize(
163126  sqlite3 *db,                    /* Database handle */
163127  Rtree *pRtree,                  /* Rtree handle */
163128  int isCreate,                   /* True for xCreate, false for xConnect */
163129  char **pzErr                    /* OUT: Error message, if any */
163130){
163131  int rc;
163132  char *zSql;
163133  if( isCreate ){
163134    int iPageSize = 0;
163135    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
163136    rc = getIntFromStmt(db, zSql, &iPageSize);
163137    if( rc==SQLITE_OK ){
163138      pRtree->iNodeSize = iPageSize-64;
163139      if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
163140        pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
163141      }
163142    }else{
163143      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
163144    }
163145  }else{
163146    zSql = sqlite3_mprintf(
163147        "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
163148        pRtree->zDb, pRtree->zName
163149    );
163150    rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
163151    if( rc!=SQLITE_OK ){
163152      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
163153    }
163154  }
163155
163156  sqlite3_free(zSql);
163157  return rc;
163158}
163159
163160/*
163161** This function is the implementation of both the xConnect and xCreate
163162** methods of the r-tree virtual table.
163163**
163164**   argv[0]   -> module name
163165**   argv[1]   -> database name
163166**   argv[2]   -> table name
163167**   argv[...] -> column names...
163168*/
163169static int rtreeInit(
163170  sqlite3 *db,                        /* Database connection */
163171  void *pAux,                         /* One of the RTREE_COORD_* constants */
163172  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
163173  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
163174  char **pzErr,                       /* OUT: Error message, if any */
163175  int isCreate                        /* True for xCreate, false for xConnect */
163176){
163177  int rc = SQLITE_OK;
163178  Rtree *pRtree;
163179  int nDb;              /* Length of string argv[1] */
163180  int nName;            /* Length of string argv[2] */
163181  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
163182
163183  const char *aErrMsg[] = {
163184    0,                                                    /* 0 */
163185    "Wrong number of columns for an rtree table",         /* 1 */
163186    "Too few columns for an rtree table",                 /* 2 */
163187    "Too many columns for an rtree table"                 /* 3 */
163188  };
163189
163190  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
163191  if( aErrMsg[iErr] ){
163192    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
163193    return SQLITE_ERROR;
163194  }
163195
163196  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
163197
163198  /* Allocate the sqlite3_vtab structure */
163199  nDb = (int)strlen(argv[1]);
163200  nName = (int)strlen(argv[2]);
163201  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
163202  if( !pRtree ){
163203    return SQLITE_NOMEM;
163204  }
163205  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
163206  pRtree->nBusy = 1;
163207  pRtree->base.pModule = &rtreeModule;
163208  pRtree->zDb = (char *)&pRtree[1];
163209  pRtree->zName = &pRtree->zDb[nDb+1];
163210  pRtree->nDim = (argc-4)/2;
163211  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
163212  pRtree->eCoordType = eCoordType;
163213  memcpy(pRtree->zDb, argv[1], nDb);
163214  memcpy(pRtree->zName, argv[2], nName);
163215
163216  /* Figure out the node size to use. */
163217  rc = getNodeSize(db, pRtree, isCreate, pzErr);
163218
163219  /* Create/Connect to the underlying relational database schema. If
163220  ** that is successful, call sqlite3_declare_vtab() to configure
163221  ** the r-tree table schema.
163222  */
163223  if( rc==SQLITE_OK ){
163224    if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
163225      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
163226    }else{
163227      char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
163228      char *zTmp;
163229      int ii;
163230      for(ii=4; zSql && ii<argc; ii++){
163231        zTmp = zSql;
163232        zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
163233        sqlite3_free(zTmp);
163234      }
163235      if( zSql ){
163236        zTmp = zSql;
163237        zSql = sqlite3_mprintf("%s);", zTmp);
163238        sqlite3_free(zTmp);
163239      }
163240      if( !zSql ){
163241        rc = SQLITE_NOMEM;
163242      }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
163243        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
163244      }
163245      sqlite3_free(zSql);
163246    }
163247  }
163248
163249  if( rc==SQLITE_OK ){
163250    *ppVtab = (sqlite3_vtab *)pRtree;
163251  }else{
163252    assert( *ppVtab==0 );
163253    assert( pRtree->nBusy==1 );
163254    rtreeRelease(pRtree);
163255  }
163256  return rc;
163257}
163258
163259
163260/*
163261** Implementation of a scalar function that decodes r-tree nodes to
163262** human readable strings. This can be used for debugging and analysis.
163263**
163264** The scalar function takes two arguments: (1) the number of dimensions
163265** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
163266** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
163267** deserialize all nodes, a statement like:
163268**
163269**   SELECT rtreenode(2, data) FROM rt_node;
163270**
163271** The human readable string takes the form of a Tcl list with one
163272** entry for each cell in the r-tree node. Each entry is itself a
163273** list, containing the 8-byte rowid/pageno followed by the
163274** <num-dimension>*2 coordinates.
163275*/
163276static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
163277  char *zText = 0;
163278  RtreeNode node;
163279  Rtree tree;
163280  int ii;
163281
163282  UNUSED_PARAMETER(nArg);
163283  memset(&node, 0, sizeof(RtreeNode));
163284  memset(&tree, 0, sizeof(Rtree));
163285  tree.nDim = sqlite3_value_int(apArg[0]);
163286  tree.nBytesPerCell = 8 + 8 * tree.nDim;
163287  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
163288
163289  for(ii=0; ii<NCELL(&node); ii++){
163290    char zCell[512];
163291    int nCell = 0;
163292    RtreeCell cell;
163293    int jj;
163294
163295    nodeGetCell(&tree, &node, ii, &cell);
163296    sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
163297    nCell = (int)strlen(zCell);
163298    for(jj=0; jj<tree.nDim*2; jj++){
163299#ifndef SQLITE_RTREE_INT_ONLY
163300      sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
163301                       (double)cell.aCoord[jj].f);
163302#else
163303      sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
163304                       cell.aCoord[jj].i);
163305#endif
163306      nCell = (int)strlen(zCell);
163307    }
163308
163309    if( zText ){
163310      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
163311      sqlite3_free(zText);
163312      zText = zTextNew;
163313    }else{
163314      zText = sqlite3_mprintf("{%s}", zCell);
163315    }
163316  }
163317
163318  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
163319}
163320
163321/* This routine implements an SQL function that returns the "depth" parameter
163322** from the front of a blob that is an r-tree node.  For example:
163323**
163324**     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
163325**
163326** The depth value is 0 for all nodes other than the root node, and the root
163327** node always has nodeno=1, so the example above is the primary use for this
163328** routine.  This routine is intended for testing and analysis only.
163329*/
163330static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
163331  UNUSED_PARAMETER(nArg);
163332  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
163333   || sqlite3_value_bytes(apArg[0])<2
163334  ){
163335    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
163336  }else{
163337    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
163338    sqlite3_result_int(ctx, readInt16(zBlob));
163339  }
163340}
163341
163342/*
163343** Register the r-tree module with database handle db. This creates the
163344** virtual table module "rtree" and the debugging/analysis scalar
163345** function "rtreenode".
163346*/
163347SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
163348  const int utf8 = SQLITE_UTF8;
163349  int rc;
163350
163351  rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
163352  if( rc==SQLITE_OK ){
163353    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
163354  }
163355  if( rc==SQLITE_OK ){
163356#ifdef SQLITE_RTREE_INT_ONLY
163357    void *c = (void *)RTREE_COORD_INT32;
163358#else
163359    void *c = (void *)RTREE_COORD_REAL32;
163360#endif
163361    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
163362  }
163363  if( rc==SQLITE_OK ){
163364    void *c = (void *)RTREE_COORD_INT32;
163365    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
163366  }
163367
163368  return rc;
163369}
163370
163371/*
163372** This routine deletes the RtreeGeomCallback object that was attached
163373** one of the SQL functions create by sqlite3_rtree_geometry_callback()
163374** or sqlite3_rtree_query_callback().  In other words, this routine is the
163375** destructor for an RtreeGeomCallback objecct.  This routine is called when
163376** the corresponding SQL function is deleted.
163377*/
163378static void rtreeFreeCallback(void *p){
163379  RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
163380  if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
163381  sqlite3_free(p);
163382}
163383
163384/*
163385** This routine frees the BLOB that is returned by geomCallback().
163386*/
163387static void rtreeMatchArgFree(void *pArg){
163388  int i;
163389  RtreeMatchArg *p = (RtreeMatchArg*)pArg;
163390  for(i=0; i<p->nParam; i++){
163391    sqlite3_value_free(p->apSqlParam[i]);
163392  }
163393  sqlite3_free(p);
163394}
163395
163396/*
163397** Each call to sqlite3_rtree_geometry_callback() or
163398** sqlite3_rtree_query_callback() creates an ordinary SQLite
163399** scalar function that is implemented by this routine.
163400**
163401** All this function does is construct an RtreeMatchArg object that
163402** contains the geometry-checking callback routines and a list of
163403** parameters to this function, then return that RtreeMatchArg object
163404** as a BLOB.
163405**
163406** The R-Tree MATCH operator will read the returned BLOB, deserialize
163407** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
163408** out which elements of the R-Tree should be returned by the query.
163409*/
163410static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
163411  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
163412  RtreeMatchArg *pBlob;
163413  int nBlob;
163414  int memErr = 0;
163415
163416  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
163417           + nArg*sizeof(sqlite3_value*);
163418  pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
163419  if( !pBlob ){
163420    sqlite3_result_error_nomem(ctx);
163421  }else{
163422    int i;
163423    pBlob->magic = RTREE_GEOMETRY_MAGIC;
163424    pBlob->cb = pGeomCtx[0];
163425    pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
163426    pBlob->nParam = nArg;
163427    for(i=0; i<nArg; i++){
163428      pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
163429      if( pBlob->apSqlParam[i]==0 ) memErr = 1;
163430#ifdef SQLITE_RTREE_INT_ONLY
163431      pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
163432#else
163433      pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
163434#endif
163435    }
163436    if( memErr ){
163437      sqlite3_result_error_nomem(ctx);
163438      rtreeMatchArgFree(pBlob);
163439    }else{
163440      sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree);
163441    }
163442  }
163443}
163444
163445/*
163446** Register a new geometry function for use with the r-tree MATCH operator.
163447*/
163448SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
163449  sqlite3 *db,                  /* Register SQL function on this connection */
163450  const char *zGeom,            /* Name of the new SQL function */
163451  int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
163452  void *pContext                /* Extra data associated with the callback */
163453){
163454  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
163455
163456  /* Allocate and populate the context object. */
163457  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
163458  if( !pGeomCtx ) return SQLITE_NOMEM;
163459  pGeomCtx->xGeom = xGeom;
163460  pGeomCtx->xQueryFunc = 0;
163461  pGeomCtx->xDestructor = 0;
163462  pGeomCtx->pContext = pContext;
163463  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
163464      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
163465  );
163466}
163467
163468/*
163469** Register a new 2nd-generation geometry function for use with the
163470** r-tree MATCH operator.
163471*/
163472SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
163473  sqlite3 *db,                 /* Register SQL function on this connection */
163474  const char *zQueryFunc,      /* Name of new SQL function */
163475  int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
163476  void *pContext,              /* Extra data passed into the callback */
163477  void (*xDestructor)(void*)   /* Destructor for the extra data */
163478){
163479  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
163480
163481  /* Allocate and populate the context object. */
163482  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
163483  if( !pGeomCtx ) return SQLITE_NOMEM;
163484  pGeomCtx->xGeom = 0;
163485  pGeomCtx->xQueryFunc = xQueryFunc;
163486  pGeomCtx->xDestructor = xDestructor;
163487  pGeomCtx->pContext = pContext;
163488  return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
163489      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
163490  );
163491}
163492
163493#if !SQLITE_CORE
163494#ifdef _WIN32
163495__declspec(dllexport)
163496#endif
163497SQLITE_API int SQLITE_STDCALL sqlite3_rtree_init(
163498  sqlite3 *db,
163499  char **pzErrMsg,
163500  const sqlite3_api_routines *pApi
163501){
163502  SQLITE_EXTENSION_INIT2(pApi)
163503  return sqlite3RtreeInit(db);
163504}
163505#endif
163506
163507#endif
163508
163509/************** End of rtree.c ***********************************************/
163510/************** Begin file icu.c *********************************************/
163511/*
163512** 2007 May 6
163513**
163514** The author disclaims copyright to this source code.  In place of
163515** a legal notice, here is a blessing:
163516**
163517**    May you do good and not evil.
163518**    May you find forgiveness for yourself and forgive others.
163519**    May you share freely, never taking more than you give.
163520**
163521*************************************************************************
163522** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
163523**
163524** This file implements an integration between the ICU library
163525** ("International Components for Unicode", an open-source library
163526** for handling unicode data) and SQLite. The integration uses
163527** ICU to provide the following to SQLite:
163528**
163529**   * An implementation of the SQL regexp() function (and hence REGEXP
163530**     operator) using the ICU uregex_XX() APIs.
163531**
163532**   * Implementations of the SQL scalar upper() and lower() functions
163533**     for case mapping.
163534**
163535**   * Integration of ICU and SQLite collation sequences.
163536**
163537**   * An implementation of the LIKE operator that uses ICU to
163538**     provide case-independent matching.
163539*/
163540
163541#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
163542
163543/* Include ICU headers */
163544#include <unicode/utypes.h>
163545#include <unicode/uregex.h>
163546#include <unicode/ustring.h>
163547#include <unicode/ucol.h>
163548
163549/* #include <assert.h> */
163550
163551#ifndef SQLITE_CORE
163552/*   #include "sqlite3ext.h" */
163553  SQLITE_EXTENSION_INIT1
163554#else
163555/*   #include "sqlite3.h" */
163556#endif
163557
163558/*
163559** Maximum length (in bytes) of the pattern in a LIKE or GLOB
163560** operator.
163561*/
163562#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
163563# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
163564#endif
163565
163566/*
163567** Version of sqlite3_free() that is always a function, never a macro.
163568*/
163569static void xFree(void *p){
163570  sqlite3_free(p);
163571}
163572
163573/*
163574** This lookup table is used to help decode the first byte of
163575** a multi-byte UTF8 character. It is copied here from SQLite source
163576** code file utf8.c.
163577*/
163578static const unsigned char icuUtf8Trans1[] = {
163579  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
163580  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
163581  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
163582  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
163583  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
163584  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
163585  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
163586  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
163587};
163588
163589#define SQLITE_ICU_READ_UTF8(zIn, c)                       \
163590  c = *(zIn++);                                            \
163591  if( c>=0xc0 ){                                           \
163592    c = icuUtf8Trans1[c-0xc0];                             \
163593    while( (*zIn & 0xc0)==0x80 ){                          \
163594      c = (c<<6) + (0x3f & *(zIn++));                      \
163595    }                                                      \
163596  }
163597
163598#define SQLITE_ICU_SKIP_UTF8(zIn)                          \
163599  assert( *zIn );                                          \
163600  if( *(zIn++)>=0xc0 ){                                    \
163601    while( (*zIn & 0xc0)==0x80 ){zIn++;}                   \
163602  }
163603
163604
163605/*
163606** Compare two UTF-8 strings for equality where the first string is
163607** a "LIKE" expression. Return true (1) if they are the same and
163608** false (0) if they are different.
163609*/
163610static int icuLikeCompare(
163611  const uint8_t *zPattern,   /* LIKE pattern */
163612  const uint8_t *zString,    /* The UTF-8 string to compare against */
163613  const UChar32 uEsc         /* The escape character */
163614){
163615  static const int MATCH_ONE = (UChar32)'_';
163616  static const int MATCH_ALL = (UChar32)'%';
163617
163618  int prevEscape = 0;     /* True if the previous character was uEsc */
163619
163620  while( 1 ){
163621
163622    /* Read (and consume) the next character from the input pattern. */
163623    UChar32 uPattern;
163624    SQLITE_ICU_READ_UTF8(zPattern, uPattern);
163625    if( uPattern==0 ) break;
163626
163627    /* There are now 4 possibilities:
163628    **
163629    **     1. uPattern is an unescaped match-all character "%",
163630    **     2. uPattern is an unescaped match-one character "_",
163631    **     3. uPattern is an unescaped escape character, or
163632    **     4. uPattern is to be handled as an ordinary character
163633    */
163634    if( !prevEscape && uPattern==MATCH_ALL ){
163635      /* Case 1. */
163636      uint8_t c;
163637
163638      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
163639      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
163640      ** test string.
163641      */
163642      while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
163643        if( c==MATCH_ONE ){
163644          if( *zString==0 ) return 0;
163645          SQLITE_ICU_SKIP_UTF8(zString);
163646        }
163647        zPattern++;
163648      }
163649
163650      if( *zPattern==0 ) return 1;
163651
163652      while( *zString ){
163653        if( icuLikeCompare(zPattern, zString, uEsc) ){
163654          return 1;
163655        }
163656        SQLITE_ICU_SKIP_UTF8(zString);
163657      }
163658      return 0;
163659
163660    }else if( !prevEscape && uPattern==MATCH_ONE ){
163661      /* Case 2. */
163662      if( *zString==0 ) return 0;
163663      SQLITE_ICU_SKIP_UTF8(zString);
163664
163665    }else if( !prevEscape && uPattern==uEsc){
163666      /* Case 3. */
163667      prevEscape = 1;
163668
163669    }else{
163670      /* Case 4. */
163671      UChar32 uString;
163672      SQLITE_ICU_READ_UTF8(zString, uString);
163673      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
163674      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
163675      if( uString!=uPattern ){
163676        return 0;
163677      }
163678      prevEscape = 0;
163679    }
163680  }
163681
163682  return *zString==0;
163683}
163684
163685/*
163686** Implementation of the like() SQL function.  This function implements
163687** the build-in LIKE operator.  The first argument to the function is the
163688** pattern and the second argument is the string.  So, the SQL statements:
163689**
163690**       A LIKE B
163691**
163692** is implemented as like(B, A). If there is an escape character E,
163693**
163694**       A LIKE B ESCAPE E
163695**
163696** is mapped to like(B, A, E).
163697*/
163698static void icuLikeFunc(
163699  sqlite3_context *context,
163700  int argc,
163701  sqlite3_value **argv
163702){
163703  const unsigned char *zA = sqlite3_value_text(argv[0]);
163704  const unsigned char *zB = sqlite3_value_text(argv[1]);
163705  UChar32 uEsc = 0;
163706
163707  /* Limit the length of the LIKE or GLOB pattern to avoid problems
163708  ** of deep recursion and N*N behavior in patternCompare().
163709  */
163710  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
163711    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
163712    return;
163713  }
163714
163715
163716  if( argc==3 ){
163717    /* The escape character string must consist of a single UTF-8 character.
163718    ** Otherwise, return an error.
163719    */
163720    int nE= sqlite3_value_bytes(argv[2]);
163721    const unsigned char *zE = sqlite3_value_text(argv[2]);
163722    int i = 0;
163723    if( zE==0 ) return;
163724    U8_NEXT(zE, i, nE, uEsc);
163725    if( i!=nE){
163726      sqlite3_result_error(context,
163727          "ESCAPE expression must be a single character", -1);
163728      return;
163729    }
163730  }
163731
163732  if( zA && zB ){
163733    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
163734  }
163735}
163736
163737/*
163738** This function is called when an ICU function called from within
163739** the implementation of an SQL scalar function returns an error.
163740**
163741** The scalar function context passed as the first argument is
163742** loaded with an error message based on the following two args.
163743*/
163744static void icuFunctionError(
163745  sqlite3_context *pCtx,       /* SQLite scalar function context */
163746  const char *zName,           /* Name of ICU function that failed */
163747  UErrorCode e                 /* Error code returned by ICU function */
163748){
163749  char zBuf[128];
163750  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
163751  zBuf[127] = '\0';
163752  sqlite3_result_error(pCtx, zBuf, -1);
163753}
163754
163755/*
163756** Function to delete compiled regexp objects. Registered as
163757** a destructor function with sqlite3_set_auxdata().
163758*/
163759static void icuRegexpDelete(void *p){
163760  URegularExpression *pExpr = (URegularExpression *)p;
163761  uregex_close(pExpr);
163762}
163763
163764/*
163765** Implementation of SQLite REGEXP operator. This scalar function takes
163766** two arguments. The first is a regular expression pattern to compile
163767** the second is a string to match against that pattern. If either
163768** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
163769** is 1 if the string matches the pattern, or 0 otherwise.
163770**
163771** SQLite maps the regexp() function to the regexp() operator such
163772** that the following two are equivalent:
163773**
163774**     zString REGEXP zPattern
163775**     regexp(zPattern, zString)
163776**
163777** Uses the following ICU regexp APIs:
163778**
163779**     uregex_open()
163780**     uregex_matches()
163781**     uregex_close()
163782*/
163783static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
163784  UErrorCode status = U_ZERO_ERROR;
163785  URegularExpression *pExpr;
163786  UBool res;
163787  const UChar *zString = sqlite3_value_text16(apArg[1]);
163788
163789  (void)nArg;  /* Unused parameter */
163790
163791  /* If the left hand side of the regexp operator is NULL,
163792  ** then the result is also NULL.
163793  */
163794  if( !zString ){
163795    return;
163796  }
163797
163798  pExpr = sqlite3_get_auxdata(p, 0);
163799  if( !pExpr ){
163800    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
163801    if( !zPattern ){
163802      return;
163803    }
163804    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
163805
163806    if( U_SUCCESS(status) ){
163807      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
163808    }else{
163809      assert(!pExpr);
163810      icuFunctionError(p, "uregex_open", status);
163811      return;
163812    }
163813  }
163814
163815  /* Configure the text that the regular expression operates on. */
163816  uregex_setText(pExpr, zString, -1, &status);
163817  if( !U_SUCCESS(status) ){
163818    icuFunctionError(p, "uregex_setText", status);
163819    return;
163820  }
163821
163822  /* Attempt the match */
163823  res = uregex_matches(pExpr, 0, &status);
163824  if( !U_SUCCESS(status) ){
163825    icuFunctionError(p, "uregex_matches", status);
163826    return;
163827  }
163828
163829  /* Set the text that the regular expression operates on to a NULL
163830  ** pointer. This is not really necessary, but it is tidier than
163831  ** leaving the regular expression object configured with an invalid
163832  ** pointer after this function returns.
163833  */
163834  uregex_setText(pExpr, 0, 0, &status);
163835
163836  /* Return 1 or 0. */
163837  sqlite3_result_int(p, res ? 1 : 0);
163838}
163839
163840/*
163841** Implementations of scalar functions for case mapping - upper() and
163842** lower(). Function upper() converts its input to upper-case (ABC).
163843** Function lower() converts to lower-case (abc).
163844**
163845** ICU provides two types of case mapping, "general" case mapping and
163846** "language specific". Refer to ICU documentation for the differences
163847** between the two.
163848**
163849** To utilise "general" case mapping, the upper() or lower() scalar
163850** functions are invoked with one argument:
163851**
163852**     upper('ABC') -> 'abc'
163853**     lower('abc') -> 'ABC'
163854**
163855** To access ICU "language specific" case mapping, upper() or lower()
163856** should be invoked with two arguments. The second argument is the name
163857** of the locale to use. Passing an empty string ("") or SQL NULL value
163858** as the second argument is the same as invoking the 1 argument version
163859** of upper() or lower().
163860**
163861**     lower('I', 'en_us') -> 'i'
163862**     lower('I', 'tr_tr') -> 'ı' (small dotless i)
163863**
163864** http://www.icu-project.org/userguide/posix.html#case_mappings
163865*/
163866static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
163867  const UChar *zInput;            /* Pointer to input string */
163868  UChar *zOutput = 0;             /* Pointer to output buffer */
163869  int nInput;                     /* Size of utf-16 input string in bytes */
163870  int nOut;                       /* Size of output buffer in bytes */
163871  int cnt;
163872  int bToUpper;                   /* True for toupper(), false for tolower() */
163873  UErrorCode status;
163874  const char *zLocale = 0;
163875
163876  assert(nArg==1 || nArg==2);
163877  bToUpper = (sqlite3_user_data(p)!=0);
163878  if( nArg==2 ){
163879    zLocale = (const char *)sqlite3_value_text(apArg[1]);
163880  }
163881
163882  zInput = sqlite3_value_text16(apArg[0]);
163883  if( !zInput ){
163884    return;
163885  }
163886  nOut = nInput = sqlite3_value_bytes16(apArg[0]);
163887  if( nOut==0 ){
163888    sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
163889    return;
163890  }
163891
163892  for(cnt=0; cnt<2; cnt++){
163893    UChar *zNew = sqlite3_realloc(zOutput, nOut);
163894    if( zNew==0 ){
163895      sqlite3_free(zOutput);
163896      sqlite3_result_error_nomem(p);
163897      return;
163898    }
163899    zOutput = zNew;
163900    status = U_ZERO_ERROR;
163901    if( bToUpper ){
163902      nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
163903    }else{
163904      nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
163905    }
163906
163907    if( U_SUCCESS(status) ){
163908      sqlite3_result_text16(p, zOutput, nOut, xFree);
163909    }else if( status==U_BUFFER_OVERFLOW_ERROR ){
163910      assert( cnt==0 );
163911      continue;
163912    }else{
163913      icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
163914    }
163915    return;
163916  }
163917  assert( 0 );     /* Unreachable */
163918}
163919
163920/*
163921** Collation sequence destructor function. The pCtx argument points to
163922** a UCollator structure previously allocated using ucol_open().
163923*/
163924static void icuCollationDel(void *pCtx){
163925  UCollator *p = (UCollator *)pCtx;
163926  ucol_close(p);
163927}
163928
163929/*
163930** Collation sequence comparison function. The pCtx argument points to
163931** a UCollator structure previously allocated using ucol_open().
163932*/
163933static int icuCollationColl(
163934  void *pCtx,
163935  int nLeft,
163936  const void *zLeft,
163937  int nRight,
163938  const void *zRight
163939){
163940  UCollationResult res;
163941  UCollator *p = (UCollator *)pCtx;
163942  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
163943  switch( res ){
163944    case UCOL_LESS:    return -1;
163945    case UCOL_GREATER: return +1;
163946    case UCOL_EQUAL:   return 0;
163947  }
163948  assert(!"Unexpected return value from ucol_strcoll()");
163949  return 0;
163950}
163951
163952/*
163953** Implementation of the scalar function icu_load_collation().
163954**
163955** This scalar function is used to add ICU collation based collation
163956** types to an SQLite database connection. It is intended to be called
163957** as follows:
163958**
163959**     SELECT icu_load_collation(<locale>, <collation-name>);
163960**
163961** Where <locale> is a string containing an ICU locale identifier (i.e.
163962** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
163963** collation sequence to create.
163964*/
163965static void icuLoadCollation(
163966  sqlite3_context *p,
163967  int nArg,
163968  sqlite3_value **apArg
163969){
163970  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
163971  UErrorCode status = U_ZERO_ERROR;
163972  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
163973  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
163974  UCollator *pUCollator;    /* ICU library collation object */
163975  int rc;                   /* Return code from sqlite3_create_collation_x() */
163976
163977  assert(nArg==2);
163978  (void)nArg; /* Unused parameter */
163979  zLocale = (const char *)sqlite3_value_text(apArg[0]);
163980  zName = (const char *)sqlite3_value_text(apArg[1]);
163981
163982  if( !zLocale || !zName ){
163983    return;
163984  }
163985
163986  pUCollator = ucol_open(zLocale, &status);
163987  if( !U_SUCCESS(status) ){
163988    icuFunctionError(p, "ucol_open", status);
163989    return;
163990  }
163991  assert(p);
163992
163993  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
163994      icuCollationColl, icuCollationDel
163995  );
163996  if( rc!=SQLITE_OK ){
163997    ucol_close(pUCollator);
163998    sqlite3_result_error(p, "Error registering collation function", -1);
163999  }
164000}
164001
164002/*
164003** Register the ICU extension functions with database db.
164004*/
164005SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
164006  struct IcuScalar {
164007    const char *zName;                        /* Function name */
164008    int nArg;                                 /* Number of arguments */
164009    int enc;                                  /* Optimal text encoding */
164010    void *pContext;                           /* sqlite3_user_data() context */
164011    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
164012  } scalars[] = {
164013    {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
164014
164015    {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
164016    {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
164017    {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
164018    {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
164019
164020    {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
164021    {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
164022    {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
164023    {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
164024
164025    {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
164026    {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
164027
164028    {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
164029  };
164030
164031  int rc = SQLITE_OK;
164032  int i;
164033
164034  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
164035    struct IcuScalar *p = &scalars[i];
164036    rc = sqlite3_create_function(
164037        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
164038    );
164039  }
164040
164041  return rc;
164042}
164043
164044#if !SQLITE_CORE
164045#ifdef _WIN32
164046__declspec(dllexport)
164047#endif
164048SQLITE_API int SQLITE_STDCALL sqlite3_icu_init(
164049  sqlite3 *db,
164050  char **pzErrMsg,
164051  const sqlite3_api_routines *pApi
164052){
164053  SQLITE_EXTENSION_INIT2(pApi)
164054  return sqlite3IcuInit(db);
164055}
164056#endif
164057
164058#endif
164059
164060/************** End of icu.c *************************************************/
164061/************** Begin file fts3_icu.c ****************************************/
164062/*
164063** 2007 June 22
164064**
164065** The author disclaims copyright to this source code.  In place of
164066** a legal notice, here is a blessing:
164067**
164068**    May you do good and not evil.
164069**    May you find forgiveness for yourself and forgive others.
164070**    May you share freely, never taking more than you give.
164071**
164072*************************************************************************
164073** This file implements a tokenizer for fts3 based on the ICU library.
164074*/
164075/* #include "fts3Int.h" */
164076#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
164077#ifdef SQLITE_ENABLE_ICU
164078
164079/* #include <assert.h> */
164080/* #include <string.h> */
164081/* #include "fts3_tokenizer.h" */
164082
164083#include <unicode/ubrk.h>
164084/* #include <unicode/ucol.h> */
164085/* #include <unicode/ustring.h> */
164086#include <unicode/utf16.h>
164087
164088typedef struct IcuTokenizer IcuTokenizer;
164089typedef struct IcuCursor IcuCursor;
164090
164091struct IcuTokenizer {
164092  sqlite3_tokenizer base;
164093  char *zLocale;
164094};
164095
164096struct IcuCursor {
164097  sqlite3_tokenizer_cursor base;
164098
164099  UBreakIterator *pIter;      /* ICU break-iterator object */
164100  int nChar;                  /* Number of UChar elements in pInput */
164101  UChar *aChar;               /* Copy of input using utf-16 encoding */
164102  int *aOffset;               /* Offsets of each character in utf-8 input */
164103
164104  int nBuffer;
164105  char *zBuffer;
164106
164107  int iToken;
164108};
164109
164110/*
164111** Create a new tokenizer instance.
164112*/
164113static int icuCreate(
164114  int argc,                            /* Number of entries in argv[] */
164115  const char * const *argv,            /* Tokenizer creation arguments */
164116  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
164117){
164118  IcuTokenizer *p;
164119  int n = 0;
164120
164121  if( argc>0 ){
164122    n = strlen(argv[0])+1;
164123  }
164124  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
164125  if( !p ){
164126    return SQLITE_NOMEM;
164127  }
164128  memset(p, 0, sizeof(IcuTokenizer));
164129
164130  if( n ){
164131    p->zLocale = (char *)&p[1];
164132    memcpy(p->zLocale, argv[0], n);
164133  }
164134
164135  *ppTokenizer = (sqlite3_tokenizer *)p;
164136
164137  return SQLITE_OK;
164138}
164139
164140/*
164141** Destroy a tokenizer
164142*/
164143static int icuDestroy(sqlite3_tokenizer *pTokenizer){
164144  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
164145  sqlite3_free(p);
164146  return SQLITE_OK;
164147}
164148
164149/*
164150** Prepare to begin tokenizing a particular string.  The input
164151** string to be tokenized is pInput[0..nBytes-1].  A cursor
164152** used to incrementally tokenize this string is returned in
164153** *ppCursor.
164154*/
164155static int icuOpen(
164156  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
164157  const char *zInput,                    /* Input string */
164158  int nInput,                            /* Length of zInput in bytes */
164159  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
164160){
164161  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
164162  IcuCursor *pCsr;
164163
164164  const int32_t opt = U_FOLD_CASE_DEFAULT;
164165  UErrorCode status = U_ZERO_ERROR;
164166  int nChar;
164167
164168  UChar32 c;
164169  int iInput = 0;
164170  int iOut = 0;
164171
164172  *ppCursor = 0;
164173
164174  if( zInput==0 ){
164175    nInput = 0;
164176    zInput = "";
164177  }else if( nInput<0 ){
164178    nInput = strlen(zInput);
164179  }
164180  nChar = nInput+1;
164181  pCsr = (IcuCursor *)sqlite3_malloc(
164182      sizeof(IcuCursor) +                /* IcuCursor */
164183      ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
164184      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
164185  );
164186  if( !pCsr ){
164187    return SQLITE_NOMEM;
164188  }
164189  memset(pCsr, 0, sizeof(IcuCursor));
164190  pCsr->aChar = (UChar *)&pCsr[1];
164191  pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
164192
164193  pCsr->aOffset[iOut] = iInput;
164194  U8_NEXT(zInput, iInput, nInput, c);
164195  while( c>0 ){
164196    int isError = 0;
164197    c = u_foldCase(c, opt);
164198    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
164199    if( isError ){
164200      sqlite3_free(pCsr);
164201      return SQLITE_ERROR;
164202    }
164203    pCsr->aOffset[iOut] = iInput;
164204
164205    if( iInput<nInput ){
164206      U8_NEXT(zInput, iInput, nInput, c);
164207    }else{
164208      c = 0;
164209    }
164210  }
164211
164212  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
164213  if( !U_SUCCESS(status) ){
164214    sqlite3_free(pCsr);
164215    return SQLITE_ERROR;
164216  }
164217  pCsr->nChar = iOut;
164218
164219  ubrk_first(pCsr->pIter);
164220  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
164221  return SQLITE_OK;
164222}
164223
164224/*
164225** Close a tokenization cursor previously opened by a call to icuOpen().
164226*/
164227static int icuClose(sqlite3_tokenizer_cursor *pCursor){
164228  IcuCursor *pCsr = (IcuCursor *)pCursor;
164229  ubrk_close(pCsr->pIter);
164230  sqlite3_free(pCsr->zBuffer);
164231  sqlite3_free(pCsr);
164232  return SQLITE_OK;
164233}
164234
164235/*
164236** Extract the next token from a tokenization cursor.
164237*/
164238static int icuNext(
164239  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
164240  const char **ppToken,               /* OUT: *ppToken is the token text */
164241  int *pnBytes,                       /* OUT: Number of bytes in token */
164242  int *piStartOffset,                 /* OUT: Starting offset of token */
164243  int *piEndOffset,                   /* OUT: Ending offset of token */
164244  int *piPosition                     /* OUT: Position integer of token */
164245){
164246  IcuCursor *pCsr = (IcuCursor *)pCursor;
164247
164248  int iStart = 0;
164249  int iEnd = 0;
164250  int nByte = 0;
164251
164252  while( iStart==iEnd ){
164253    UChar32 c;
164254
164255    iStart = ubrk_current(pCsr->pIter);
164256    iEnd = ubrk_next(pCsr->pIter);
164257    if( iEnd==UBRK_DONE ){
164258      return SQLITE_DONE;
164259    }
164260
164261    while( iStart<iEnd ){
164262      int iWhite = iStart;
164263      U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
164264      if( u_isspace(c) ){
164265        iStart = iWhite;
164266      }else{
164267        break;
164268      }
164269    }
164270    assert(iStart<=iEnd);
164271  }
164272
164273  do {
164274    UErrorCode status = U_ZERO_ERROR;
164275    if( nByte ){
164276      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
164277      if( !zNew ){
164278        return SQLITE_NOMEM;
164279      }
164280      pCsr->zBuffer = zNew;
164281      pCsr->nBuffer = nByte;
164282    }
164283
164284    u_strToUTF8(
164285        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
164286        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
164287        &status                                  /* Output success/failure */
164288    );
164289  } while( nByte>pCsr->nBuffer );
164290
164291  *ppToken = pCsr->zBuffer;
164292  *pnBytes = nByte;
164293  *piStartOffset = pCsr->aOffset[iStart];
164294  *piEndOffset = pCsr->aOffset[iEnd];
164295  *piPosition = pCsr->iToken++;
164296
164297  return SQLITE_OK;
164298}
164299
164300/*
164301** The set of routines that implement the simple tokenizer
164302*/
164303static const sqlite3_tokenizer_module icuTokenizerModule = {
164304  0,                           /* iVersion    */
164305  icuCreate,                   /* xCreate     */
164306  icuDestroy,                  /* xCreate     */
164307  icuOpen,                     /* xOpen       */
164308  icuClose,                    /* xClose      */
164309  icuNext,                     /* xNext       */
164310  0,                           /* xLanguageid */
164311};
164312
164313/*
164314** Set *ppModule to point at the implementation of the ICU tokenizer.
164315*/
164316SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
164317  sqlite3_tokenizer_module const**ppModule
164318){
164319  *ppModule = &icuTokenizerModule;
164320}
164321
164322#endif /* defined(SQLITE_ENABLE_ICU) */
164323#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
164324
164325/************** End of fts3_icu.c ********************************************/
164326/************** Begin file sqlite3rbu.c **************************************/
164327/*
164328** 2014 August 30
164329**
164330** The author disclaims copyright to this source code.  In place of
164331** a legal notice, here is a blessing:
164332**
164333**    May you do good and not evil.
164334**    May you find forgiveness for yourself and forgive others.
164335**    May you share freely, never taking more than you give.
164336**
164337*************************************************************************
164338**
164339**
164340** OVERVIEW
164341**
164342**  The RBU extension requires that the RBU update be packaged as an
164343**  SQLite database. The tables it expects to find are described in
164344**  sqlite3rbu.h.  Essentially, for each table xyz in the target database
164345**  that the user wishes to write to, a corresponding data_xyz table is
164346**  created in the RBU database and populated with one row for each row to
164347**  update, insert or delete from the target table.
164348**
164349**  The update proceeds in three stages:
164350**
164351**  1) The database is updated. The modified database pages are written
164352**     to a *-oal file. A *-oal file is just like a *-wal file, except
164353**     that it is named "<database>-oal" instead of "<database>-wal".
164354**     Because regular SQLite clients do not look for file named
164355**     "<database>-oal", they go on using the original database in
164356**     rollback mode while the *-oal file is being generated.
164357**
164358**     During this stage RBU does not update the database by writing
164359**     directly to the target tables. Instead it creates "imposter"
164360**     tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
164361**     to update each b-tree individually. All updates required by each
164362**     b-tree are completed before moving on to the next, and all
164363**     updates are done in sorted key order.
164364**
164365**  2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
164366**     location using a call to rename(2). Before doing this the RBU
164367**     module takes an EXCLUSIVE lock on the database file, ensuring
164368**     that there are no other active readers.
164369**
164370**     Once the EXCLUSIVE lock is released, any other database readers
164371**     detect the new *-wal file and read the database in wal mode. At
164372**     this point they see the new version of the database - including
164373**     the updates made as part of the RBU update.
164374**
164375**  3) The new *-wal file is checkpointed. This proceeds in the same way
164376**     as a regular database checkpoint, except that a single frame is
164377**     checkpointed each time sqlite3rbu_step() is called. If the RBU
164378**     handle is closed before the entire *-wal file is checkpointed,
164379**     the checkpoint progress is saved in the RBU database and the
164380**     checkpoint can be resumed by another RBU client at some point in
164381**     the future.
164382**
164383** POTENTIAL PROBLEMS
164384**
164385**  The rename() call might not be portable. And RBU is not currently
164386**  syncing the directory after renaming the file.
164387**
164388**  When state is saved, any commit to the *-oal file and the commit to
164389**  the RBU update database are not atomic. So if the power fails at the
164390**  wrong moment they might get out of sync. As the main database will be
164391**  committed before the RBU update database this will likely either just
164392**  pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
164393**  constraint violations).
164394**
164395**  If some client does modify the target database mid RBU update, or some
164396**  other error occurs, the RBU extension will keep throwing errors. It's
164397**  not really clear how to get out of this state. The system could just
164398**  by delete the RBU update database and *-oal file and have the device
164399**  download the update again and start over.
164400**
164401**  At present, for an UPDATE, both the new.* and old.* records are
164402**  collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
164403**  fields are collected.  This means we're probably writing a lot more
164404**  data to disk when saving the state of an ongoing update to the RBU
164405**  update database than is strictly necessary.
164406**
164407*/
164408
164409/* #include <assert.h> */
164410/* #include <string.h> */
164411/* #include <stdio.h> */
164412
164413/* #include "sqlite3.h" */
164414
164415#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
164416/************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
164417/************** Begin file sqlite3rbu.h **************************************/
164418/*
164419** 2014 August 30
164420**
164421** The author disclaims copyright to this source code.  In place of
164422** a legal notice, here is a blessing:
164423**
164424**    May you do good and not evil.
164425**    May you find forgiveness for yourself and forgive others.
164426**    May you share freely, never taking more than you give.
164427**
164428*************************************************************************
164429**
164430** This file contains the public interface for the RBU extension.
164431*/
164432
164433/*
164434** SUMMARY
164435**
164436** Writing a transaction containing a large number of operations on
164437** b-tree indexes that are collectively larger than the available cache
164438** memory can be very inefficient.
164439**
164440** The problem is that in order to update a b-tree, the leaf page (at least)
164441** containing the entry being inserted or deleted must be modified. If the
164442** working set of leaves is larger than the available cache memory, then a
164443** single leaf that is modified more than once as part of the transaction
164444** may be loaded from or written to the persistent media multiple times.
164445** Additionally, because the index updates are likely to be applied in
164446** random order, access to pages within the database is also likely to be in
164447** random order, which is itself quite inefficient.
164448**
164449** One way to improve the situation is to sort the operations on each index
164450** by index key before applying them to the b-tree. This leads to an IO
164451** pattern that resembles a single linear scan through the index b-tree,
164452** and all but guarantees each modified leaf page is loaded and stored
164453** exactly once. SQLite uses this trick to improve the performance of
164454** CREATE INDEX commands. This extension allows it to be used to improve
164455** the performance of large transactions on existing databases.
164456**
164457** Additionally, this extension allows the work involved in writing the
164458** large transaction to be broken down into sub-transactions performed
164459** sequentially by separate processes. This is useful if the system cannot
164460** guarantee that a single update process will run for long enough to apply
164461** the entire update, for example because the update is being applied on a
164462** mobile device that is frequently rebooted. Even after the writer process
164463** has committed one or more sub-transactions, other database clients continue
164464** to read from the original database snapshot. In other words, partially
164465** applied transactions are not visible to other clients.
164466**
164467** "RBU" stands for "Resumable Bulk Update". As in a large database update
164468** transmitted via a wireless network to a mobile device. A transaction
164469** applied using this extension is hence refered to as an "RBU update".
164470**
164471**
164472** LIMITATIONS
164473**
164474** An "RBU update" transaction is subject to the following limitations:
164475**
164476**   * The transaction must consist of INSERT, UPDATE and DELETE operations
164477**     only.
164478**
164479**   * INSERT statements may not use any default values.
164480**
164481**   * UPDATE and DELETE statements must identify their target rows by
164482**     non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
164483**     KEY fields may not be updated or deleted. If the table being written
164484**     has no PRIMARY KEY, affected rows must be identified by rowid.
164485**
164486**   * UPDATE statements may not modify PRIMARY KEY columns.
164487**
164488**   * No triggers will be fired.
164489**
164490**   * No foreign key violations are detected or reported.
164491**
164492**   * CHECK constraints are not enforced.
164493**
164494**   * No constraint handling mode except for "OR ROLLBACK" is supported.
164495**
164496**
164497** PREPARATION
164498**
164499** An "RBU update" is stored as a separate SQLite database. A database
164500** containing an RBU update is an "RBU database". For each table in the
164501** target database to be updated, the RBU database should contain a table
164502** named "data_<target name>" containing the same set of columns as the
164503** target table, and one more - "rbu_control". The data_% table should
164504** have no PRIMARY KEY or UNIQUE constraints, but each column should have
164505** the same type as the corresponding column in the target database.
164506** The "rbu_control" column should have no type at all. For example, if
164507** the target database contains:
164508**
164509**   CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
164510**
164511** Then the RBU database should contain:
164512**
164513**   CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
164514**
164515** The order of the columns in the data_% table does not matter.
164516**
164517** Instead of a regular table, the RBU database may also contain virtual
164518** tables or view named using the data_<target> naming scheme.
164519**
164520** Instead of the plain data_<target> naming scheme, RBU database tables
164521** may also be named data<integer>_<target>, where <integer> is any sequence
164522** of zero or more numeric characters (0-9). This can be significant because
164523** tables within the RBU database are always processed in order sorted by
164524** name. By judicious selection of the the <integer> portion of the names
164525** of the RBU tables the user can therefore control the order in which they
164526** are processed. This can be useful, for example, to ensure that "external
164527** content" FTS4 tables are updated before their underlying content tables.
164528**
164529** If the target database table is a virtual table or a table that has no
164530** PRIMARY KEY declaration, the data_% table must also contain a column
164531** named "rbu_rowid". This column is mapped to the tables implicit primary
164532** key column - "rowid". Virtual tables for which the "rowid" column does
164533** not function like a primary key value cannot be updated using RBU. For
164534** example, if the target db contains either of the following:
164535**
164536**   CREATE VIRTUAL TABLE x1 USING fts3(a, b);
164537**   CREATE TABLE x1(a, b)
164538**
164539** then the RBU database should contain:
164540**
164541**   CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
164542**
164543** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
164544** target table must be present in the input table. For virtual tables,
164545** hidden columns are optional - they are updated by RBU if present in
164546** the input table, or not otherwise. For example, to write to an fts4
164547** table with a hidden languageid column such as:
164548**
164549**   CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
164550**
164551** Either of the following input table schemas may be used:
164552**
164553**   CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
164554**   CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
164555**
164556** For each row to INSERT into the target database as part of the RBU
164557** update, the corresponding data_% table should contain a single record
164558** with the "rbu_control" column set to contain integer value 0. The
164559** other columns should be set to the values that make up the new record
164560** to insert.
164561**
164562** If the target database table has an INTEGER PRIMARY KEY, it is not
164563** possible to insert a NULL value into the IPK column. Attempting to
164564** do so results in an SQLITE_MISMATCH error.
164565**
164566** For each row to DELETE from the target database as part of the RBU
164567** update, the corresponding data_% table should contain a single record
164568** with the "rbu_control" column set to contain integer value 1. The
164569** real primary key values of the row to delete should be stored in the
164570** corresponding columns of the data_% table. The values stored in the
164571** other columns are not used.
164572**
164573** For each row to UPDATE from the target database as part of the RBU
164574** update, the corresponding data_% table should contain a single record
164575** with the "rbu_control" column set to contain a value of type text.
164576** The real primary key values identifying the row to update should be
164577** stored in the corresponding columns of the data_% table row, as should
164578** the new values of all columns being update. The text value in the
164579** "rbu_control" column must contain the same number of characters as
164580** there are columns in the target database table, and must consist entirely
164581** of 'x' and '.' characters (or in some special cases 'd' - see below). For
164582** each column that is being updated, the corresponding character is set to
164583** 'x'. For those that remain as they are, the corresponding character of the
164584** rbu_control value should be set to '.'. For example, given the tables
164585** above, the update statement:
164586**
164587**   UPDATE t1 SET c = 'usa' WHERE a = 4;
164588**
164589** is represented by the data_t1 row created by:
164590**
164591**   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
164592**
164593** Instead of an 'x' character, characters of the rbu_control value specified
164594** for UPDATEs may also be set to 'd'. In this case, instead of updating the
164595** target table with the value stored in the corresponding data_% column, the
164596** user-defined SQL function "rbu_delta()" is invoked and the result stored in
164597** the target table column. rbu_delta() is invoked with two arguments - the
164598** original value currently stored in the target table column and the
164599** value specified in the data_xxx table.
164600**
164601** For example, this row:
164602**
164603**   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
164604**
164605** is similar to an UPDATE statement such as:
164606**
164607**   UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
164608**
164609** Finally, if an 'f' character appears in place of a 'd' or 's' in an
164610** ota_control string, the contents of the data_xxx table column is assumed
164611** to be a "fossil delta" - a patch to be applied to a blob value in the
164612** format used by the fossil source-code management system. In this case
164613** the existing value within the target database table must be of type BLOB.
164614** It is replaced by the result of applying the specified fossil delta to
164615** itself.
164616**
164617** If the target database table is a virtual table or a table with no PRIMARY
164618** KEY, the rbu_control value should not include a character corresponding
164619** to the rbu_rowid value. For example, this:
164620**
164621**   INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
164622**       VALUES(NULL, 'usa', 12, '.x');
164623**
164624** causes a result similar to:
164625**
164626**   UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
164627**
164628** The data_xxx tables themselves should have no PRIMARY KEY declarations.
164629** However, RBU is more efficient if reading the rows in from each data_xxx
164630** table in "rowid" order is roughly the same as reading them sorted by
164631** the PRIMARY KEY of the corresponding target database table. In other
164632** words, rows should be sorted using the destination table PRIMARY KEY
164633** fields before they are inserted into the data_xxx tables.
164634**
164635** USAGE
164636**
164637** The API declared below allows an application to apply an RBU update
164638** stored on disk to an existing target database. Essentially, the
164639** application:
164640**
164641**     1) Opens an RBU handle using the sqlite3rbu_open() function.
164642**
164643**     2) Registers any required virtual table modules with the database
164644**        handle returned by sqlite3rbu_db(). Also, if required, register
164645**        the rbu_delta() implementation.
164646**
164647**     3) Calls the sqlite3rbu_step() function one or more times on
164648**        the new handle. Each call to sqlite3rbu_step() performs a single
164649**        b-tree operation, so thousands of calls may be required to apply
164650**        a complete update.
164651**
164652**     4) Calls sqlite3rbu_close() to close the RBU update handle. If
164653**        sqlite3rbu_step() has been called enough times to completely
164654**        apply the update to the target database, then the RBU database
164655**        is marked as fully applied. Otherwise, the state of the RBU
164656**        update application is saved in the RBU database for later
164657**        resumption.
164658**
164659** See comments below for more detail on APIs.
164660**
164661** If an update is only partially applied to the target database by the
164662** time sqlite3rbu_close() is called, various state information is saved
164663** within the RBU database. This allows subsequent processes to automatically
164664** resume the RBU update from where it left off.
164665**
164666** To remove all RBU extension state information, returning an RBU database
164667** to its original contents, it is sufficient to drop all tables that begin
164668** with the prefix "rbu_"
164669**
164670** DATABASE LOCKING
164671**
164672** An RBU update may not be applied to a database in WAL mode. Attempting
164673** to do so is an error (SQLITE_ERROR).
164674**
164675** While an RBU handle is open, a SHARED lock may be held on the target
164676** database file. This means it is possible for other clients to read the
164677** database, but not to write it.
164678**
164679** If an RBU update is started and then suspended before it is completed,
164680** then an external client writes to the database, then attempting to resume
164681** the suspended RBU update is also an error (SQLITE_BUSY).
164682*/
164683
164684#ifndef _SQLITE3RBU_H
164685#define _SQLITE3RBU_H
164686
164687/* #include "sqlite3.h"              ** Required for error code definitions ** */
164688
164689#if 0
164690extern "C" {
164691#endif
164692
164693typedef struct sqlite3rbu sqlite3rbu;
164694
164695/*
164696** Open an RBU handle.
164697**
164698** Argument zTarget is the path to the target database. Argument zRbu is
164699** the path to the RBU database. Each call to this function must be matched
164700** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
164701** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
164702** or zRbu begin with "file:", it will be interpreted as an SQLite
164703** database URI, not a regular file name.
164704**
164705** If the zState argument is passed a NULL value, the RBU extension stores
164706** the current state of the update (how many rows have been updated, which
164707** indexes are yet to be updated etc.) within the RBU database itself. This
164708** can be convenient, as it means that the RBU application does not need to
164709** organize removing a separate state file after the update is concluded.
164710** Or, if zState is non-NULL, it must be a path to a database file in which
164711** the RBU extension can store the state of the update.
164712**
164713** When resuming an RBU update, the zState argument must be passed the same
164714** value as when the RBU update was started.
164715**
164716** Once the RBU update is finished, the RBU extension does not
164717** automatically remove any zState database file, even if it created it.
164718**
164719** By default, RBU uses the default VFS to access the files on disk. To
164720** use a VFS other than the default, an SQLite "file:" URI containing a
164721** "vfs=..." option may be passed as the zTarget option.
164722**
164723** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
164724** SQLite's built-in VFSs, including the multiplexor VFS. However it does
164725** not work out of the box with zipvfs. Refer to the comment describing
164726** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
164727*/
164728SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
164729  const char *zTarget,
164730  const char *zRbu,
164731  const char *zState
164732);
164733
164734/*
164735** Open an RBU handle to perform an RBU vacuum on database file zTarget.
164736** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
164737** that it can be suspended and resumed like an RBU update.
164738**
164739** The second argument to this function, which may not be NULL, identifies
164740** a database in which to store the state of the RBU vacuum operation if
164741** it is suspended. The first time sqlite3rbu_vacuum() is called, to start
164742** an RBU vacuum operation, the state database should either not exist or
164743** be empty (contain no tables). If an RBU vacuum is suspended by calling
164744** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
164745** returned SQLITE_DONE, the vacuum state is stored in the state database.
164746** The vacuum can be resumed by calling this function to open a new RBU
164747** handle specifying the same target and state databases.
164748**
164749** This function does not delete the state database after an RBU vacuum
164750** is completed, even if it created it. However, if the call to
164751** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
164752** of the state tables within the state database are zeroed. This way,
164753** the next call to sqlite3rbu_vacuum() opens a handle that starts a
164754** new RBU vacuum operation.
164755**
164756** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
164757** describing the sqlite3rbu_create_vfs() API function below for
164758** a description of the complications associated with using RBU with
164759** zipvfs databases.
164760*/
164761SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_vacuum(
164762  const char *zTarget,
164763  const char *zState
164764);
164765
164766/*
164767** Internally, each RBU connection uses a separate SQLite database
164768** connection to access the target and rbu update databases. This
164769** API allows the application direct access to these database handles.
164770**
164771** The first argument passed to this function must be a valid, open, RBU
164772** handle. The second argument should be passed zero to access the target
164773** database handle, or non-zero to access the rbu update database handle.
164774** Accessing the underlying database handles may be useful in the
164775** following scenarios:
164776**
164777**   * If any target tables are virtual tables, it may be necessary to
164778**     call sqlite3_create_module() on the target database handle to
164779**     register the required virtual table implementations.
164780**
164781**   * If the data_xxx tables in the RBU source database are virtual
164782**     tables, the application may need to call sqlite3_create_module() on
164783**     the rbu update db handle to any required virtual table
164784**     implementations.
164785**
164786**   * If the application uses the "rbu_delta()" feature described above,
164787**     it must use sqlite3_create_function() or similar to register the
164788**     rbu_delta() implementation with the target database handle.
164789**
164790** If an error has occurred, either while opening or stepping the RBU object,
164791** this function may return NULL. The error code and message may be collected
164792** when sqlite3rbu_close() is called.
164793**
164794** Database handles returned by this function remain valid until the next
164795** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
164796*/
164797SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu*, int bRbu);
164798
164799/*
164800** Do some work towards applying the RBU update to the target db.
164801**
164802** Return SQLITE_DONE if the update has been completely applied, or
164803** SQLITE_OK if no error occurs but there remains work to do to apply
164804** the RBU update. If an error does occur, some other error code is
164805** returned.
164806**
164807** Once a call to sqlite3rbu_step() has returned a value other than
164808** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
164809** that immediately return the same value.
164810*/
164811SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *pRbu);
164812
164813/*
164814** Force RBU to save its state to disk.
164815**
164816** If a power failure or application crash occurs during an update, following
164817** system recovery RBU may resume the update from the point at which the state
164818** was last saved. In other words, from the most recent successful call to
164819** sqlite3rbu_close() or this function.
164820**
164821** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
164822*/
164823SQLITE_API int SQLITE_STDCALL sqlite3rbu_savestate(sqlite3rbu *pRbu);
164824
164825/*
164826** Close an RBU handle.
164827**
164828** If the RBU update has been completely applied, mark the RBU database
164829** as fully applied. Otherwise, assuming no error has occurred, save the
164830** current state of the RBU update appliation to the RBU database.
164831**
164832** If an error has already occurred as part of an sqlite3rbu_step()
164833** or sqlite3rbu_open() call, or if one occurs within this function, an
164834** SQLite error code is returned. Additionally, *pzErrmsg may be set to
164835** point to a buffer containing a utf-8 formatted English language error
164836** message. It is the responsibility of the caller to eventually free any
164837** such buffer using sqlite3_free().
164838**
164839** Otherwise, if no error occurs, this function returns SQLITE_OK if the
164840** update has been partially applied, or SQLITE_DONE if it has been
164841** completely applied.
164842*/
164843SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
164844
164845/*
164846** Return the total number of key-value operations (inserts, deletes or
164847** updates) that have been performed on the target database since the
164848** current RBU update was started.
164849*/
164850SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu);
164851
164852/*
164853** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
164854** progress indications for the two stages of an RBU update. This API may
164855** be useful for driving GUI progress indicators and similar.
164856**
164857** An RBU update is divided into two stages:
164858**
164859**   * Stage 1, in which changes are accumulated in an oal/wal file, and
164860**   * Stage 2, in which the contents of the wal file are copied into the
164861**     main database.
164862**
164863** The update is visible to non-RBU clients during stage 2. During stage 1
164864** non-RBU reader clients may see the original database.
164865**
164866** If this API is called during stage 2 of the update, output variable
164867** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
164868** to a value between 0 and 10000 to indicate the permyriadage progress of
164869** stage 2. A value of 5000 indicates that stage 2 is half finished,
164870** 9000 indicates that it is 90% finished, and so on.
164871**
164872** If this API is called during stage 1 of the update, output variable
164873** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
164874** value to which (*pnOne) is set depends on whether or not the RBU
164875** database contains an "rbu_count" table. The rbu_count table, if it
164876** exists, must contain the same columns as the following:
164877**
164878**   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
164879**
164880** There must be one row in the table for each source (data_xxx) table within
164881** the RBU database. The 'tbl' column should contain the name of the source
164882** table. The 'cnt' column should contain the number of rows within the
164883** source table.
164884**
164885** If the rbu_count table is present and populated correctly and this
164886** API is called during stage 1, the *pnOne output variable is set to the
164887** permyriadage progress of the same stage. If the rbu_count table does
164888** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
164889** table exists but is not correctly populated, the value of the *pnOne
164890** output variable during stage 1 is undefined.
164891*/
164892SQLITE_API void SQLITE_STDCALL sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int *pnTwo);
164893
164894/*
164895** Obtain an indication as to the current stage of an RBU update or vacuum.
164896** This function always returns one of the SQLITE_RBU_STATE_XXX constants
164897** defined in this file. Return values should be interpreted as follows:
164898**
164899** SQLITE_RBU_STATE_OAL:
164900**   RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
164901**   may either add further data to the *-oal file, or compute data that will
164902**   be added by a subsequent call.
164903**
164904** SQLITE_RBU_STATE_MOVE:
164905**   RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
164906**   will move the *-oal file to the equivalent *-wal path. If the current
164907**   operation is an RBU update, then the updated version of the database
164908**   file will become visible to ordinary SQLite clients following the next
164909**   call to sqlite3rbu_step().
164910**
164911** SQLITE_RBU_STATE_CHECKPOINT:
164912**   RBU is currently performing an incremental checkpoint. The next call to
164913**   sqlite3rbu_step() will copy a page of data from the *-wal file into
164914**   the target database file.
164915**
164916** SQLITE_RBU_STATE_DONE:
164917**   The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
164918**   will immediately return SQLITE_DONE.
164919**
164920** SQLITE_RBU_STATE_ERROR:
164921**   An error has occurred. Any subsequent calls to sqlite3rbu_step() will
164922**   immediately return the SQLite error code associated with the error.
164923*/
164924#define SQLITE_RBU_STATE_OAL        1
164925#define SQLITE_RBU_STATE_MOVE       2
164926#define SQLITE_RBU_STATE_CHECKPOINT 3
164927#define SQLITE_RBU_STATE_DONE       4
164928#define SQLITE_RBU_STATE_ERROR      5
164929
164930SQLITE_API int SQLITE_STDCALL sqlite3rbu_state(sqlite3rbu *pRbu);
164931
164932/*
164933** Create an RBU VFS named zName that accesses the underlying file-system
164934** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
164935** then the new RBU VFS uses the default system VFS to access the file-system.
164936** The new object is registered as a non-default VFS with SQLite before
164937** returning.
164938**
164939** Part of the RBU implementation uses a custom VFS object. Usually, this
164940** object is created and deleted automatically by RBU.
164941**
164942** The exception is for applications that also use zipvfs. In this case,
164943** the custom VFS must be explicitly created by the user before the RBU
164944** handle is opened. The RBU VFS should be installed so that the zipvfs
164945** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
164946** (for example multiplexor) to access the file-system. For example,
164947** to assemble an RBU enabled VFS stack that uses both zipvfs and
164948** multiplexor (error checking omitted):
164949**
164950**     // Create a VFS named "multiplex" (not the default).
164951**     sqlite3_multiplex_initialize(0, 0);
164952**
164953**     // Create an rbu VFS named "rbu" that uses multiplexor. If the
164954**     // second argument were replaced with NULL, the "rbu" VFS would
164955**     // access the file-system via the system default VFS, bypassing the
164956**     // multiplexor.
164957**     sqlite3rbu_create_vfs("rbu", "multiplex");
164958**
164959**     // Create a zipvfs VFS named "zipvfs" that uses rbu.
164960**     zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
164961**
164962**     // Make zipvfs the default VFS.
164963**     sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
164964**
164965** Because the default VFS created above includes a RBU functionality, it
164966** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
164967** that does not include the RBU layer results in an error.
164968**
164969** The overhead of adding the "rbu" VFS to the system is negligible for
164970** non-RBU users. There is no harm in an application accessing the
164971** file-system via "rbu" all the time, even if it only uses RBU functionality
164972** occasionally.
164973*/
164974SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent);
164975
164976/*
164977** Deregister and destroy an RBU vfs created by an earlier call to
164978** sqlite3rbu_create_vfs().
164979**
164980** VFS objects are not reference counted. If a VFS object is destroyed
164981** before all database handles that use it have been closed, the results
164982** are undefined.
164983*/
164984SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName);
164985
164986#if 0
164987}  /* end of the 'extern "C"' block */
164988#endif
164989
164990#endif /* _SQLITE3RBU_H */
164991
164992/************** End of sqlite3rbu.h ******************************************/
164993/************** Continuing where we left off in sqlite3rbu.c *****************/
164994
164995#if defined(_WIN32_WCE)
164996/* #include "windows.h" */
164997#endif
164998
164999/* Maximum number of prepared UPDATE statements held by this module */
165000#define SQLITE_RBU_UPDATE_CACHESIZE 16
165001
165002/*
165003** Swap two objects of type TYPE.
165004*/
165005#if !defined(SQLITE_AMALGAMATION)
165006# define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
165007#endif
165008
165009/*
165010** The rbu_state table is used to save the state of a partially applied
165011** update so that it can be resumed later. The table consists of integer
165012** keys mapped to values as follows:
165013**
165014** RBU_STATE_STAGE:
165015**   May be set to integer values 1, 2, 4 or 5. As follows:
165016**       1: the *-rbu file is currently under construction.
165017**       2: the *-rbu file has been constructed, but not yet moved
165018**          to the *-wal path.
165019**       4: the checkpoint is underway.
165020**       5: the rbu update has been checkpointed.
165021**
165022** RBU_STATE_TBL:
165023**   Only valid if STAGE==1. The target database name of the table
165024**   currently being written.
165025**
165026** RBU_STATE_IDX:
165027**   Only valid if STAGE==1. The target database name of the index
165028**   currently being written, or NULL if the main table is currently being
165029**   updated.
165030**
165031** RBU_STATE_ROW:
165032**   Only valid if STAGE==1. Number of rows already processed for the current
165033**   table/index.
165034**
165035** RBU_STATE_PROGRESS:
165036**   Trbul number of sqlite3rbu_step() calls made so far as part of this
165037**   rbu update.
165038**
165039** RBU_STATE_CKPT:
165040**   Valid if STAGE==4. The 64-bit checksum associated with the wal-index
165041**   header created by recovering the *-wal file. This is used to detect
165042**   cases when another client appends frames to the *-wal file in the
165043**   middle of an incremental checkpoint (an incremental checkpoint cannot
165044**   be continued if this happens).
165045**
165046** RBU_STATE_COOKIE:
165047**   Valid if STAGE==1. The current change-counter cookie value in the
165048**   target db file.
165049**
165050** RBU_STATE_OALSZ:
165051**   Valid if STAGE==1. The size in bytes of the *-oal file.
165052*/
165053#define RBU_STATE_STAGE        1
165054#define RBU_STATE_TBL          2
165055#define RBU_STATE_IDX          3
165056#define RBU_STATE_ROW          4
165057#define RBU_STATE_PROGRESS     5
165058#define RBU_STATE_CKPT         6
165059#define RBU_STATE_COOKIE       7
165060#define RBU_STATE_OALSZ        8
165061#define RBU_STATE_PHASEONESTEP 9
165062
165063#define RBU_STAGE_OAL         1
165064#define RBU_STAGE_MOVE        2
165065#define RBU_STAGE_CAPTURE     3
165066#define RBU_STAGE_CKPT        4
165067#define RBU_STAGE_DONE        5
165068
165069
165070#define RBU_CREATE_STATE \
165071  "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
165072
165073typedef struct RbuFrame RbuFrame;
165074typedef struct RbuObjIter RbuObjIter;
165075typedef struct RbuState RbuState;
165076typedef struct rbu_vfs rbu_vfs;
165077typedef struct rbu_file rbu_file;
165078typedef struct RbuUpdateStmt RbuUpdateStmt;
165079
165080#if !defined(SQLITE_AMALGAMATION)
165081typedef unsigned int u32;
165082typedef unsigned short u16;
165083typedef unsigned char u8;
165084typedef sqlite3_int64 i64;
165085#endif
165086
165087/*
165088** These values must match the values defined in wal.c for the equivalent
165089** locks. These are not magic numbers as they are part of the SQLite file
165090** format.
165091*/
165092#define WAL_LOCK_WRITE  0
165093#define WAL_LOCK_CKPT   1
165094#define WAL_LOCK_READ0  3
165095
165096#define SQLITE_FCNTL_RBUCNT    5149216
165097
165098/*
165099** A structure to store values read from the rbu_state table in memory.
165100*/
165101struct RbuState {
165102  int eStage;
165103  char *zTbl;
165104  char *zIdx;
165105  i64 iWalCksum;
165106  int nRow;
165107  i64 nProgress;
165108  u32 iCookie;
165109  i64 iOalSz;
165110  i64 nPhaseOneStep;
165111};
165112
165113struct RbuUpdateStmt {
165114  char *zMask;                    /* Copy of update mask used with pUpdate */
165115  sqlite3_stmt *pUpdate;          /* Last update statement (or NULL) */
165116  RbuUpdateStmt *pNext;
165117};
165118
165119/*
165120** An iterator of this type is used to iterate through all objects in
165121** the target database that require updating. For each such table, the
165122** iterator visits, in order:
165123**
165124**     * the table itself,
165125**     * each index of the table (zero or more points to visit), and
165126**     * a special "cleanup table" state.
165127**
165128** abIndexed:
165129**   If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
165130**   it points to an array of flags nTblCol elements in size. The flag is
165131**   set for each column that is either a part of the PK or a part of an
165132**   index. Or clear otherwise.
165133**
165134*/
165135struct RbuObjIter {
165136  sqlite3_stmt *pTblIter;         /* Iterate through tables */
165137  sqlite3_stmt *pIdxIter;         /* Index iterator */
165138  int nTblCol;                    /* Size of azTblCol[] array */
165139  char **azTblCol;                /* Array of unquoted target column names */
165140  char **azTblType;               /* Array of target column types */
165141  int *aiSrcOrder;                /* src table col -> target table col */
165142  u8 *abTblPk;                    /* Array of flags, set on target PK columns */
165143  u8 *abNotNull;                  /* Array of flags, set on NOT NULL columns */
165144  u8 *abIndexed;                  /* Array of flags, set on indexed & PK cols */
165145  int eType;                      /* Table type - an RBU_PK_XXX value */
165146
165147  /* Output variables. zTbl==0 implies EOF. */
165148  int bCleanup;                   /* True in "cleanup" state */
165149  const char *zTbl;               /* Name of target db table */
165150  const char *zDataTbl;           /* Name of rbu db table (or null) */
165151  const char *zIdx;               /* Name of target db index (or null) */
165152  int iTnum;                      /* Root page of current object */
165153  int iPkTnum;                    /* If eType==EXTERNAL, root of PK index */
165154  int bUnique;                    /* Current index is unique */
165155  int nIndex;                     /* Number of aux. indexes on table zTbl */
165156
165157  /* Statements created by rbuObjIterPrepareAll() */
165158  int nCol;                       /* Number of columns in current object */
165159  sqlite3_stmt *pSelect;          /* Source data */
165160  sqlite3_stmt *pInsert;          /* Statement for INSERT operations */
165161  sqlite3_stmt *pDelete;          /* Statement for DELETE ops */
165162  sqlite3_stmt *pTmpInsert;       /* Insert into rbu_tmp_$zDataTbl */
165163
165164  /* Last UPDATE used (for PK b-tree updates only), or NULL. */
165165  RbuUpdateStmt *pRbuUpdate;
165166};
165167
165168/*
165169** Values for RbuObjIter.eType
165170**
165171**     0: Table does not exist (error)
165172**     1: Table has an implicit rowid.
165173**     2: Table has an explicit IPK column.
165174**     3: Table has an external PK index.
165175**     4: Table is WITHOUT ROWID.
165176**     5: Table is a virtual table.
165177*/
165178#define RBU_PK_NOTABLE        0
165179#define RBU_PK_NONE           1
165180#define RBU_PK_IPK            2
165181#define RBU_PK_EXTERNAL       3
165182#define RBU_PK_WITHOUT_ROWID  4
165183#define RBU_PK_VTAB           5
165184
165185
165186/*
165187** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
165188** one of the following operations.
165189*/
165190#define RBU_INSERT     1          /* Insert on a main table b-tree */
165191#define RBU_DELETE     2          /* Delete a row from a main table b-tree */
165192#define RBU_REPLACE    3          /* Delete and then insert a row */
165193#define RBU_IDX_DELETE 4          /* Delete a row from an aux. index b-tree */
165194#define RBU_IDX_INSERT 5          /* Insert on an aux. index b-tree */
165195
165196#define RBU_UPDATE     6          /* Update a row in a main table b-tree */
165197
165198/*
165199** A single step of an incremental checkpoint - frame iWalFrame of the wal
165200** file should be copied to page iDbPage of the database file.
165201*/
165202struct RbuFrame {
165203  u32 iDbPage;
165204  u32 iWalFrame;
165205};
165206
165207/*
165208** RBU handle.
165209**
165210** nPhaseOneStep:
165211**   If the RBU database contains an rbu_count table, this value is set to
165212**   a running estimate of the number of b-tree operations required to
165213**   finish populating the *-oal file. This allows the sqlite3_bp_progress()
165214**   API to calculate the permyriadage progress of populating the *-oal file
165215**   using the formula:
165216**
165217**     permyriadage = (10000 * nProgress) / nPhaseOneStep
165218**
165219**   nPhaseOneStep is initialized to the sum of:
165220**
165221**     nRow * (nIndex + 1)
165222**
165223**   for all source tables in the RBU database, where nRow is the number
165224**   of rows in the source table and nIndex the number of indexes on the
165225**   corresponding target database table.
165226**
165227**   This estimate is accurate if the RBU update consists entirely of
165228**   INSERT operations. However, it is inaccurate if:
165229**
165230**     * the RBU update contains any UPDATE operations. If the PK specified
165231**       for an UPDATE operation does not exist in the target table, then
165232**       no b-tree operations are required on index b-trees. Or if the
165233**       specified PK does exist, then (nIndex*2) such operations are
165234**       required (one delete and one insert on each index b-tree).
165235**
165236**     * the RBU update contains any DELETE operations for which the specified
165237**       PK does not exist. In this case no operations are required on index
165238**       b-trees.
165239**
165240**     * the RBU update contains REPLACE operations. These are similar to
165241**       UPDATE operations.
165242**
165243**   nPhaseOneStep is updated to account for the conditions above during the
165244**   first pass of each source table. The updated nPhaseOneStep value is
165245**   stored in the rbu_state table if the RBU update is suspended.
165246*/
165247struct sqlite3rbu {
165248  int eStage;                     /* Value of RBU_STATE_STAGE field */
165249  sqlite3 *dbMain;                /* target database handle */
165250  sqlite3 *dbRbu;                 /* rbu database handle */
165251  char *zTarget;                  /* Path to target db */
165252  char *zRbu;                     /* Path to rbu db */
165253  char *zState;                   /* Path to state db (or NULL if zRbu) */
165254  char zStateDb[5];               /* Db name for state ("stat" or "main") */
165255  int rc;                         /* Value returned by last rbu_step() call */
165256  char *zErrmsg;                  /* Error message if rc!=SQLITE_OK */
165257  int nStep;                      /* Rows processed for current object */
165258  int nProgress;                  /* Rows processed for all objects */
165259  RbuObjIter objiter;             /* Iterator for skipping through tbl/idx */
165260  const char *zVfsName;           /* Name of automatically created rbu vfs */
165261  rbu_file *pTargetFd;            /* File handle open on target db */
165262  i64 iOalSz;
165263  i64 nPhaseOneStep;
165264
165265  /* The following state variables are used as part of the incremental
165266  ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
165267  ** function rbuSetupCheckpoint() for details.  */
165268  u32 iMaxFrame;                  /* Largest iWalFrame value in aFrame[] */
165269  u32 mLock;
165270  int nFrame;                     /* Entries in aFrame[] array */
165271  int nFrameAlloc;                /* Allocated size of aFrame[] array */
165272  RbuFrame *aFrame;
165273  int pgsz;
165274  u8 *aBuf;
165275  i64 iWalCksum;
165276
165277  /* Used in RBU vacuum mode only */
165278  int nRbu;                       /* Number of RBU VFS in the stack */
165279  rbu_file *pRbuFd;               /* Fd for main db of dbRbu */
165280};
165281
165282/*
165283** An rbu VFS is implemented using an instance of this structure.
165284*/
165285struct rbu_vfs {
165286  sqlite3_vfs base;               /* rbu VFS shim methods */
165287  sqlite3_vfs *pRealVfs;          /* Underlying VFS */
165288  sqlite3_mutex *mutex;           /* Mutex to protect pMain */
165289  rbu_file *pMain;                /* Linked list of main db files */
165290};
165291
165292/*
165293** Each file opened by an rbu VFS is represented by an instance of
165294** the following structure.
165295*/
165296struct rbu_file {
165297  sqlite3_file base;              /* sqlite3_file methods */
165298  sqlite3_file *pReal;            /* Underlying file handle */
165299  rbu_vfs *pRbuVfs;               /* Pointer to the rbu_vfs object */
165300  sqlite3rbu *pRbu;               /* Pointer to rbu object (rbu target only) */
165301
165302  int openFlags;                  /* Flags this file was opened with */
165303  u32 iCookie;                    /* Cookie value for main db files */
165304  u8 iWriteVer;                   /* "write-version" value for main db files */
165305  u8 bNolock;                     /* True to fail EXCLUSIVE locks */
165306
165307  int nShm;                       /* Number of entries in apShm[] array */
165308  char **apShm;                   /* Array of mmap'd *-shm regions */
165309  char *zDel;                     /* Delete this when closing file */
165310
165311  const char *zWal;               /* Wal filename for this main db file */
165312  rbu_file *pWalFd;               /* Wal file descriptor for this main db */
165313  rbu_file *pMainNext;            /* Next MAIN_DB file */
165314};
165315
165316/*
165317** True for an RBU vacuum handle, or false otherwise.
165318*/
165319#define rbuIsVacuum(p) ((p)->zTarget==0)
165320
165321
165322/*************************************************************************
165323** The following three functions, found below:
165324**
165325**   rbuDeltaGetInt()
165326**   rbuDeltaChecksum()
165327**   rbuDeltaApply()
165328**
165329** are lifted from the fossil source code (http://fossil-scm.org). They
165330** are used to implement the scalar SQL function rbu_fossil_delta().
165331*/
165332
165333/*
165334** Read bytes from *pz and convert them into a positive integer.  When
165335** finished, leave *pz pointing to the first character past the end of
165336** the integer.  The *pLen parameter holds the length of the string
165337** in *pz and is decremented once for each character in the integer.
165338*/
165339static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
165340  static const signed char zValue[] = {
165341    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
165342    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
165343    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
165344     0,  1,  2,  3,  4,  5,  6,  7,    8,  9, -1, -1, -1, -1, -1, -1,
165345    -1, 10, 11, 12, 13, 14, 15, 16,   17, 18, 19, 20, 21, 22, 23, 24,
165346    25, 26, 27, 28, 29, 30, 31, 32,   33, 34, 35, -1, -1, -1, -1, 36,
165347    -1, 37, 38, 39, 40, 41, 42, 43,   44, 45, 46, 47, 48, 49, 50, 51,
165348    52, 53, 54, 55, 56, 57, 58, 59,   60, 61, 62, -1, -1, -1, 63, -1,
165349  };
165350  unsigned int v = 0;
165351  int c;
165352  unsigned char *z = (unsigned char*)*pz;
165353  unsigned char *zStart = z;
165354  while( (c = zValue[0x7f&*(z++)])>=0 ){
165355     v = (v<<6) + c;
165356  }
165357  z--;
165358  *pLen -= z - zStart;
165359  *pz = (char*)z;
165360  return v;
165361}
165362
165363/*
165364** Compute a 32-bit checksum on the N-byte buffer.  Return the result.
165365*/
165366static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
165367  const unsigned char *z = (const unsigned char *)zIn;
165368  unsigned sum0 = 0;
165369  unsigned sum1 = 0;
165370  unsigned sum2 = 0;
165371  unsigned sum3 = 0;
165372  while(N >= 16){
165373    sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
165374    sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
165375    sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
165376    sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
165377    z += 16;
165378    N -= 16;
165379  }
165380  while(N >= 4){
165381    sum0 += z[0];
165382    sum1 += z[1];
165383    sum2 += z[2];
165384    sum3 += z[3];
165385    z += 4;
165386    N -= 4;
165387  }
165388  sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
165389  switch(N){
165390    case 3:   sum3 += (z[2] << 8);
165391    case 2:   sum3 += (z[1] << 16);
165392    case 1:   sum3 += (z[0] << 24);
165393    default:  ;
165394  }
165395  return sum3;
165396}
165397
165398/*
165399** Apply a delta.
165400**
165401** The output buffer should be big enough to hold the whole output
165402** file and a NUL terminator at the end.  The delta_output_size()
165403** routine will determine this size for you.
165404**
165405** The delta string should be null-terminated.  But the delta string
165406** may contain embedded NUL characters (if the input and output are
165407** binary files) so we also have to pass in the length of the delta in
165408** the lenDelta parameter.
165409**
165410** This function returns the size of the output file in bytes (excluding
165411** the final NUL terminator character).  Except, if the delta string is
165412** malformed or intended for use with a source file other than zSrc,
165413** then this routine returns -1.
165414**
165415** Refer to the delta_create() documentation above for a description
165416** of the delta file format.
165417*/
165418static int rbuDeltaApply(
165419  const char *zSrc,      /* The source or pattern file */
165420  int lenSrc,            /* Length of the source file */
165421  const char *zDelta,    /* Delta to apply to the pattern */
165422  int lenDelta,          /* Length of the delta */
165423  char *zOut             /* Write the output into this preallocated buffer */
165424){
165425  unsigned int limit;
165426  unsigned int total = 0;
165427#ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
165428  char *zOrigOut = zOut;
165429#endif
165430
165431  limit = rbuDeltaGetInt(&zDelta, &lenDelta);
165432  if( *zDelta!='\n' ){
165433    /* ERROR: size integer not terminated by "\n" */
165434    return -1;
165435  }
165436  zDelta++; lenDelta--;
165437  while( *zDelta && lenDelta>0 ){
165438    unsigned int cnt, ofst;
165439    cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
165440    switch( zDelta[0] ){
165441      case '@': {
165442        zDelta++; lenDelta--;
165443        ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
165444        if( lenDelta>0 && zDelta[0]!=',' ){
165445          /* ERROR: copy command not terminated by ',' */
165446          return -1;
165447        }
165448        zDelta++; lenDelta--;
165449        total += cnt;
165450        if( total>limit ){
165451          /* ERROR: copy exceeds output file size */
165452          return -1;
165453        }
165454        if( (int)(ofst+cnt) > lenSrc ){
165455          /* ERROR: copy extends past end of input */
165456          return -1;
165457        }
165458        memcpy(zOut, &zSrc[ofst], cnt);
165459        zOut += cnt;
165460        break;
165461      }
165462      case ':': {
165463        zDelta++; lenDelta--;
165464        total += cnt;
165465        if( total>limit ){
165466          /* ERROR:  insert command gives an output larger than predicted */
165467          return -1;
165468        }
165469        if( (int)cnt>lenDelta ){
165470          /* ERROR: insert count exceeds size of delta */
165471          return -1;
165472        }
165473        memcpy(zOut, zDelta, cnt);
165474        zOut += cnt;
165475        zDelta += cnt;
165476        lenDelta -= cnt;
165477        break;
165478      }
165479      case ';': {
165480        zDelta++; lenDelta--;
165481        zOut[0] = 0;
165482#ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
165483        if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
165484          /* ERROR:  bad checksum */
165485          return -1;
165486        }
165487#endif
165488        if( total!=limit ){
165489          /* ERROR: generated size does not match predicted size */
165490          return -1;
165491        }
165492        return total;
165493      }
165494      default: {
165495        /* ERROR: unknown delta operator */
165496        return -1;
165497      }
165498    }
165499  }
165500  /* ERROR: unterminated delta */
165501  return -1;
165502}
165503
165504static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
165505  int size;
165506  size = rbuDeltaGetInt(&zDelta, &lenDelta);
165507  if( *zDelta!='\n' ){
165508    /* ERROR: size integer not terminated by "\n" */
165509    return -1;
165510  }
165511  return size;
165512}
165513
165514/*
165515** End of code taken from fossil.
165516*************************************************************************/
165517
165518/*
165519** Implementation of SQL scalar function rbu_fossil_delta().
165520**
165521** This function applies a fossil delta patch to a blob. Exactly two
165522** arguments must be passed to this function. The first is the blob to
165523** patch and the second the patch to apply. If no error occurs, this
165524** function returns the patched blob.
165525*/
165526static void rbuFossilDeltaFunc(
165527  sqlite3_context *context,
165528  int argc,
165529  sqlite3_value **argv
165530){
165531  const char *aDelta;
165532  int nDelta;
165533  const char *aOrig;
165534  int nOrig;
165535
165536  int nOut;
165537  int nOut2;
165538  char *aOut;
165539
165540  assert( argc==2 );
165541
165542  nOrig = sqlite3_value_bytes(argv[0]);
165543  aOrig = (const char*)sqlite3_value_blob(argv[0]);
165544  nDelta = sqlite3_value_bytes(argv[1]);
165545  aDelta = (const char*)sqlite3_value_blob(argv[1]);
165546
165547  /* Figure out the size of the output */
165548  nOut = rbuDeltaOutputSize(aDelta, nDelta);
165549  if( nOut<0 ){
165550    sqlite3_result_error(context, "corrupt fossil delta", -1);
165551    return;
165552  }
165553
165554  aOut = sqlite3_malloc(nOut+1);
165555  if( aOut==0 ){
165556    sqlite3_result_error_nomem(context);
165557  }else{
165558    nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
165559    if( nOut2!=nOut ){
165560      sqlite3_result_error(context, "corrupt fossil delta", -1);
165561    }else{
165562      sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
165563    }
165564  }
165565}
165566
165567
165568/*
165569** Prepare the SQL statement in buffer zSql against database handle db.
165570** If successful, set *ppStmt to point to the new statement and return
165571** SQLITE_OK.
165572**
165573** Otherwise, if an error does occur, set *ppStmt to NULL and return
165574** an SQLite error code. Additionally, set output variable *pzErrmsg to
165575** point to a buffer containing an error message. It is the responsibility
165576** of the caller to (eventually) free this buffer using sqlite3_free().
165577*/
165578static int prepareAndCollectError(
165579  sqlite3 *db,
165580  sqlite3_stmt **ppStmt,
165581  char **pzErrmsg,
165582  const char *zSql
165583){
165584  int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
165585  if( rc!=SQLITE_OK ){
165586    *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
165587    *ppStmt = 0;
165588  }
165589  return rc;
165590}
165591
165592/*
165593** Reset the SQL statement passed as the first argument. Return a copy
165594** of the value returned by sqlite3_reset().
165595**
165596** If an error has occurred, then set *pzErrmsg to point to a buffer
165597** containing an error message. It is the responsibility of the caller
165598** to eventually free this buffer using sqlite3_free().
165599*/
165600static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
165601  int rc = sqlite3_reset(pStmt);
165602  if( rc!=SQLITE_OK ){
165603    *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
165604  }
165605  return rc;
165606}
165607
165608/*
165609** Unless it is NULL, argument zSql points to a buffer allocated using
165610** sqlite3_malloc containing an SQL statement. This function prepares the SQL
165611** statement against database db and frees the buffer. If statement
165612** compilation is successful, *ppStmt is set to point to the new statement
165613** handle and SQLITE_OK is returned.
165614**
165615** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
165616** returned. In this case, *pzErrmsg may also be set to point to an error
165617** message. It is the responsibility of the caller to free this error message
165618** buffer using sqlite3_free().
165619**
165620** If argument zSql is NULL, this function assumes that an OOM has occurred.
165621** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
165622*/
165623static int prepareFreeAndCollectError(
165624  sqlite3 *db,
165625  sqlite3_stmt **ppStmt,
165626  char **pzErrmsg,
165627  char *zSql
165628){
165629  int rc;
165630  assert( *pzErrmsg==0 );
165631  if( zSql==0 ){
165632    rc = SQLITE_NOMEM;
165633    *ppStmt = 0;
165634  }else{
165635    rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
165636    sqlite3_free(zSql);
165637  }
165638  return rc;
165639}
165640
165641/*
165642** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
165643** by an earlier call to rbuObjIterCacheTableInfo().
165644*/
165645static void rbuObjIterFreeCols(RbuObjIter *pIter){
165646  int i;
165647  for(i=0; i<pIter->nTblCol; i++){
165648    sqlite3_free(pIter->azTblCol[i]);
165649    sqlite3_free(pIter->azTblType[i]);
165650  }
165651  sqlite3_free(pIter->azTblCol);
165652  pIter->azTblCol = 0;
165653  pIter->azTblType = 0;
165654  pIter->aiSrcOrder = 0;
165655  pIter->abTblPk = 0;
165656  pIter->abNotNull = 0;
165657  pIter->nTblCol = 0;
165658  pIter->eType = 0;               /* Invalid value */
165659}
165660
165661/*
165662** Finalize all statements and free all allocations that are specific to
165663** the current object (table/index pair).
165664*/
165665static void rbuObjIterClearStatements(RbuObjIter *pIter){
165666  RbuUpdateStmt *pUp;
165667
165668  sqlite3_finalize(pIter->pSelect);
165669  sqlite3_finalize(pIter->pInsert);
165670  sqlite3_finalize(pIter->pDelete);
165671  sqlite3_finalize(pIter->pTmpInsert);
165672  pUp = pIter->pRbuUpdate;
165673  while( pUp ){
165674    RbuUpdateStmt *pTmp = pUp->pNext;
165675    sqlite3_finalize(pUp->pUpdate);
165676    sqlite3_free(pUp);
165677    pUp = pTmp;
165678  }
165679
165680  pIter->pSelect = 0;
165681  pIter->pInsert = 0;
165682  pIter->pDelete = 0;
165683  pIter->pRbuUpdate = 0;
165684  pIter->pTmpInsert = 0;
165685  pIter->nCol = 0;
165686}
165687
165688/*
165689** Clean up any resources allocated as part of the iterator object passed
165690** as the only argument.
165691*/
165692static void rbuObjIterFinalize(RbuObjIter *pIter){
165693  rbuObjIterClearStatements(pIter);
165694  sqlite3_finalize(pIter->pTblIter);
165695  sqlite3_finalize(pIter->pIdxIter);
165696  rbuObjIterFreeCols(pIter);
165697  memset(pIter, 0, sizeof(RbuObjIter));
165698}
165699
165700/*
165701** Advance the iterator to the next position.
165702**
165703** If no error occurs, SQLITE_OK is returned and the iterator is left
165704** pointing to the next entry. Otherwise, an error code and message is
165705** left in the RBU handle passed as the first argument. A copy of the
165706** error code is returned.
165707*/
165708static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
165709  int rc = p->rc;
165710  if( rc==SQLITE_OK ){
165711
165712    /* Free any SQLite statements used while processing the previous object */
165713    rbuObjIterClearStatements(pIter);
165714    if( pIter->zIdx==0 ){
165715      rc = sqlite3_exec(p->dbMain,
165716          "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
165717          "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
165718          "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
165719          "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
165720          , 0, 0, &p->zErrmsg
165721      );
165722    }
165723
165724    if( rc==SQLITE_OK ){
165725      if( pIter->bCleanup ){
165726        rbuObjIterFreeCols(pIter);
165727        pIter->bCleanup = 0;
165728        rc = sqlite3_step(pIter->pTblIter);
165729        if( rc!=SQLITE_ROW ){
165730          rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
165731          pIter->zTbl = 0;
165732        }else{
165733          pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
165734          pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
165735          rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
165736        }
165737      }else{
165738        if( pIter->zIdx==0 ){
165739          sqlite3_stmt *pIdx = pIter->pIdxIter;
165740          rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
165741        }
165742        if( rc==SQLITE_OK ){
165743          rc = sqlite3_step(pIter->pIdxIter);
165744          if( rc!=SQLITE_ROW ){
165745            rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
165746            pIter->bCleanup = 1;
165747            pIter->zIdx = 0;
165748          }else{
165749            pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
165750            pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
165751            pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
165752            rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
165753          }
165754        }
165755      }
165756    }
165757  }
165758
165759  if( rc!=SQLITE_OK ){
165760    rbuObjIterFinalize(pIter);
165761    p->rc = rc;
165762  }
165763  return rc;
165764}
165765
165766
165767/*
165768** The implementation of the rbu_target_name() SQL function. This function
165769** accepts one or two arguments. The first argument is the name of a table -
165770** the name of a table in the RBU database.  The second, if it is present, is 1
165771** for a view or 0 for a table.
165772**
165773** For a non-vacuum RBU handle, if the table name matches the pattern:
165774**
165775**     data[0-9]_<name>
165776**
165777** where <name> is any sequence of 1 or more characters, <name> is returned.
165778** Otherwise, if the only argument does not match the above pattern, an SQL
165779** NULL is returned.
165780**
165781**     "data_t1"     -> "t1"
165782**     "data0123_t2" -> "t2"
165783**     "dataAB_t3"   -> NULL
165784**
165785** For an rbu vacuum handle, a copy of the first argument is returned if
165786** the second argument is either missing or 0 (not a view).
165787*/
165788static void rbuTargetNameFunc(
165789  sqlite3_context *pCtx,
165790  int argc,
165791  sqlite3_value **argv
165792){
165793  sqlite3rbu *p = sqlite3_user_data(pCtx);
165794  const char *zIn;
165795  assert( argc==1 || argc==2 );
165796
165797  zIn = (const char*)sqlite3_value_text(argv[0]);
165798  if( zIn ){
165799    if( rbuIsVacuum(p) ){
165800      if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
165801        sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
165802      }
165803    }else{
165804      if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
165805        int i;
165806        for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
165807        if( zIn[i]=='_' && zIn[i+1] ){
165808          sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
165809        }
165810      }
165811    }
165812  }
165813}
165814
165815/*
165816** Initialize the iterator structure passed as the second argument.
165817**
165818** If no error occurs, SQLITE_OK is returned and the iterator is left
165819** pointing to the first entry. Otherwise, an error code and message is
165820** left in the RBU handle passed as the first argument. A copy of the
165821** error code is returned.
165822*/
165823static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
165824  int rc;
165825  memset(pIter, 0, sizeof(RbuObjIter));
165826
165827  rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
165828    sqlite3_mprintf(
165829      "SELECT rbu_target_name(name, type='view') AS target, name "
165830      "FROM sqlite_master "
165831      "WHERE type IN ('table', 'view') AND target IS NOT NULL "
165832      " %s "
165833      "ORDER BY name"
165834  , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
165835
165836  if( rc==SQLITE_OK ){
165837    rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
165838        "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
165839        "  FROM main.sqlite_master "
165840        "  WHERE type='index' AND tbl_name = ?"
165841    );
165842  }
165843
165844  pIter->bCleanup = 1;
165845  p->rc = rc;
165846  return rbuObjIterNext(p, pIter);
165847}
165848
165849/*
165850** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
165851** an error code is stored in the RBU handle passed as the first argument.
165852**
165853** If an error has already occurred (p->rc is already set to something other
165854** than SQLITE_OK), then this function returns NULL without modifying the
165855** stored error code. In this case it still calls sqlite3_free() on any
165856** printf() parameters associated with %z conversions.
165857*/
165858static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
165859  char *zSql = 0;
165860  va_list ap;
165861  va_start(ap, zFmt);
165862  zSql = sqlite3_vmprintf(zFmt, ap);
165863  if( p->rc==SQLITE_OK ){
165864    if( zSql==0 ) p->rc = SQLITE_NOMEM;
165865  }else{
165866    sqlite3_free(zSql);
165867    zSql = 0;
165868  }
165869  va_end(ap);
165870  return zSql;
165871}
165872
165873/*
165874** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
165875** arguments are the usual subsitution values. This function performs
165876** the printf() style substitutions and executes the result as an SQL
165877** statement on the RBU handles database.
165878**
165879** If an error occurs, an error code and error message is stored in the
165880** RBU handle. If an error has already occurred when this function is
165881** called, it is a no-op.
165882*/
165883static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
165884  va_list ap;
165885  char *zSql;
165886  va_start(ap, zFmt);
165887  zSql = sqlite3_vmprintf(zFmt, ap);
165888  if( p->rc==SQLITE_OK ){
165889    if( zSql==0 ){
165890      p->rc = SQLITE_NOMEM;
165891    }else{
165892      p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
165893    }
165894  }
165895  sqlite3_free(zSql);
165896  va_end(ap);
165897  return p->rc;
165898}
165899
165900/*
165901** Attempt to allocate and return a pointer to a zeroed block of nByte
165902** bytes.
165903**
165904** If an error (i.e. an OOM condition) occurs, return NULL and leave an
165905** error code in the rbu handle passed as the first argument. Or, if an
165906** error has already occurred when this function is called, return NULL
165907** immediately without attempting the allocation or modifying the stored
165908** error code.
165909*/
165910static void *rbuMalloc(sqlite3rbu *p, int nByte){
165911  void *pRet = 0;
165912  if( p->rc==SQLITE_OK ){
165913    assert( nByte>0 );
165914    pRet = sqlite3_malloc64(nByte);
165915    if( pRet==0 ){
165916      p->rc = SQLITE_NOMEM;
165917    }else{
165918      memset(pRet, 0, nByte);
165919    }
165920  }
165921  return pRet;
165922}
165923
165924
165925/*
165926** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
165927** there is room for at least nCol elements. If an OOM occurs, store an
165928** error code in the RBU handle passed as the first argument.
165929*/
165930static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
165931  int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
165932  char **azNew;
165933
165934  azNew = (char**)rbuMalloc(p, nByte);
165935  if( azNew ){
165936    pIter->azTblCol = azNew;
165937    pIter->azTblType = &azNew[nCol];
165938    pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
165939    pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
165940    pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
165941    pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
165942  }
165943}
165944
165945/*
165946** The first argument must be a nul-terminated string. This function
165947** returns a copy of the string in memory obtained from sqlite3_malloc().
165948** It is the responsibility of the caller to eventually free this memory
165949** using sqlite3_free().
165950**
165951** If an OOM condition is encountered when attempting to allocate memory,
165952** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
165953** if the allocation succeeds, (*pRc) is left unchanged.
165954*/
165955static char *rbuStrndup(const char *zStr, int *pRc){
165956  char *zRet = 0;
165957
165958  assert( *pRc==SQLITE_OK );
165959  if( zStr ){
165960    size_t nCopy = strlen(zStr) + 1;
165961    zRet = (char*)sqlite3_malloc64(nCopy);
165962    if( zRet ){
165963      memcpy(zRet, zStr, nCopy);
165964    }else{
165965      *pRc = SQLITE_NOMEM;
165966    }
165967  }
165968
165969  return zRet;
165970}
165971
165972/*
165973** Finalize the statement passed as the second argument.
165974**
165975** If the sqlite3_finalize() call indicates that an error occurs, and the
165976** rbu handle error code is not already set, set the error code and error
165977** message accordingly.
165978*/
165979static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
165980  sqlite3 *db = sqlite3_db_handle(pStmt);
165981  int rc = sqlite3_finalize(pStmt);
165982  if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
165983    p->rc = rc;
165984    p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
165985  }
165986}
165987
165988/* Determine the type of a table.
165989**
165990**   peType is of type (int*), a pointer to an output parameter of type
165991**   (int). This call sets the output parameter as follows, depending
165992**   on the type of the table specified by parameters dbName and zTbl.
165993**
165994**     RBU_PK_NOTABLE:       No such table.
165995**     RBU_PK_NONE:          Table has an implicit rowid.
165996**     RBU_PK_IPK:           Table has an explicit IPK column.
165997**     RBU_PK_EXTERNAL:      Table has an external PK index.
165998**     RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
165999**     RBU_PK_VTAB:          Table is a virtual table.
166000**
166001**   Argument *piPk is also of type (int*), and also points to an output
166002**   parameter. Unless the table has an external primary key index
166003**   (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
166004**   if the table does have an external primary key index, then *piPk
166005**   is set to the root page number of the primary key index before
166006**   returning.
166007**
166008** ALGORITHM:
166009**
166010**   if( no entry exists in sqlite_master ){
166011**     return RBU_PK_NOTABLE
166012**   }else if( sql for the entry starts with "CREATE VIRTUAL" ){
166013**     return RBU_PK_VTAB
166014**   }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
166015**     if( the index that is the pk exists in sqlite_master ){
166016**       *piPK = rootpage of that index.
166017**       return RBU_PK_EXTERNAL
166018**     }else{
166019**       return RBU_PK_WITHOUT_ROWID
166020**     }
166021**   }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
166022**     return RBU_PK_IPK
166023**   }else{
166024**     return RBU_PK_NONE
166025**   }
166026*/
166027static void rbuTableType(
166028  sqlite3rbu *p,
166029  const char *zTab,
166030  int *peType,
166031  int *piTnum,
166032  int *piPk
166033){
166034  /*
166035  ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
166036  ** 1) PRAGMA index_list = ?
166037  ** 2) SELECT count(*) FROM sqlite_master where name=%Q
166038  ** 3) PRAGMA table_info = ?
166039  */
166040  sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
166041
166042  *peType = RBU_PK_NOTABLE;
166043  *piPk = 0;
166044
166045  assert( p->rc==SQLITE_OK );
166046  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
166047    sqlite3_mprintf(
166048          "SELECT (sql LIKE 'create virtual%%'), rootpage"
166049          "  FROM sqlite_master"
166050          " WHERE name=%Q", zTab
166051  ));
166052  if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
166053    /* Either an error, or no such table. */
166054    goto rbuTableType_end;
166055  }
166056  if( sqlite3_column_int(aStmt[0], 0) ){
166057    *peType = RBU_PK_VTAB;                     /* virtual table */
166058    goto rbuTableType_end;
166059  }
166060  *piTnum = sqlite3_column_int(aStmt[0], 1);
166061
166062  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
166063    sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
166064  );
166065  if( p->rc ) goto rbuTableType_end;
166066  while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
166067    const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
166068    const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
166069    if( zOrig && zIdx && zOrig[0]=='p' ){
166070      p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
166071          sqlite3_mprintf(
166072            "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
166073      ));
166074      if( p->rc==SQLITE_OK ){
166075        if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
166076          *piPk = sqlite3_column_int(aStmt[2], 0);
166077          *peType = RBU_PK_EXTERNAL;
166078        }else{
166079          *peType = RBU_PK_WITHOUT_ROWID;
166080        }
166081      }
166082      goto rbuTableType_end;
166083    }
166084  }
166085
166086  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
166087    sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
166088  );
166089  if( p->rc==SQLITE_OK ){
166090    while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
166091      if( sqlite3_column_int(aStmt[3],5)>0 ){
166092        *peType = RBU_PK_IPK;                /* explicit IPK column */
166093        goto rbuTableType_end;
166094      }
166095    }
166096    *peType = RBU_PK_NONE;
166097  }
166098
166099rbuTableType_end: {
166100    unsigned int i;
166101    for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
166102      rbuFinalize(p, aStmt[i]);
166103    }
166104  }
166105}
166106
166107/*
166108** This is a helper function for rbuObjIterCacheTableInfo(). It populates
166109** the pIter->abIndexed[] array.
166110*/
166111static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
166112  sqlite3_stmt *pList = 0;
166113  int bIndex = 0;
166114
166115  if( p->rc==SQLITE_OK ){
166116    memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
166117    p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
166118        sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
166119    );
166120  }
166121
166122  pIter->nIndex = 0;
166123  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
166124    const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
166125    sqlite3_stmt *pXInfo = 0;
166126    if( zIdx==0 ) break;
166127    p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
166128        sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
166129    );
166130    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
166131      int iCid = sqlite3_column_int(pXInfo, 1);
166132      if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
166133    }
166134    rbuFinalize(p, pXInfo);
166135    bIndex = 1;
166136    pIter->nIndex++;
166137  }
166138
166139  if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
166140    /* "PRAGMA index_list" includes the main PK b-tree */
166141    pIter->nIndex--;
166142  }
166143
166144  rbuFinalize(p, pList);
166145  if( bIndex==0 ) pIter->abIndexed = 0;
166146}
166147
166148
166149/*
166150** If they are not already populated, populate the pIter->azTblCol[],
166151** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
166152** the table (not index) that the iterator currently points to.
166153**
166154** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
166155** an error does occur, an error code and error message are also left in
166156** the RBU handle.
166157*/
166158static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
166159  if( pIter->azTblCol==0 ){
166160    sqlite3_stmt *pStmt = 0;
166161    int nCol = 0;
166162    int i;                        /* for() loop iterator variable */
166163    int bRbuRowid = 0;            /* If input table has column "rbu_rowid" */
166164    int iOrder = 0;
166165    int iTnum = 0;
166166
166167    /* Figure out the type of table this step will deal with. */
166168    assert( pIter->eType==0 );
166169    rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
166170    if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
166171      p->rc = SQLITE_ERROR;
166172      p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
166173    }
166174    if( p->rc ) return p->rc;
166175    if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
166176
166177    assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
166178         || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
166179         || pIter->eType==RBU_PK_VTAB
166180    );
166181
166182    /* Populate the azTblCol[] and nTblCol variables based on the columns
166183    ** of the input table. Ignore any input table columns that begin with
166184    ** "rbu_".  */
166185    p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
166186        sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
166187    );
166188    if( p->rc==SQLITE_OK ){
166189      nCol = sqlite3_column_count(pStmt);
166190      rbuAllocateIterArrays(p, pIter, nCol);
166191    }
166192    for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
166193      const char *zName = (const char*)sqlite3_column_name(pStmt, i);
166194      if( sqlite3_strnicmp("rbu_", zName, 4) ){
166195        char *zCopy = rbuStrndup(zName, &p->rc);
166196        pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
166197        pIter->azTblCol[pIter->nTblCol++] = zCopy;
166198      }
166199      else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
166200        bRbuRowid = 1;
166201      }
166202    }
166203    sqlite3_finalize(pStmt);
166204    pStmt = 0;
166205
166206    if( p->rc==SQLITE_OK
166207     && rbuIsVacuum(p)==0
166208     && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
166209    ){
166210      p->rc = SQLITE_ERROR;
166211      p->zErrmsg = sqlite3_mprintf(
166212          "table %q %s rbu_rowid column", pIter->zDataTbl,
166213          (bRbuRowid ? "may not have" : "requires")
166214      );
166215    }
166216
166217    /* Check that all non-HIDDEN columns in the destination table are also
166218    ** present in the input table. Populate the abTblPk[], azTblType[] and
166219    ** aiTblOrder[] arrays at the same time.  */
166220    if( p->rc==SQLITE_OK ){
166221      p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
166222          sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
166223      );
166224    }
166225    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
166226      const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
166227      if( zName==0 ) break;  /* An OOM - finalize() below returns S_NOMEM */
166228      for(i=iOrder; i<pIter->nTblCol; i++){
166229        if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
166230      }
166231      if( i==pIter->nTblCol ){
166232        p->rc = SQLITE_ERROR;
166233        p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
166234            pIter->zDataTbl, zName
166235        );
166236      }else{
166237        int iPk = sqlite3_column_int(pStmt, 5);
166238        int bNotNull = sqlite3_column_int(pStmt, 3);
166239        const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
166240
166241        if( i!=iOrder ){
166242          SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
166243          SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
166244        }
166245
166246        pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
166247        pIter->abTblPk[iOrder] = (iPk!=0);
166248        pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
166249        iOrder++;
166250      }
166251    }
166252
166253    rbuFinalize(p, pStmt);
166254    rbuObjIterCacheIndexedCols(p, pIter);
166255    assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
166256    assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
166257  }
166258
166259  return p->rc;
166260}
166261
166262/*
166263** This function constructs and returns a pointer to a nul-terminated
166264** string containing some SQL clause or list based on one or more of the
166265** column names currently stored in the pIter->azTblCol[] array.
166266*/
166267static char *rbuObjIterGetCollist(
166268  sqlite3rbu *p,                  /* RBU object */
166269  RbuObjIter *pIter               /* Object iterator for column names */
166270){
166271  char *zList = 0;
166272  const char *zSep = "";
166273  int i;
166274  for(i=0; i<pIter->nTblCol; i++){
166275    const char *z = pIter->azTblCol[i];
166276    zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
166277    zSep = ", ";
166278  }
166279  return zList;
166280}
166281
166282/*
166283** This function is used to create a SELECT list (the list of SQL
166284** expressions that follows a SELECT keyword) for a SELECT statement
166285** used to read from an data_xxx or rbu_tmp_xxx table while updating the
166286** index object currently indicated by the iterator object passed as the
166287** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
166288** to obtain the required information.
166289**
166290** If the index is of the following form:
166291**
166292**   CREATE INDEX i1 ON t1(c, b COLLATE nocase);
166293**
166294** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
166295** "ipk", the returned string is:
166296**
166297**   "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
166298**
166299** As well as the returned string, three other malloc'd strings are
166300** returned via output parameters. As follows:
166301**
166302**   pzImposterCols: ...
166303**   pzImposterPk: ...
166304**   pzWhere: ...
166305*/
166306static char *rbuObjIterGetIndexCols(
166307  sqlite3rbu *p,                  /* RBU object */
166308  RbuObjIter *pIter,              /* Object iterator for column names */
166309  char **pzImposterCols,          /* OUT: Columns for imposter table */
166310  char **pzImposterPk,            /* OUT: Imposter PK clause */
166311  char **pzWhere,                 /* OUT: WHERE clause */
166312  int *pnBind                     /* OUT: Trbul number of columns */
166313){
166314  int rc = p->rc;                 /* Error code */
166315  int rc2;                        /* sqlite3_finalize() return code */
166316  char *zRet = 0;                 /* String to return */
166317  char *zImpCols = 0;             /* String to return via *pzImposterCols */
166318  char *zImpPK = 0;               /* String to return via *pzImposterPK */
166319  char *zWhere = 0;               /* String to return via *pzWhere */
166320  int nBind = 0;                  /* Value to return via *pnBind */
166321  const char *zCom = "";          /* Set to ", " later on */
166322  const char *zAnd = "";          /* Set to " AND " later on */
166323  sqlite3_stmt *pXInfo = 0;       /* PRAGMA index_xinfo = ? */
166324
166325  if( rc==SQLITE_OK ){
166326    assert( p->zErrmsg==0 );
166327    rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
166328        sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
166329    );
166330  }
166331
166332  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
166333    int iCid = sqlite3_column_int(pXInfo, 1);
166334    int bDesc = sqlite3_column_int(pXInfo, 3);
166335    const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
166336    const char *zCol;
166337    const char *zType;
166338
166339    if( iCid<0 ){
166340      /* An integer primary key. If the table has an explicit IPK, use
166341      ** its name. Otherwise, use "rbu_rowid".  */
166342      if( pIter->eType==RBU_PK_IPK ){
166343        int i;
166344        for(i=0; pIter->abTblPk[i]==0; i++);
166345        assert( i<pIter->nTblCol );
166346        zCol = pIter->azTblCol[i];
166347      }else if( rbuIsVacuum(p) ){
166348        zCol = "_rowid_";
166349      }else{
166350        zCol = "rbu_rowid";
166351      }
166352      zType = "INTEGER";
166353    }else{
166354      zCol = pIter->azTblCol[iCid];
166355      zType = pIter->azTblType[iCid];
166356    }
166357
166358    zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
166359    if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
166360      const char *zOrder = (bDesc ? " DESC" : "");
166361      zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
166362          zImpPK, zCom, nBind, zCol, zOrder
166363      );
166364    }
166365    zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
166366        zImpCols, zCom, nBind, zCol, zType, zCollate
166367    );
166368    zWhere = sqlite3_mprintf(
166369        "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
166370    );
166371    if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
166372    zCom = ", ";
166373    zAnd = " AND ";
166374    nBind++;
166375  }
166376
166377  rc2 = sqlite3_finalize(pXInfo);
166378  if( rc==SQLITE_OK ) rc = rc2;
166379
166380  if( rc!=SQLITE_OK ){
166381    sqlite3_free(zRet);
166382    sqlite3_free(zImpCols);
166383    sqlite3_free(zImpPK);
166384    sqlite3_free(zWhere);
166385    zRet = 0;
166386    zImpCols = 0;
166387    zImpPK = 0;
166388    zWhere = 0;
166389    p->rc = rc;
166390  }
166391
166392  *pzImposterCols = zImpCols;
166393  *pzImposterPk = zImpPK;
166394  *pzWhere = zWhere;
166395  *pnBind = nBind;
166396  return zRet;
166397}
166398
166399/*
166400** Assuming the current table columns are "a", "b" and "c", and the zObj
166401** paramter is passed "old", return a string of the form:
166402**
166403**     "old.a, old.b, old.b"
166404**
166405** With the column names escaped.
166406**
166407** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
166408** the text ", old._rowid_" to the returned value.
166409*/
166410static char *rbuObjIterGetOldlist(
166411  sqlite3rbu *p,
166412  RbuObjIter *pIter,
166413  const char *zObj
166414){
166415  char *zList = 0;
166416  if( p->rc==SQLITE_OK && pIter->abIndexed ){
166417    const char *zS = "";
166418    int i;
166419    for(i=0; i<pIter->nTblCol; i++){
166420      if( pIter->abIndexed[i] ){
166421        const char *zCol = pIter->azTblCol[i];
166422        zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
166423      }else{
166424        zList = sqlite3_mprintf("%z%sNULL", zList, zS);
166425      }
166426      zS = ", ";
166427      if( zList==0 ){
166428        p->rc = SQLITE_NOMEM;
166429        break;
166430      }
166431    }
166432
166433    /* For a table with implicit rowids, append "old._rowid_" to the list. */
166434    if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
166435      zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
166436    }
166437  }
166438  return zList;
166439}
166440
166441/*
166442** Return an expression that can be used in a WHERE clause to match the
166443** primary key of the current table. For example, if the table is:
166444**
166445**   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
166446**
166447** Return the string:
166448**
166449**   "b = ?1 AND c = ?2"
166450*/
166451static char *rbuObjIterGetWhere(
166452  sqlite3rbu *p,
166453  RbuObjIter *pIter
166454){
166455  char *zList = 0;
166456  if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
166457    zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
166458  }else if( pIter->eType==RBU_PK_EXTERNAL ){
166459    const char *zSep = "";
166460    int i;
166461    for(i=0; i<pIter->nTblCol; i++){
166462      if( pIter->abTblPk[i] ){
166463        zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
166464        zSep = " AND ";
166465      }
166466    }
166467    zList = rbuMPrintf(p,
166468        "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
166469    );
166470
166471  }else{
166472    const char *zSep = "";
166473    int i;
166474    for(i=0; i<pIter->nTblCol; i++){
166475      if( pIter->abTblPk[i] ){
166476        const char *zCol = pIter->azTblCol[i];
166477        zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
166478        zSep = " AND ";
166479      }
166480    }
166481  }
166482  return zList;
166483}
166484
166485/*
166486** The SELECT statement iterating through the keys for the current object
166487** (p->objiter.pSelect) currently points to a valid row. However, there
166488** is something wrong with the rbu_control value in the rbu_control value
166489** stored in the (p->nCol+1)'th column. Set the error code and error message
166490** of the RBU handle to something reflecting this.
166491*/
166492static void rbuBadControlError(sqlite3rbu *p){
166493  p->rc = SQLITE_ERROR;
166494  p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
166495}
166496
166497
166498/*
166499** Return a nul-terminated string containing the comma separated list of
166500** assignments that should be included following the "SET" keyword of
166501** an UPDATE statement used to update the table object that the iterator
166502** passed as the second argument currently points to if the rbu_control
166503** column of the data_xxx table entry is set to zMask.
166504**
166505** The memory for the returned string is obtained from sqlite3_malloc().
166506** It is the responsibility of the caller to eventually free it using
166507** sqlite3_free().
166508**
166509** If an OOM error is encountered when allocating space for the new
166510** string, an error code is left in the rbu handle passed as the first
166511** argument and NULL is returned. Or, if an error has already occurred
166512** when this function is called, NULL is returned immediately, without
166513** attempting the allocation or modifying the stored error code.
166514*/
166515static char *rbuObjIterGetSetlist(
166516  sqlite3rbu *p,
166517  RbuObjIter *pIter,
166518  const char *zMask
166519){
166520  char *zList = 0;
166521  if( p->rc==SQLITE_OK ){
166522    int i;
166523
166524    if( (int)strlen(zMask)!=pIter->nTblCol ){
166525      rbuBadControlError(p);
166526    }else{
166527      const char *zSep = "";
166528      for(i=0; i<pIter->nTblCol; i++){
166529        char c = zMask[pIter->aiSrcOrder[i]];
166530        if( c=='x' ){
166531          zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
166532              zList, zSep, pIter->azTblCol[i], i+1
166533          );
166534          zSep = ", ";
166535        }
166536        else if( c=='d' ){
166537          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
166538              zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
166539          );
166540          zSep = ", ";
166541        }
166542        else if( c=='f' ){
166543          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
166544              zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
166545          );
166546          zSep = ", ";
166547        }
166548      }
166549    }
166550  }
166551  return zList;
166552}
166553
166554/*
166555** Return a nul-terminated string consisting of nByte comma separated
166556** "?" expressions. For example, if nByte is 3, return a pointer to
166557** a buffer containing the string "?,?,?".
166558**
166559** The memory for the returned string is obtained from sqlite3_malloc().
166560** It is the responsibility of the caller to eventually free it using
166561** sqlite3_free().
166562**
166563** If an OOM error is encountered when allocating space for the new
166564** string, an error code is left in the rbu handle passed as the first
166565** argument and NULL is returned. Or, if an error has already occurred
166566** when this function is called, NULL is returned immediately, without
166567** attempting the allocation or modifying the stored error code.
166568*/
166569static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
166570  char *zRet = 0;
166571  int nByte = nBind*2 + 1;
166572
166573  zRet = (char*)rbuMalloc(p, nByte);
166574  if( zRet ){
166575    int i;
166576    for(i=0; i<nBind; i++){
166577      zRet[i*2] = '?';
166578      zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
166579    }
166580  }
166581  return zRet;
166582}
166583
166584/*
166585** The iterator currently points to a table (not index) of type
166586** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
166587** declaration for the corresponding imposter table. For example,
166588** if the iterator points to a table created as:
166589**
166590**   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
166591**
166592** this function returns:
166593**
166594**   PRIMARY KEY("b", "a" DESC)
166595*/
166596static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
166597  char *z = 0;
166598  assert( pIter->zIdx==0 );
166599  if( p->rc==SQLITE_OK ){
166600    const char *zSep = "PRIMARY KEY(";
166601    sqlite3_stmt *pXList = 0;     /* PRAGMA index_list = (pIter->zTbl) */
166602    sqlite3_stmt *pXInfo = 0;     /* PRAGMA index_xinfo = <pk-index> */
166603
166604    p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
166605        sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
166606    );
166607    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
166608      const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
166609      if( zOrig && strcmp(zOrig, "pk")==0 ){
166610        const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
166611        if( zIdx ){
166612          p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
166613              sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
166614          );
166615        }
166616        break;
166617      }
166618    }
166619    rbuFinalize(p, pXList);
166620
166621    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
166622      if( sqlite3_column_int(pXInfo, 5) ){
166623        /* int iCid = sqlite3_column_int(pXInfo, 0); */
166624        const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
166625        const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
166626        z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
166627        zSep = ", ";
166628      }
166629    }
166630    z = rbuMPrintf(p, "%z)", z);
166631    rbuFinalize(p, pXInfo);
166632  }
166633  return z;
166634}
166635
166636/*
166637** This function creates the second imposter table used when writing to
166638** a table b-tree where the table has an external primary key. If the
166639** iterator passed as the second argument does not currently point to
166640** a table (not index) with an external primary key, this function is a
166641** no-op.
166642**
166643** Assuming the iterator does point to a table with an external PK, this
166644** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
166645** used to access that PK index. For example, if the target table is
166646** declared as follows:
166647**
166648**   CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
166649**
166650** then the imposter table schema is:
166651**
166652**   CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
166653**
166654*/
166655static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
166656  if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
166657    int tnum = pIter->iPkTnum;    /* Root page of PK index */
166658    sqlite3_stmt *pQuery = 0;     /* SELECT name ... WHERE rootpage = $tnum */
166659    const char *zIdx = 0;         /* Name of PK index */
166660    sqlite3_stmt *pXInfo = 0;     /* PRAGMA main.index_xinfo = $zIdx */
166661    const char *zComma = "";
166662    char *zCols = 0;              /* Used to build up list of table cols */
166663    char *zPk = 0;                /* Used to build up table PK declaration */
166664
166665    /* Figure out the name of the primary key index for the current table.
166666    ** This is needed for the argument to "PRAGMA index_xinfo". Set
166667    ** zIdx to point to a nul-terminated string containing this name. */
166668    p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
166669        "SELECT name FROM sqlite_master WHERE rootpage = ?"
166670    );
166671    if( p->rc==SQLITE_OK ){
166672      sqlite3_bind_int(pQuery, 1, tnum);
166673      if( SQLITE_ROW==sqlite3_step(pQuery) ){
166674        zIdx = (const char*)sqlite3_column_text(pQuery, 0);
166675      }
166676    }
166677    if( zIdx ){
166678      p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
166679          sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
166680      );
166681    }
166682    rbuFinalize(p, pQuery);
166683
166684    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
166685      int bKey = sqlite3_column_int(pXInfo, 5);
166686      if( bKey ){
166687        int iCid = sqlite3_column_int(pXInfo, 1);
166688        int bDesc = sqlite3_column_int(pXInfo, 3);
166689        const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
166690        zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
166691            iCid, pIter->azTblType[iCid], zCollate
166692        );
166693        zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
166694        zComma = ", ";
166695      }
166696    }
166697    zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
166698    rbuFinalize(p, pXInfo);
166699
166700    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
166701    rbuMPrintfExec(p, p->dbMain,
166702        "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
166703        zCols, zPk
166704    );
166705    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
166706  }
166707}
166708
166709/*
166710** If an error has already occurred when this function is called, it
166711** immediately returns zero (without doing any work). Or, if an error
166712** occurs during the execution of this function, it sets the error code
166713** in the sqlite3rbu object indicated by the first argument and returns
166714** zero.
166715**
166716** The iterator passed as the second argument is guaranteed to point to
166717** a table (not an index) when this function is called. This function
166718** attempts to create any imposter table required to write to the main
166719** table b-tree of the table before returning. Non-zero is returned if
166720** an imposter table are created, or zero otherwise.
166721**
166722** An imposter table is required in all cases except RBU_PK_VTAB. Only
166723** virtual tables are written to directly. The imposter table has the
166724** same schema as the actual target table (less any UNIQUE constraints).
166725** More precisely, the "same schema" means the same columns, types,
166726** collation sequences. For tables that do not have an external PRIMARY
166727** KEY, it also means the same PRIMARY KEY declaration.
166728*/
166729static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
166730  if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
166731    int tnum = pIter->iTnum;
166732    const char *zComma = "";
166733    char *zSql = 0;
166734    int iCol;
166735    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
166736
166737    for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
166738      const char *zPk = "";
166739      const char *zCol = pIter->azTblCol[iCol];
166740      const char *zColl = 0;
166741
166742      p->rc = sqlite3_table_column_metadata(
166743          p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
166744      );
166745
166746      if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
166747        /* If the target table column is an "INTEGER PRIMARY KEY", add
166748        ** "PRIMARY KEY" to the imposter table column declaration. */
166749        zPk = "PRIMARY KEY ";
166750      }
166751      zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
166752          zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
166753          (pIter->abNotNull[iCol] ? " NOT NULL" : "")
166754      );
166755      zComma = ", ";
166756    }
166757
166758    if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
166759      char *zPk = rbuWithoutRowidPK(p, pIter);
166760      if( zPk ){
166761        zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
166762      }
166763    }
166764
166765    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
166766    rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
166767        pIter->zTbl, zSql,
166768        (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
166769    );
166770    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
166771  }
166772}
166773
166774/*
166775** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
166776** Specifically a statement of the form:
166777**
166778**     INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
166779**
166780** The number of bound variables is equal to the number of columns in
166781** the target table, plus one (for the rbu_control column), plus one more
166782** (for the rbu_rowid column) if the target table is an implicit IPK or
166783** virtual table.
166784*/
166785static void rbuObjIterPrepareTmpInsert(
166786  sqlite3rbu *p,
166787  RbuObjIter *pIter,
166788  const char *zCollist,
166789  const char *zRbuRowid
166790){
166791  int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
166792  char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
166793  if( zBind ){
166794    assert( pIter->pTmpInsert==0 );
166795    p->rc = prepareFreeAndCollectError(
166796        p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
166797          "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
166798          p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
166799    ));
166800  }
166801}
166802
166803static void rbuTmpInsertFunc(
166804  sqlite3_context *pCtx,
166805  int nVal,
166806  sqlite3_value **apVal
166807){
166808  sqlite3rbu *p = sqlite3_user_data(pCtx);
166809  int rc = SQLITE_OK;
166810  int i;
166811
166812  assert( sqlite3_value_int(apVal[0])!=0
166813      || p->objiter.eType==RBU_PK_EXTERNAL
166814      || p->objiter.eType==RBU_PK_NONE
166815  );
166816  if( sqlite3_value_int(apVal[0])!=0 ){
166817    p->nPhaseOneStep += p->objiter.nIndex;
166818  }
166819
166820  for(i=0; rc==SQLITE_OK && i<nVal; i++){
166821    rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
166822  }
166823  if( rc==SQLITE_OK ){
166824    sqlite3_step(p->objiter.pTmpInsert);
166825    rc = sqlite3_reset(p->objiter.pTmpInsert);
166826  }
166827
166828  if( rc!=SQLITE_OK ){
166829    sqlite3_result_error_code(pCtx, rc);
166830  }
166831}
166832
166833/*
166834** Ensure that the SQLite statement handles required to update the
166835** target database object currently indicated by the iterator passed
166836** as the second argument are available.
166837*/
166838static int rbuObjIterPrepareAll(
166839  sqlite3rbu *p,
166840  RbuObjIter *pIter,
166841  int nOffset                     /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
166842){
166843  assert( pIter->bCleanup==0 );
166844  if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
166845    const int tnum = pIter->iTnum;
166846    char *zCollist = 0;           /* List of indexed columns */
166847    char **pz = &p->zErrmsg;
166848    const char *zIdx = pIter->zIdx;
166849    char *zLimit = 0;
166850
166851    if( nOffset ){
166852      zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
166853      if( !zLimit ) p->rc = SQLITE_NOMEM;
166854    }
166855
166856    if( zIdx ){
166857      const char *zTbl = pIter->zTbl;
166858      char *zImposterCols = 0;    /* Columns for imposter table */
166859      char *zImposterPK = 0;      /* Primary key declaration for imposter */
166860      char *zWhere = 0;           /* WHERE clause on PK columns */
166861      char *zBind = 0;
166862      int nBind = 0;
166863
166864      assert( pIter->eType!=RBU_PK_VTAB );
166865      zCollist = rbuObjIterGetIndexCols(
166866          p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
166867      );
166868      zBind = rbuObjIterGetBindlist(p, nBind);
166869
166870      /* Create the imposter table used to write to this index. */
166871      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
166872      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
166873      rbuMPrintfExec(p, p->dbMain,
166874          "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
166875          zTbl, zImposterCols, zImposterPK
166876      );
166877      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
166878
166879      /* Create the statement to insert index entries */
166880      pIter->nCol = nBind;
166881      if( p->rc==SQLITE_OK ){
166882        p->rc = prepareFreeAndCollectError(
166883            p->dbMain, &pIter->pInsert, &p->zErrmsg,
166884          sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
166885        );
166886      }
166887
166888      /* And to delete index entries */
166889      if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
166890        p->rc = prepareFreeAndCollectError(
166891            p->dbMain, &pIter->pDelete, &p->zErrmsg,
166892          sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
166893        );
166894      }
166895
166896      /* Create the SELECT statement to read keys in sorted order */
166897      if( p->rc==SQLITE_OK ){
166898        char *zSql;
166899        if( rbuIsVacuum(p) ){
166900          zSql = sqlite3_mprintf(
166901              "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
166902              zCollist,
166903              pIter->zDataTbl,
166904              zCollist, zLimit
166905          );
166906        }else
166907
166908        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
166909          zSql = sqlite3_mprintf(
166910              "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
166911              zCollist, p->zStateDb, pIter->zDataTbl,
166912              zCollist, zLimit
166913          );
166914        }else{
166915          zSql = sqlite3_mprintf(
166916              "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
166917              "UNION ALL "
166918              "SELECT %s, rbu_control FROM '%q' "
166919              "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
166920              "ORDER BY %s%s",
166921              zCollist, p->zStateDb, pIter->zDataTbl,
166922              zCollist, pIter->zDataTbl,
166923              zCollist, zLimit
166924          );
166925        }
166926        p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
166927      }
166928
166929      sqlite3_free(zImposterCols);
166930      sqlite3_free(zImposterPK);
166931      sqlite3_free(zWhere);
166932      sqlite3_free(zBind);
166933    }else{
166934      int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
166935                    ||(pIter->eType==RBU_PK_NONE)
166936                    ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
166937      const char *zTbl = pIter->zTbl;       /* Table this step applies to */
166938      const char *zWrite;                   /* Imposter table name */
166939
166940      char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
166941      char *zWhere = rbuObjIterGetWhere(p, pIter);
166942      char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
166943      char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
166944
166945      zCollist = rbuObjIterGetCollist(p, pIter);
166946      pIter->nCol = pIter->nTblCol;
166947
166948      /* Create the imposter table or tables (if required). */
166949      rbuCreateImposterTable(p, pIter);
166950      rbuCreateImposterTable2(p, pIter);
166951      zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
166952
166953      /* Create the INSERT statement to write to the target PK b-tree */
166954      if( p->rc==SQLITE_OK ){
166955        p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
166956            sqlite3_mprintf(
166957              "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
166958              zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
166959            )
166960        );
166961      }
166962
166963      /* Create the DELETE statement to write to the target PK b-tree.
166964      ** Because it only performs INSERT operations, this is not required for
166965      ** an rbu vacuum handle.  */
166966      if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
166967        p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
166968            sqlite3_mprintf(
166969              "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
166970            )
166971        );
166972      }
166973
166974      if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
166975        const char *zRbuRowid = "";
166976        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
166977          zRbuRowid = ", rbu_rowid";
166978        }
166979
166980        /* Create the rbu_tmp_xxx table and the triggers to populate it. */
166981        rbuMPrintfExec(p, p->dbRbu,
166982            "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
166983            "SELECT *%s FROM '%q' WHERE 0;"
166984            , p->zStateDb, pIter->zDataTbl
166985            , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
166986            , pIter->zDataTbl
166987        );
166988
166989        rbuMPrintfExec(p, p->dbMain,
166990            "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
166991            "BEGIN "
166992            "  SELECT rbu_tmp_insert(3, %s);"
166993            "END;"
166994
166995            "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
166996            "BEGIN "
166997            "  SELECT rbu_tmp_insert(3, %s);"
166998            "END;"
166999
167000            "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
167001            "BEGIN "
167002            "  SELECT rbu_tmp_insert(4, %s);"
167003            "END;",
167004            zWrite, zTbl, zOldlist,
167005            zWrite, zTbl, zOldlist,
167006            zWrite, zTbl, zNewlist
167007        );
167008
167009        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
167010          rbuMPrintfExec(p, p->dbMain,
167011              "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
167012              "BEGIN "
167013              "  SELECT rbu_tmp_insert(0, %s);"
167014              "END;",
167015              zWrite, zTbl, zNewlist
167016          );
167017        }
167018
167019        rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
167020      }
167021
167022      /* Create the SELECT statement to read keys from data_xxx */
167023      if( p->rc==SQLITE_OK ){
167024        const char *zRbuRowid = "";
167025        if( bRbuRowid ){
167026          zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
167027        }
167028        p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
167029            sqlite3_mprintf(
167030              "SELECT %s,%s rbu_control%s FROM '%q'%s",
167031              zCollist,
167032              (rbuIsVacuum(p) ? "0 AS " : ""),
167033              zRbuRowid,
167034              pIter->zDataTbl, zLimit
167035            )
167036        );
167037      }
167038
167039      sqlite3_free(zWhere);
167040      sqlite3_free(zOldlist);
167041      sqlite3_free(zNewlist);
167042      sqlite3_free(zBindings);
167043    }
167044    sqlite3_free(zCollist);
167045    sqlite3_free(zLimit);
167046  }
167047
167048  return p->rc;
167049}
167050
167051/*
167052** Set output variable *ppStmt to point to an UPDATE statement that may
167053** be used to update the imposter table for the main table b-tree of the
167054** table object that pIter currently points to, assuming that the
167055** rbu_control column of the data_xyz table contains zMask.
167056**
167057** If the zMask string does not specify any columns to update, then this
167058** is not an error. Output variable *ppStmt is set to NULL in this case.
167059*/
167060static int rbuGetUpdateStmt(
167061  sqlite3rbu *p,                  /* RBU handle */
167062  RbuObjIter *pIter,              /* Object iterator */
167063  const char *zMask,              /* rbu_control value ('x.x.') */
167064  sqlite3_stmt **ppStmt           /* OUT: UPDATE statement handle */
167065){
167066  RbuUpdateStmt **pp;
167067  RbuUpdateStmt *pUp = 0;
167068  int nUp = 0;
167069
167070  /* In case an error occurs */
167071  *ppStmt = 0;
167072
167073  /* Search for an existing statement. If one is found, shift it to the front
167074  ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
167075  ** to the number of statements currently in the cache and pUp to the
167076  ** last object in the list.  */
167077  for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
167078    pUp = *pp;
167079    if( strcmp(pUp->zMask, zMask)==0 ){
167080      *pp = pUp->pNext;
167081      pUp->pNext = pIter->pRbuUpdate;
167082      pIter->pRbuUpdate = pUp;
167083      *ppStmt = pUp->pUpdate;
167084      return SQLITE_OK;
167085    }
167086    nUp++;
167087  }
167088  assert( pUp==0 || pUp->pNext==0 );
167089
167090  if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
167091    for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
167092    *pp = 0;
167093    sqlite3_finalize(pUp->pUpdate);
167094    pUp->pUpdate = 0;
167095  }else{
167096    pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
167097  }
167098
167099  if( pUp ){
167100    char *zWhere = rbuObjIterGetWhere(p, pIter);
167101    char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
167102    char *zUpdate = 0;
167103
167104    pUp->zMask = (char*)&pUp[1];
167105    memcpy(pUp->zMask, zMask, pIter->nTblCol);
167106    pUp->pNext = pIter->pRbuUpdate;
167107    pIter->pRbuUpdate = pUp;
167108
167109    if( zSet ){
167110      const char *zPrefix = "";
167111
167112      if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
167113      zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
167114          zPrefix, pIter->zTbl, zSet, zWhere
167115      );
167116      p->rc = prepareFreeAndCollectError(
167117          p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
167118      );
167119      *ppStmt = pUp->pUpdate;
167120    }
167121    sqlite3_free(zWhere);
167122    sqlite3_free(zSet);
167123  }
167124
167125  return p->rc;
167126}
167127
167128static sqlite3 *rbuOpenDbhandle(
167129  sqlite3rbu *p,
167130  const char *zName,
167131  int bUseVfs
167132){
167133  sqlite3 *db = 0;
167134  if( p->rc==SQLITE_OK ){
167135    const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
167136    p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
167137    if( p->rc ){
167138      p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
167139      sqlite3_close(db);
167140      db = 0;
167141    }
167142  }
167143  return db;
167144}
167145
167146/*
167147** Free an RbuState object allocated by rbuLoadState().
167148*/
167149static void rbuFreeState(RbuState *p){
167150  if( p ){
167151    sqlite3_free(p->zTbl);
167152    sqlite3_free(p->zIdx);
167153    sqlite3_free(p);
167154  }
167155}
167156
167157/*
167158** Allocate an RbuState object and load the contents of the rbu_state
167159** table into it. Return a pointer to the new object. It is the
167160** responsibility of the caller to eventually free the object using
167161** sqlite3_free().
167162**
167163** If an error occurs, leave an error code and message in the rbu handle
167164** and return NULL.
167165*/
167166static RbuState *rbuLoadState(sqlite3rbu *p){
167167  RbuState *pRet = 0;
167168  sqlite3_stmt *pStmt = 0;
167169  int rc;
167170  int rc2;
167171
167172  pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
167173  if( pRet==0 ) return 0;
167174
167175  rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
167176      sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
167177  );
167178  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
167179    switch( sqlite3_column_int(pStmt, 0) ){
167180      case RBU_STATE_STAGE:
167181        pRet->eStage = sqlite3_column_int(pStmt, 1);
167182        if( pRet->eStage!=RBU_STAGE_OAL
167183         && pRet->eStage!=RBU_STAGE_MOVE
167184         && pRet->eStage!=RBU_STAGE_CKPT
167185        ){
167186          p->rc = SQLITE_CORRUPT;
167187        }
167188        break;
167189
167190      case RBU_STATE_TBL:
167191        pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
167192        break;
167193
167194      case RBU_STATE_IDX:
167195        pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
167196        break;
167197
167198      case RBU_STATE_ROW:
167199        pRet->nRow = sqlite3_column_int(pStmt, 1);
167200        break;
167201
167202      case RBU_STATE_PROGRESS:
167203        pRet->nProgress = sqlite3_column_int64(pStmt, 1);
167204        break;
167205
167206      case RBU_STATE_CKPT:
167207        pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
167208        break;
167209
167210      case RBU_STATE_COOKIE:
167211        pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
167212        break;
167213
167214      case RBU_STATE_OALSZ:
167215        pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
167216        break;
167217
167218      case RBU_STATE_PHASEONESTEP:
167219        pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
167220        break;
167221
167222      default:
167223        rc = SQLITE_CORRUPT;
167224        break;
167225    }
167226  }
167227  rc2 = sqlite3_finalize(pStmt);
167228  if( rc==SQLITE_OK ) rc = rc2;
167229
167230  p->rc = rc;
167231  return pRet;
167232}
167233
167234
167235/*
167236** Open the database handle and attach the RBU database as "rbu". If an
167237** error occurs, leave an error code and message in the RBU handle.
167238*/
167239static void rbuOpenDatabase(sqlite3rbu *p){
167240  assert( p->rc==SQLITE_OK );
167241  assert( p->dbMain==0 && p->dbRbu==0 );
167242  assert( rbuIsVacuum(p) || p->zTarget!=0 );
167243
167244  /* Open the RBU database */
167245  p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
167246
167247  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
167248    sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
167249  }
167250
167251  /* If using separate RBU and state databases, attach the state database to
167252  ** the RBU db handle now.  */
167253  if( p->zState ){
167254    rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
167255    memcpy(p->zStateDb, "stat", 4);
167256  }else{
167257    memcpy(p->zStateDb, "main", 4);
167258  }
167259
167260#if 0
167261  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
167262    p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
167263  }
167264#endif
167265
167266  /* If it has not already been created, create the rbu_state table */
167267  rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
167268
167269#if 0
167270  if( rbuIsVacuum(p) ){
167271    if( p->rc==SQLITE_OK ){
167272      int rc2;
167273      int bOk = 0;
167274      sqlite3_stmt *pCnt = 0;
167275      p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
167276          "SELECT count(*) FROM stat.sqlite_master"
167277      );
167278      if( p->rc==SQLITE_OK
167279       && sqlite3_step(pCnt)==SQLITE_ROW
167280       && 1==sqlite3_column_int(pCnt, 0)
167281      ){
167282        bOk = 1;
167283      }
167284      rc2 = sqlite3_finalize(pCnt);
167285      if( p->rc==SQLITE_OK ) p->rc = rc2;
167286
167287      if( p->rc==SQLITE_OK && bOk==0 ){
167288        p->rc = SQLITE_ERROR;
167289        p->zErrmsg = sqlite3_mprintf("invalid state database");
167290      }
167291
167292      if( p->rc==SQLITE_OK ){
167293        p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
167294      }
167295    }
167296  }
167297#endif
167298
167299  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
167300    int bOpen = 0;
167301    int rc;
167302    p->nRbu = 0;
167303    p->pRbuFd = 0;
167304    rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
167305    if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
167306    if( p->eStage>=RBU_STAGE_MOVE ){
167307      bOpen = 1;
167308    }else{
167309      RbuState *pState = rbuLoadState(p);
167310      if( pState ){
167311        bOpen = (pState->eStage>RBU_STAGE_MOVE);
167312        rbuFreeState(pState);
167313      }
167314    }
167315    if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
167316  }
167317
167318  p->eStage = 0;
167319  if( p->rc==SQLITE_OK && p->dbMain==0 ){
167320    if( !rbuIsVacuum(p) ){
167321      p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
167322    }else if( p->pRbuFd->pWalFd ){
167323      p->rc = SQLITE_ERROR;
167324      p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
167325    }else{
167326      char *zTarget;
167327      char *zExtra = 0;
167328      if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
167329        zExtra = &p->zRbu[5];
167330        while( *zExtra ){
167331          if( *zExtra++=='?' ) break;
167332        }
167333        if( *zExtra=='\0' ) zExtra = 0;
167334      }
167335
167336      zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s",
167337          sqlite3_db_filename(p->dbRbu, "main"),
167338          (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
167339      );
167340
167341      if( zTarget==0 ){
167342        p->rc = SQLITE_NOMEM;
167343        return;
167344      }
167345      p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
167346      sqlite3_free(zTarget);
167347    }
167348  }
167349
167350  if( p->rc==SQLITE_OK ){
167351    p->rc = sqlite3_create_function(p->dbMain,
167352        "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
167353    );
167354  }
167355
167356  if( p->rc==SQLITE_OK ){
167357    p->rc = sqlite3_create_function(p->dbMain,
167358        "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
167359    );
167360  }
167361
167362  if( p->rc==SQLITE_OK ){
167363    p->rc = sqlite3_create_function(p->dbRbu,
167364        "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
167365    );
167366  }
167367
167368  if( p->rc==SQLITE_OK ){
167369    p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
167370  }
167371  rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
167372
167373  /* Mark the database file just opened as an RBU target database. If
167374  ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
167375  ** This is an error.  */
167376  if( p->rc==SQLITE_OK ){
167377    p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
167378  }
167379
167380  if( p->rc==SQLITE_NOTFOUND ){
167381    p->rc = SQLITE_ERROR;
167382    p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
167383  }
167384}
167385
167386/*
167387** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
167388** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
167389**
167390** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
167391** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
167392** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
167393** three characters, then shorten the suffix on z[] to be the last three
167394** characters of the original suffix.
167395**
167396** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
167397** do the suffix shortening regardless of URI parameter.
167398**
167399** Examples:
167400**
167401**     test.db-journal    =>   test.nal
167402**     test.db-wal        =>   test.wal
167403**     test.db-shm        =>   test.shm
167404**     test.db-mj7f3319fa =>   test.9fa
167405*/
167406static void rbuFileSuffix3(const char *zBase, char *z){
167407#ifdef SQLITE_ENABLE_8_3_NAMES
167408#if SQLITE_ENABLE_8_3_NAMES<2
167409  if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
167410#endif
167411  {
167412    int i, sz;
167413    sz = (int)strlen(z)&0xffffff;
167414    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
167415    if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
167416  }
167417#endif
167418}
167419
167420/*
167421** Return the current wal-index header checksum for the target database
167422** as a 64-bit integer.
167423**
167424** The checksum is store in the first page of xShmMap memory as an 8-byte
167425** blob starting at byte offset 40.
167426*/
167427static i64 rbuShmChecksum(sqlite3rbu *p){
167428  i64 iRet = 0;
167429  if( p->rc==SQLITE_OK ){
167430    sqlite3_file *pDb = p->pTargetFd->pReal;
167431    u32 volatile *ptr;
167432    p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
167433    if( p->rc==SQLITE_OK ){
167434      iRet = ((i64)ptr[10] << 32) + ptr[11];
167435    }
167436  }
167437  return iRet;
167438}
167439
167440/*
167441** This function is called as part of initializing or reinitializing an
167442** incremental checkpoint.
167443**
167444** It populates the sqlite3rbu.aFrame[] array with the set of
167445** (wal frame -> db page) copy operations required to checkpoint the
167446** current wal file, and obtains the set of shm locks required to safely
167447** perform the copy operations directly on the file-system.
167448**
167449** If argument pState is not NULL, then the incremental checkpoint is
167450** being resumed. In this case, if the checksum of the wal-index-header
167451** following recovery is not the same as the checksum saved in the RbuState
167452** object, then the rbu handle is set to DONE state. This occurs if some
167453** other client appends a transaction to the wal file in the middle of
167454** an incremental checkpoint.
167455*/
167456static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
167457
167458  /* If pState is NULL, then the wal file may not have been opened and
167459  ** recovered. Running a read-statement here to ensure that doing so
167460  ** does not interfere with the "capture" process below.  */
167461  if( pState==0 ){
167462    p->eStage = 0;
167463    if( p->rc==SQLITE_OK ){
167464      p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
167465    }
167466  }
167467
167468  /* Assuming no error has occurred, run a "restart" checkpoint with the
167469  ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
167470  ** special behaviour in the rbu VFS:
167471  **
167472  **   * If the exclusive shm WRITER or READ0 lock cannot be obtained,
167473  **     the checkpoint fails with SQLITE_BUSY (normally SQLite would
167474  **     proceed with running a passive checkpoint instead of failing).
167475  **
167476  **   * Attempts to read from the *-wal file or write to the database file
167477  **     do not perform any IO. Instead, the frame/page combinations that
167478  **     would be read/written are recorded in the sqlite3rbu.aFrame[]
167479  **     array.
167480  **
167481  **   * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
167482  **     READ0 and CHECKPOINT locks taken as part of the checkpoint are
167483  **     no-ops. These locks will not be released until the connection
167484  **     is closed.
167485  **
167486  **   * Attempting to xSync() the database file causes an SQLITE_INTERNAL
167487  **     error.
167488  **
167489  ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
167490  ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
167491  ** array populated with a set of (frame -> page) mappings. Because the
167492  ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
167493  ** data from the wal file into the database file according to the
167494  ** contents of aFrame[].
167495  */
167496  if( p->rc==SQLITE_OK ){
167497    int rc2;
167498    p->eStage = RBU_STAGE_CAPTURE;
167499    rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
167500    if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
167501  }
167502
167503  if( p->rc==SQLITE_OK ){
167504    p->eStage = RBU_STAGE_CKPT;
167505    p->nStep = (pState ? pState->nRow : 0);
167506    p->aBuf = rbuMalloc(p, p->pgsz);
167507    p->iWalCksum = rbuShmChecksum(p);
167508  }
167509
167510  if( p->rc==SQLITE_OK && pState && pState->iWalCksum!=p->iWalCksum ){
167511    p->rc = SQLITE_DONE;
167512    p->eStage = RBU_STAGE_DONE;
167513  }
167514}
167515
167516/*
167517** Called when iAmt bytes are read from offset iOff of the wal file while
167518** the rbu object is in capture mode. Record the frame number of the frame
167519** being read in the aFrame[] array.
167520*/
167521static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
167522  const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
167523  u32 iFrame;
167524
167525  if( pRbu->mLock!=mReq ){
167526    pRbu->rc = SQLITE_BUSY;
167527    return SQLITE_INTERNAL;
167528  }
167529
167530  pRbu->pgsz = iAmt;
167531  if( pRbu->nFrame==pRbu->nFrameAlloc ){
167532    int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
167533    RbuFrame *aNew;
167534    aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
167535    if( aNew==0 ) return SQLITE_NOMEM;
167536    pRbu->aFrame = aNew;
167537    pRbu->nFrameAlloc = nNew;
167538  }
167539
167540  iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
167541  if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
167542  pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
167543  pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
167544  pRbu->nFrame++;
167545  return SQLITE_OK;
167546}
167547
167548/*
167549** Called when a page of data is written to offset iOff of the database
167550** file while the rbu handle is in capture mode. Record the page number
167551** of the page being written in the aFrame[] array.
167552*/
167553static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
167554  pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
167555  return SQLITE_OK;
167556}
167557
167558/*
167559** This is called as part of an incremental checkpoint operation. Copy
167560** a single frame of data from the wal file into the database file, as
167561** indicated by the RbuFrame object.
167562*/
167563static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
167564  sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
167565  sqlite3_file *pDb = p->pTargetFd->pReal;
167566  i64 iOff;
167567
167568  assert( p->rc==SQLITE_OK );
167569  iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
167570  p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
167571  if( p->rc ) return;
167572
167573  iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
167574  p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
167575}
167576
167577
167578/*
167579** Take an EXCLUSIVE lock on the database file.
167580*/
167581static void rbuLockDatabase(sqlite3rbu *p){
167582  sqlite3_file *pReal = p->pTargetFd->pReal;
167583  assert( p->rc==SQLITE_OK );
167584  p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
167585  if( p->rc==SQLITE_OK ){
167586    p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
167587  }
167588}
167589
167590#if defined(_WIN32_WCE)
167591static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
167592  int nChar;
167593  LPWSTR zWideFilename;
167594
167595  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
167596  if( nChar==0 ){
167597    return 0;
167598  }
167599  zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
167600  if( zWideFilename==0 ){
167601    return 0;
167602  }
167603  memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
167604  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
167605                                nChar);
167606  if( nChar==0 ){
167607    sqlite3_free(zWideFilename);
167608    zWideFilename = 0;
167609  }
167610  return zWideFilename;
167611}
167612#endif
167613
167614/*
167615** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
167616** on the database file. This proc moves the *-oal file to the *-wal path,
167617** then reopens the database file (this time in vanilla, non-oal, WAL mode).
167618** If an error occurs, leave an error code and error message in the rbu
167619** handle.
167620*/
167621static void rbuMoveOalFile(sqlite3rbu *p){
167622  const char *zBase = sqlite3_db_filename(p->dbMain, "main");
167623  const char *zMove = zBase;
167624  char *zOal;
167625  char *zWal;
167626
167627  if( rbuIsVacuum(p) ){
167628    zMove = sqlite3_db_filename(p->dbRbu, "main");
167629  }
167630  zOal = sqlite3_mprintf("%s-oal", zMove);
167631  zWal = sqlite3_mprintf("%s-wal", zMove);
167632
167633  assert( p->eStage==RBU_STAGE_MOVE );
167634  assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
167635  if( zWal==0 || zOal==0 ){
167636    p->rc = SQLITE_NOMEM;
167637  }else{
167638    /* Move the *-oal file to *-wal. At this point connection p->db is
167639    ** holding a SHARED lock on the target database file (because it is
167640    ** in WAL mode). So no other connection may be writing the db.
167641    **
167642    ** In order to ensure that there are no database readers, an EXCLUSIVE
167643    ** lock is obtained here before the *-oal is moved to *-wal.
167644    */
167645    rbuLockDatabase(p);
167646    if( p->rc==SQLITE_OK ){
167647      rbuFileSuffix3(zBase, zWal);
167648      rbuFileSuffix3(zBase, zOal);
167649
167650      /* Re-open the databases. */
167651      rbuObjIterFinalize(&p->objiter);
167652      sqlite3_close(p->dbRbu);
167653      sqlite3_close(p->dbMain);
167654      p->dbMain = 0;
167655      p->dbRbu = 0;
167656
167657#if defined(_WIN32_WCE)
167658      {
167659        LPWSTR zWideOal;
167660        LPWSTR zWideWal;
167661
167662        zWideOal = rbuWinUtf8ToUnicode(zOal);
167663        if( zWideOal ){
167664          zWideWal = rbuWinUtf8ToUnicode(zWal);
167665          if( zWideWal ){
167666            if( MoveFileW(zWideOal, zWideWal) ){
167667              p->rc = SQLITE_OK;
167668            }else{
167669              p->rc = SQLITE_IOERR;
167670            }
167671            sqlite3_free(zWideWal);
167672          }else{
167673            p->rc = SQLITE_IOERR_NOMEM;
167674          }
167675          sqlite3_free(zWideOal);
167676        }else{
167677          p->rc = SQLITE_IOERR_NOMEM;
167678        }
167679      }
167680#else
167681      p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
167682#endif
167683
167684      if( p->rc==SQLITE_OK ){
167685        rbuOpenDatabase(p);
167686        rbuSetupCheckpoint(p, 0);
167687      }
167688    }
167689  }
167690
167691  sqlite3_free(zWal);
167692  sqlite3_free(zOal);
167693}
167694
167695/*
167696** The SELECT statement iterating through the keys for the current object
167697** (p->objiter.pSelect) currently points to a valid row. This function
167698** determines the type of operation requested by this row and returns
167699** one of the following values to indicate the result:
167700**
167701**     * RBU_INSERT
167702**     * RBU_DELETE
167703**     * RBU_IDX_DELETE
167704**     * RBU_UPDATE
167705**
167706** If RBU_UPDATE is returned, then output variable *pzMask is set to
167707** point to the text value indicating the columns to update.
167708**
167709** If the rbu_control field contains an invalid value, an error code and
167710** message are left in the RBU handle and zero returned.
167711*/
167712static int rbuStepType(sqlite3rbu *p, const char **pzMask){
167713  int iCol = p->objiter.nCol;     /* Index of rbu_control column */
167714  int res = 0;                    /* Return value */
167715
167716  switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
167717    case SQLITE_INTEGER: {
167718      int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
167719      switch( iVal ){
167720        case 0: res = RBU_INSERT;     break;
167721        case 1: res = RBU_DELETE;     break;
167722        case 2: res = RBU_REPLACE;    break;
167723        case 3: res = RBU_IDX_DELETE; break;
167724        case 4: res = RBU_IDX_INSERT; break;
167725      }
167726      break;
167727    }
167728
167729    case SQLITE_TEXT: {
167730      const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
167731      if( z==0 ){
167732        p->rc = SQLITE_NOMEM;
167733      }else{
167734        *pzMask = (const char*)z;
167735      }
167736      res = RBU_UPDATE;
167737
167738      break;
167739    }
167740
167741    default:
167742      break;
167743  }
167744
167745  if( res==0 ){
167746    rbuBadControlError(p);
167747  }
167748  return res;
167749}
167750
167751#ifdef SQLITE_DEBUG
167752/*
167753** Assert that column iCol of statement pStmt is named zName.
167754*/
167755static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
167756  const char *zCol = sqlite3_column_name(pStmt, iCol);
167757  assert( 0==sqlite3_stricmp(zName, zCol) );
167758}
167759#else
167760# define assertColumnName(x,y,z)
167761#endif
167762
167763/*
167764** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
167765** RBU_IDX_DELETE. This function performs the work of a single
167766** sqlite3rbu_step() call for the type of operation specified by eType.
167767*/
167768static void rbuStepOneOp(sqlite3rbu *p, int eType){
167769  RbuObjIter *pIter = &p->objiter;
167770  sqlite3_value *pVal;
167771  sqlite3_stmt *pWriter;
167772  int i;
167773
167774  assert( p->rc==SQLITE_OK );
167775  assert( eType!=RBU_DELETE || pIter->zIdx==0 );
167776  assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
167777       || eType==RBU_INSERT || eType==RBU_IDX_INSERT
167778  );
167779
167780  /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
167781  ** statement below does actually delete a row, nPhaseOneStep will be
167782  ** incremented by the same amount when SQL function rbu_tmp_insert()
167783  ** is invoked by the trigger.  */
167784  if( eType==RBU_DELETE ){
167785    p->nPhaseOneStep -= p->objiter.nIndex;
167786  }
167787
167788  if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
167789    pWriter = pIter->pDelete;
167790  }else{
167791    pWriter = pIter->pInsert;
167792  }
167793
167794  for(i=0; i<pIter->nCol; i++){
167795    /* If this is an INSERT into a table b-tree and the table has an
167796    ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
167797    ** to write a NULL into the IPK column. That is not permitted.  */
167798    if( eType==RBU_INSERT
167799     && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
167800     && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
167801    ){
167802      p->rc = SQLITE_MISMATCH;
167803      p->zErrmsg = sqlite3_mprintf("datatype mismatch");
167804      return;
167805    }
167806
167807    if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
167808      continue;
167809    }
167810
167811    pVal = sqlite3_column_value(pIter->pSelect, i);
167812    p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
167813    if( p->rc ) return;
167814  }
167815  if( pIter->zIdx==0 ){
167816    if( pIter->eType==RBU_PK_VTAB
167817     || pIter->eType==RBU_PK_NONE
167818     || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
167819    ){
167820      /* For a virtual table, or a table with no primary key, the
167821      ** SELECT statement is:
167822      **
167823      **   SELECT <cols>, rbu_control, rbu_rowid FROM ....
167824      **
167825      ** Hence column_value(pIter->nCol+1).
167826      */
167827      assertColumnName(pIter->pSelect, pIter->nCol+1,
167828          rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
167829      );
167830      pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
167831      p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
167832    }
167833  }
167834  if( p->rc==SQLITE_OK ){
167835    sqlite3_step(pWriter);
167836    p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
167837  }
167838}
167839
167840/*
167841** This function does the work for an sqlite3rbu_step() call.
167842**
167843** The object-iterator (p->objiter) currently points to a valid object,
167844** and the input cursor (p->objiter.pSelect) currently points to a valid
167845** input row. Perform whatever processing is required and return.
167846**
167847** If no  error occurs, SQLITE_OK is returned. Otherwise, an error code
167848** and message is left in the RBU handle and a copy of the error code
167849** returned.
167850*/
167851static int rbuStep(sqlite3rbu *p){
167852  RbuObjIter *pIter = &p->objiter;
167853  const char *zMask = 0;
167854  int eType = rbuStepType(p, &zMask);
167855
167856  if( eType ){
167857    assert( eType==RBU_INSERT     || eType==RBU_DELETE
167858         || eType==RBU_REPLACE    || eType==RBU_IDX_DELETE
167859         || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
167860    );
167861    assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
167862
167863    if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
167864      rbuBadControlError(p);
167865    }
167866    else if( eType==RBU_REPLACE ){
167867      if( pIter->zIdx==0 ){
167868        p->nPhaseOneStep += p->objiter.nIndex;
167869        rbuStepOneOp(p, RBU_DELETE);
167870      }
167871      if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
167872    }
167873    else if( eType!=RBU_UPDATE ){
167874      rbuStepOneOp(p, eType);
167875    }
167876    else{
167877      sqlite3_value *pVal;
167878      sqlite3_stmt *pUpdate = 0;
167879      assert( eType==RBU_UPDATE );
167880      p->nPhaseOneStep -= p->objiter.nIndex;
167881      rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
167882      if( pUpdate ){
167883        int i;
167884        for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
167885          char c = zMask[pIter->aiSrcOrder[i]];
167886          pVal = sqlite3_column_value(pIter->pSelect, i);
167887          if( pIter->abTblPk[i] || c!='.' ){
167888            p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
167889          }
167890        }
167891        if( p->rc==SQLITE_OK
167892         && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
167893        ){
167894          /* Bind the rbu_rowid value to column _rowid_ */
167895          assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
167896          pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
167897          p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
167898        }
167899        if( p->rc==SQLITE_OK ){
167900          sqlite3_step(pUpdate);
167901          p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
167902        }
167903      }
167904    }
167905  }
167906  return p->rc;
167907}
167908
167909/*
167910** Increment the schema cookie of the main database opened by p->dbMain.
167911**
167912** Or, if this is an RBU vacuum, set the schema cookie of the main db
167913** opened by p->dbMain to one more than the schema cookie of the main
167914** db opened by p->dbRbu.
167915*/
167916static void rbuIncrSchemaCookie(sqlite3rbu *p){
167917  if( p->rc==SQLITE_OK ){
167918    sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
167919    int iCookie = 1000000;
167920    sqlite3_stmt *pStmt;
167921
167922    p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
167923        "PRAGMA schema_version"
167924    );
167925    if( p->rc==SQLITE_OK ){
167926      /* Coverage: it may be that this sqlite3_step() cannot fail. There
167927      ** is already a transaction open, so the prepared statement cannot
167928      ** throw an SQLITE_SCHEMA exception. The only database page the
167929      ** statement reads is page 1, which is guaranteed to be in the cache.
167930      ** And no memory allocations are required.  */
167931      if( SQLITE_ROW==sqlite3_step(pStmt) ){
167932        iCookie = sqlite3_column_int(pStmt, 0);
167933      }
167934      rbuFinalize(p, pStmt);
167935    }
167936    if( p->rc==SQLITE_OK ){
167937      rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
167938    }
167939  }
167940}
167941
167942/*
167943** Update the contents of the rbu_state table within the rbu database. The
167944** value stored in the RBU_STATE_STAGE column is eStage. All other values
167945** are determined by inspecting the rbu handle passed as the first argument.
167946*/
167947static void rbuSaveState(sqlite3rbu *p, int eStage){
167948  if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
167949    sqlite3_stmt *pInsert = 0;
167950    rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
167951    int rc;
167952
167953    assert( p->zErrmsg==0 );
167954    rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
167955        sqlite3_mprintf(
167956          "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
167957          "(%d, %d), "
167958          "(%d, %Q), "
167959          "(%d, %Q), "
167960          "(%d, %d), "
167961          "(%d, %d), "
167962          "(%d, %lld), "
167963          "(%d, %lld), "
167964          "(%d, %lld), "
167965          "(%d, %lld) ",
167966          p->zStateDb,
167967          RBU_STATE_STAGE, eStage,
167968          RBU_STATE_TBL, p->objiter.zTbl,
167969          RBU_STATE_IDX, p->objiter.zIdx,
167970          RBU_STATE_ROW, p->nStep,
167971          RBU_STATE_PROGRESS, p->nProgress,
167972          RBU_STATE_CKPT, p->iWalCksum,
167973          RBU_STATE_COOKIE, (i64)pFd->iCookie,
167974          RBU_STATE_OALSZ, p->iOalSz,
167975          RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
167976      )
167977    );
167978    assert( pInsert==0 || rc==SQLITE_OK );
167979
167980    if( rc==SQLITE_OK ){
167981      sqlite3_step(pInsert);
167982      rc = sqlite3_finalize(pInsert);
167983    }
167984    if( rc!=SQLITE_OK ) p->rc = rc;
167985  }
167986}
167987
167988
167989/*
167990** The second argument passed to this function is the name of a PRAGMA
167991** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
167992** This function executes the following on sqlite3rbu.dbRbu:
167993**
167994**   "PRAGMA main.$zPragma"
167995**
167996** where $zPragma is the string passed as the second argument, then
167997** on sqlite3rbu.dbMain:
167998**
167999**   "PRAGMA main.$zPragma = $val"
168000**
168001** where $val is the value returned by the first PRAGMA invocation.
168002**
168003** In short, it copies the value  of the specified PRAGMA setting from
168004** dbRbu to dbMain.
168005*/
168006static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
168007  if( p->rc==SQLITE_OK ){
168008    sqlite3_stmt *pPragma = 0;
168009    p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
168010        sqlite3_mprintf("PRAGMA main.%s", zPragma)
168011    );
168012    if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
168013      p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
168014          zPragma, sqlite3_column_int(pPragma, 0)
168015      );
168016    }
168017    rbuFinalize(p, pPragma);
168018  }
168019}
168020
168021/*
168022** The RBU handle passed as the only argument has just been opened and
168023** the state database is empty. If this RBU handle was opened for an
168024** RBU vacuum operation, create the schema in the target db.
168025*/
168026static void rbuCreateTargetSchema(sqlite3rbu *p){
168027  sqlite3_stmt *pSql = 0;
168028  sqlite3_stmt *pInsert = 0;
168029
168030  assert( rbuIsVacuum(p) );
168031  p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
168032  if( p->rc==SQLITE_OK ){
168033    p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
168034      "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
168035      " AND name!='sqlite_sequence' "
168036      " ORDER BY type DESC"
168037    );
168038  }
168039
168040  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
168041    const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
168042    p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
168043  }
168044  rbuFinalize(p, pSql);
168045  if( p->rc!=SQLITE_OK ) return;
168046
168047  if( p->rc==SQLITE_OK ){
168048    p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
168049        "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
168050    );
168051  }
168052
168053  if( p->rc==SQLITE_OK ){
168054    p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
168055        "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
168056    );
168057  }
168058
168059  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
168060    int i;
168061    for(i=0; i<5; i++){
168062      sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
168063    }
168064    sqlite3_step(pInsert);
168065    p->rc = sqlite3_reset(pInsert);
168066  }
168067  if( p->rc==SQLITE_OK ){
168068    p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
168069  }
168070
168071  rbuFinalize(p, pSql);
168072  rbuFinalize(p, pInsert);
168073}
168074
168075/*
168076** Step the RBU object.
168077*/
168078SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *p){
168079  if( p ){
168080    switch( p->eStage ){
168081      case RBU_STAGE_OAL: {
168082        RbuObjIter *pIter = &p->objiter;
168083
168084        /* If this is an RBU vacuum operation and the state table was empty
168085        ** when this handle was opened, create the target database schema. */
168086        if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
168087          rbuCreateTargetSchema(p);
168088          rbuCopyPragma(p, "user_version");
168089          rbuCopyPragma(p, "application_id");
168090        }
168091
168092        while( p->rc==SQLITE_OK && pIter->zTbl ){
168093
168094          if( pIter->bCleanup ){
168095            /* Clean up the rbu_tmp_xxx table for the previous table. It
168096            ** cannot be dropped as there are currently active SQL statements.
168097            ** But the contents can be deleted.  */
168098            if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
168099              rbuMPrintfExec(p, p->dbRbu,
168100                  "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
168101              );
168102            }
168103          }else{
168104            rbuObjIterPrepareAll(p, pIter, 0);
168105
168106            /* Advance to the next row to process. */
168107            if( p->rc==SQLITE_OK ){
168108              int rc = sqlite3_step(pIter->pSelect);
168109              if( rc==SQLITE_ROW ){
168110                p->nProgress++;
168111                p->nStep++;
168112                return rbuStep(p);
168113              }
168114              p->rc = sqlite3_reset(pIter->pSelect);
168115              p->nStep = 0;
168116            }
168117          }
168118
168119          rbuObjIterNext(p, pIter);
168120        }
168121
168122        if( p->rc==SQLITE_OK ){
168123          assert( pIter->zTbl==0 );
168124          rbuSaveState(p, RBU_STAGE_MOVE);
168125          rbuIncrSchemaCookie(p);
168126          if( p->rc==SQLITE_OK ){
168127            p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
168128          }
168129          if( p->rc==SQLITE_OK ){
168130            p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
168131          }
168132          p->eStage = RBU_STAGE_MOVE;
168133        }
168134        break;
168135      }
168136
168137      case RBU_STAGE_MOVE: {
168138        if( p->rc==SQLITE_OK ){
168139          rbuMoveOalFile(p);
168140          p->nProgress++;
168141        }
168142        break;
168143      }
168144
168145      case RBU_STAGE_CKPT: {
168146        if( p->rc==SQLITE_OK ){
168147          if( p->nStep>=p->nFrame ){
168148            sqlite3_file *pDb = p->pTargetFd->pReal;
168149
168150            /* Sync the db file */
168151            p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
168152
168153            /* Update nBackfill */
168154            if( p->rc==SQLITE_OK ){
168155              void volatile *ptr;
168156              p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
168157              if( p->rc==SQLITE_OK ){
168158                ((u32 volatile*)ptr)[24] = p->iMaxFrame;
168159              }
168160            }
168161
168162            if( p->rc==SQLITE_OK ){
168163              p->eStage = RBU_STAGE_DONE;
168164              p->rc = SQLITE_DONE;
168165            }
168166          }else{
168167            RbuFrame *pFrame = &p->aFrame[p->nStep];
168168            rbuCheckpointFrame(p, pFrame);
168169            p->nStep++;
168170          }
168171          p->nProgress++;
168172        }
168173        break;
168174      }
168175
168176      default:
168177        break;
168178    }
168179    return p->rc;
168180  }else{
168181    return SQLITE_NOMEM;
168182  }
168183}
168184
168185/*
168186** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
168187** otherwise. Either or both argument may be NULL. Two NULL values are
168188** considered equal, and NULL is considered distinct from all other values.
168189*/
168190static int rbuStrCompare(const char *z1, const char *z2){
168191  if( z1==0 && z2==0 ) return 0;
168192  if( z1==0 || z2==0 ) return 1;
168193  return (sqlite3_stricmp(z1, z2)!=0);
168194}
168195
168196/*
168197** This function is called as part of sqlite3rbu_open() when initializing
168198** an rbu handle in OAL stage. If the rbu update has not started (i.e.
168199** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
168200** things so that the next call to sqlite3rbu_step() continues on from
168201** where the previous rbu handle left off.
168202**
168203** If an error occurs, an error code and error message are left in the
168204** rbu handle passed as the first argument.
168205*/
168206static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
168207  assert( p->rc==SQLITE_OK );
168208  if( pState->zTbl ){
168209    RbuObjIter *pIter = &p->objiter;
168210    int rc = SQLITE_OK;
168211
168212    while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
168213       || rbuStrCompare(pIter->zIdx, pState->zIdx)
168214       || rbuStrCompare(pIter->zTbl, pState->zTbl)
168215    )){
168216      rc = rbuObjIterNext(p, pIter);
168217    }
168218
168219    if( rc==SQLITE_OK && !pIter->zTbl ){
168220      rc = SQLITE_ERROR;
168221      p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
168222    }
168223
168224    if( rc==SQLITE_OK ){
168225      p->nStep = pState->nRow;
168226      rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
168227    }
168228
168229    p->rc = rc;
168230  }
168231}
168232
168233/*
168234** If there is a "*-oal" file in the file-system corresponding to the
168235** target database in the file-system, delete it. If an error occurs,
168236** leave an error code and error message in the rbu handle.
168237*/
168238static void rbuDeleteOalFile(sqlite3rbu *p){
168239  char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
168240  if( zOal ){
168241    sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
168242    assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
168243    pVfs->xDelete(pVfs, zOal, 0);
168244    sqlite3_free(zOal);
168245  }
168246}
168247
168248/*
168249** Allocate a private rbu VFS for the rbu handle passed as the only
168250** argument. This VFS will be used unless the call to sqlite3rbu_open()
168251** specified a URI with a vfs=? option in place of a target database
168252** file name.
168253*/
168254static void rbuCreateVfs(sqlite3rbu *p){
168255  int rnd;
168256  char zRnd[64];
168257
168258  assert( p->rc==SQLITE_OK );
168259  sqlite3_randomness(sizeof(int), (void*)&rnd);
168260  sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
168261  p->rc = sqlite3rbu_create_vfs(zRnd, 0);
168262  if( p->rc==SQLITE_OK ){
168263    sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
168264    assert( pVfs );
168265    p->zVfsName = pVfs->zName;
168266  }
168267}
168268
168269/*
168270** Destroy the private VFS created for the rbu handle passed as the only
168271** argument by an earlier call to rbuCreateVfs().
168272*/
168273static void rbuDeleteVfs(sqlite3rbu *p){
168274  if( p->zVfsName ){
168275    sqlite3rbu_destroy_vfs(p->zVfsName);
168276    p->zVfsName = 0;
168277  }
168278}
168279
168280/*
168281** This user-defined SQL function is invoked with a single argument - the
168282** name of a table expected to appear in the target database. It returns
168283** the number of auxilliary indexes on the table.
168284*/
168285static void rbuIndexCntFunc(
168286  sqlite3_context *pCtx,
168287  int nVal,
168288  sqlite3_value **apVal
168289){
168290  sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
168291  sqlite3_stmt *pStmt = 0;
168292  char *zErrmsg = 0;
168293  int rc;
168294
168295  assert( nVal==1 );
168296
168297  rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
168298      sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
168299        "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
168300  );
168301  if( rc!=SQLITE_OK ){
168302    sqlite3_result_error(pCtx, zErrmsg, -1);
168303  }else{
168304    int nIndex = 0;
168305    if( SQLITE_ROW==sqlite3_step(pStmt) ){
168306      nIndex = sqlite3_column_int(pStmt, 0);
168307    }
168308    rc = sqlite3_finalize(pStmt);
168309    if( rc==SQLITE_OK ){
168310      sqlite3_result_int(pCtx, nIndex);
168311    }else{
168312      sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
168313    }
168314  }
168315
168316  sqlite3_free(zErrmsg);
168317}
168318
168319/*
168320** If the RBU database contains the rbu_count table, use it to initialize
168321** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
168322** is assumed to contain the same columns as:
168323**
168324**   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
168325**
168326** There should be one row in the table for each data_xxx table in the
168327** database. The 'tbl' column should contain the name of a data_xxx table,
168328** and the cnt column the number of rows it contains.
168329**
168330** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
168331** for all rows in the rbu_count table, where nIndex is the number of
168332** indexes on the corresponding target database table.
168333*/
168334static void rbuInitPhaseOneSteps(sqlite3rbu *p){
168335  if( p->rc==SQLITE_OK ){
168336    sqlite3_stmt *pStmt = 0;
168337    int bExists = 0;                /* True if rbu_count exists */
168338
168339    p->nPhaseOneStep = -1;
168340
168341    p->rc = sqlite3_create_function(p->dbRbu,
168342        "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
168343    );
168344
168345    /* Check for the rbu_count table. If it does not exist, or if an error
168346    ** occurs, nPhaseOneStep will be left set to -1. */
168347    if( p->rc==SQLITE_OK ){
168348      p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
168349          "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
168350      );
168351    }
168352    if( p->rc==SQLITE_OK ){
168353      if( SQLITE_ROW==sqlite3_step(pStmt) ){
168354        bExists = 1;
168355      }
168356      p->rc = sqlite3_finalize(pStmt);
168357    }
168358
168359    if( p->rc==SQLITE_OK && bExists ){
168360      p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
168361          "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
168362          "FROM rbu_count"
168363      );
168364      if( p->rc==SQLITE_OK ){
168365        if( SQLITE_ROW==sqlite3_step(pStmt) ){
168366          p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
168367        }
168368        p->rc = sqlite3_finalize(pStmt);
168369      }
168370    }
168371  }
168372}
168373
168374
168375static sqlite3rbu *openRbuHandle(
168376  const char *zTarget,
168377  const char *zRbu,
168378  const char *zState
168379){
168380  sqlite3rbu *p;
168381  size_t nTarget = zTarget ? strlen(zTarget) : 0;
168382  size_t nRbu = strlen(zRbu);
168383  size_t nState = zState ? strlen(zState) : 0;
168384  size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1+ nState+1;
168385
168386  p = (sqlite3rbu*)sqlite3_malloc64(nByte);
168387  if( p ){
168388    RbuState *pState = 0;
168389
168390    /* Create the custom VFS. */
168391    memset(p, 0, sizeof(sqlite3rbu));
168392    rbuCreateVfs(p);
168393
168394    /* Open the target, RBU and state databases */
168395    if( p->rc==SQLITE_OK ){
168396      char *pCsr = (char*)&p[1];
168397      if( zTarget ){
168398        p->zTarget = pCsr;
168399        memcpy(p->zTarget, zTarget, nTarget+1);
168400        pCsr += nTarget+1;
168401      }
168402      p->zRbu = pCsr;
168403      memcpy(p->zRbu, zRbu, nRbu+1);
168404      pCsr += nRbu+1;
168405      if( zState ){
168406        p->zState = pCsr;
168407        memcpy(p->zState, zState, nState+1);
168408      }
168409      rbuOpenDatabase(p);
168410    }
168411
168412    if( p->rc==SQLITE_OK ){
168413      pState = rbuLoadState(p);
168414      assert( pState || p->rc!=SQLITE_OK );
168415      if( p->rc==SQLITE_OK ){
168416
168417        if( pState->eStage==0 ){
168418          rbuDeleteOalFile(p);
168419          rbuInitPhaseOneSteps(p);
168420          p->eStage = RBU_STAGE_OAL;
168421        }else{
168422          p->eStage = pState->eStage;
168423          p->nPhaseOneStep = pState->nPhaseOneStep;
168424        }
168425        p->nProgress = pState->nProgress;
168426        p->iOalSz = pState->iOalSz;
168427      }
168428    }
168429    assert( p->rc!=SQLITE_OK || p->eStage!=0 );
168430
168431    if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
168432      if( p->eStage==RBU_STAGE_OAL ){
168433        p->rc = SQLITE_ERROR;
168434        p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
168435      }else if( p->eStage==RBU_STAGE_MOVE ){
168436        p->eStage = RBU_STAGE_CKPT;
168437        p->nStep = 0;
168438      }
168439    }
168440
168441    if( p->rc==SQLITE_OK
168442     && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
168443     && pState->eStage!=0
168444    ){
168445      rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
168446      if( pFd->iCookie!=pState->iCookie ){
168447        /* At this point (pTargetFd->iCookie) contains the value of the
168448        ** change-counter cookie (the thing that gets incremented when a
168449        ** transaction is committed in rollback mode) currently stored on
168450        ** page 1 of the database file. */
168451        p->rc = SQLITE_BUSY;
168452        p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
168453            (rbuIsVacuum(p) ? "vacuum" : "update")
168454        );
168455      }
168456    }
168457
168458    if( p->rc==SQLITE_OK ){
168459      if( p->eStage==RBU_STAGE_OAL ){
168460        sqlite3 *db = p->dbMain;
168461        p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
168462
168463        /* Point the object iterator at the first object */
168464        if( p->rc==SQLITE_OK ){
168465          p->rc = rbuObjIterFirst(p, &p->objiter);
168466        }
168467
168468        /* If the RBU database contains no data_xxx tables, declare the RBU
168469        ** update finished.  */
168470        if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
168471          p->rc = SQLITE_DONE;
168472          p->eStage = RBU_STAGE_DONE;
168473        }else{
168474          if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
168475            rbuCopyPragma(p, "page_size");
168476            rbuCopyPragma(p, "auto_vacuum");
168477          }
168478
168479          /* Open transactions both databases. The *-oal file is opened or
168480          ** created at this point. */
168481          if( p->rc==SQLITE_OK ){
168482            p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
168483          }
168484
168485          /* Check if the main database is a zipvfs db. If it is, set the upper
168486          ** level pager to use "journal_mode=off". This prevents it from
168487          ** generating a large journal using a temp file.  */
168488          if( p->rc==SQLITE_OK ){
168489            int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
168490            if( frc==SQLITE_OK ){
168491              p->rc = sqlite3_exec(
168492                db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
168493            }
168494          }
168495
168496          if( p->rc==SQLITE_OK ){
168497            rbuSetupOal(p, pState);
168498          }
168499        }
168500      }else if( p->eStage==RBU_STAGE_MOVE ){
168501        /* no-op */
168502      }else if( p->eStage==RBU_STAGE_CKPT ){
168503        rbuSetupCheckpoint(p, pState);
168504      }else if( p->eStage==RBU_STAGE_DONE ){
168505        p->rc = SQLITE_DONE;
168506      }else{
168507        p->rc = SQLITE_CORRUPT;
168508      }
168509    }
168510
168511    rbuFreeState(pState);
168512  }
168513
168514  return p;
168515}
168516
168517/*
168518** Open and return a new RBU handle.
168519*/
168520SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
168521  const char *zTarget,
168522  const char *zRbu,
168523  const char *zState
168524){
168525  /* TODO: Check that zTarget and zRbu are non-NULL */
168526  return openRbuHandle(zTarget, zRbu, zState);
168527}
168528
168529/*
168530** Open a handle to begin or resume an RBU VACUUM operation.
168531*/
168532SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_vacuum(
168533  const char *zTarget,
168534  const char *zState
168535){
168536  /* TODO: Check that both arguments are non-NULL */
168537  return openRbuHandle(0, zTarget, zState);
168538}
168539
168540/*
168541** Return the database handle used by pRbu.
168542*/
168543SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
168544  sqlite3 *db = 0;
168545  if( pRbu ){
168546    db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
168547  }
168548  return db;
168549}
168550
168551
168552/*
168553** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
168554** then edit any error message string so as to remove all occurrences of
168555** the pattern "rbu_imp_[0-9]*".
168556*/
168557static void rbuEditErrmsg(sqlite3rbu *p){
168558  if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
168559    unsigned int i;
168560    size_t nErrmsg = strlen(p->zErrmsg);
168561    for(i=0; i<(nErrmsg-8); i++){
168562      if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
168563        int nDel = 8;
168564        while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
168565        memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
168566        nErrmsg -= nDel;
168567      }
168568    }
168569  }
168570}
168571
168572/*
168573** Close the RBU handle.
168574*/
168575SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
168576  int rc;
168577  if( p ){
168578
168579    /* Commit the transaction to the *-oal file. */
168580    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
168581      p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
168582    }
168583
168584    rbuSaveState(p, p->eStage);
168585
168586    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
168587      p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
168588    }
168589
168590    /* Close any open statement handles. */
168591    rbuObjIterFinalize(&p->objiter);
168592
168593    /* If this is an RBU vacuum handle and the vacuum has either finished
168594    ** successfully or encountered an error, delete the contents of the
168595    ** state table. This causes the next call to sqlite3rbu_vacuum()
168596    ** specifying the current target and state databases to start a new
168597    ** vacuum from scratch.  */
168598    if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
168599      int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
168600      if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
168601    }
168602
168603    /* Close the open database handle and VFS object. */
168604    sqlite3_close(p->dbRbu);
168605    sqlite3_close(p->dbMain);
168606    rbuDeleteVfs(p);
168607    sqlite3_free(p->aBuf);
168608    sqlite3_free(p->aFrame);
168609
168610    rbuEditErrmsg(p);
168611    rc = p->rc;
168612    *pzErrmsg = p->zErrmsg;
168613    sqlite3_free(p);
168614  }else{
168615    rc = SQLITE_NOMEM;
168616    *pzErrmsg = 0;
168617  }
168618  return rc;
168619}
168620
168621/*
168622** Return the total number of key-value operations (inserts, deletes or
168623** updates) that have been performed on the target database since the
168624** current RBU update was started.
168625*/
168626SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu){
168627  return pRbu->nProgress;
168628}
168629
168630/*
168631** Return permyriadage progress indications for the two main stages of
168632** an RBU update.
168633*/
168634SQLITE_API void SQLITE_STDCALL sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
168635  const int MAX_PROGRESS = 10000;
168636  switch( p->eStage ){
168637    case RBU_STAGE_OAL:
168638      if( p->nPhaseOneStep>0 ){
168639        *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
168640      }else{
168641        *pnOne = -1;
168642      }
168643      *pnTwo = 0;
168644      break;
168645
168646    case RBU_STAGE_MOVE:
168647      *pnOne = MAX_PROGRESS;
168648      *pnTwo = 0;
168649      break;
168650
168651    case RBU_STAGE_CKPT:
168652      *pnOne = MAX_PROGRESS;
168653      *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
168654      break;
168655
168656    case RBU_STAGE_DONE:
168657      *pnOne = MAX_PROGRESS;
168658      *pnTwo = MAX_PROGRESS;
168659      break;
168660
168661    default:
168662      assert( 0 );
168663  }
168664}
168665
168666/*
168667** Return the current state of the RBU vacuum or update operation.
168668*/
168669SQLITE_API int SQLITE_STDCALL sqlite3rbu_state(sqlite3rbu *p){
168670  int aRes[] = {
168671    0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
168672    0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
168673  };
168674
168675  assert( RBU_STAGE_OAL==1 );
168676  assert( RBU_STAGE_MOVE==2 );
168677  assert( RBU_STAGE_CKPT==4 );
168678  assert( RBU_STAGE_DONE==5 );
168679  assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
168680  assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
168681  assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
168682  assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
168683
168684  if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
168685    return SQLITE_RBU_STATE_ERROR;
168686  }else{
168687    assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
168688    assert( p->eStage==RBU_STAGE_OAL
168689         || p->eStage==RBU_STAGE_MOVE
168690         || p->eStage==RBU_STAGE_CKPT
168691         || p->eStage==RBU_STAGE_DONE
168692    );
168693    return aRes[p->eStage];
168694  }
168695}
168696
168697SQLITE_API int SQLITE_STDCALL sqlite3rbu_savestate(sqlite3rbu *p){
168698  int rc = p->rc;
168699  if( rc==SQLITE_DONE ) return SQLITE_OK;
168700
168701  assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
168702  if( p->eStage==RBU_STAGE_OAL ){
168703    assert( rc!=SQLITE_DONE );
168704    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
168705  }
168706
168707  p->rc = rc;
168708  rbuSaveState(p, p->eStage);
168709  rc = p->rc;
168710
168711  if( p->eStage==RBU_STAGE_OAL ){
168712    assert( rc!=SQLITE_DONE );
168713    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
168714    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
168715    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
168716  }
168717
168718  p->rc = rc;
168719  return rc;
168720}
168721
168722/**************************************************************************
168723** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
168724** of a standard VFS in the following ways:
168725**
168726** 1. Whenever the first page of a main database file is read or
168727**    written, the value of the change-counter cookie is stored in
168728**    rbu_file.iCookie. Similarly, the value of the "write-version"
168729**    database header field is stored in rbu_file.iWriteVer. This ensures
168730**    that the values are always trustworthy within an open transaction.
168731**
168732** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
168733**    member variable of the associated database file descriptor is set
168734**    to point to the new file. A mutex protected linked list of all main
168735**    db fds opened using a particular RBU VFS is maintained at
168736**    rbu_vfs.pMain to facilitate this.
168737**
168738** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
168739**    object can be marked as the target database of an RBU update. This
168740**    turns on the following extra special behaviour:
168741**
168742** 3a. If xAccess() is called to check if there exists a *-wal file
168743**     associated with an RBU target database currently in RBU_STAGE_OAL
168744**     stage (preparing the *-oal file), the following special handling
168745**     applies:
168746**
168747**      * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
168748**        target database may not be in wal mode already.
168749**
168750**      * if the *-wal file does not exist, set the output parameter to
168751**        non-zero (to tell SQLite that it does exist) anyway.
168752**
168753**     Then, when xOpen() is called to open the *-wal file associated with
168754**     the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
168755**     file, the rbu vfs opens the corresponding *-oal file instead.
168756**
168757** 3b. The *-shm pages returned by xShmMap() for a target db file in
168758**     RBU_STAGE_OAL mode are actually stored in heap memory. This is to
168759**     avoid creating a *-shm file on disk. Additionally, xShmLock() calls
168760**     are no-ops on target database files in RBU_STAGE_OAL mode. This is
168761**     because assert() statements in some VFS implementations fail if
168762**     xShmLock() is called before xShmMap().
168763**
168764** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
168765**     mode except RBU_STAGE_DONE (all work completed and checkpointed), it
168766**     fails with an SQLITE_BUSY error. This is to stop RBU connections
168767**     from automatically checkpointing a *-wal (or *-oal) file from within
168768**     sqlite3_close().
168769**
168770** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
168771**     all xWrite() calls on the target database file perform no IO.
168772**     Instead the frame and page numbers that would be read and written
168773**     are recorded. Additionally, successful attempts to obtain exclusive
168774**     xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
168775**     database file are recorded. xShmLock() calls to unlock the same
168776**     locks are no-ops (so that once obtained, these locks are never
168777**     relinquished). Finally, calls to xSync() on the target database
168778**     file fail with SQLITE_INTERNAL errors.
168779*/
168780
168781static void rbuUnlockShm(rbu_file *p){
168782  if( p->pRbu ){
168783    int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
168784    int i;
168785    for(i=0; i<SQLITE_SHM_NLOCK;i++){
168786      if( (1<<i) & p->pRbu->mLock ){
168787        xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
168788      }
168789    }
168790    p->pRbu->mLock = 0;
168791  }
168792}
168793
168794/*
168795** Close an rbu file.
168796*/
168797static int rbuVfsClose(sqlite3_file *pFile){
168798  rbu_file *p = (rbu_file*)pFile;
168799  int rc;
168800  int i;
168801
168802  /* Free the contents of the apShm[] array. And the array itself. */
168803  for(i=0; i<p->nShm; i++){
168804    sqlite3_free(p->apShm[i]);
168805  }
168806  sqlite3_free(p->apShm);
168807  p->apShm = 0;
168808  sqlite3_free(p->zDel);
168809
168810  if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
168811    rbu_file **pp;
168812    sqlite3_mutex_enter(p->pRbuVfs->mutex);
168813    for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
168814    *pp = p->pMainNext;
168815    sqlite3_mutex_leave(p->pRbuVfs->mutex);
168816    rbuUnlockShm(p);
168817    p->pReal->pMethods->xShmUnmap(p->pReal, 0);
168818  }
168819
168820  /* Close the underlying file handle */
168821  rc = p->pReal->pMethods->xClose(p->pReal);
168822  return rc;
168823}
168824
168825
168826/*
168827** Read and return an unsigned 32-bit big-endian integer from the buffer
168828** passed as the only argument.
168829*/
168830static u32 rbuGetU32(u8 *aBuf){
168831  return ((u32)aBuf[0] << 24)
168832       + ((u32)aBuf[1] << 16)
168833       + ((u32)aBuf[2] <<  8)
168834       + ((u32)aBuf[3]);
168835}
168836
168837/*
168838** Write an unsigned 32-bit value in big-endian format to the supplied
168839** buffer.
168840*/
168841static void rbuPutU32(u8 *aBuf, u32 iVal){
168842  aBuf[0] = (iVal >> 24) & 0xFF;
168843  aBuf[1] = (iVal >> 16) & 0xFF;
168844  aBuf[2] = (iVal >>  8) & 0xFF;
168845  aBuf[3] = (iVal >>  0) & 0xFF;
168846}
168847
168848static void rbuPutU16(u8 *aBuf, u16 iVal){
168849  aBuf[0] = (iVal >>  8) & 0xFF;
168850  aBuf[1] = (iVal >>  0) & 0xFF;
168851}
168852
168853/*
168854** Read data from an rbuVfs-file.
168855*/
168856static int rbuVfsRead(
168857  sqlite3_file *pFile,
168858  void *zBuf,
168859  int iAmt,
168860  sqlite_int64 iOfst
168861){
168862  rbu_file *p = (rbu_file*)pFile;
168863  sqlite3rbu *pRbu = p->pRbu;
168864  int rc;
168865
168866  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
168867    assert( p->openFlags & SQLITE_OPEN_WAL );
168868    rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
168869  }else{
168870    if( pRbu && pRbu->eStage==RBU_STAGE_OAL
168871     && (p->openFlags & SQLITE_OPEN_WAL)
168872     && iOfst>=pRbu->iOalSz
168873    ){
168874      rc = SQLITE_OK;
168875      memset(zBuf, 0, iAmt);
168876    }else{
168877      rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
168878#if 1
168879      /* If this is being called to read the first page of the target
168880      ** database as part of an rbu vacuum operation, synthesize the
168881      ** contents of the first page if it does not yet exist. Otherwise,
168882      ** SQLite will not check for a *-wal file.  */
168883      if( pRbu && rbuIsVacuum(pRbu)
168884          && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
168885          && (p->openFlags & SQLITE_OPEN_MAIN_DB)
168886          && pRbu->rc==SQLITE_OK
168887      ){
168888        sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
168889        rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
168890        if( rc==SQLITE_OK ){
168891          u8 *aBuf = (u8*)zBuf;
168892          u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
168893          rbuPutU32(&aBuf[52], iRoot);      /* largest root page number */
168894          rbuPutU32(&aBuf[36], 0);          /* number of free pages */
168895          rbuPutU32(&aBuf[32], 0);          /* first page on free list trunk */
168896          rbuPutU32(&aBuf[28], 1);          /* size of db file in pages */
168897          rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1);  /* Change counter */
168898
168899          if( iAmt>100 ){
168900            memset(&aBuf[100], 0, iAmt-100);
168901            rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
168902            aBuf[100] = 0x0D;
168903          }
168904        }
168905      }
168906#endif
168907    }
168908    if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
168909      /* These look like magic numbers. But they are stable, as they are part
168910       ** of the definition of the SQLite file format, which may not change. */
168911      u8 *pBuf = (u8*)zBuf;
168912      p->iCookie = rbuGetU32(&pBuf[24]);
168913      p->iWriteVer = pBuf[19];
168914    }
168915  }
168916  return rc;
168917}
168918
168919/*
168920** Write data to an rbuVfs-file.
168921*/
168922static int rbuVfsWrite(
168923  sqlite3_file *pFile,
168924  const void *zBuf,
168925  int iAmt,
168926  sqlite_int64 iOfst
168927){
168928  rbu_file *p = (rbu_file*)pFile;
168929  sqlite3rbu *pRbu = p->pRbu;
168930  int rc;
168931
168932  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
168933    assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
168934    rc = rbuCaptureDbWrite(p->pRbu, iOfst);
168935  }else{
168936    if( pRbu && pRbu->eStage==RBU_STAGE_OAL
168937     && (p->openFlags & SQLITE_OPEN_WAL)
168938     && iOfst>=pRbu->iOalSz
168939    ){
168940      pRbu->iOalSz = iAmt + iOfst;
168941    }
168942    rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
168943    if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
168944      /* These look like magic numbers. But they are stable, as they are part
168945      ** of the definition of the SQLite file format, which may not change. */
168946      u8 *pBuf = (u8*)zBuf;
168947      p->iCookie = rbuGetU32(&pBuf[24]);
168948      p->iWriteVer = pBuf[19];
168949    }
168950  }
168951  return rc;
168952}
168953
168954/*
168955** Truncate an rbuVfs-file.
168956*/
168957static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
168958  rbu_file *p = (rbu_file*)pFile;
168959  return p->pReal->pMethods->xTruncate(p->pReal, size);
168960}
168961
168962/*
168963** Sync an rbuVfs-file.
168964*/
168965static int rbuVfsSync(sqlite3_file *pFile, int flags){
168966  rbu_file *p = (rbu_file *)pFile;
168967  if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
168968    if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
168969      return SQLITE_INTERNAL;
168970    }
168971    return SQLITE_OK;
168972  }
168973  return p->pReal->pMethods->xSync(p->pReal, flags);
168974}
168975
168976/*
168977** Return the current file-size of an rbuVfs-file.
168978*/
168979static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
168980  rbu_file *p = (rbu_file *)pFile;
168981  int rc;
168982  rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
168983
168984  /* If this is an RBU vacuum operation and this is the target database,
168985  ** pretend that it has at least one page. Otherwise, SQLite will not
168986  ** check for the existance of a *-wal file. rbuVfsRead() contains
168987  ** similar logic.  */
168988  if( rc==SQLITE_OK && *pSize==0
168989   && p->pRbu && rbuIsVacuum(p->pRbu)
168990   && (p->openFlags & SQLITE_OPEN_MAIN_DB)
168991  ){
168992    *pSize = 1024;
168993  }
168994  return rc;
168995}
168996
168997/*
168998** Lock an rbuVfs-file.
168999*/
169000static int rbuVfsLock(sqlite3_file *pFile, int eLock){
169001  rbu_file *p = (rbu_file*)pFile;
169002  sqlite3rbu *pRbu = p->pRbu;
169003  int rc = SQLITE_OK;
169004
169005  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
169006  if( eLock==SQLITE_LOCK_EXCLUSIVE
169007   && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
169008  ){
169009    /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
169010    ** prevents it from checkpointing the database from sqlite3_close(). */
169011    rc = SQLITE_BUSY;
169012  }else{
169013    rc = p->pReal->pMethods->xLock(p->pReal, eLock);
169014  }
169015
169016  return rc;
169017}
169018
169019/*
169020** Unlock an rbuVfs-file.
169021*/
169022static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
169023  rbu_file *p = (rbu_file *)pFile;
169024  return p->pReal->pMethods->xUnlock(p->pReal, eLock);
169025}
169026
169027/*
169028** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
169029*/
169030static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
169031  rbu_file *p = (rbu_file *)pFile;
169032  return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
169033}
169034
169035/*
169036** File control method. For custom operations on an rbuVfs-file.
169037*/
169038static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
169039  rbu_file *p = (rbu_file *)pFile;
169040  int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
169041  int rc;
169042
169043  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
169044       || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
169045  );
169046  if( op==SQLITE_FCNTL_RBU ){
169047    sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
169048
169049    /* First try to find another RBU vfs lower down in the vfs stack. If
169050    ** one is found, this vfs will operate in pass-through mode. The lower
169051    ** level vfs will do the special RBU handling.  */
169052    rc = xControl(p->pReal, op, pArg);
169053
169054    if( rc==SQLITE_NOTFOUND ){
169055      /* Now search for a zipvfs instance lower down in the VFS stack. If
169056      ** one is found, this is an error.  */
169057      void *dummy = 0;
169058      rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
169059      if( rc==SQLITE_OK ){
169060        rc = SQLITE_ERROR;
169061        pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
169062      }else if( rc==SQLITE_NOTFOUND ){
169063        pRbu->pTargetFd = p;
169064        p->pRbu = pRbu;
169065        if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
169066        rc = SQLITE_OK;
169067      }
169068    }
169069    return rc;
169070  }
169071  else if( op==SQLITE_FCNTL_RBUCNT ){
169072    sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
169073    pRbu->nRbu++;
169074    pRbu->pRbuFd = p;
169075    p->bNolock = 1;
169076  }
169077
169078  rc = xControl(p->pReal, op, pArg);
169079  if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
169080    rbu_vfs *pRbuVfs = p->pRbuVfs;
169081    char *zIn = *(char**)pArg;
169082    char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
169083    *(char**)pArg = zOut;
169084    if( zOut==0 ) rc = SQLITE_NOMEM;
169085  }
169086
169087  return rc;
169088}
169089
169090/*
169091** Return the sector-size in bytes for an rbuVfs-file.
169092*/
169093static int rbuVfsSectorSize(sqlite3_file *pFile){
169094  rbu_file *p = (rbu_file *)pFile;
169095  return p->pReal->pMethods->xSectorSize(p->pReal);
169096}
169097
169098/*
169099** Return the device characteristic flags supported by an rbuVfs-file.
169100*/
169101static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
169102  rbu_file *p = (rbu_file *)pFile;
169103  return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
169104}
169105
169106/*
169107** Take or release a shared-memory lock.
169108*/
169109static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
169110  rbu_file *p = (rbu_file*)pFile;
169111  sqlite3rbu *pRbu = p->pRbu;
169112  int rc = SQLITE_OK;
169113
169114#ifdef SQLITE_AMALGAMATION
169115    assert( WAL_CKPT_LOCK==1 );
169116#endif
169117
169118  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
169119  if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
169120    /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
169121    ** taking this lock also prevents any checkpoints from occurring.
169122    ** todo: really, it's not clear why this might occur, as
169123    ** wal_autocheckpoint ought to be turned off.  */
169124    if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
169125  }else{
169126    int bCapture = 0;
169127    if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
169128     && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
169129     && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
169130    ){
169131      bCapture = 1;
169132    }
169133
169134    if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
169135      rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
169136      if( bCapture && rc==SQLITE_OK ){
169137        pRbu->mLock |= (1 << ofst);
169138      }
169139    }
169140  }
169141
169142  return rc;
169143}
169144
169145/*
169146** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
169147*/
169148static int rbuVfsShmMap(
169149  sqlite3_file *pFile,
169150  int iRegion,
169151  int szRegion,
169152  int isWrite,
169153  void volatile **pp
169154){
169155  rbu_file *p = (rbu_file*)pFile;
169156  int rc = SQLITE_OK;
169157  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
169158
169159  /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
169160  ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
169161  ** instead of a file on disk.  */
169162  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
169163  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
169164    if( iRegion<=p->nShm ){
169165      int nByte = (iRegion+1) * sizeof(char*);
169166      char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
169167      if( apNew==0 ){
169168        rc = SQLITE_NOMEM;
169169      }else{
169170        memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
169171        p->apShm = apNew;
169172        p->nShm = iRegion+1;
169173      }
169174    }
169175
169176    if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
169177      char *pNew = (char*)sqlite3_malloc64(szRegion);
169178      if( pNew==0 ){
169179        rc = SQLITE_NOMEM;
169180      }else{
169181        memset(pNew, 0, szRegion);
169182        p->apShm[iRegion] = pNew;
169183      }
169184    }
169185
169186    if( rc==SQLITE_OK ){
169187      *pp = p->apShm[iRegion];
169188    }else{
169189      *pp = 0;
169190    }
169191  }else{
169192    assert( p->apShm==0 );
169193    rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
169194  }
169195
169196  return rc;
169197}
169198
169199/*
169200** Memory barrier.
169201*/
169202static void rbuVfsShmBarrier(sqlite3_file *pFile){
169203  rbu_file *p = (rbu_file *)pFile;
169204  p->pReal->pMethods->xShmBarrier(p->pReal);
169205}
169206
169207/*
169208** The xShmUnmap method.
169209*/
169210static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
169211  rbu_file *p = (rbu_file*)pFile;
169212  int rc = SQLITE_OK;
169213  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
169214
169215  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
169216  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
169217    /* no-op */
169218  }else{
169219    /* Release the checkpointer and writer locks */
169220    rbuUnlockShm(p);
169221    rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
169222  }
169223  return rc;
169224}
169225
169226/*
169227** Given that zWal points to a buffer containing a wal file name passed to
169228** either the xOpen() or xAccess() VFS method, return a pointer to the
169229** file-handle opened by the same database connection on the corresponding
169230** database file.
169231*/
169232static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
169233  rbu_file *pDb;
169234  sqlite3_mutex_enter(pRbuVfs->mutex);
169235  for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
169236  sqlite3_mutex_leave(pRbuVfs->mutex);
169237  return pDb;
169238}
169239
169240/*
169241** A main database named zName has just been opened. The following
169242** function returns a pointer to a buffer owned by SQLite that contains
169243** the name of the *-wal file this db connection will use. SQLite
169244** happens to pass a pointer to this buffer when using xAccess()
169245** or xOpen() to operate on the *-wal file.
169246*/
169247static const char *rbuMainToWal(const char *zName, int flags){
169248  int n = (int)strlen(zName);
169249  const char *z = &zName[n];
169250  if( flags & SQLITE_OPEN_URI ){
169251    int odd = 0;
169252    while( 1 ){
169253      if( z[0]==0 ){
169254        odd = 1 - odd;
169255        if( odd && z[1]==0 ) break;
169256      }
169257      z++;
169258    }
169259    z += 2;
169260  }else{
169261    while( *z==0 ) z++;
169262  }
169263  z += (n + 8 + 1);
169264  return z;
169265}
169266
169267/*
169268** Open an rbu file handle.
169269*/
169270static int rbuVfsOpen(
169271  sqlite3_vfs *pVfs,
169272  const char *zName,
169273  sqlite3_file *pFile,
169274  int flags,
169275  int *pOutFlags
169276){
169277  static sqlite3_io_methods rbuvfs_io_methods = {
169278    2,                            /* iVersion */
169279    rbuVfsClose,                  /* xClose */
169280    rbuVfsRead,                   /* xRead */
169281    rbuVfsWrite,                  /* xWrite */
169282    rbuVfsTruncate,               /* xTruncate */
169283    rbuVfsSync,                   /* xSync */
169284    rbuVfsFileSize,               /* xFileSize */
169285    rbuVfsLock,                   /* xLock */
169286    rbuVfsUnlock,                 /* xUnlock */
169287    rbuVfsCheckReservedLock,      /* xCheckReservedLock */
169288    rbuVfsFileControl,            /* xFileControl */
169289    rbuVfsSectorSize,             /* xSectorSize */
169290    rbuVfsDeviceCharacteristics,  /* xDeviceCharacteristics */
169291    rbuVfsShmMap,                 /* xShmMap */
169292    rbuVfsShmLock,                /* xShmLock */
169293    rbuVfsShmBarrier,             /* xShmBarrier */
169294    rbuVfsShmUnmap,               /* xShmUnmap */
169295    0, 0                          /* xFetch, xUnfetch */
169296  };
169297  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
169298  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
169299  rbu_file *pFd = (rbu_file *)pFile;
169300  int rc = SQLITE_OK;
169301  const char *zOpen = zName;
169302  int oflags = flags;
169303
169304  memset(pFd, 0, sizeof(rbu_file));
169305  pFd->pReal = (sqlite3_file*)&pFd[1];
169306  pFd->pRbuVfs = pRbuVfs;
169307  pFd->openFlags = flags;
169308  if( zName ){
169309    if( flags & SQLITE_OPEN_MAIN_DB ){
169310      /* A main database has just been opened. The following block sets
169311      ** (pFd->zWal) to point to a buffer owned by SQLite that contains
169312      ** the name of the *-wal file this db connection will use. SQLite
169313      ** happens to pass a pointer to this buffer when using xAccess()
169314      ** or xOpen() to operate on the *-wal file.  */
169315      pFd->zWal = rbuMainToWal(zName, flags);
169316    }
169317    else if( flags & SQLITE_OPEN_WAL ){
169318      rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
169319      if( pDb ){
169320        if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
169321          /* This call is to open a *-wal file. Intead, open the *-oal. This
169322          ** code ensures that the string passed to xOpen() is terminated by a
169323          ** pair of '\0' bytes in case the VFS attempts to extract a URI
169324          ** parameter from it.  */
169325          const char *zBase = zName;
169326          size_t nCopy;
169327          char *zCopy;
169328          if( rbuIsVacuum(pDb->pRbu) ){
169329            zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
169330            zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
169331          }
169332          nCopy = strlen(zBase);
169333          zCopy = sqlite3_malloc64(nCopy+2);
169334          if( zCopy ){
169335            memcpy(zCopy, zBase, nCopy);
169336            zCopy[nCopy-3] = 'o';
169337            zCopy[nCopy] = '\0';
169338            zCopy[nCopy+1] = '\0';
169339            zOpen = (const char*)(pFd->zDel = zCopy);
169340          }else{
169341            rc = SQLITE_NOMEM;
169342          }
169343          pFd->pRbu = pDb->pRbu;
169344        }
169345        pDb->pWalFd = pFd;
169346      }
169347    }
169348  }
169349
169350  if( oflags & SQLITE_OPEN_MAIN_DB
169351   && sqlite3_uri_boolean(zName, "rbu_memory", 0)
169352  ){
169353    assert( oflags & SQLITE_OPEN_MAIN_DB );
169354    oflags =  SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
169355              SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
169356    zOpen = 0;
169357  }
169358
169359  if( rc==SQLITE_OK ){
169360    rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
169361  }
169362  if( pFd->pReal->pMethods ){
169363    /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
169364    ** pointer and, if the file is a main database file, link it into the
169365    ** mutex protected linked list of all such files.  */
169366    pFile->pMethods = &rbuvfs_io_methods;
169367    if( flags & SQLITE_OPEN_MAIN_DB ){
169368      sqlite3_mutex_enter(pRbuVfs->mutex);
169369      pFd->pMainNext = pRbuVfs->pMain;
169370      pRbuVfs->pMain = pFd;
169371      sqlite3_mutex_leave(pRbuVfs->mutex);
169372    }
169373  }else{
169374    sqlite3_free(pFd->zDel);
169375  }
169376
169377  return rc;
169378}
169379
169380/*
169381** Delete the file located at zPath.
169382*/
169383static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
169384  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169385  return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
169386}
169387
169388/*
169389** Test for access permissions. Return true if the requested permission
169390** is available, or false otherwise.
169391*/
169392static int rbuVfsAccess(
169393  sqlite3_vfs *pVfs,
169394  const char *zPath,
169395  int flags,
169396  int *pResOut
169397){
169398  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
169399  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
169400  int rc;
169401
169402  rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
169403
169404  /* If this call is to check if a *-wal file associated with an RBU target
169405  ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
169406  ** the following special handling is activated:
169407  **
169408  **   a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
169409  **      ensures that the RBU extension never tries to update a database
169410  **      in wal mode, even if the first page of the database file has
169411  **      been damaged.
169412  **
169413  **   b) if the *-wal file does not exist, claim that it does anyway,
169414  **      causing SQLite to call xOpen() to open it. This call will also
169415  **      be intercepted (see the rbuVfsOpen() function) and the *-oal
169416  **      file opened instead.
169417  */
169418  if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
169419    rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
169420    if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
169421      if( *pResOut ){
169422        rc = SQLITE_CANTOPEN;
169423      }else{
169424        *pResOut = 1;
169425      }
169426    }
169427  }
169428
169429  return rc;
169430}
169431
169432/*
169433** Populate buffer zOut with the full canonical pathname corresponding
169434** to the pathname in zPath. zOut is guaranteed to point to a buffer
169435** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
169436*/
169437static int rbuVfsFullPathname(
169438  sqlite3_vfs *pVfs,
169439  const char *zPath,
169440  int nOut,
169441  char *zOut
169442){
169443  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169444  return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
169445}
169446
169447#ifndef SQLITE_OMIT_LOAD_EXTENSION
169448/*
169449** Open the dynamic library located at zPath and return a handle.
169450*/
169451static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
169452  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169453  return pRealVfs->xDlOpen(pRealVfs, zPath);
169454}
169455
169456/*
169457** Populate the buffer zErrMsg (size nByte bytes) with a human readable
169458** utf-8 string describing the most recent error encountered associated
169459** with dynamic libraries.
169460*/
169461static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
169462  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169463  pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
169464}
169465
169466/*
169467** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
169468*/
169469static void (*rbuVfsDlSym(
169470  sqlite3_vfs *pVfs,
169471  void *pArg,
169472  const char *zSym
169473))(void){
169474  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169475  return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
169476}
169477
169478/*
169479** Close the dynamic library handle pHandle.
169480*/
169481static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
169482  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169483  pRealVfs->xDlClose(pRealVfs, pHandle);
169484}
169485#endif /* SQLITE_OMIT_LOAD_EXTENSION */
169486
169487/*
169488** Populate the buffer pointed to by zBufOut with nByte bytes of
169489** random data.
169490*/
169491static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
169492  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169493  return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
169494}
169495
169496/*
169497** Sleep for nMicro microseconds. Return the number of microseconds
169498** actually slept.
169499*/
169500static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
169501  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169502  return pRealVfs->xSleep(pRealVfs, nMicro);
169503}
169504
169505/*
169506** Return the current time as a Julian Day number in *pTimeOut.
169507*/
169508static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
169509  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169510  return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
169511}
169512
169513/*
169514** No-op.
169515*/
169516static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
169517  return 0;
169518}
169519
169520/*
169521** Deregister and destroy an RBU vfs created by an earlier call to
169522** sqlite3rbu_create_vfs().
169523*/
169524SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName){
169525  sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
169526  if( pVfs && pVfs->xOpen==rbuVfsOpen ){
169527    sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
169528    sqlite3_vfs_unregister(pVfs);
169529    sqlite3_free(pVfs);
169530  }
169531}
169532
169533/*
169534** Create an RBU VFS named zName that accesses the underlying file-system
169535** via existing VFS zParent. The new object is registered as a non-default
169536** VFS with SQLite before returning.
169537*/
169538SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent){
169539
169540  /* Template for VFS */
169541  static sqlite3_vfs vfs_template = {
169542    1,                            /* iVersion */
169543    0,                            /* szOsFile */
169544    0,                            /* mxPathname */
169545    0,                            /* pNext */
169546    0,                            /* zName */
169547    0,                            /* pAppData */
169548    rbuVfsOpen,                   /* xOpen */
169549    rbuVfsDelete,                 /* xDelete */
169550    rbuVfsAccess,                 /* xAccess */
169551    rbuVfsFullPathname,           /* xFullPathname */
169552
169553#ifndef SQLITE_OMIT_LOAD_EXTENSION
169554    rbuVfsDlOpen,                 /* xDlOpen */
169555    rbuVfsDlError,                /* xDlError */
169556    rbuVfsDlSym,                  /* xDlSym */
169557    rbuVfsDlClose,                /* xDlClose */
169558#else
169559    0, 0, 0, 0,
169560#endif
169561
169562    rbuVfsRandomness,             /* xRandomness */
169563    rbuVfsSleep,                  /* xSleep */
169564    rbuVfsCurrentTime,            /* xCurrentTime */
169565    rbuVfsGetLastError,           /* xGetLastError */
169566    0,                            /* xCurrentTimeInt64 (version 2) */
169567    0, 0, 0                       /* Unimplemented version 3 methods */
169568  };
169569
169570  rbu_vfs *pNew = 0;              /* Newly allocated VFS */
169571  int rc = SQLITE_OK;
169572  size_t nName;
169573  size_t nByte;
169574
169575  nName = strlen(zName);
169576  nByte = sizeof(rbu_vfs) + nName + 1;
169577  pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
169578  if( pNew==0 ){
169579    rc = SQLITE_NOMEM;
169580  }else{
169581    sqlite3_vfs *pParent;           /* Parent VFS */
169582    memset(pNew, 0, nByte);
169583    pParent = sqlite3_vfs_find(zParent);
169584    if( pParent==0 ){
169585      rc = SQLITE_NOTFOUND;
169586    }else{
169587      char *zSpace;
169588      memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
169589      pNew->base.mxPathname = pParent->mxPathname;
169590      pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
169591      pNew->pRealVfs = pParent;
169592      pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
169593      memcpy(zSpace, zName, nName);
169594
169595      /* Allocate the mutex and register the new VFS (not as the default) */
169596      pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
169597      if( pNew->mutex==0 ){
169598        rc = SQLITE_NOMEM;
169599      }else{
169600        rc = sqlite3_vfs_register(&pNew->base, 0);
169601      }
169602    }
169603
169604    if( rc!=SQLITE_OK ){
169605      sqlite3_mutex_free(pNew->mutex);
169606      sqlite3_free(pNew);
169607    }
169608  }
169609
169610  return rc;
169611}
169612
169613
169614/**************************************************************************/
169615
169616#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
169617
169618/************** End of sqlite3rbu.c ******************************************/
169619/************** Begin file dbstat.c ******************************************/
169620/*
169621** 2010 July 12
169622**
169623** The author disclaims copyright to this source code.  In place of
169624** a legal notice, here is a blessing:
169625**
169626**    May you do good and not evil.
169627**    May you find forgiveness for yourself and forgive others.
169628**    May you share freely, never taking more than you give.
169629**
169630******************************************************************************
169631**
169632** This file contains an implementation of the "dbstat" virtual table.
169633**
169634** The dbstat virtual table is used to extract low-level formatting
169635** information from an SQLite database in order to implement the
169636** "sqlite3_analyzer" utility.  See the ../tool/spaceanal.tcl script
169637** for an example implementation.
169638**
169639** Additional information is available on the "dbstat.html" page of the
169640** official SQLite documentation.
169641*/
169642
169643/* #include "sqliteInt.h"   ** Requires access to internal data structures ** */
169644#if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
169645    && !defined(SQLITE_OMIT_VIRTUALTABLE)
169646
169647/*
169648** Page paths:
169649**
169650**   The value of the 'path' column describes the path taken from the
169651**   root-node of the b-tree structure to each page. The value of the
169652**   root-node path is '/'.
169653**
169654**   The value of the path for the left-most child page of the root of
169655**   a b-tree is '/000/'. (Btrees store content ordered from left to right
169656**   so the pages to the left have smaller keys than the pages to the right.)
169657**   The next to left-most child of the root page is
169658**   '/001', and so on, each sibling page identified by a 3-digit hex
169659**   value. The children of the 451st left-most sibling have paths such
169660**   as '/1c2/000/, '/1c2/001/' etc.
169661**
169662**   Overflow pages are specified by appending a '+' character and a
169663**   six-digit hexadecimal value to the path to the cell they are linked
169664**   from. For example, the three overflow pages in a chain linked from
169665**   the left-most cell of the 450th child of the root page are identified
169666**   by the paths:
169667**
169668**      '/1c2/000+000000'         // First page in overflow chain
169669**      '/1c2/000+000001'         // Second page in overflow chain
169670**      '/1c2/000+000002'         // Third page in overflow chain
169671**
169672**   If the paths are sorted using the BINARY collation sequence, then
169673**   the overflow pages associated with a cell will appear earlier in the
169674**   sort-order than its child page:
169675**
169676**      '/1c2/000/'               // Left-most child of 451st child of root
169677*/
169678#define VTAB_SCHEMA                                                         \
169679  "CREATE TABLE xx( "                                                       \
169680  "  name       TEXT,             /* Name of table or index */"             \
169681  "  path       TEXT,             /* Path to page from root */"             \
169682  "  pageno     INTEGER,          /* Page number */"                        \
169683  "  pagetype   TEXT,             /* 'internal', 'leaf' or 'overflow' */"   \
169684  "  ncell      INTEGER,          /* Cells on page (0 for overflow) */"     \
169685  "  payload    INTEGER,          /* Bytes of payload on this page */"      \
169686  "  unused     INTEGER,          /* Bytes of unused space on this page */" \
169687  "  mx_payload INTEGER,          /* Largest payload size of all cells */"  \
169688  "  pgoffset   INTEGER,          /* Offset of page in file */"             \
169689  "  pgsize     INTEGER,          /* Size of the page */"                   \
169690  "  schema     TEXT HIDDEN       /* Database schema being analyzed */"     \
169691  ");"
169692
169693
169694typedef struct StatTable StatTable;
169695typedef struct StatCursor StatCursor;
169696typedef struct StatPage StatPage;
169697typedef struct StatCell StatCell;
169698
169699struct StatCell {
169700  int nLocal;                     /* Bytes of local payload */
169701  u32 iChildPg;                   /* Child node (or 0 if this is a leaf) */
169702  int nOvfl;                      /* Entries in aOvfl[] */
169703  u32 *aOvfl;                     /* Array of overflow page numbers */
169704  int nLastOvfl;                  /* Bytes of payload on final overflow page */
169705  int iOvfl;                      /* Iterates through aOvfl[] */
169706};
169707
169708struct StatPage {
169709  u32 iPgno;
169710  DbPage *pPg;
169711  int iCell;
169712
169713  char *zPath;                    /* Path to this page */
169714
169715  /* Variables populated by statDecodePage(): */
169716  u8 flags;                       /* Copy of flags byte */
169717  int nCell;                      /* Number of cells on page */
169718  int nUnused;                    /* Number of unused bytes on page */
169719  StatCell *aCell;                /* Array of parsed cells */
169720  u32 iRightChildPg;              /* Right-child page number (or 0) */
169721  int nMxPayload;                 /* Largest payload of any cell on this page */
169722};
169723
169724struct StatCursor {
169725  sqlite3_vtab_cursor base;
169726  sqlite3_stmt *pStmt;            /* Iterates through set of root pages */
169727  int isEof;                      /* After pStmt has returned SQLITE_DONE */
169728  int iDb;                        /* Schema used for this query */
169729
169730  StatPage aPage[32];
169731  int iPage;                      /* Current entry in aPage[] */
169732
169733  /* Values to return. */
169734  char *zName;                    /* Value of 'name' column */
169735  char *zPath;                    /* Value of 'path' column */
169736  u32 iPageno;                    /* Value of 'pageno' column */
169737  char *zPagetype;                /* Value of 'pagetype' column */
169738  int nCell;                      /* Value of 'ncell' column */
169739  int nPayload;                   /* Value of 'payload' column */
169740  int nUnused;                    /* Value of 'unused' column */
169741  int nMxPayload;                 /* Value of 'mx_payload' column */
169742  i64 iOffset;                    /* Value of 'pgOffset' column */
169743  int szPage;                     /* Value of 'pgSize' column */
169744};
169745
169746struct StatTable {
169747  sqlite3_vtab base;
169748  sqlite3 *db;
169749  int iDb;                        /* Index of database to analyze */
169750};
169751
169752#ifndef get2byte
169753# define get2byte(x)   ((x)[0]<<8 | (x)[1])
169754#endif
169755
169756/*
169757** Connect to or create a statvfs virtual table.
169758*/
169759static int statConnect(
169760  sqlite3 *db,
169761  void *pAux,
169762  int argc, const char *const*argv,
169763  sqlite3_vtab **ppVtab,
169764  char **pzErr
169765){
169766  StatTable *pTab = 0;
169767  int rc = SQLITE_OK;
169768  int iDb;
169769
169770  if( argc>=4 ){
169771    Token nm;
169772    sqlite3TokenInit(&nm, (char*)argv[3]);
169773    iDb = sqlite3FindDb(db, &nm);
169774    if( iDb<0 ){
169775      *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
169776      return SQLITE_ERROR;
169777    }
169778  }else{
169779    iDb = 0;
169780  }
169781  rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
169782  if( rc==SQLITE_OK ){
169783    pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
169784    if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
169785  }
169786
169787  assert( rc==SQLITE_OK || pTab==0 );
169788  if( rc==SQLITE_OK ){
169789    memset(pTab, 0, sizeof(StatTable));
169790    pTab->db = db;
169791    pTab->iDb = iDb;
169792  }
169793
169794  *ppVtab = (sqlite3_vtab*)pTab;
169795  return rc;
169796}
169797
169798/*
169799** Disconnect from or destroy a statvfs virtual table.
169800*/
169801static int statDisconnect(sqlite3_vtab *pVtab){
169802  sqlite3_free(pVtab);
169803  return SQLITE_OK;
169804}
169805
169806/*
169807** There is no "best-index". This virtual table always does a linear
169808** scan.  However, a schema=? constraint should cause this table to
169809** operate on a different database schema, so check for it.
169810**
169811** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
169812*/
169813static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
169814  int i;
169815
169816  pIdxInfo->estimatedCost = 1.0e6;  /* Initial cost estimate */
169817
169818  /* Look for a valid schema=? constraint.  If found, change the idxNum to
169819  ** 1 and request the value of that constraint be sent to xFilter.  And
169820  ** lower the cost estimate to encourage the constrained version to be
169821  ** used.
169822  */
169823  for(i=0; i<pIdxInfo->nConstraint; i++){
169824    if( pIdxInfo->aConstraint[i].usable==0 ) continue;
169825    if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
169826    if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
169827    pIdxInfo->idxNum = 1;
169828    pIdxInfo->estimatedCost = 1.0;
169829    pIdxInfo->aConstraintUsage[i].argvIndex = 1;
169830    pIdxInfo->aConstraintUsage[i].omit = 1;
169831    break;
169832  }
169833
169834
169835  /* Records are always returned in ascending order of (name, path).
169836  ** If this will satisfy the client, set the orderByConsumed flag so that
169837  ** SQLite does not do an external sort.
169838  */
169839  if( ( pIdxInfo->nOrderBy==1
169840     && pIdxInfo->aOrderBy[0].iColumn==0
169841     && pIdxInfo->aOrderBy[0].desc==0
169842     ) ||
169843      ( pIdxInfo->nOrderBy==2
169844     && pIdxInfo->aOrderBy[0].iColumn==0
169845     && pIdxInfo->aOrderBy[0].desc==0
169846     && pIdxInfo->aOrderBy[1].iColumn==1
169847     && pIdxInfo->aOrderBy[1].desc==0
169848     )
169849  ){
169850    pIdxInfo->orderByConsumed = 1;
169851  }
169852
169853  return SQLITE_OK;
169854}
169855
169856/*
169857** Open a new statvfs cursor.
169858*/
169859static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
169860  StatTable *pTab = (StatTable *)pVTab;
169861  StatCursor *pCsr;
169862
169863  pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
169864  if( pCsr==0 ){
169865    return SQLITE_NOMEM_BKPT;
169866  }else{
169867    memset(pCsr, 0, sizeof(StatCursor));
169868    pCsr->base.pVtab = pVTab;
169869    pCsr->iDb = pTab->iDb;
169870  }
169871
169872  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
169873  return SQLITE_OK;
169874}
169875
169876static void statClearPage(StatPage *p){
169877  int i;
169878  if( p->aCell ){
169879    for(i=0; i<p->nCell; i++){
169880      sqlite3_free(p->aCell[i].aOvfl);
169881    }
169882    sqlite3_free(p->aCell);
169883  }
169884  sqlite3PagerUnref(p->pPg);
169885  sqlite3_free(p->zPath);
169886  memset(p, 0, sizeof(StatPage));
169887}
169888
169889static void statResetCsr(StatCursor *pCsr){
169890  int i;
169891  sqlite3_reset(pCsr->pStmt);
169892  for(i=0; i<ArraySize(pCsr->aPage); i++){
169893    statClearPage(&pCsr->aPage[i]);
169894  }
169895  pCsr->iPage = 0;
169896  sqlite3_free(pCsr->zPath);
169897  pCsr->zPath = 0;
169898  pCsr->isEof = 0;
169899}
169900
169901/*
169902** Close a statvfs cursor.
169903*/
169904static int statClose(sqlite3_vtab_cursor *pCursor){
169905  StatCursor *pCsr = (StatCursor *)pCursor;
169906  statResetCsr(pCsr);
169907  sqlite3_finalize(pCsr->pStmt);
169908  sqlite3_free(pCsr);
169909  return SQLITE_OK;
169910}
169911
169912static void getLocalPayload(
169913  int nUsable,                    /* Usable bytes per page */
169914  u8 flags,                       /* Page flags */
169915  int nTotal,                     /* Total record (payload) size */
169916  int *pnLocal                    /* OUT: Bytes stored locally */
169917){
169918  int nLocal;
169919  int nMinLocal;
169920  int nMaxLocal;
169921
169922  if( flags==0x0D ){              /* Table leaf node */
169923    nMinLocal = (nUsable - 12) * 32 / 255 - 23;
169924    nMaxLocal = nUsable - 35;
169925  }else{                          /* Index interior and leaf nodes */
169926    nMinLocal = (nUsable - 12) * 32 / 255 - 23;
169927    nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
169928  }
169929
169930  nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
169931  if( nLocal>nMaxLocal ) nLocal = nMinLocal;
169932  *pnLocal = nLocal;
169933}
169934
169935static int statDecodePage(Btree *pBt, StatPage *p){
169936  int nUnused;
169937  int iOff;
169938  int nHdr;
169939  int isLeaf;
169940  int szPage;
169941
169942  u8 *aData = sqlite3PagerGetData(p->pPg);
169943  u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
169944
169945  p->flags = aHdr[0];
169946  p->nCell = get2byte(&aHdr[3]);
169947  p->nMxPayload = 0;
169948
169949  isLeaf = (p->flags==0x0A || p->flags==0x0D);
169950  nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
169951
169952  nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
169953  nUnused += (int)aHdr[7];
169954  iOff = get2byte(&aHdr[1]);
169955  while( iOff ){
169956    nUnused += get2byte(&aData[iOff+2]);
169957    iOff = get2byte(&aData[iOff]);
169958  }
169959  p->nUnused = nUnused;
169960  p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
169961  szPage = sqlite3BtreeGetPageSize(pBt);
169962
169963  if( p->nCell ){
169964    int i;                        /* Used to iterate through cells */
169965    int nUsable;                  /* Usable bytes per page */
169966
169967    sqlite3BtreeEnter(pBt);
169968    nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
169969    sqlite3BtreeLeave(pBt);
169970    p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
169971    if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
169972    memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
169973
169974    for(i=0; i<p->nCell; i++){
169975      StatCell *pCell = &p->aCell[i];
169976
169977      iOff = get2byte(&aData[nHdr+i*2]);
169978      if( !isLeaf ){
169979        pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
169980        iOff += 4;
169981      }
169982      if( p->flags==0x05 ){
169983        /* A table interior node. nPayload==0. */
169984      }else{
169985        u32 nPayload;             /* Bytes of payload total (local+overflow) */
169986        int nLocal;               /* Bytes of payload stored locally */
169987        iOff += getVarint32(&aData[iOff], nPayload);
169988        if( p->flags==0x0D ){
169989          u64 dummy;
169990          iOff += sqlite3GetVarint(&aData[iOff], &dummy);
169991        }
169992        if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
169993        getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
169994        pCell->nLocal = nLocal;
169995        assert( nLocal>=0 );
169996        assert( nPayload>=(u32)nLocal );
169997        assert( nLocal<=(nUsable-35) );
169998        if( nPayload>(u32)nLocal ){
169999          int j;
170000          int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
170001          pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
170002          pCell->nOvfl = nOvfl;
170003          pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
170004          if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
170005          pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
170006          for(j=1; j<nOvfl; j++){
170007            int rc;
170008            u32 iPrev = pCell->aOvfl[j-1];
170009            DbPage *pPg = 0;
170010            rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
170011            if( rc!=SQLITE_OK ){
170012              assert( pPg==0 );
170013              return rc;
170014            }
170015            pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
170016            sqlite3PagerUnref(pPg);
170017          }
170018        }
170019      }
170020    }
170021  }
170022
170023  return SQLITE_OK;
170024}
170025
170026/*
170027** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
170028** the current value of pCsr->iPageno.
170029*/
170030static void statSizeAndOffset(StatCursor *pCsr){
170031  StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
170032  Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
170033  Pager *pPager = sqlite3BtreePager(pBt);
170034  sqlite3_file *fd;
170035  sqlite3_int64 x[2];
170036
170037  /* The default page size and offset */
170038  pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
170039  pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
170040
170041  /* If connected to a ZIPVFS backend, override the page size and
170042  ** offset with actual values obtained from ZIPVFS.
170043  */
170044  fd = sqlite3PagerFile(pPager);
170045  x[0] = pCsr->iPageno;
170046  if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
170047    pCsr->iOffset = x[0];
170048    pCsr->szPage = (int)x[1];
170049  }
170050}
170051
170052/*
170053** Move a statvfs cursor to the next entry in the file.
170054*/
170055static int statNext(sqlite3_vtab_cursor *pCursor){
170056  int rc;
170057  int nPayload;
170058  char *z;
170059  StatCursor *pCsr = (StatCursor *)pCursor;
170060  StatTable *pTab = (StatTable *)pCursor->pVtab;
170061  Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
170062  Pager *pPager = sqlite3BtreePager(pBt);
170063
170064  sqlite3_free(pCsr->zPath);
170065  pCsr->zPath = 0;
170066
170067statNextRestart:
170068  if( pCsr->aPage[0].pPg==0 ){
170069    rc = sqlite3_step(pCsr->pStmt);
170070    if( rc==SQLITE_ROW ){
170071      int nPage;
170072      u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
170073      sqlite3PagerPagecount(pPager, &nPage);
170074      if( nPage==0 ){
170075        pCsr->isEof = 1;
170076        return sqlite3_reset(pCsr->pStmt);
170077      }
170078      rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
170079      pCsr->aPage[0].iPgno = iRoot;
170080      pCsr->aPage[0].iCell = 0;
170081      pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
170082      pCsr->iPage = 0;
170083      if( z==0 ) rc = SQLITE_NOMEM_BKPT;
170084    }else{
170085      pCsr->isEof = 1;
170086      return sqlite3_reset(pCsr->pStmt);
170087    }
170088  }else{
170089
170090    /* Page p itself has already been visited. */
170091    StatPage *p = &pCsr->aPage[pCsr->iPage];
170092
170093    while( p->iCell<p->nCell ){
170094      StatCell *pCell = &p->aCell[p->iCell];
170095      if( pCell->iOvfl<pCell->nOvfl ){
170096        int nUsable;
170097        sqlite3BtreeEnter(pBt);
170098        nUsable = sqlite3BtreeGetPageSize(pBt) -
170099                        sqlite3BtreeGetReserveNoMutex(pBt);
170100        sqlite3BtreeLeave(pBt);
170101        pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
170102        pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
170103        pCsr->zPagetype = "overflow";
170104        pCsr->nCell = 0;
170105        pCsr->nMxPayload = 0;
170106        pCsr->zPath = z = sqlite3_mprintf(
170107            "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
170108        );
170109        if( pCell->iOvfl<pCell->nOvfl-1 ){
170110          pCsr->nUnused = 0;
170111          pCsr->nPayload = nUsable - 4;
170112        }else{
170113          pCsr->nPayload = pCell->nLastOvfl;
170114          pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
170115        }
170116        pCell->iOvfl++;
170117        statSizeAndOffset(pCsr);
170118        return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
170119      }
170120      if( p->iRightChildPg ) break;
170121      p->iCell++;
170122    }
170123
170124    if( !p->iRightChildPg || p->iCell>p->nCell ){
170125      statClearPage(p);
170126      if( pCsr->iPage==0 ) return statNext(pCursor);
170127      pCsr->iPage--;
170128      goto statNextRestart; /* Tail recursion */
170129    }
170130    pCsr->iPage++;
170131    assert( p==&pCsr->aPage[pCsr->iPage-1] );
170132
170133    if( p->iCell==p->nCell ){
170134      p[1].iPgno = p->iRightChildPg;
170135    }else{
170136      p[1].iPgno = p->aCell[p->iCell].iChildPg;
170137    }
170138    rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
170139    p[1].iCell = 0;
170140    p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
170141    p->iCell++;
170142    if( z==0 ) rc = SQLITE_NOMEM_BKPT;
170143  }
170144
170145
170146  /* Populate the StatCursor fields with the values to be returned
170147  ** by the xColumn() and xRowid() methods.
170148  */
170149  if( rc==SQLITE_OK ){
170150    int i;
170151    StatPage *p = &pCsr->aPage[pCsr->iPage];
170152    pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
170153    pCsr->iPageno = p->iPgno;
170154
170155    rc = statDecodePage(pBt, p);
170156    if( rc==SQLITE_OK ){
170157      statSizeAndOffset(pCsr);
170158
170159      switch( p->flags ){
170160        case 0x05:             /* table internal */
170161        case 0x02:             /* index internal */
170162          pCsr->zPagetype = "internal";
170163          break;
170164        case 0x0D:             /* table leaf */
170165        case 0x0A:             /* index leaf */
170166          pCsr->zPagetype = "leaf";
170167          break;
170168        default:
170169          pCsr->zPagetype = "corrupted";
170170          break;
170171      }
170172      pCsr->nCell = p->nCell;
170173      pCsr->nUnused = p->nUnused;
170174      pCsr->nMxPayload = p->nMxPayload;
170175      pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
170176      if( z==0 ) rc = SQLITE_NOMEM_BKPT;
170177      nPayload = 0;
170178      for(i=0; i<p->nCell; i++){
170179        nPayload += p->aCell[i].nLocal;
170180      }
170181      pCsr->nPayload = nPayload;
170182    }
170183  }
170184
170185  return rc;
170186}
170187
170188static int statEof(sqlite3_vtab_cursor *pCursor){
170189  StatCursor *pCsr = (StatCursor *)pCursor;
170190  return pCsr->isEof;
170191}
170192
170193static int statFilter(
170194  sqlite3_vtab_cursor *pCursor,
170195  int idxNum, const char *idxStr,
170196  int argc, sqlite3_value **argv
170197){
170198  StatCursor *pCsr = (StatCursor *)pCursor;
170199  StatTable *pTab = (StatTable*)(pCursor->pVtab);
170200  char *zSql;
170201  int rc = SQLITE_OK;
170202  char *zMaster;
170203
170204  if( idxNum==1 ){
170205    const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
170206    pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
170207    if( pCsr->iDb<0 ){
170208      sqlite3_free(pCursor->pVtab->zErrMsg);
170209      pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
170210      return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
170211    }
170212  }else{
170213    pCsr->iDb = pTab->iDb;
170214  }
170215  statResetCsr(pCsr);
170216  sqlite3_finalize(pCsr->pStmt);
170217  pCsr->pStmt = 0;
170218  zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
170219  zSql = sqlite3_mprintf(
170220      "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
170221      "  UNION ALL  "
170222      "SELECT name, rootpage, type"
170223      "  FROM \"%w\".%s WHERE rootpage!=0"
170224      "  ORDER BY name", pTab->db->aDb[pCsr->iDb].zName, zMaster);
170225  if( zSql==0 ){
170226    return SQLITE_NOMEM_BKPT;
170227  }else{
170228    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
170229    sqlite3_free(zSql);
170230  }
170231
170232  if( rc==SQLITE_OK ){
170233    rc = statNext(pCursor);
170234  }
170235  return rc;
170236}
170237
170238static int statColumn(
170239  sqlite3_vtab_cursor *pCursor,
170240  sqlite3_context *ctx,
170241  int i
170242){
170243  StatCursor *pCsr = (StatCursor *)pCursor;
170244  switch( i ){
170245    case 0:            /* name */
170246      sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
170247      break;
170248    case 1:            /* path */
170249      sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
170250      break;
170251    case 2:            /* pageno */
170252      sqlite3_result_int64(ctx, pCsr->iPageno);
170253      break;
170254    case 3:            /* pagetype */
170255      sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
170256      break;
170257    case 4:            /* ncell */
170258      sqlite3_result_int(ctx, pCsr->nCell);
170259      break;
170260    case 5:            /* payload */
170261      sqlite3_result_int(ctx, pCsr->nPayload);
170262      break;
170263    case 6:            /* unused */
170264      sqlite3_result_int(ctx, pCsr->nUnused);
170265      break;
170266    case 7:            /* mx_payload */
170267      sqlite3_result_int(ctx, pCsr->nMxPayload);
170268      break;
170269    case 8:            /* pgoffset */
170270      sqlite3_result_int64(ctx, pCsr->iOffset);
170271      break;
170272    case 9:            /* pgsize */
170273      sqlite3_result_int(ctx, pCsr->szPage);
170274      break;
170275    default: {          /* schema */
170276      sqlite3 *db = sqlite3_context_db_handle(ctx);
170277      int iDb = pCsr->iDb;
170278      sqlite3_result_text(ctx, db->aDb[iDb].zName, -1, SQLITE_STATIC);
170279      break;
170280    }
170281  }
170282  return SQLITE_OK;
170283}
170284
170285static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
170286  StatCursor *pCsr = (StatCursor *)pCursor;
170287  *pRowid = pCsr->iPageno;
170288  return SQLITE_OK;
170289}
170290
170291/*
170292** Invoke this routine to register the "dbstat" virtual table module
170293*/
170294SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
170295  static sqlite3_module dbstat_module = {
170296    0,                            /* iVersion */
170297    statConnect,                  /* xCreate */
170298    statConnect,                  /* xConnect */
170299    statBestIndex,                /* xBestIndex */
170300    statDisconnect,               /* xDisconnect */
170301    statDisconnect,               /* xDestroy */
170302    statOpen,                     /* xOpen - open a cursor */
170303    statClose,                    /* xClose - close a cursor */
170304    statFilter,                   /* xFilter - configure scan constraints */
170305    statNext,                     /* xNext - advance a cursor */
170306    statEof,                      /* xEof - check for end of scan */
170307    statColumn,                   /* xColumn - read data */
170308    statRowid,                    /* xRowid - read data */
170309    0,                            /* xUpdate */
170310    0,                            /* xBegin */
170311    0,                            /* xSync */
170312    0,                            /* xCommit */
170313    0,                            /* xRollback */
170314    0,                            /* xFindMethod */
170315    0,                            /* xRename */
170316  };
170317  return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
170318}
170319#elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
170320SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
170321#endif /* SQLITE_ENABLE_DBSTAT_VTAB */
170322
170323/************** End of dbstat.c **********************************************/
170324/************** Begin file sqlite3session.c **********************************/
170325
170326#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
170327/* #include "sqlite3session.h" */
170328/* #include <assert.h> */
170329/* #include <string.h> */
170330
170331#ifndef SQLITE_AMALGAMATION
170332/* # include "sqliteInt.h" */
170333/* # include "vdbeInt.h" */
170334#endif
170335
170336typedef struct SessionTable SessionTable;
170337typedef struct SessionChange SessionChange;
170338typedef struct SessionBuffer SessionBuffer;
170339typedef struct SessionInput SessionInput;
170340
170341/*
170342** Minimum chunk size used by streaming versions of functions.
170343*/
170344#ifndef SESSIONS_STRM_CHUNK_SIZE
170345# ifdef SQLITE_TEST
170346#   define SESSIONS_STRM_CHUNK_SIZE 64
170347# else
170348#   define SESSIONS_STRM_CHUNK_SIZE 1024
170349# endif
170350#endif
170351
170352typedef struct SessionHook SessionHook;
170353struct SessionHook {
170354  void *pCtx;
170355  int (*xOld)(void*,int,sqlite3_value**);
170356  int (*xNew)(void*,int,sqlite3_value**);
170357  int (*xCount)(void*);
170358  int (*xDepth)(void*);
170359};
170360
170361/*
170362** Session handle structure.
170363*/
170364struct sqlite3_session {
170365  sqlite3 *db;                    /* Database handle session is attached to */
170366  char *zDb;                      /* Name of database session is attached to */
170367  int bEnable;                    /* True if currently recording */
170368  int bIndirect;                  /* True if all changes are indirect */
170369  int bAutoAttach;                /* True to auto-attach tables */
170370  int rc;                         /* Non-zero if an error has occurred */
170371  void *pFilterCtx;               /* First argument to pass to xTableFilter */
170372  int (*xTableFilter)(void *pCtx, const char *zTab);
170373  sqlite3_session *pNext;         /* Next session object on same db. */
170374  SessionTable *pTable;           /* List of attached tables */
170375  SessionHook hook;               /* APIs to grab new and old data with */
170376};
170377
170378/*
170379** Instances of this structure are used to build strings or binary records.
170380*/
170381struct SessionBuffer {
170382  u8 *aBuf;                       /* Pointer to changeset buffer */
170383  int nBuf;                       /* Size of buffer aBuf */
170384  int nAlloc;                     /* Size of allocation containing aBuf */
170385};
170386
170387/*
170388** An object of this type is used internally as an abstraction for
170389** input data. Input data may be supplied either as a single large buffer
170390** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
170391**  sqlite3changeset_start_strm()).
170392*/
170393struct SessionInput {
170394  int bNoDiscard;                 /* If true, discard no data */
170395  int iCurrent;                   /* Offset in aData[] of current change */
170396  int iNext;                      /* Offset in aData[] of next change */
170397  u8 *aData;                      /* Pointer to buffer containing changeset */
170398  int nData;                      /* Number of bytes in aData */
170399
170400  SessionBuffer buf;              /* Current read buffer */
170401  int (*xInput)(void*, void*, int*);        /* Input stream call (or NULL) */
170402  void *pIn;                                /* First argument to xInput */
170403  int bEof;                       /* Set to true after xInput finished */
170404};
170405
170406/*
170407** Structure for changeset iterators.
170408*/
170409struct sqlite3_changeset_iter {
170410  SessionInput in;                /* Input buffer or stream */
170411  SessionBuffer tblhdr;           /* Buffer to hold apValue/zTab/abPK/ */
170412  int bPatchset;                  /* True if this is a patchset */
170413  int rc;                         /* Iterator error code */
170414  sqlite3_stmt *pConflict;        /* Points to conflicting row, if any */
170415  char *zTab;                     /* Current table */
170416  int nCol;                       /* Number of columns in zTab */
170417  int op;                         /* Current operation */
170418  int bIndirect;                  /* True if current change was indirect */
170419  u8 *abPK;                       /* Primary key array */
170420  sqlite3_value **apValue;        /* old.* and new.* values */
170421};
170422
170423/*
170424** Each session object maintains a set of the following structures, one
170425** for each table the session object is monitoring. The structures are
170426** stored in a linked list starting at sqlite3_session.pTable.
170427**
170428** The keys of the SessionTable.aChange[] hash table are all rows that have
170429** been modified in any way since the session object was attached to the
170430** table.
170431**
170432** The data associated with each hash-table entry is a structure containing
170433** a subset of the initial values that the modified row contained at the
170434** start of the session. Or no initial values if the row was inserted.
170435*/
170436struct SessionTable {
170437  SessionTable *pNext;
170438  char *zName;                    /* Local name of table */
170439  int nCol;                       /* Number of columns in table zName */
170440  const char **azCol;             /* Column names */
170441  u8 *abPK;                       /* Array of primary key flags */
170442  int nEntry;                     /* Total number of entries in hash table */
170443  int nChange;                    /* Size of apChange[] array */
170444  SessionChange **apChange;       /* Hash table buckets */
170445};
170446
170447/*
170448** RECORD FORMAT:
170449**
170450** The following record format is similar to (but not compatible with) that
170451** used in SQLite database files. This format is used as part of the
170452** change-set binary format, and so must be architecture independent.
170453**
170454** Unlike the SQLite database record format, each field is self-contained -
170455** there is no separation of header and data. Each field begins with a
170456** single byte describing its type, as follows:
170457**
170458**       0x00: Undefined value.
170459**       0x01: Integer value.
170460**       0x02: Real value.
170461**       0x03: Text value.
170462**       0x04: Blob value.
170463**       0x05: SQL NULL value.
170464**
170465** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
170466** and so on in sqlite3.h. For undefined and NULL values, the field consists
170467** only of the single type byte. For other types of values, the type byte
170468** is followed by:
170469**
170470**   Text values:
170471**     A varint containing the number of bytes in the value (encoded using
170472**     UTF-8). Followed by a buffer containing the UTF-8 representation
170473**     of the text value. There is no nul terminator.
170474**
170475**   Blob values:
170476**     A varint containing the number of bytes in the value, followed by
170477**     a buffer containing the value itself.
170478**
170479**   Integer values:
170480**     An 8-byte big-endian integer value.
170481**
170482**   Real values:
170483**     An 8-byte big-endian IEEE 754-2008 real value.
170484**
170485** Varint values are encoded in the same way as varints in the SQLite
170486** record format.
170487**
170488** CHANGESET FORMAT:
170489**
170490** A changeset is a collection of DELETE, UPDATE and INSERT operations on
170491** one or more tables. Operations on a single table are grouped together,
170492** but may occur in any order (i.e. deletes, updates and inserts are all
170493** mixed together).
170494**
170495** Each group of changes begins with a table header:
170496**
170497**   1 byte: Constant 0x54 (capital 'T')
170498**   Varint: Number of columns in the table.
170499**   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
170500**   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
170501**
170502** Followed by one or more changes to the table.
170503**
170504**   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
170505**   1 byte: The "indirect-change" flag.
170506**   old.* record: (delete and update only)
170507**   new.* record: (insert and update only)
170508**
170509** The "old.*" and "new.*" records, if present, are N field records in the
170510** format described above under "RECORD FORMAT", where N is the number of
170511** columns in the table. The i'th field of each record is associated with
170512** the i'th column of the table, counting from left to right in the order
170513** in which columns were declared in the CREATE TABLE statement.
170514**
170515** The new.* record that is part of each INSERT change contains the values
170516** that make up the new row. Similarly, the old.* record that is part of each
170517** DELETE change contains the values that made up the row that was deleted
170518** from the database. In the changeset format, the records that are part
170519** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
170520** fields.
170521**
170522** Within the old.* record associated with an UPDATE change, all fields
170523** associated with table columns that are not PRIMARY KEY columns and are
170524** not modified by the UPDATE change are set to "undefined". Other fields
170525** are set to the values that made up the row before the UPDATE that the
170526** change records took place. Within the new.* record, fields associated
170527** with table columns modified by the UPDATE change contain the new
170528** values. Fields associated with table columns that are not modified
170529** are set to "undefined".
170530**
170531** PATCHSET FORMAT:
170532**
170533** A patchset is also a collection of changes. It is similar to a changeset,
170534** but leaves undefined those fields that are not useful if no conflict
170535** resolution is required when applying the changeset.
170536**
170537** Each group of changes begins with a table header:
170538**
170539**   1 byte: Constant 0x50 (capital 'P')
170540**   Varint: Number of columns in the table.
170541**   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
170542**   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
170543**
170544** Followed by one or more changes to the table.
170545**
170546**   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
170547**   1 byte: The "indirect-change" flag.
170548**   single record: (PK fields for DELETE, PK and modified fields for UPDATE,
170549**                   full record for INSERT).
170550**
170551** As in the changeset format, each field of the single record that is part
170552** of a patchset change is associated with the correspondingly positioned
170553** table column, counting from left to right within the CREATE TABLE
170554** statement.
170555**
170556** For a DELETE change, all fields within the record except those associated
170557** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields
170558** contain the values identifying the row to delete.
170559**
170560** For an UPDATE change, all fields except those associated with PRIMARY KEY
170561** columns and columns that are modified by the UPDATE are set to "undefined".
170562** PRIMARY KEY fields contain the values identifying the table row to update,
170563** and fields associated with modified columns contain the new column values.
170564**
170565** The records associated with INSERT changes are in the same format as for
170566** changesets. It is not possible for a record associated with an INSERT
170567** change to contain a field set to "undefined".
170568*/
170569
170570/*
170571** For each row modified during a session, there exists a single instance of
170572** this structure stored in a SessionTable.aChange[] hash table.
170573*/
170574struct SessionChange {
170575  int op;                         /* One of UPDATE, DELETE, INSERT */
170576  int bIndirect;                  /* True if this change is "indirect" */
170577  int nRecord;                    /* Number of bytes in buffer aRecord[] */
170578  u8 *aRecord;                    /* Buffer containing old.* record */
170579  SessionChange *pNext;           /* For hash-table collisions */
170580};
170581
170582/*
170583** Write a varint with value iVal into the buffer at aBuf. Return the
170584** number of bytes written.
170585*/
170586static int sessionVarintPut(u8 *aBuf, int iVal){
170587  return putVarint32(aBuf, iVal);
170588}
170589
170590/*
170591** Return the number of bytes required to store value iVal as a varint.
170592*/
170593static int sessionVarintLen(int iVal){
170594  return sqlite3VarintLen(iVal);
170595}
170596
170597/*
170598** Read a varint value from aBuf[] into *piVal. Return the number of
170599** bytes read.
170600*/
170601static int sessionVarintGet(u8 *aBuf, int *piVal){
170602  return getVarint32(aBuf, *piVal);
170603}
170604
170605/* Load an unaligned and unsigned 32-bit integer */
170606#define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
170607
170608/*
170609** Read a 64-bit big-endian integer value from buffer aRec[]. Return
170610** the value read.
170611*/
170612static sqlite3_int64 sessionGetI64(u8 *aRec){
170613  u64 x = SESSION_UINT32(aRec);
170614  u32 y = SESSION_UINT32(aRec+4);
170615  x = (x<<32) + y;
170616  return (sqlite3_int64)x;
170617}
170618
170619/*
170620** Write a 64-bit big-endian integer value to the buffer aBuf[].
170621*/
170622static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
170623  aBuf[0] = (i>>56) & 0xFF;
170624  aBuf[1] = (i>>48) & 0xFF;
170625  aBuf[2] = (i>>40) & 0xFF;
170626  aBuf[3] = (i>>32) & 0xFF;
170627  aBuf[4] = (i>>24) & 0xFF;
170628  aBuf[5] = (i>>16) & 0xFF;
170629  aBuf[6] = (i>> 8) & 0xFF;
170630  aBuf[7] = (i>> 0) & 0xFF;
170631}
170632
170633/*
170634** This function is used to serialize the contents of value pValue (see
170635** comment titled "RECORD FORMAT" above).
170636**
170637** If it is non-NULL, the serialized form of the value is written to
170638** buffer aBuf. *pnWrite is set to the number of bytes written before
170639** returning. Or, if aBuf is NULL, the only thing this function does is
170640** set *pnWrite.
170641**
170642** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
170643** within a call to sqlite3_value_text() (may fail if the db is utf-16))
170644** SQLITE_NOMEM is returned.
170645*/
170646static int sessionSerializeValue(
170647  u8 *aBuf,                       /* If non-NULL, write serialized value here */
170648  sqlite3_value *pValue,          /* Value to serialize */
170649  int *pnWrite                    /* IN/OUT: Increment by bytes written */
170650){
170651  int nByte;                      /* Size of serialized value in bytes */
170652
170653  if( pValue ){
170654    int eType;                    /* Value type (SQLITE_NULL, TEXT etc.) */
170655
170656    eType = sqlite3_value_type(pValue);
170657    if( aBuf ) aBuf[0] = eType;
170658
170659    switch( eType ){
170660      case SQLITE_NULL:
170661        nByte = 1;
170662        break;
170663
170664      case SQLITE_INTEGER:
170665      case SQLITE_FLOAT:
170666        if( aBuf ){
170667          /* TODO: SQLite does something special to deal with mixed-endian
170668          ** floating point values (e.g. ARM7). This code probably should
170669          ** too.  */
170670          u64 i;
170671          if( eType==SQLITE_INTEGER ){
170672            i = (u64)sqlite3_value_int64(pValue);
170673          }else{
170674            double r;
170675            assert( sizeof(double)==8 && sizeof(u64)==8 );
170676            r = sqlite3_value_double(pValue);
170677            memcpy(&i, &r, 8);
170678          }
170679          sessionPutI64(&aBuf[1], i);
170680        }
170681        nByte = 9;
170682        break;
170683
170684      default: {
170685        u8 *z;
170686        int n;
170687        int nVarint;
170688
170689        assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
170690        if( eType==SQLITE_TEXT ){
170691          z = (u8 *)sqlite3_value_text(pValue);
170692        }else{
170693          z = (u8 *)sqlite3_value_blob(pValue);
170694        }
170695        n = sqlite3_value_bytes(pValue);
170696        if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
170697        nVarint = sessionVarintLen(n);
170698
170699        if( aBuf ){
170700          sessionVarintPut(&aBuf[1], n);
170701          memcpy(&aBuf[nVarint + 1], eType==SQLITE_TEXT ?
170702              sqlite3_value_text(pValue) : sqlite3_value_blob(pValue), n
170703          );
170704        }
170705
170706        nByte = 1 + nVarint + n;
170707        break;
170708      }
170709    }
170710  }else{
170711    nByte = 1;
170712    if( aBuf ) aBuf[0] = '\0';
170713  }
170714
170715  if( pnWrite ) *pnWrite += nByte;
170716  return SQLITE_OK;
170717}
170718
170719
170720/*
170721** This macro is used to calculate hash key values for data structures. In
170722** order to use this macro, the entire data structure must be represented
170723** as a series of unsigned integers. In order to calculate a hash-key value
170724** for a data structure represented as three such integers, the macro may
170725** then be used as follows:
170726**
170727**    int hash_key_value;
170728**    hash_key_value = HASH_APPEND(0, <value 1>);
170729**    hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
170730**    hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
170731**
170732** In practice, the data structures this macro is used for are the primary
170733** key values of modified rows.
170734*/
170735#define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
170736
170737/*
170738** Append the hash of the 64-bit integer passed as the second argument to the
170739** hash-key value passed as the first. Return the new hash-key value.
170740*/
170741static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
170742  h = HASH_APPEND(h, i & 0xFFFFFFFF);
170743  return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
170744}
170745
170746/*
170747** Append the hash of the blob passed via the second and third arguments to
170748** the hash-key value passed as the first. Return the new hash-key value.
170749*/
170750static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
170751  int i;
170752  for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
170753  return h;
170754}
170755
170756/*
170757** Append the hash of the data type passed as the second argument to the
170758** hash-key value passed as the first. Return the new hash-key value.
170759*/
170760static unsigned int sessionHashAppendType(unsigned int h, int eType){
170761  return HASH_APPEND(h, eType);
170762}
170763
170764/*
170765** This function may only be called from within a pre-update callback.
170766** It calculates a hash based on the primary key values of the old.* or
170767** new.* row currently available and, assuming no error occurs, writes it to
170768** *piHash before returning. If the primary key contains one or more NULL
170769** values, *pbNullPK is set to true before returning.
170770**
170771** If an error occurs, an SQLite error code is returned and the final values
170772** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
170773** and the output variables are set as described above.
170774*/
170775static int sessionPreupdateHash(
170776  sqlite3_session *pSession,      /* Session object that owns pTab */
170777  SessionTable *pTab,             /* Session table handle */
170778  int bNew,                       /* True to hash the new.* PK */
170779  int *piHash,                    /* OUT: Hash value */
170780  int *pbNullPK                   /* OUT: True if there are NULL values in PK */
170781){
170782  unsigned int h = 0;             /* Hash value to return */
170783  int i;                          /* Used to iterate through columns */
170784
170785  assert( *pbNullPK==0 );
170786  assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
170787  for(i=0; i<pTab->nCol; i++){
170788    if( pTab->abPK[i] ){
170789      int rc;
170790      int eType;
170791      sqlite3_value *pVal;
170792
170793      if( bNew ){
170794        rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
170795      }else{
170796        rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
170797      }
170798      if( rc!=SQLITE_OK ) return rc;
170799
170800      eType = sqlite3_value_type(pVal);
170801      h = sessionHashAppendType(h, eType);
170802      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
170803        i64 iVal;
170804        if( eType==SQLITE_INTEGER ){
170805          iVal = sqlite3_value_int64(pVal);
170806        }else{
170807          double rVal = sqlite3_value_double(pVal);
170808          assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
170809          memcpy(&iVal, &rVal, 8);
170810        }
170811        h = sessionHashAppendI64(h, iVal);
170812      }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
170813        const u8 *z;
170814        int n;
170815        if( eType==SQLITE_TEXT ){
170816          z = (const u8 *)sqlite3_value_text(pVal);
170817        }else{
170818          z = (const u8 *)sqlite3_value_blob(pVal);
170819        }
170820        n = sqlite3_value_bytes(pVal);
170821        if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
170822        h = sessionHashAppendBlob(h, n, z);
170823      }else{
170824        assert( eType==SQLITE_NULL );
170825        *pbNullPK = 1;
170826      }
170827    }
170828  }
170829
170830  *piHash = (h % pTab->nChange);
170831  return SQLITE_OK;
170832}
170833
170834/*
170835** The buffer that the argument points to contains a serialized SQL value.
170836** Return the number of bytes of space occupied by the value (including
170837** the type byte).
170838*/
170839static int sessionSerialLen(u8 *a){
170840  int e = *a;
170841  int n;
170842  if( e==0 ) return 1;
170843  if( e==SQLITE_NULL ) return 1;
170844  if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
170845  return sessionVarintGet(&a[1], &n) + 1 + n;
170846}
170847
170848/*
170849** Based on the primary key values stored in change aRecord, calculate a
170850** hash key. Assume the has table has nBucket buckets. The hash keys
170851** calculated by this function are compatible with those calculated by
170852** sessionPreupdateHash().
170853**
170854** The bPkOnly argument is non-zero if the record at aRecord[] is from
170855** a patchset DELETE. In this case the non-PK fields are omitted entirely.
170856*/
170857static unsigned int sessionChangeHash(
170858  SessionTable *pTab,             /* Table handle */
170859  int bPkOnly,                    /* Record consists of PK fields only */
170860  u8 *aRecord,                    /* Change record */
170861  int nBucket                     /* Assume this many buckets in hash table */
170862){
170863  unsigned int h = 0;             /* Value to return */
170864  int i;                          /* Used to iterate through columns */
170865  u8 *a = aRecord;                /* Used to iterate through change record */
170866
170867  for(i=0; i<pTab->nCol; i++){
170868    int eType = *a;
170869    int isPK = pTab->abPK[i];
170870    if( bPkOnly && isPK==0 ) continue;
170871
170872    /* It is not possible for eType to be SQLITE_NULL here. The session
170873    ** module does not record changes for rows with NULL values stored in
170874    ** primary key columns. */
170875    assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
170876         || eType==SQLITE_TEXT || eType==SQLITE_BLOB
170877         || eType==SQLITE_NULL || eType==0
170878    );
170879    assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
170880
170881    if( isPK ){
170882      a++;
170883      h = sessionHashAppendType(h, eType);
170884      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
170885        h = sessionHashAppendI64(h, sessionGetI64(a));
170886        a += 8;
170887      }else{
170888        int n;
170889        a += sessionVarintGet(a, &n);
170890        h = sessionHashAppendBlob(h, n, a);
170891        a += n;
170892      }
170893    }else{
170894      a += sessionSerialLen(a);
170895    }
170896  }
170897  return (h % nBucket);
170898}
170899
170900/*
170901** Arguments aLeft and aRight are pointers to change records for table pTab.
170902** This function returns true if the two records apply to the same row (i.e.
170903** have the same values stored in the primary key columns), or false
170904** otherwise.
170905*/
170906static int sessionChangeEqual(
170907  SessionTable *pTab,             /* Table used for PK definition */
170908  int bLeftPkOnly,                /* True if aLeft[] contains PK fields only */
170909  u8 *aLeft,                      /* Change record */
170910  int bRightPkOnly,               /* True if aRight[] contains PK fields only */
170911  u8 *aRight                      /* Change record */
170912){
170913  u8 *a1 = aLeft;                 /* Cursor to iterate through aLeft */
170914  u8 *a2 = aRight;                /* Cursor to iterate through aRight */
170915  int iCol;                       /* Used to iterate through table columns */
170916
170917  for(iCol=0; iCol<pTab->nCol; iCol++){
170918    if( pTab->abPK[iCol] ){
170919      int n1 = sessionSerialLen(a1);
170920      int n2 = sessionSerialLen(a2);
170921
170922      if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
170923        return 0;
170924      }
170925      a1 += n1;
170926      a2 += n2;
170927    }else{
170928      if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
170929      if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
170930    }
170931  }
170932
170933  return 1;
170934}
170935
170936/*
170937** Arguments aLeft and aRight both point to buffers containing change
170938** records with nCol columns. This function "merges" the two records into
170939** a single records which is written to the buffer at *paOut. *paOut is
170940** then set to point to one byte after the last byte written before
170941** returning.
170942**
170943** The merging of records is done as follows: For each column, if the
170944** aRight record contains a value for the column, copy the value from
170945** their. Otherwise, if aLeft contains a value, copy it. If neither
170946** record contains a value for a given column, then neither does the
170947** output record.
170948*/
170949static void sessionMergeRecord(
170950  u8 **paOut,
170951  int nCol,
170952  u8 *aLeft,
170953  u8 *aRight
170954){
170955  u8 *a1 = aLeft;                 /* Cursor used to iterate through aLeft */
170956  u8 *a2 = aRight;                /* Cursor used to iterate through aRight */
170957  u8 *aOut = *paOut;              /* Output cursor */
170958  int iCol;                       /* Used to iterate from 0 to nCol */
170959
170960  for(iCol=0; iCol<nCol; iCol++){
170961    int n1 = sessionSerialLen(a1);
170962    int n2 = sessionSerialLen(a2);
170963    if( *a2 ){
170964      memcpy(aOut, a2, n2);
170965      aOut += n2;
170966    }else{
170967      memcpy(aOut, a1, n1);
170968      aOut += n1;
170969    }
170970    a1 += n1;
170971    a2 += n2;
170972  }
170973
170974  *paOut = aOut;
170975}
170976
170977/*
170978** This is a helper function used by sessionMergeUpdate().
170979**
170980** When this function is called, both *paOne and *paTwo point to a value
170981** within a change record. Before it returns, both have been advanced so
170982** as to point to the next value in the record.
170983**
170984** If, when this function is called, *paTwo points to a valid value (i.e.
170985** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
170986** pointer is returned and *pnVal is set to the number of bytes in the
170987** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
170988** set to the number of bytes in the value at *paOne. If *paOne points
170989** to the "no value" placeholder, *pnVal is set to 1. In other words:
170990**
170991**   if( *paTwo is valid ) return *paTwo;
170992**   return *paOne;
170993**
170994*/
170995static u8 *sessionMergeValue(
170996  u8 **paOne,                     /* IN/OUT: Left-hand buffer pointer */
170997  u8 **paTwo,                     /* IN/OUT: Right-hand buffer pointer */
170998  int *pnVal                      /* OUT: Bytes in returned value */
170999){
171000  u8 *a1 = *paOne;
171001  u8 *a2 = *paTwo;
171002  u8 *pRet = 0;
171003  int n1;
171004
171005  assert( a1 );
171006  if( a2 ){
171007    int n2 = sessionSerialLen(a2);
171008    if( *a2 ){
171009      *pnVal = n2;
171010      pRet = a2;
171011    }
171012    *paTwo = &a2[n2];
171013  }
171014
171015  n1 = sessionSerialLen(a1);
171016  if( pRet==0 ){
171017    *pnVal = n1;
171018    pRet = a1;
171019  }
171020  *paOne = &a1[n1];
171021
171022  return pRet;
171023}
171024
171025/*
171026** This function is used by changeset_concat() to merge two UPDATE changes
171027** on the same row.
171028*/
171029static int sessionMergeUpdate(
171030  u8 **paOut,                     /* IN/OUT: Pointer to output buffer */
171031  SessionTable *pTab,             /* Table change pertains to */
171032  int bPatchset,                  /* True if records are patchset records */
171033  u8 *aOldRecord1,                /* old.* record for first change */
171034  u8 *aOldRecord2,                /* old.* record for second change */
171035  u8 *aNewRecord1,                /* new.* record for first change */
171036  u8 *aNewRecord2                 /* new.* record for second change */
171037){
171038  u8 *aOld1 = aOldRecord1;
171039  u8 *aOld2 = aOldRecord2;
171040  u8 *aNew1 = aNewRecord1;
171041  u8 *aNew2 = aNewRecord2;
171042
171043  u8 *aOut = *paOut;
171044  int i;
171045
171046  if( bPatchset==0 ){
171047    int bRequired = 0;
171048
171049    assert( aOldRecord1 && aNewRecord1 );
171050
171051    /* Write the old.* vector first. */
171052    for(i=0; i<pTab->nCol; i++){
171053      int nOld;
171054      u8 *aOld;
171055      int nNew;
171056      u8 *aNew;
171057
171058      aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
171059      aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
171060      if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
171061        if( pTab->abPK[i]==0 ) bRequired = 1;
171062        memcpy(aOut, aOld, nOld);
171063        aOut += nOld;
171064      }else{
171065        *(aOut++) = '\0';
171066      }
171067    }
171068
171069    if( !bRequired ) return 0;
171070  }
171071
171072  /* Write the new.* vector */
171073  aOld1 = aOldRecord1;
171074  aOld2 = aOldRecord2;
171075  aNew1 = aNewRecord1;
171076  aNew2 = aNewRecord2;
171077  for(i=0; i<pTab->nCol; i++){
171078    int nOld;
171079    u8 *aOld;
171080    int nNew;
171081    u8 *aNew;
171082
171083    aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
171084    aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
171085    if( bPatchset==0
171086     && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
171087    ){
171088      *(aOut++) = '\0';
171089    }else{
171090      memcpy(aOut, aNew, nNew);
171091      aOut += nNew;
171092    }
171093  }
171094
171095  *paOut = aOut;
171096  return 1;
171097}
171098
171099/*
171100** This function is only called from within a pre-update-hook callback.
171101** It determines if the current pre-update-hook change affects the same row
171102** as the change stored in argument pChange. If so, it returns true. Otherwise
171103** if the pre-update-hook does not affect the same row as pChange, it returns
171104** false.
171105*/
171106static int sessionPreupdateEqual(
171107  sqlite3_session *pSession,      /* Session object that owns SessionTable */
171108  SessionTable *pTab,             /* Table associated with change */
171109  SessionChange *pChange,         /* Change to compare to */
171110  int op                          /* Current pre-update operation */
171111){
171112  int iCol;                       /* Used to iterate through columns */
171113  u8 *a = pChange->aRecord;       /* Cursor used to scan change record */
171114
171115  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
171116  for(iCol=0; iCol<pTab->nCol; iCol++){
171117    if( !pTab->abPK[iCol] ){
171118      a += sessionSerialLen(a);
171119    }else{
171120      sqlite3_value *pVal;        /* Value returned by preupdate_new/old */
171121      int rc;                     /* Error code from preupdate_new/old */
171122      int eType = *a++;           /* Type of value from change record */
171123
171124      /* The following calls to preupdate_new() and preupdate_old() can not
171125      ** fail. This is because they cache their return values, and by the
171126      ** time control flows to here they have already been called once from
171127      ** within sessionPreupdateHash(). The first two asserts below verify
171128      ** this (that the method has already been called). */
171129      if( op==SQLITE_INSERT ){
171130        /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
171131        rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
171132      }else{
171133        /* assert( db->pPreUpdate->pUnpacked ); */
171134        rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
171135      }
171136      assert( rc==SQLITE_OK );
171137      if( sqlite3_value_type(pVal)!=eType ) return 0;
171138
171139      /* A SessionChange object never has a NULL value in a PK column */
171140      assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
171141           || eType==SQLITE_BLOB    || eType==SQLITE_TEXT
171142      );
171143
171144      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
171145        i64 iVal = sessionGetI64(a);
171146        a += 8;
171147        if( eType==SQLITE_INTEGER ){
171148          if( sqlite3_value_int64(pVal)!=iVal ) return 0;
171149        }else{
171150          double rVal;
171151          assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
171152          memcpy(&rVal, &iVal, 8);
171153          if( sqlite3_value_double(pVal)!=rVal ) return 0;
171154        }
171155      }else{
171156        int n;
171157        const u8 *z;
171158        a += sessionVarintGet(a, &n);
171159        if( sqlite3_value_bytes(pVal)!=n ) return 0;
171160        if( eType==SQLITE_TEXT ){
171161          z = sqlite3_value_text(pVal);
171162        }else{
171163          z = sqlite3_value_blob(pVal);
171164        }
171165        if( memcmp(a, z, n) ) return 0;
171166        a += n;
171167        break;
171168      }
171169    }
171170  }
171171
171172  return 1;
171173}
171174
171175/*
171176** If required, grow the hash table used to store changes on table pTab
171177** (part of the session pSession). If a fatal OOM error occurs, set the
171178** session object to failed and return SQLITE_ERROR. Otherwise, return
171179** SQLITE_OK.
171180**
171181** It is possible that a non-fatal OOM error occurs in this function. In
171182** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
171183** Growing the hash table in this case is a performance optimization only,
171184** it is not required for correct operation.
171185*/
171186static int sessionGrowHash(int bPatchset, SessionTable *pTab){
171187  if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
171188    int i;
171189    SessionChange **apNew;
171190    int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
171191
171192    apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
171193    if( apNew==0 ){
171194      if( pTab->nChange==0 ){
171195        return SQLITE_ERROR;
171196      }
171197      return SQLITE_OK;
171198    }
171199    memset(apNew, 0, sizeof(SessionChange *) * nNew);
171200
171201    for(i=0; i<pTab->nChange; i++){
171202      SessionChange *p;
171203      SessionChange *pNext;
171204      for(p=pTab->apChange[i]; p; p=pNext){
171205        int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
171206        int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
171207        pNext = p->pNext;
171208        p->pNext = apNew[iHash];
171209        apNew[iHash] = p;
171210      }
171211    }
171212
171213    sqlite3_free(pTab->apChange);
171214    pTab->nChange = nNew;
171215    pTab->apChange = apNew;
171216  }
171217
171218  return SQLITE_OK;
171219}
171220
171221/*
171222** This function queries the database for the names of the columns of table
171223** zThis, in schema zDb. It is expected that the table has nCol columns. If
171224** not, SQLITE_SCHEMA is returned and none of the output variables are
171225** populated.
171226**
171227** Otherwise, if they are not NULL, variable *pnCol is set to the number
171228** of columns in the database table and variable *pzTab is set to point to a
171229** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
171230** point to an array of pointers to column names. And *pabPK (again, if not
171231** NULL) is set to point to an array of booleans - true if the corresponding
171232** column is part of the primary key.
171233**
171234** For example, if the table is declared as:
171235**
171236**     CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
171237**
171238** Then the four output variables are populated as follows:
171239**
171240**     *pnCol  = 4
171241**     *pzTab  = "tbl1"
171242**     *pazCol = {"w", "x", "y", "z"}
171243**     *pabPK  = {1, 0, 0, 1}
171244**
171245** All returned buffers are part of the same single allocation, which must
171246** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then
171247** pointer *pazCol should be freed to release all memory. Otherwise, pointer
171248** *pabPK. It is illegal for both pazCol and pabPK to be NULL.
171249*/
171250static int sessionTableInfo(
171251  sqlite3 *db,                    /* Database connection */
171252  const char *zDb,                /* Name of attached database (e.g. "main") */
171253  const char *zThis,              /* Table name */
171254  int *pnCol,                     /* OUT: number of columns */
171255  const char **pzTab,             /* OUT: Copy of zThis */
171256  const char ***pazCol,           /* OUT: Array of column names for table */
171257  u8 **pabPK                      /* OUT: Array of booleans - true for PK col */
171258){
171259  char *zPragma;
171260  sqlite3_stmt *pStmt;
171261  int rc;
171262  int nByte;
171263  int nDbCol = 0;
171264  int nThis;
171265  int i;
171266  u8 *pAlloc = 0;
171267  char **azCol = 0;
171268  u8 *abPK = 0;
171269
171270  assert( pazCol && pabPK );
171271
171272  nThis = sqlite3Strlen30(zThis);
171273  zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
171274  if( !zPragma ) return SQLITE_NOMEM;
171275
171276  rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
171277  sqlite3_free(zPragma);
171278  if( rc!=SQLITE_OK ) return rc;
171279
171280  nByte = nThis + 1;
171281  while( SQLITE_ROW==sqlite3_step(pStmt) ){
171282    nByte += sqlite3_column_bytes(pStmt, 1);
171283    nDbCol++;
171284  }
171285  rc = sqlite3_reset(pStmt);
171286
171287  if( rc==SQLITE_OK ){
171288    nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
171289    pAlloc = sqlite3_malloc(nByte);
171290    if( pAlloc==0 ){
171291      rc = SQLITE_NOMEM;
171292    }
171293  }
171294  if( rc==SQLITE_OK ){
171295    azCol = (char **)pAlloc;
171296    pAlloc = (u8 *)&azCol[nDbCol];
171297    abPK = (u8 *)pAlloc;
171298    pAlloc = &abPK[nDbCol];
171299    if( pzTab ){
171300      memcpy(pAlloc, zThis, nThis+1);
171301      *pzTab = (char *)pAlloc;
171302      pAlloc += nThis+1;
171303    }
171304
171305    i = 0;
171306    while( SQLITE_ROW==sqlite3_step(pStmt) ){
171307      int nName = sqlite3_column_bytes(pStmt, 1);
171308      const unsigned char *zName = sqlite3_column_text(pStmt, 1);
171309      if( zName==0 ) break;
171310      memcpy(pAlloc, zName, nName+1);
171311      azCol[i] = (char *)pAlloc;
171312      pAlloc += nName+1;
171313      abPK[i] = sqlite3_column_int(pStmt, 5);
171314      i++;
171315    }
171316    rc = sqlite3_reset(pStmt);
171317
171318  }
171319
171320  /* If successful, populate the output variables. Otherwise, zero them and
171321  ** free any allocation made. An error code will be returned in this case.
171322  */
171323  if( rc==SQLITE_OK ){
171324    *pazCol = (const char **)azCol;
171325    *pabPK = abPK;
171326    *pnCol = nDbCol;
171327  }else{
171328    *pazCol = 0;
171329    *pabPK = 0;
171330    *pnCol = 0;
171331    if( pzTab ) *pzTab = 0;
171332    sqlite3_free(azCol);
171333  }
171334  sqlite3_finalize(pStmt);
171335  return rc;
171336}
171337
171338/*
171339** This function is only called from within a pre-update handler for a
171340** write to table pTab, part of session pSession. If this is the first
171341** write to this table, initalize the SessionTable.nCol, azCol[] and
171342** abPK[] arrays accordingly.
171343**
171344** If an error occurs, an error code is stored in sqlite3_session.rc and
171345** non-zero returned. Or, if no error occurs but the table has no primary
171346** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
171347** indicate that updates on this table should be ignored. SessionTable.abPK
171348** is set to NULL in this case.
171349*/
171350static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
171351  if( pTab->nCol==0 ){
171352    u8 *abPK;
171353    assert( pTab->azCol==0 || pTab->abPK==0 );
171354    pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
171355        pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
171356    );
171357    if( pSession->rc==SQLITE_OK ){
171358      int i;
171359      for(i=0; i<pTab->nCol; i++){
171360        if( abPK[i] ){
171361          pTab->abPK = abPK;
171362          break;
171363        }
171364      }
171365    }
171366  }
171367  return (pSession->rc || pTab->abPK==0);
171368}
171369
171370/*
171371** This function is only called from with a pre-update-hook reporting a
171372** change on table pTab (attached to session pSession). The type of change
171373** (UPDATE, INSERT, DELETE) is specified by the first argument.
171374**
171375** Unless one is already present or an error occurs, an entry is added
171376** to the changed-rows hash table associated with table pTab.
171377*/
171378static void sessionPreupdateOneChange(
171379  int op,                         /* One of SQLITE_UPDATE, INSERT, DELETE */
171380  sqlite3_session *pSession,      /* Session object pTab is attached to */
171381  SessionTable *pTab              /* Table that change applies to */
171382){
171383  int iHash;
171384  int bNull = 0;
171385  int rc = SQLITE_OK;
171386
171387  if( pSession->rc ) return;
171388
171389  /* Load table details if required */
171390  if( sessionInitTable(pSession, pTab) ) return;
171391
171392  /* Check the number of columns in this xPreUpdate call matches the
171393  ** number of columns in the table.  */
171394  if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
171395    pSession->rc = SQLITE_SCHEMA;
171396    return;
171397  }
171398
171399  /* Grow the hash table if required */
171400  if( sessionGrowHash(0, pTab) ){
171401    pSession->rc = SQLITE_NOMEM;
171402    return;
171403  }
171404
171405  /* Calculate the hash-key for this change. If the primary key of the row
171406  ** includes a NULL value, exit early. Such changes are ignored by the
171407  ** session module. */
171408  rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
171409  if( rc!=SQLITE_OK ) goto error_out;
171410
171411  if( bNull==0 ){
171412    /* Search the hash table for an existing record for this row. */
171413    SessionChange *pC;
171414    for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
171415      if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
171416    }
171417
171418    if( pC==0 ){
171419      /* Create a new change object containing all the old values (if
171420      ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
171421      ** values (if this is an INSERT). */
171422      SessionChange *pChange; /* New change object */
171423      int nByte;              /* Number of bytes to allocate */
171424      int i;                  /* Used to iterate through columns */
171425
171426      assert( rc==SQLITE_OK );
171427      pTab->nEntry++;
171428
171429      /* Figure out how large an allocation is required */
171430      nByte = sizeof(SessionChange);
171431      for(i=0; i<pTab->nCol; i++){
171432        sqlite3_value *p = 0;
171433        if( op!=SQLITE_INSERT ){
171434          TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
171435          assert( trc==SQLITE_OK );
171436        }else if( pTab->abPK[i] ){
171437          TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
171438          assert( trc==SQLITE_OK );
171439        }
171440
171441        /* This may fail if SQLite value p contains a utf-16 string that must
171442        ** be converted to utf-8 and an OOM error occurs while doing so. */
171443        rc = sessionSerializeValue(0, p, &nByte);
171444        if( rc!=SQLITE_OK ) goto error_out;
171445      }
171446
171447      /* Allocate the change object */
171448      pChange = (SessionChange *)sqlite3_malloc(nByte);
171449      if( !pChange ){
171450        rc = SQLITE_NOMEM;
171451        goto error_out;
171452      }else{
171453        memset(pChange, 0, sizeof(SessionChange));
171454        pChange->aRecord = (u8 *)&pChange[1];
171455      }
171456
171457      /* Populate the change object. None of the preupdate_old(),
171458      ** preupdate_new() or SerializeValue() calls below may fail as all
171459      ** required values and encodings have already been cached in memory.
171460      ** It is not possible for an OOM to occur in this block. */
171461      nByte = 0;
171462      for(i=0; i<pTab->nCol; i++){
171463        sqlite3_value *p = 0;
171464        if( op!=SQLITE_INSERT ){
171465          pSession->hook.xOld(pSession->hook.pCtx, i, &p);
171466        }else if( pTab->abPK[i] ){
171467          pSession->hook.xNew(pSession->hook.pCtx, i, &p);
171468        }
171469        sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
171470      }
171471
171472      /* Add the change to the hash-table */
171473      if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
171474        pChange->bIndirect = 1;
171475      }
171476      pChange->nRecord = nByte;
171477      pChange->op = op;
171478      pChange->pNext = pTab->apChange[iHash];
171479      pTab->apChange[iHash] = pChange;
171480
171481    }else if( pC->bIndirect ){
171482      /* If the existing change is considered "indirect", but this current
171483      ** change is "direct", mark the change object as direct. */
171484      if( pSession->hook.xDepth(pSession->hook.pCtx)==0
171485       && pSession->bIndirect==0
171486      ){
171487        pC->bIndirect = 0;
171488      }
171489    }
171490  }
171491
171492  /* If an error has occurred, mark the session object as failed. */
171493 error_out:
171494  if( rc!=SQLITE_OK ){
171495    pSession->rc = rc;
171496  }
171497}
171498
171499static int sessionFindTable(
171500  sqlite3_session *pSession,
171501  const char *zName,
171502  SessionTable **ppTab
171503){
171504  int rc = SQLITE_OK;
171505  int nName = sqlite3Strlen30(zName);
171506  SessionTable *pRet;
171507
171508  /* Search for an existing table */
171509  for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
171510    if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
171511  }
171512
171513  if( pRet==0 && pSession->bAutoAttach ){
171514    /* If there is a table-filter configured, invoke it. If it returns 0,
171515    ** do not automatically add the new table. */
171516    if( pSession->xTableFilter==0
171517     || pSession->xTableFilter(pSession->pFilterCtx, zName)
171518    ){
171519      rc = sqlite3session_attach(pSession, zName);
171520      if( rc==SQLITE_OK ){
171521        for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
171522        assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
171523      }
171524    }
171525  }
171526
171527  assert( rc==SQLITE_OK || pRet==0 );
171528  *ppTab = pRet;
171529  return rc;
171530}
171531
171532/*
171533** The 'pre-update' hook registered by this module with SQLite databases.
171534*/
171535static void xPreUpdate(
171536  void *pCtx,                     /* Copy of third arg to preupdate_hook() */
171537  sqlite3 *db,                    /* Database handle */
171538  int op,                         /* SQLITE_UPDATE, DELETE or INSERT */
171539  char const *zDb,                /* Database name */
171540  char const *zName,              /* Table name */
171541  sqlite3_int64 iKey1,            /* Rowid of row about to be deleted/updated */
171542  sqlite3_int64 iKey2             /* New rowid value (for a rowid UPDATE) */
171543){
171544  sqlite3_session *pSession;
171545  int nDb = sqlite3Strlen30(zDb);
171546
171547  assert( sqlite3_mutex_held(db->mutex) );
171548
171549  for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
171550    SessionTable *pTab;
171551
171552    /* If this session is attached to a different database ("main", "temp"
171553    ** etc.), or if it is not currently enabled, there is nothing to do. Skip
171554    ** to the next session object attached to this database. */
171555    if( pSession->bEnable==0 ) continue;
171556    if( pSession->rc ) continue;
171557    if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
171558
171559    pSession->rc = sessionFindTable(pSession, zName, &pTab);
171560    if( pTab ){
171561      assert( pSession->rc==SQLITE_OK );
171562      sessionPreupdateOneChange(op, pSession, pTab);
171563      if( op==SQLITE_UPDATE ){
171564        sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
171565      }
171566    }
171567  }
171568}
171569
171570/*
171571** The pre-update hook implementations.
171572*/
171573static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
171574  return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
171575}
171576static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
171577  return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
171578}
171579static int sessionPreupdateCount(void *pCtx){
171580  return sqlite3_preupdate_count((sqlite3*)pCtx);
171581}
171582static int sessionPreupdateDepth(void *pCtx){
171583  return sqlite3_preupdate_depth((sqlite3*)pCtx);
171584}
171585
171586/*
171587** Install the pre-update hooks on the session object passed as the only
171588** argument.
171589*/
171590static void sessionPreupdateHooks(
171591  sqlite3_session *pSession
171592){
171593  pSession->hook.pCtx = (void*)pSession->db;
171594  pSession->hook.xOld = sessionPreupdateOld;
171595  pSession->hook.xNew = sessionPreupdateNew;
171596  pSession->hook.xCount = sessionPreupdateCount;
171597  pSession->hook.xDepth = sessionPreupdateDepth;
171598}
171599
171600typedef struct SessionDiffCtx SessionDiffCtx;
171601struct SessionDiffCtx {
171602  sqlite3_stmt *pStmt;
171603  int nOldOff;
171604};
171605
171606/*
171607** The diff hook implementations.
171608*/
171609static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
171610  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
171611  *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
171612  return SQLITE_OK;
171613}
171614static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
171615  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
171616  *ppVal = sqlite3_column_value(p->pStmt, iVal);
171617   return SQLITE_OK;
171618}
171619static int sessionDiffCount(void *pCtx){
171620  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
171621  return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
171622}
171623static int sessionDiffDepth(void *pCtx){
171624  return 0;
171625}
171626
171627/*
171628** Install the diff hooks on the session object passed as the only
171629** argument.
171630*/
171631static void sessionDiffHooks(
171632  sqlite3_session *pSession,
171633  SessionDiffCtx *pDiffCtx
171634){
171635  pSession->hook.pCtx = (void*)pDiffCtx;
171636  pSession->hook.xOld = sessionDiffOld;
171637  pSession->hook.xNew = sessionDiffNew;
171638  pSession->hook.xCount = sessionDiffCount;
171639  pSession->hook.xDepth = sessionDiffDepth;
171640}
171641
171642static char *sessionExprComparePK(
171643  int nCol,
171644  const char *zDb1, const char *zDb2,
171645  const char *zTab,
171646  const char **azCol, u8 *abPK
171647){
171648  int i;
171649  const char *zSep = "";
171650  char *zRet = 0;
171651
171652  for(i=0; i<nCol; i++){
171653    if( abPK[i] ){
171654      zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
171655          zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
171656      );
171657      zSep = " AND ";
171658      if( zRet==0 ) break;
171659    }
171660  }
171661
171662  return zRet;
171663}
171664
171665static char *sessionExprCompareOther(
171666  int nCol,
171667  const char *zDb1, const char *zDb2,
171668  const char *zTab,
171669  const char **azCol, u8 *abPK
171670){
171671  int i;
171672  const char *zSep = "";
171673  char *zRet = 0;
171674  int bHave = 0;
171675
171676  for(i=0; i<nCol; i++){
171677    if( abPK[i]==0 ){
171678      bHave = 1;
171679      zRet = sqlite3_mprintf(
171680          "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
171681          zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
171682      );
171683      zSep = " OR ";
171684      if( zRet==0 ) break;
171685    }
171686  }
171687
171688  if( bHave==0 ){
171689    assert( zRet==0 );
171690    zRet = sqlite3_mprintf("0");
171691  }
171692
171693  return zRet;
171694}
171695
171696static char *sessionSelectFindNew(
171697  int nCol,
171698  const char *zDb1,      /* Pick rows in this db only */
171699  const char *zDb2,      /* But not in this one */
171700  const char *zTbl,      /* Table name */
171701  const char *zExpr
171702){
171703  char *zRet = sqlite3_mprintf(
171704      "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
171705      "  SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
171706      ")",
171707      zDb1, zTbl, zDb2, zTbl, zExpr
171708  );
171709  return zRet;
171710}
171711
171712static int sessionDiffFindNew(
171713  int op,
171714  sqlite3_session *pSession,
171715  SessionTable *pTab,
171716  const char *zDb1,
171717  const char *zDb2,
171718  char *zExpr
171719){
171720  int rc = SQLITE_OK;
171721  char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
171722
171723  if( zStmt==0 ){
171724    rc = SQLITE_NOMEM;
171725  }else{
171726    sqlite3_stmt *pStmt;
171727    rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
171728    if( rc==SQLITE_OK ){
171729      SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
171730      pDiffCtx->pStmt = pStmt;
171731      pDiffCtx->nOldOff = 0;
171732      while( SQLITE_ROW==sqlite3_step(pStmt) ){
171733        sessionPreupdateOneChange(op, pSession, pTab);
171734      }
171735      rc = sqlite3_finalize(pStmt);
171736    }
171737    sqlite3_free(zStmt);
171738  }
171739
171740  return rc;
171741}
171742
171743static int sessionDiffFindModified(
171744  sqlite3_session *pSession,
171745  SessionTable *pTab,
171746  const char *zFrom,
171747  const char *zExpr
171748){
171749  int rc = SQLITE_OK;
171750
171751  char *zExpr2 = sessionExprCompareOther(pTab->nCol,
171752      pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
171753  );
171754  if( zExpr2==0 ){
171755    rc = SQLITE_NOMEM;
171756  }else{
171757    char *zStmt = sqlite3_mprintf(
171758        "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
171759        pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
171760    );
171761    if( zStmt==0 ){
171762      rc = SQLITE_NOMEM;
171763    }else{
171764      sqlite3_stmt *pStmt;
171765      rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
171766
171767      if( rc==SQLITE_OK ){
171768        SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
171769        pDiffCtx->pStmt = pStmt;
171770        pDiffCtx->nOldOff = pTab->nCol;
171771        while( SQLITE_ROW==sqlite3_step(pStmt) ){
171772          sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
171773        }
171774        rc = sqlite3_finalize(pStmt);
171775      }
171776      sqlite3_free(zStmt);
171777    }
171778  }
171779
171780  return rc;
171781}
171782
171783SQLITE_API int SQLITE_STDCALL sqlite3session_diff(
171784  sqlite3_session *pSession,
171785  const char *zFrom,
171786  const char *zTbl,
171787  char **pzErrMsg
171788){
171789  const char *zDb = pSession->zDb;
171790  int rc = pSession->rc;
171791  SessionDiffCtx d;
171792
171793  memset(&d, 0, sizeof(d));
171794  sessionDiffHooks(pSession, &d);
171795
171796  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
171797  if( pzErrMsg ) *pzErrMsg = 0;
171798  if( rc==SQLITE_OK ){
171799    char *zExpr = 0;
171800    sqlite3 *db = pSession->db;
171801    SessionTable *pTo;            /* Table zTbl */
171802
171803    /* Locate and if necessary initialize the target table object */
171804    rc = sessionFindTable(pSession, zTbl, &pTo);
171805    if( pTo==0 ) goto diff_out;
171806    if( sessionInitTable(pSession, pTo) ){
171807      rc = pSession->rc;
171808      goto diff_out;
171809    }
171810
171811    /* Check the table schemas match */
171812    if( rc==SQLITE_OK ){
171813      int bHasPk = 0;
171814      int bMismatch = 0;
171815      int nCol;                   /* Columns in zFrom.zTbl */
171816      u8 *abPK;
171817      const char **azCol = 0;
171818      rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
171819      if( rc==SQLITE_OK ){
171820        if( pTo->nCol!=nCol ){
171821          bMismatch = 1;
171822        }else{
171823          int i;
171824          for(i=0; i<nCol; i++){
171825            if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
171826            if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
171827            if( abPK[i] ) bHasPk = 1;
171828          }
171829        }
171830
171831      }
171832      sqlite3_free((char*)azCol);
171833      if( bMismatch ){
171834        *pzErrMsg = sqlite3_mprintf("table schemas do not match");
171835        rc = SQLITE_SCHEMA;
171836      }
171837      if( bHasPk==0 ){
171838        /* Ignore tables with no primary keys */
171839        goto diff_out;
171840      }
171841    }
171842
171843    if( rc==SQLITE_OK ){
171844      zExpr = sessionExprComparePK(pTo->nCol,
171845          zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
171846      );
171847    }
171848
171849    /* Find new rows */
171850    if( rc==SQLITE_OK ){
171851      rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
171852    }
171853
171854    /* Find old rows */
171855    if( rc==SQLITE_OK ){
171856      rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
171857    }
171858
171859    /* Find modified rows */
171860    if( rc==SQLITE_OK ){
171861      rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
171862    }
171863
171864    sqlite3_free(zExpr);
171865  }
171866
171867 diff_out:
171868  sessionPreupdateHooks(pSession);
171869  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
171870  return rc;
171871}
171872
171873/*
171874** Create a session object. This session object will record changes to
171875** database zDb attached to connection db.
171876*/
171877SQLITE_API int SQLITE_STDCALL sqlite3session_create(
171878  sqlite3 *db,                    /* Database handle */
171879  const char *zDb,                /* Name of db (e.g. "main") */
171880  sqlite3_session **ppSession     /* OUT: New session object */
171881){
171882  sqlite3_session *pNew;          /* Newly allocated session object */
171883  sqlite3_session *pOld;          /* Session object already attached to db */
171884  int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
171885
171886  /* Zero the output value in case an error occurs. */
171887  *ppSession = 0;
171888
171889  /* Allocate and populate the new session object. */
171890  pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
171891  if( !pNew ) return SQLITE_NOMEM;
171892  memset(pNew, 0, sizeof(sqlite3_session));
171893  pNew->db = db;
171894  pNew->zDb = (char *)&pNew[1];
171895  pNew->bEnable = 1;
171896  memcpy(pNew->zDb, zDb, nDb+1);
171897  sessionPreupdateHooks(pNew);
171898
171899  /* Add the new session object to the linked list of session objects
171900  ** attached to database handle $db. Do this under the cover of the db
171901  ** handle mutex.  */
171902  sqlite3_mutex_enter(sqlite3_db_mutex(db));
171903  pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
171904  pNew->pNext = pOld;
171905  sqlite3_mutex_leave(sqlite3_db_mutex(db));
171906
171907  *ppSession = pNew;
171908  return SQLITE_OK;
171909}
171910
171911/*
171912** Free the list of table objects passed as the first argument. The contents
171913** of the changed-rows hash tables are also deleted.
171914*/
171915static void sessionDeleteTable(SessionTable *pList){
171916  SessionTable *pNext;
171917  SessionTable *pTab;
171918
171919  for(pTab=pList; pTab; pTab=pNext){
171920    int i;
171921    pNext = pTab->pNext;
171922    for(i=0; i<pTab->nChange; i++){
171923      SessionChange *p;
171924      SessionChange *pNextChange;
171925      for(p=pTab->apChange[i]; p; p=pNextChange){
171926        pNextChange = p->pNext;
171927        sqlite3_free(p);
171928      }
171929    }
171930    sqlite3_free((char*)pTab->azCol);  /* cast works around VC++ bug */
171931    sqlite3_free(pTab->apChange);
171932    sqlite3_free(pTab);
171933  }
171934}
171935
171936/*
171937** Delete a session object previously allocated using sqlite3session_create().
171938*/
171939SQLITE_API void SQLITE_STDCALL sqlite3session_delete(sqlite3_session *pSession){
171940  sqlite3 *db = pSession->db;
171941  sqlite3_session *pHead;
171942  sqlite3_session **pp;
171943
171944  /* Unlink the session from the linked list of sessions attached to the
171945  ** database handle. Hold the db mutex while doing so.  */
171946  sqlite3_mutex_enter(sqlite3_db_mutex(db));
171947  pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
171948  for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
171949    if( (*pp)==pSession ){
171950      *pp = (*pp)->pNext;
171951      if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
171952      break;
171953    }
171954  }
171955  sqlite3_mutex_leave(sqlite3_db_mutex(db));
171956
171957  /* Delete all attached table objects. And the contents of their
171958  ** associated hash-tables. */
171959  sessionDeleteTable(pSession->pTable);
171960
171961  /* Free the session object itself. */
171962  sqlite3_free(pSession);
171963}
171964
171965/*
171966** Set a table filter on a Session Object.
171967*/
171968SQLITE_API void SQLITE_STDCALL sqlite3session_table_filter(
171969  sqlite3_session *pSession,
171970  int(*xFilter)(void*, const char*),
171971  void *pCtx                      /* First argument passed to xFilter */
171972){
171973  pSession->bAutoAttach = 1;
171974  pSession->pFilterCtx = pCtx;
171975  pSession->xTableFilter = xFilter;
171976}
171977
171978/*
171979** Attach a table to a session. All subsequent changes made to the table
171980** while the session object is enabled will be recorded.
171981**
171982** Only tables that have a PRIMARY KEY defined may be attached. It does
171983** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
171984** or not.
171985*/
171986SQLITE_API int SQLITE_STDCALL sqlite3session_attach(
171987  sqlite3_session *pSession,      /* Session object */
171988  const char *zName               /* Table name */
171989){
171990  int rc = SQLITE_OK;
171991  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
171992
171993  if( !zName ){
171994    pSession->bAutoAttach = 1;
171995  }else{
171996    SessionTable *pTab;           /* New table object (if required) */
171997    int nName;                    /* Number of bytes in string zName */
171998
171999    /* First search for an existing entry. If one is found, this call is
172000    ** a no-op. Return early. */
172001    nName = sqlite3Strlen30(zName);
172002    for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
172003      if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
172004    }
172005
172006    if( !pTab ){
172007      /* Allocate new SessionTable object. */
172008      pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
172009      if( !pTab ){
172010        rc = SQLITE_NOMEM;
172011      }else{
172012        /* Populate the new SessionTable object and link it into the list.
172013        ** The new object must be linked onto the end of the list, not
172014        ** simply added to the start of it in order to ensure that tables
172015        ** appear in the correct order when a changeset or patchset is
172016        ** eventually generated. */
172017        SessionTable **ppTab;
172018        memset(pTab, 0, sizeof(SessionTable));
172019        pTab->zName = (char *)&pTab[1];
172020        memcpy(pTab->zName, zName, nName+1);
172021        for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
172022        *ppTab = pTab;
172023      }
172024    }
172025  }
172026
172027  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
172028  return rc;
172029}
172030
172031/*
172032** Ensure that there is room in the buffer to append nByte bytes of data.
172033** If not, use sqlite3_realloc() to grow the buffer so that there is.
172034**
172035** If successful, return zero. Otherwise, if an OOM condition is encountered,
172036** set *pRc to SQLITE_NOMEM and return non-zero.
172037*/
172038static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
172039  if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
172040    u8 *aNew;
172041    int nNew = p->nAlloc ? p->nAlloc : 128;
172042    do {
172043      nNew = nNew*2;
172044    }while( nNew<(p->nBuf+nByte) );
172045
172046    aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
172047    if( 0==aNew ){
172048      *pRc = SQLITE_NOMEM;
172049    }else{
172050      p->aBuf = aNew;
172051      p->nAlloc = nNew;
172052    }
172053  }
172054  return (*pRc!=SQLITE_OK);
172055}
172056
172057/*
172058** Append the value passed as the second argument to the buffer passed
172059** as the first.
172060**
172061** This function is a no-op if *pRc is non-zero when it is called.
172062** Otherwise, if an error occurs, *pRc is set to an SQLite error code
172063** before returning.
172064*/
172065static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
172066  int rc = *pRc;
172067  if( rc==SQLITE_OK ){
172068    int nByte = 0;
172069    rc = sessionSerializeValue(0, pVal, &nByte);
172070    sessionBufferGrow(p, nByte, &rc);
172071    if( rc==SQLITE_OK ){
172072      rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
172073      p->nBuf += nByte;
172074    }else{
172075      *pRc = rc;
172076    }
172077  }
172078}
172079
172080/*
172081** This function is a no-op if *pRc is other than SQLITE_OK when it is
172082** called. Otherwise, append a single byte to the buffer.
172083**
172084** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172085** returning.
172086*/
172087static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
172088  if( 0==sessionBufferGrow(p, 1, pRc) ){
172089    p->aBuf[p->nBuf++] = v;
172090  }
172091}
172092
172093/*
172094** This function is a no-op if *pRc is other than SQLITE_OK when it is
172095** called. Otherwise, append a single varint to the buffer.
172096**
172097** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172098** returning.
172099*/
172100static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
172101  if( 0==sessionBufferGrow(p, 9, pRc) ){
172102    p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
172103  }
172104}
172105
172106/*
172107** This function is a no-op if *pRc is other than SQLITE_OK when it is
172108** called. Otherwise, append a blob of data to the buffer.
172109**
172110** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172111** returning.
172112*/
172113static void sessionAppendBlob(
172114  SessionBuffer *p,
172115  const u8 *aBlob,
172116  int nBlob,
172117  int *pRc
172118){
172119  if( 0==sessionBufferGrow(p, nBlob, pRc) ){
172120    memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
172121    p->nBuf += nBlob;
172122  }
172123}
172124
172125/*
172126** This function is a no-op if *pRc is other than SQLITE_OK when it is
172127** called. Otherwise, append a string to the buffer. All bytes in the string
172128** up to (but not including) the nul-terminator are written to the buffer.
172129**
172130** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172131** returning.
172132*/
172133static void sessionAppendStr(
172134  SessionBuffer *p,
172135  const char *zStr,
172136  int *pRc
172137){
172138  int nStr = sqlite3Strlen30(zStr);
172139  if( 0==sessionBufferGrow(p, nStr, pRc) ){
172140    memcpy(&p->aBuf[p->nBuf], zStr, nStr);
172141    p->nBuf += nStr;
172142  }
172143}
172144
172145/*
172146** This function is a no-op if *pRc is other than SQLITE_OK when it is
172147** called. Otherwise, append the string representation of integer iVal
172148** to the buffer. No nul-terminator is written.
172149**
172150** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172151** returning.
172152*/
172153static void sessionAppendInteger(
172154  SessionBuffer *p,               /* Buffer to append to */
172155  int iVal,                       /* Value to write the string rep. of */
172156  int *pRc                        /* IN/OUT: Error code */
172157){
172158  char aBuf[24];
172159  sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
172160  sessionAppendStr(p, aBuf, pRc);
172161}
172162
172163/*
172164** This function is a no-op if *pRc is other than SQLITE_OK when it is
172165** called. Otherwise, append the string zStr enclosed in quotes (") and
172166** with any embedded quote characters escaped to the buffer. No
172167** nul-terminator byte is written.
172168**
172169** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172170** returning.
172171*/
172172static void sessionAppendIdent(
172173  SessionBuffer *p,               /* Buffer to a append to */
172174  const char *zStr,               /* String to quote, escape and append */
172175  int *pRc                        /* IN/OUT: Error code */
172176){
172177  int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
172178  if( 0==sessionBufferGrow(p, nStr, pRc) ){
172179    char *zOut = (char *)&p->aBuf[p->nBuf];
172180    const char *zIn = zStr;
172181    *zOut++ = '"';
172182    while( *zIn ){
172183      if( *zIn=='"' ) *zOut++ = '"';
172184      *zOut++ = *(zIn++);
172185    }
172186    *zOut++ = '"';
172187    p->nBuf = (int)((u8 *)zOut - p->aBuf);
172188  }
172189}
172190
172191/*
172192** This function is a no-op if *pRc is other than SQLITE_OK when it is
172193** called. Otherwse, it appends the serialized version of the value stored
172194** in column iCol of the row that SQL statement pStmt currently points
172195** to to the buffer.
172196*/
172197static void sessionAppendCol(
172198  SessionBuffer *p,               /* Buffer to append to */
172199  sqlite3_stmt *pStmt,            /* Handle pointing to row containing value */
172200  int iCol,                       /* Column to read value from */
172201  int *pRc                        /* IN/OUT: Error code */
172202){
172203  if( *pRc==SQLITE_OK ){
172204    int eType = sqlite3_column_type(pStmt, iCol);
172205    sessionAppendByte(p, (u8)eType, pRc);
172206    if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
172207      sqlite3_int64 i;
172208      u8 aBuf[8];
172209      if( eType==SQLITE_INTEGER ){
172210        i = sqlite3_column_int64(pStmt, iCol);
172211      }else{
172212        double r = sqlite3_column_double(pStmt, iCol);
172213        memcpy(&i, &r, 8);
172214      }
172215      sessionPutI64(aBuf, i);
172216      sessionAppendBlob(p, aBuf, 8, pRc);
172217    }
172218    if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
172219      u8 *z;
172220      int nByte;
172221      if( eType==SQLITE_BLOB ){
172222        z = (u8 *)sqlite3_column_blob(pStmt, iCol);
172223      }else{
172224        z = (u8 *)sqlite3_column_text(pStmt, iCol);
172225      }
172226      nByte = sqlite3_column_bytes(pStmt, iCol);
172227      if( z || (eType==SQLITE_BLOB && nByte==0) ){
172228        sessionAppendVarint(p, nByte, pRc);
172229        sessionAppendBlob(p, z, nByte, pRc);
172230      }else{
172231        *pRc = SQLITE_NOMEM;
172232      }
172233    }
172234  }
172235}
172236
172237/*
172238**
172239** This function appends an update change to the buffer (see the comments
172240** under "CHANGESET FORMAT" at the top of the file). An update change
172241** consists of:
172242**
172243**   1 byte:  SQLITE_UPDATE (0x17)
172244**   n bytes: old.* record (see RECORD FORMAT)
172245**   m bytes: new.* record (see RECORD FORMAT)
172246**
172247** The SessionChange object passed as the third argument contains the
172248** values that were stored in the row when the session began (the old.*
172249** values). The statement handle passed as the second argument points
172250** at the current version of the row (the new.* values).
172251**
172252** If all of the old.* values are equal to their corresponding new.* value
172253** (i.e. nothing has changed), then no data at all is appended to the buffer.
172254**
172255** Otherwise, the old.* record contains all primary key values and the
172256** original values of any fields that have been modified. The new.* record
172257** contains the new values of only those fields that have been modified.
172258*/
172259static int sessionAppendUpdate(
172260  SessionBuffer *pBuf,            /* Buffer to append to */
172261  int bPatchset,                  /* True for "patchset", 0 for "changeset" */
172262  sqlite3_stmt *pStmt,            /* Statement handle pointing at new row */
172263  SessionChange *p,               /* Object containing old values */
172264  u8 *abPK                        /* Boolean array - true for PK columns */
172265){
172266  int rc = SQLITE_OK;
172267  SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
172268  int bNoop = 1;                /* Set to zero if any values are modified */
172269  int nRewind = pBuf->nBuf;     /* Set to zero if any values are modified */
172270  int i;                        /* Used to iterate through columns */
172271  u8 *pCsr = p->aRecord;        /* Used to iterate through old.* values */
172272
172273  sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
172274  sessionAppendByte(pBuf, p->bIndirect, &rc);
172275  for(i=0; i<sqlite3_column_count(pStmt); i++){
172276    int bChanged = 0;
172277    int nAdvance;
172278    int eType = *pCsr;
172279    switch( eType ){
172280      case SQLITE_NULL:
172281        nAdvance = 1;
172282        if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
172283          bChanged = 1;
172284        }
172285        break;
172286
172287      case SQLITE_FLOAT:
172288      case SQLITE_INTEGER: {
172289        nAdvance = 9;
172290        if( eType==sqlite3_column_type(pStmt, i) ){
172291          sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
172292          if( eType==SQLITE_INTEGER ){
172293            if( iVal==sqlite3_column_int64(pStmt, i) ) break;
172294          }else{
172295            double dVal;
172296            memcpy(&dVal, &iVal, 8);
172297            if( dVal==sqlite3_column_double(pStmt, i) ) break;
172298          }
172299        }
172300        bChanged = 1;
172301        break;
172302      }
172303
172304      default: {
172305        int nByte;
172306        int nHdr = 1 + sessionVarintGet(&pCsr[1], &nByte);
172307        assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
172308        nAdvance = nHdr + nByte;
172309        if( eType==sqlite3_column_type(pStmt, i)
172310         && nByte==sqlite3_column_bytes(pStmt, i)
172311         && 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), nByte)
172312        ){
172313          break;
172314        }
172315        bChanged = 1;
172316      }
172317    }
172318
172319    /* If at least one field has been modified, this is not a no-op. */
172320    if( bChanged ) bNoop = 0;
172321
172322    /* Add a field to the old.* record. This is omitted if this modules is
172323    ** currently generating a patchset. */
172324    if( bPatchset==0 ){
172325      if( bChanged || abPK[i] ){
172326        sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
172327      }else{
172328        sessionAppendByte(pBuf, 0, &rc);
172329      }
172330    }
172331
172332    /* Add a field to the new.* record. Or the only record if currently
172333    ** generating a patchset.  */
172334    if( bChanged || (bPatchset && abPK[i]) ){
172335      sessionAppendCol(&buf2, pStmt, i, &rc);
172336    }else{
172337      sessionAppendByte(&buf2, 0, &rc);
172338    }
172339
172340    pCsr += nAdvance;
172341  }
172342
172343  if( bNoop ){
172344    pBuf->nBuf = nRewind;
172345  }else{
172346    sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
172347  }
172348  sqlite3_free(buf2.aBuf);
172349
172350  return rc;
172351}
172352
172353/*
172354** Append a DELETE change to the buffer passed as the first argument. Use
172355** the changeset format if argument bPatchset is zero, or the patchset
172356** format otherwise.
172357*/
172358static int sessionAppendDelete(
172359  SessionBuffer *pBuf,            /* Buffer to append to */
172360  int bPatchset,                  /* True for "patchset", 0 for "changeset" */
172361  SessionChange *p,               /* Object containing old values */
172362  int nCol,                       /* Number of columns in table */
172363  u8 *abPK                        /* Boolean array - true for PK columns */
172364){
172365  int rc = SQLITE_OK;
172366
172367  sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
172368  sessionAppendByte(pBuf, p->bIndirect, &rc);
172369
172370  if( bPatchset==0 ){
172371    sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
172372  }else{
172373    int i;
172374    u8 *a = p->aRecord;
172375    for(i=0; i<nCol; i++){
172376      u8 *pStart = a;
172377      int eType = *a++;
172378
172379      switch( eType ){
172380        case 0:
172381        case SQLITE_NULL:
172382          assert( abPK[i]==0 );
172383          break;
172384
172385        case SQLITE_FLOAT:
172386        case SQLITE_INTEGER:
172387          a += 8;
172388          break;
172389
172390        default: {
172391          int n;
172392          a += sessionVarintGet(a, &n);
172393          a += n;
172394          break;
172395        }
172396      }
172397      if( abPK[i] ){
172398        sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
172399      }
172400    }
172401    assert( (a - p->aRecord)==p->nRecord );
172402  }
172403
172404  return rc;
172405}
172406
172407/*
172408** Formulate and prepare a SELECT statement to retrieve a row from table
172409** zTab in database zDb based on its primary key. i.e.
172410**
172411**   SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
172412*/
172413static int sessionSelectStmt(
172414  sqlite3 *db,                    /* Database handle */
172415  const char *zDb,                /* Database name */
172416  const char *zTab,               /* Table name */
172417  int nCol,                       /* Number of columns in table */
172418  const char **azCol,             /* Names of table columns */
172419  u8 *abPK,                       /* PRIMARY KEY  array */
172420  sqlite3_stmt **ppStmt           /* OUT: Prepared SELECT statement */
172421){
172422  int rc = SQLITE_OK;
172423  int i;
172424  const char *zSep = "";
172425  SessionBuffer buf = {0, 0, 0};
172426
172427  sessionAppendStr(&buf, "SELECT * FROM ", &rc);
172428  sessionAppendIdent(&buf, zDb, &rc);
172429  sessionAppendStr(&buf, ".", &rc);
172430  sessionAppendIdent(&buf, zTab, &rc);
172431  sessionAppendStr(&buf, " WHERE ", &rc);
172432  for(i=0; i<nCol; i++){
172433    if( abPK[i] ){
172434      sessionAppendStr(&buf, zSep, &rc);
172435      sessionAppendIdent(&buf, azCol[i], &rc);
172436      sessionAppendStr(&buf, " = ?", &rc);
172437      sessionAppendInteger(&buf, i+1, &rc);
172438      zSep = " AND ";
172439    }
172440  }
172441  if( rc==SQLITE_OK ){
172442    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
172443  }
172444  sqlite3_free(buf.aBuf);
172445  return rc;
172446}
172447
172448/*
172449** Bind the PRIMARY KEY values from the change passed in argument pChange
172450** to the SELECT statement passed as the first argument. The SELECT statement
172451** is as prepared by function sessionSelectStmt().
172452**
172453** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
172454** error code (e.g. SQLITE_NOMEM) otherwise.
172455*/
172456static int sessionSelectBind(
172457  sqlite3_stmt *pSelect,          /* SELECT from sessionSelectStmt() */
172458  int nCol,                       /* Number of columns in table */
172459  u8 *abPK,                       /* PRIMARY KEY array */
172460  SessionChange *pChange          /* Change structure */
172461){
172462  int i;
172463  int rc = SQLITE_OK;
172464  u8 *a = pChange->aRecord;
172465
172466  for(i=0; i<nCol && rc==SQLITE_OK; i++){
172467    int eType = *a++;
172468
172469    switch( eType ){
172470      case 0:
172471      case SQLITE_NULL:
172472        assert( abPK[i]==0 );
172473        break;
172474
172475      case SQLITE_INTEGER: {
172476        if( abPK[i] ){
172477          i64 iVal = sessionGetI64(a);
172478          rc = sqlite3_bind_int64(pSelect, i+1, iVal);
172479        }
172480        a += 8;
172481        break;
172482      }
172483
172484      case SQLITE_FLOAT: {
172485        if( abPK[i] ){
172486          double rVal;
172487          i64 iVal = sessionGetI64(a);
172488          memcpy(&rVal, &iVal, 8);
172489          rc = sqlite3_bind_double(pSelect, i+1, rVal);
172490        }
172491        a += 8;
172492        break;
172493      }
172494
172495      case SQLITE_TEXT: {
172496        int n;
172497        a += sessionVarintGet(a, &n);
172498        if( abPK[i] ){
172499          rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
172500        }
172501        a += n;
172502        break;
172503      }
172504
172505      default: {
172506        int n;
172507        assert( eType==SQLITE_BLOB );
172508        a += sessionVarintGet(a, &n);
172509        if( abPK[i] ){
172510          rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
172511        }
172512        a += n;
172513        break;
172514      }
172515    }
172516  }
172517
172518  return rc;
172519}
172520
172521/*
172522** This function is a no-op if *pRc is set to other than SQLITE_OK when it
172523** is called. Otherwise, append a serialized table header (part of the binary
172524** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
172525** SQLite error code before returning.
172526*/
172527static void sessionAppendTableHdr(
172528  SessionBuffer *pBuf,            /* Append header to this buffer */
172529  int bPatchset,                  /* Use the patchset format if true */
172530  SessionTable *pTab,             /* Table object to append header for */
172531  int *pRc                        /* IN/OUT: Error code */
172532){
172533  /* Write a table header */
172534  sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
172535  sessionAppendVarint(pBuf, pTab->nCol, pRc);
172536  sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
172537  sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
172538}
172539
172540/*
172541** Generate either a changeset (if argument bPatchset is zero) or a patchset
172542** (if it is non-zero) based on the current contents of the session object
172543** passed as the first argument.
172544**
172545** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
172546** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
172547** occurs, an SQLite error code is returned and both output variables set
172548** to 0.
172549*/
172550static int sessionGenerateChangeset(
172551  sqlite3_session *pSession,      /* Session object */
172552  int bPatchset,                  /* True for patchset, false for changeset */
172553  int (*xOutput)(void *pOut, const void *pData, int nData),
172554  void *pOut,                     /* First argument for xOutput */
172555  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
172556  void **ppChangeset              /* OUT: Buffer containing changeset */
172557){
172558  sqlite3 *db = pSession->db;     /* Source database handle */
172559  SessionTable *pTab;             /* Used to iterate through attached tables */
172560  SessionBuffer buf = {0,0,0};    /* Buffer in which to accumlate changeset */
172561  int rc;                         /* Return code */
172562
172563  assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
172564
172565  /* Zero the output variables in case an error occurs. If this session
172566  ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
172567  ** this call will be a no-op.  */
172568  if( xOutput==0 ){
172569    *pnChangeset = 0;
172570    *ppChangeset = 0;
172571  }
172572
172573  if( pSession->rc ) return pSession->rc;
172574  rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
172575  if( rc!=SQLITE_OK ) return rc;
172576
172577  sqlite3_mutex_enter(sqlite3_db_mutex(db));
172578
172579  for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
172580    if( pTab->nEntry ){
172581      const char *zName = pTab->zName;
172582      int nCol;                   /* Number of columns in table */
172583      u8 *abPK;                   /* Primary key array */
172584      const char **azCol = 0;     /* Table columns */
172585      int i;                      /* Used to iterate through hash buckets */
172586      sqlite3_stmt *pSel = 0;     /* SELECT statement to query table pTab */
172587      int nRewind = buf.nBuf;     /* Initial size of write buffer */
172588      int nNoop;                  /* Size of buffer after writing tbl header */
172589
172590      /* Check the table schema is still Ok. */
172591      rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
172592      if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
172593        rc = SQLITE_SCHEMA;
172594      }
172595
172596      /* Write a table header */
172597      sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
172598
172599      /* Build and compile a statement to execute: */
172600      if( rc==SQLITE_OK ){
172601        rc = sessionSelectStmt(
172602            db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
172603      }
172604
172605      nNoop = buf.nBuf;
172606      for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
172607        SessionChange *p;         /* Used to iterate through changes */
172608
172609        for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
172610          rc = sessionSelectBind(pSel, nCol, abPK, p);
172611          if( rc!=SQLITE_OK ) continue;
172612          if( sqlite3_step(pSel)==SQLITE_ROW ){
172613            if( p->op==SQLITE_INSERT ){
172614              int iCol;
172615              sessionAppendByte(&buf, SQLITE_INSERT, &rc);
172616              sessionAppendByte(&buf, p->bIndirect, &rc);
172617              for(iCol=0; iCol<nCol; iCol++){
172618                sessionAppendCol(&buf, pSel, iCol, &rc);
172619              }
172620            }else{
172621              rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
172622            }
172623          }else if( p->op!=SQLITE_INSERT ){
172624            rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
172625          }
172626          if( rc==SQLITE_OK ){
172627            rc = sqlite3_reset(pSel);
172628          }
172629
172630          /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
172631          ** its contents to the xOutput() callback. */
172632          if( xOutput
172633           && rc==SQLITE_OK
172634           && buf.nBuf>nNoop
172635           && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
172636          ){
172637            rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
172638            nNoop = -1;
172639            buf.nBuf = 0;
172640          }
172641
172642        }
172643      }
172644
172645      sqlite3_finalize(pSel);
172646      if( buf.nBuf==nNoop ){
172647        buf.nBuf = nRewind;
172648      }
172649      sqlite3_free((char*)azCol);  /* cast works around VC++ bug */
172650    }
172651  }
172652
172653  if( rc==SQLITE_OK ){
172654    if( xOutput==0 ){
172655      *pnChangeset = buf.nBuf;
172656      *ppChangeset = buf.aBuf;
172657      buf.aBuf = 0;
172658    }else if( buf.nBuf>0 ){
172659      rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
172660    }
172661  }
172662
172663  sqlite3_free(buf.aBuf);
172664  sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
172665  sqlite3_mutex_leave(sqlite3_db_mutex(db));
172666  return rc;
172667}
172668
172669/*
172670** Obtain a changeset object containing all changes recorded by the
172671** session object passed as the first argument.
172672**
172673** It is the responsibility of the caller to eventually free the buffer
172674** using sqlite3_free().
172675*/
172676SQLITE_API int SQLITE_STDCALL sqlite3session_changeset(
172677  sqlite3_session *pSession,      /* Session object */
172678  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
172679  void **ppChangeset              /* OUT: Buffer containing changeset */
172680){
172681  return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
172682}
172683
172684/*
172685** Streaming version of sqlite3session_changeset().
172686*/
172687SQLITE_API int SQLITE_STDCALL sqlite3session_changeset_strm(
172688  sqlite3_session *pSession,
172689  int (*xOutput)(void *pOut, const void *pData, int nData),
172690  void *pOut
172691){
172692  return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
172693}
172694
172695/*
172696** Streaming version of sqlite3session_patchset().
172697*/
172698SQLITE_API int SQLITE_STDCALL sqlite3session_patchset_strm(
172699  sqlite3_session *pSession,
172700  int (*xOutput)(void *pOut, const void *pData, int nData),
172701  void *pOut
172702){
172703  return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
172704}
172705
172706/*
172707** Obtain a patchset object containing all changes recorded by the
172708** session object passed as the first argument.
172709**
172710** It is the responsibility of the caller to eventually free the buffer
172711** using sqlite3_free().
172712*/
172713SQLITE_API int SQLITE_STDCALL sqlite3session_patchset(
172714  sqlite3_session *pSession,      /* Session object */
172715  int *pnPatchset,                /* OUT: Size of buffer at *ppChangeset */
172716  void **ppPatchset               /* OUT: Buffer containing changeset */
172717){
172718  return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
172719}
172720
172721/*
172722** Enable or disable the session object passed as the first argument.
172723*/
172724SQLITE_API int SQLITE_STDCALL sqlite3session_enable(sqlite3_session *pSession, int bEnable){
172725  int ret;
172726  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
172727  if( bEnable>=0 ){
172728    pSession->bEnable = bEnable;
172729  }
172730  ret = pSession->bEnable;
172731  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
172732  return ret;
172733}
172734
172735/*
172736** Enable or disable the session object passed as the first argument.
172737*/
172738SQLITE_API int SQLITE_STDCALL sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
172739  int ret;
172740  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
172741  if( bIndirect>=0 ){
172742    pSession->bIndirect = bIndirect;
172743  }
172744  ret = pSession->bIndirect;
172745  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
172746  return ret;
172747}
172748
172749/*
172750** Return true if there have been no changes to monitored tables recorded
172751** by the session object passed as the only argument.
172752*/
172753SQLITE_API int SQLITE_STDCALL sqlite3session_isempty(sqlite3_session *pSession){
172754  int ret = 0;
172755  SessionTable *pTab;
172756
172757  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
172758  for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
172759    ret = (pTab->nEntry>0);
172760  }
172761  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
172762
172763  return (ret==0);
172764}
172765
172766/*
172767** Do the work for either sqlite3changeset_start() or start_strm().
172768*/
172769static int sessionChangesetStart(
172770  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
172771  int (*xInput)(void *pIn, void *pData, int *pnData),
172772  void *pIn,
172773  int nChangeset,                 /* Size of buffer pChangeset in bytes */
172774  void *pChangeset                /* Pointer to buffer containing changeset */
172775){
172776  sqlite3_changeset_iter *pRet;   /* Iterator to return */
172777  int nByte;                      /* Number of bytes to allocate for iterator */
172778
172779  assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
172780
172781  /* Zero the output variable in case an error occurs. */
172782  *pp = 0;
172783
172784  /* Allocate and initialize the iterator structure. */
172785  nByte = sizeof(sqlite3_changeset_iter);
172786  pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
172787  if( !pRet ) return SQLITE_NOMEM;
172788  memset(pRet, 0, sizeof(sqlite3_changeset_iter));
172789  pRet->in.aData = (u8 *)pChangeset;
172790  pRet->in.nData = nChangeset;
172791  pRet->in.xInput = xInput;
172792  pRet->in.pIn = pIn;
172793  pRet->in.bEof = (xInput ? 0 : 1);
172794
172795  /* Populate the output variable and return success. */
172796  *pp = pRet;
172797  return SQLITE_OK;
172798}
172799
172800/*
172801** Create an iterator used to iterate through the contents of a changeset.
172802*/
172803SQLITE_API int SQLITE_STDCALL sqlite3changeset_start(
172804  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
172805  int nChangeset,                 /* Size of buffer pChangeset in bytes */
172806  void *pChangeset                /* Pointer to buffer containing changeset */
172807){
172808  return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
172809}
172810
172811/*
172812** Streaming version of sqlite3changeset_start().
172813*/
172814SQLITE_API int SQLITE_STDCALL sqlite3changeset_start_strm(
172815  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
172816  int (*xInput)(void *pIn, void *pData, int *pnData),
172817  void *pIn
172818){
172819  return sessionChangesetStart(pp, xInput, pIn, 0, 0);
172820}
172821
172822/*
172823** If the SessionInput object passed as the only argument is a streaming
172824** object and the buffer is full, discard some data to free up space.
172825*/
172826static void sessionDiscardData(SessionInput *pIn){
172827  if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
172828    int nMove = pIn->buf.nBuf - pIn->iNext;
172829    assert( nMove>=0 );
172830    if( nMove>0 ){
172831      memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
172832    }
172833    pIn->buf.nBuf -= pIn->iNext;
172834    pIn->iNext = 0;
172835    pIn->nData = pIn->buf.nBuf;
172836  }
172837}
172838
172839/*
172840** Ensure that there are at least nByte bytes available in the buffer. Or,
172841** if there are not nByte bytes remaining in the input, that all available
172842** data is in the buffer.
172843**
172844** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
172845*/
172846static int sessionInputBuffer(SessionInput *pIn, int nByte){
172847  int rc = SQLITE_OK;
172848  if( pIn->xInput ){
172849    while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
172850      int nNew = SESSIONS_STRM_CHUNK_SIZE;
172851
172852      if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
172853      if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
172854        rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
172855        if( nNew==0 ){
172856          pIn->bEof = 1;
172857        }else{
172858          pIn->buf.nBuf += nNew;
172859        }
172860      }
172861
172862      pIn->aData = pIn->buf.aBuf;
172863      pIn->nData = pIn->buf.nBuf;
172864    }
172865  }
172866  return rc;
172867}
172868
172869/*
172870** When this function is called, *ppRec points to the start of a record
172871** that contains nCol values. This function advances the pointer *ppRec
172872** until it points to the byte immediately following that record.
172873*/
172874static void sessionSkipRecord(
172875  u8 **ppRec,                     /* IN/OUT: Record pointer */
172876  int nCol                        /* Number of values in record */
172877){
172878  u8 *aRec = *ppRec;
172879  int i;
172880  for(i=0; i<nCol; i++){
172881    int eType = *aRec++;
172882    if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
172883      int nByte;
172884      aRec += sessionVarintGet((u8*)aRec, &nByte);
172885      aRec += nByte;
172886    }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
172887      aRec += 8;
172888    }
172889  }
172890
172891  *ppRec = aRec;
172892}
172893
172894/*
172895** This function sets the value of the sqlite3_value object passed as the
172896** first argument to a copy of the string or blob held in the aData[]
172897** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
172898** error occurs.
172899*/
172900static int sessionValueSetStr(
172901  sqlite3_value *pVal,            /* Set the value of this object */
172902  u8 *aData,                      /* Buffer containing string or blob data */
172903  int nData,                      /* Size of buffer aData[] in bytes */
172904  u8 enc                          /* String encoding (0 for blobs) */
172905){
172906  /* In theory this code could just pass SQLITE_TRANSIENT as the final
172907  ** argument to sqlite3ValueSetStr() and have the copy created
172908  ** automatically. But doing so makes it difficult to detect any OOM
172909  ** error. Hence the code to create the copy externally. */
172910  u8 *aCopy = sqlite3_malloc(nData+1);
172911  if( aCopy==0 ) return SQLITE_NOMEM;
172912  memcpy(aCopy, aData, nData);
172913  sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
172914  return SQLITE_OK;
172915}
172916
172917/*
172918** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
172919** for details.
172920**
172921** When this function is called, *paChange points to the start of the record
172922** to deserialize. Assuming no error occurs, *paChange is set to point to
172923** one byte after the end of the same record before this function returns.
172924** If the argument abPK is NULL, then the record contains nCol values. Or,
172925** if abPK is other than NULL, then the record contains only the PK fields
172926** (in other words, it is a patchset DELETE record).
172927**
172928** If successful, each element of the apOut[] array (allocated by the caller)
172929** is set to point to an sqlite3_value object containing the value read
172930** from the corresponding position in the record. If that value is not
172931** included in the record (i.e. because the record is part of an UPDATE change
172932** and the field was not modified), the corresponding element of apOut[] is
172933** set to NULL.
172934**
172935** It is the responsibility of the caller to free all sqlite_value structures
172936** using sqlite3_free().
172937**
172938** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
172939** The apOut[] array may have been partially populated in this case.
172940*/
172941static int sessionReadRecord(
172942  SessionInput *pIn,              /* Input data */
172943  int nCol,                       /* Number of values in record */
172944  u8 *abPK,                       /* Array of primary key flags, or NULL */
172945  sqlite3_value **apOut           /* Write values to this array */
172946){
172947  int i;                          /* Used to iterate through columns */
172948  int rc = SQLITE_OK;
172949
172950  for(i=0; i<nCol && rc==SQLITE_OK; i++){
172951    int eType = 0;                /* Type of value (SQLITE_NULL, TEXT etc.) */
172952    if( abPK && abPK[i]==0 ) continue;
172953    rc = sessionInputBuffer(pIn, 9);
172954    if( rc==SQLITE_OK ){
172955      eType = pIn->aData[pIn->iNext++];
172956    }
172957
172958    assert( apOut[i]==0 );
172959    if( eType ){
172960      apOut[i] = sqlite3ValueNew(0);
172961      if( !apOut[i] ) rc = SQLITE_NOMEM;
172962    }
172963
172964    if( rc==SQLITE_OK ){
172965      u8 *aVal = &pIn->aData[pIn->iNext];
172966      if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
172967        int nByte;
172968        pIn->iNext += sessionVarintGet(aVal, &nByte);
172969        rc = sessionInputBuffer(pIn, nByte);
172970        if( rc==SQLITE_OK ){
172971          u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
172972          rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
172973        }
172974        pIn->iNext += nByte;
172975      }
172976      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
172977        sqlite3_int64 v = sessionGetI64(aVal);
172978        if( eType==SQLITE_INTEGER ){
172979          sqlite3VdbeMemSetInt64(apOut[i], v);
172980        }else{
172981          double d;
172982          memcpy(&d, &v, 8);
172983          sqlite3VdbeMemSetDouble(apOut[i], d);
172984        }
172985        pIn->iNext += 8;
172986      }
172987    }
172988  }
172989
172990  return rc;
172991}
172992
172993/*
172994** The input pointer currently points to the second byte of a table-header.
172995** Specifically, to the following:
172996**
172997**   + number of columns in table (varint)
172998**   + array of PK flags (1 byte per column),
172999**   + table name (nul terminated).
173000**
173001** This function ensures that all of the above is present in the input
173002** buffer (i.e. that it can be accessed without any calls to xInput()).
173003** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
173004** The input pointer is not moved.
173005*/
173006static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
173007  int rc = SQLITE_OK;
173008  int nCol = 0;
173009  int nRead = 0;
173010
173011  rc = sessionInputBuffer(pIn, 9);
173012  if( rc==SQLITE_OK ){
173013    nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
173014    rc = sessionInputBuffer(pIn, nRead+nCol+100);
173015    nRead += nCol;
173016  }
173017
173018  while( rc==SQLITE_OK ){
173019    while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
173020      nRead++;
173021    }
173022    if( (pIn->iNext + nRead)<pIn->nData ) break;
173023    rc = sessionInputBuffer(pIn, nRead + 100);
173024  }
173025  *pnByte = nRead+1;
173026  return rc;
173027}
173028
173029/*
173030** The input pointer currently points to the first byte of the first field
173031** of a record consisting of nCol columns. This function ensures the entire
173032** record is buffered. It does not move the input pointer.
173033**
173034** If successful, SQLITE_OK is returned and *pnByte is set to the size of
173035** the record in bytes. Otherwise, an SQLite error code is returned. The
173036** final value of *pnByte is undefined in this case.
173037*/
173038static int sessionChangesetBufferRecord(
173039  SessionInput *pIn,              /* Input data */
173040  int nCol,                       /* Number of columns in record */
173041  int *pnByte                     /* OUT: Size of record in bytes */
173042){
173043  int rc = SQLITE_OK;
173044  int nByte = 0;
173045  int i;
173046  for(i=0; rc==SQLITE_OK && i<nCol; i++){
173047    int eType;
173048    rc = sessionInputBuffer(pIn, nByte + 10);
173049    if( rc==SQLITE_OK ){
173050      eType = pIn->aData[pIn->iNext + nByte++];
173051      if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
173052        int n;
173053        nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
173054        nByte += n;
173055        rc = sessionInputBuffer(pIn, nByte);
173056      }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
173057        nByte += 8;
173058      }
173059    }
173060  }
173061  *pnByte = nByte;
173062  return rc;
173063}
173064
173065/*
173066** The input pointer currently points to the second byte of a table-header.
173067** Specifically, to the following:
173068**
173069**   + number of columns in table (varint)
173070**   + array of PK flags (1 byte per column),
173071**   + table name (nul terminated).
173072**
173073** This function decodes the table-header and populates the p->nCol,
173074** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
173075** also allocated or resized according to the new value of p->nCol. The
173076** input pointer is left pointing to the byte following the table header.
173077**
173078** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
173079** is returned and the final values of the various fields enumerated above
173080** are undefined.
173081*/
173082static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
173083  int rc;
173084  int nCopy;
173085  assert( p->rc==SQLITE_OK );
173086
173087  rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
173088  if( rc==SQLITE_OK ){
173089    int nByte;
173090    int nVarint;
173091    nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
173092    nCopy -= nVarint;
173093    p->in.iNext += nVarint;
173094    nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
173095    p->tblhdr.nBuf = 0;
173096    sessionBufferGrow(&p->tblhdr, nByte, &rc);
173097  }
173098
173099  if( rc==SQLITE_OK ){
173100    int iPK = sizeof(sqlite3_value*)*p->nCol*2;
173101    memset(p->tblhdr.aBuf, 0, iPK);
173102    memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
173103    p->in.iNext += nCopy;
173104  }
173105
173106  p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
173107  p->abPK = (u8*)&p->apValue[p->nCol*2];
173108  p->zTab = (char*)&p->abPK[p->nCol];
173109  return (p->rc = rc);
173110}
173111
173112/*
173113** Advance the changeset iterator to the next change.
173114**
173115** If both paRec and pnRec are NULL, then this function works like the public
173116** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
173117** sqlite3changeset_new() and old() APIs may be used to query for values.
173118**
173119** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
173120** record is written to *paRec before returning and the number of bytes in
173121** the record to *pnRec.
173122**
173123** Either way, this function returns SQLITE_ROW if the iterator is
173124** successfully advanced to the next change in the changeset, an SQLite
173125** error code if an error occurs, or SQLITE_DONE if there are no further
173126** changes in the changeset.
173127*/
173128static int sessionChangesetNext(
173129  sqlite3_changeset_iter *p,      /* Changeset iterator */
173130  u8 **paRec,                     /* If non-NULL, store record pointer here */
173131  int *pnRec                      /* If non-NULL, store size of record here */
173132){
173133  int i;
173134  u8 op;
173135
173136  assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
173137
173138  /* If the iterator is in the error-state, return immediately. */
173139  if( p->rc!=SQLITE_OK ) return p->rc;
173140
173141  /* Free the current contents of p->apValue[], if any. */
173142  if( p->apValue ){
173143    for(i=0; i<p->nCol*2; i++){
173144      sqlite3ValueFree(p->apValue[i]);
173145    }
173146    memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
173147  }
173148
173149  /* Make sure the buffer contains at least 10 bytes of input data, or all
173150  ** remaining data if there are less than 10 bytes available. This is
173151  ** sufficient either for the 'T' or 'P' byte and the varint that follows
173152  ** it, or for the two single byte values otherwise. */
173153  p->rc = sessionInputBuffer(&p->in, 2);
173154  if( p->rc!=SQLITE_OK ) return p->rc;
173155
173156  /* If the iterator is already at the end of the changeset, return DONE. */
173157  if( p->in.iNext>=p->in.nData ){
173158    return SQLITE_DONE;
173159  }
173160
173161  sessionDiscardData(&p->in);
173162  p->in.iCurrent = p->in.iNext;
173163
173164  op = p->in.aData[p->in.iNext++];
173165  if( op=='T' || op=='P' ){
173166    p->bPatchset = (op=='P');
173167    if( sessionChangesetReadTblhdr(p) ) return p->rc;
173168    if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
173169    p->in.iCurrent = p->in.iNext;
173170    op = p->in.aData[p->in.iNext++];
173171  }
173172
173173  p->op = op;
173174  p->bIndirect = p->in.aData[p->in.iNext++];
173175  if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
173176    return (p->rc = SQLITE_CORRUPT_BKPT);
173177  }
173178
173179  if( paRec ){
173180    int nVal;                     /* Number of values to buffer */
173181    if( p->bPatchset==0 && op==SQLITE_UPDATE ){
173182      nVal = p->nCol * 2;
173183    }else if( p->bPatchset && op==SQLITE_DELETE ){
173184      nVal = 0;
173185      for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
173186    }else{
173187      nVal = p->nCol;
173188    }
173189    p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
173190    if( p->rc!=SQLITE_OK ) return p->rc;
173191    *paRec = &p->in.aData[p->in.iNext];
173192    p->in.iNext += *pnRec;
173193  }else{
173194
173195    /* If this is an UPDATE or DELETE, read the old.* record. */
173196    if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
173197      u8 *abPK = p->bPatchset ? p->abPK : 0;
173198      p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
173199      if( p->rc!=SQLITE_OK ) return p->rc;
173200    }
173201
173202    /* If this is an INSERT or UPDATE, read the new.* record. */
173203    if( p->op!=SQLITE_DELETE ){
173204      p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
173205      if( p->rc!=SQLITE_OK ) return p->rc;
173206    }
173207
173208    if( p->bPatchset && p->op==SQLITE_UPDATE ){
173209      /* If this is an UPDATE that is part of a patchset, then all PK and
173210      ** modified fields are present in the new.* record. The old.* record
173211      ** is currently completely empty. This block shifts the PK fields from
173212      ** new.* to old.*, to accommodate the code that reads these arrays.  */
173213      for(i=0; i<p->nCol; i++){
173214        assert( p->apValue[i]==0 );
173215        assert( p->abPK[i]==0 || p->apValue[i+p->nCol] );
173216        if( p->abPK[i] ){
173217          p->apValue[i] = p->apValue[i+p->nCol];
173218          p->apValue[i+p->nCol] = 0;
173219        }
173220      }
173221    }
173222  }
173223
173224  return SQLITE_ROW;
173225}
173226
173227/*
173228** Advance an iterator created by sqlite3changeset_start() to the next
173229** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
173230** or SQLITE_CORRUPT.
173231**
173232** This function may not be called on iterators passed to a conflict handler
173233** callback by changeset_apply().
173234*/
173235SQLITE_API int SQLITE_STDCALL sqlite3changeset_next(sqlite3_changeset_iter *p){
173236  return sessionChangesetNext(p, 0, 0);
173237}
173238
173239/*
173240** The following function extracts information on the current change
173241** from a changeset iterator. It may only be called after changeset_next()
173242** has returned SQLITE_ROW.
173243*/
173244SQLITE_API int SQLITE_STDCALL sqlite3changeset_op(
173245  sqlite3_changeset_iter *pIter,  /* Iterator handle */
173246  const char **pzTab,             /* OUT: Pointer to table name */
173247  int *pnCol,                     /* OUT: Number of columns in table */
173248  int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
173249  int *pbIndirect                 /* OUT: True if change is indirect */
173250){
173251  *pOp = pIter->op;
173252  *pnCol = pIter->nCol;
173253  *pzTab = pIter->zTab;
173254  if( pbIndirect ) *pbIndirect = pIter->bIndirect;
173255  return SQLITE_OK;
173256}
173257
173258/*
173259** Return information regarding the PRIMARY KEY and number of columns in
173260** the database table affected by the change that pIter currently points
173261** to. This function may only be called after changeset_next() returns
173262** SQLITE_ROW.
173263*/
173264SQLITE_API int SQLITE_STDCALL sqlite3changeset_pk(
173265  sqlite3_changeset_iter *pIter,  /* Iterator object */
173266  unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
173267  int *pnCol                      /* OUT: Number of entries in output array */
173268){
173269  *pabPK = pIter->abPK;
173270  if( pnCol ) *pnCol = pIter->nCol;
173271  return SQLITE_OK;
173272}
173273
173274/*
173275** This function may only be called while the iterator is pointing to an
173276** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
173277** Otherwise, SQLITE_MISUSE is returned.
173278**
173279** It sets *ppValue to point to an sqlite3_value structure containing the
173280** iVal'th value in the old.* record. Or, if that particular value is not
173281** included in the record (because the change is an UPDATE and the field
173282** was not modified and is not a PK column), set *ppValue to NULL.
173283**
173284** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
173285** not modified. Otherwise, SQLITE_OK.
173286*/
173287SQLITE_API int SQLITE_STDCALL sqlite3changeset_old(
173288  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
173289  int iVal,                       /* Index of old.* value to retrieve */
173290  sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
173291){
173292  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
173293    return SQLITE_MISUSE;
173294  }
173295  if( iVal<0 || iVal>=pIter->nCol ){
173296    return SQLITE_RANGE;
173297  }
173298  *ppValue = pIter->apValue[iVal];
173299  return SQLITE_OK;
173300}
173301
173302/*
173303** This function may only be called while the iterator is pointing to an
173304** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
173305** Otherwise, SQLITE_MISUSE is returned.
173306**
173307** It sets *ppValue to point to an sqlite3_value structure containing the
173308** iVal'th value in the new.* record. Or, if that particular value is not
173309** included in the record (because the change is an UPDATE and the field
173310** was not modified), set *ppValue to NULL.
173311**
173312** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
173313** not modified. Otherwise, SQLITE_OK.
173314*/
173315SQLITE_API int SQLITE_STDCALL sqlite3changeset_new(
173316  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
173317  int iVal,                       /* Index of new.* value to retrieve */
173318  sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
173319){
173320  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
173321    return SQLITE_MISUSE;
173322  }
173323  if( iVal<0 || iVal>=pIter->nCol ){
173324    return SQLITE_RANGE;
173325  }
173326  *ppValue = pIter->apValue[pIter->nCol+iVal];
173327  return SQLITE_OK;
173328}
173329
173330/*
173331** The following two macros are used internally. They are similar to the
173332** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
173333** they omit all error checking and return a pointer to the requested value.
173334*/
173335#define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
173336#define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
173337
173338/*
173339** This function may only be called with a changeset iterator that has been
173340** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
173341** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
173342**
173343** If successful, *ppValue is set to point to an sqlite3_value structure
173344** containing the iVal'th value of the conflicting record.
173345**
173346** If value iVal is out-of-range or some other error occurs, an SQLite error
173347** code is returned. Otherwise, SQLITE_OK.
173348*/
173349SQLITE_API int SQLITE_STDCALL sqlite3changeset_conflict(
173350  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
173351  int iVal,                       /* Index of conflict record value to fetch */
173352  sqlite3_value **ppValue         /* OUT: Value from conflicting row */
173353){
173354  if( !pIter->pConflict ){
173355    return SQLITE_MISUSE;
173356  }
173357  if( iVal<0 || iVal>=sqlite3_column_count(pIter->pConflict) ){
173358    return SQLITE_RANGE;
173359  }
173360  *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
173361  return SQLITE_OK;
173362}
173363
173364/*
173365** This function may only be called with an iterator passed to an
173366** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
173367** it sets the output variable to the total number of known foreign key
173368** violations in the destination database and returns SQLITE_OK.
173369**
173370** In all other cases this function returns SQLITE_MISUSE.
173371*/
173372SQLITE_API int SQLITE_STDCALL sqlite3changeset_fk_conflicts(
173373  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
173374  int *pnOut                      /* OUT: Number of FK violations */
173375){
173376  if( pIter->pConflict || pIter->apValue ){
173377    return SQLITE_MISUSE;
173378  }
173379  *pnOut = pIter->nCol;
173380  return SQLITE_OK;
173381}
173382
173383
173384/*
173385** Finalize an iterator allocated with sqlite3changeset_start().
173386**
173387** This function may not be called on iterators passed to a conflict handler
173388** callback by changeset_apply().
173389*/
173390SQLITE_API int SQLITE_STDCALL sqlite3changeset_finalize(sqlite3_changeset_iter *p){
173391  int rc = SQLITE_OK;
173392  if( p ){
173393    int i;                        /* Used to iterate through p->apValue[] */
173394    rc = p->rc;
173395    if( p->apValue ){
173396      for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
173397    }
173398    sqlite3_free(p->tblhdr.aBuf);
173399    sqlite3_free(p->in.buf.aBuf);
173400    sqlite3_free(p);
173401  }
173402  return rc;
173403}
173404
173405static int sessionChangesetInvert(
173406  SessionInput *pInput,           /* Input changeset */
173407  int (*xOutput)(void *pOut, const void *pData, int nData),
173408  void *pOut,
173409  int *pnInverted,                /* OUT: Number of bytes in output changeset */
173410  void **ppInverted               /* OUT: Inverse of pChangeset */
173411){
173412  int rc = SQLITE_OK;             /* Return value */
173413  SessionBuffer sOut;             /* Output buffer */
173414  int nCol = 0;                   /* Number of cols in current table */
173415  u8 *abPK = 0;                   /* PK array for current table */
173416  sqlite3_value **apVal = 0;      /* Space for values for UPDATE inversion */
173417  SessionBuffer sPK = {0, 0, 0};  /* PK array for current table */
173418
173419  /* Initialize the output buffer */
173420  memset(&sOut, 0, sizeof(SessionBuffer));
173421
173422  /* Zero the output variables in case an error occurs. */
173423  if( ppInverted ){
173424    *ppInverted = 0;
173425    *pnInverted = 0;
173426  }
173427
173428  while( 1 ){
173429    u8 eType;
173430
173431    /* Test for EOF. */
173432    if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
173433    if( pInput->iNext>=pInput->nData ) break;
173434    eType = pInput->aData[pInput->iNext];
173435
173436    switch( eType ){
173437      case 'T': {
173438        /* A 'table' record consists of:
173439        **
173440        **   * A constant 'T' character,
173441        **   * Number of columns in said table (a varint),
173442        **   * An array of nCol bytes (sPK),
173443        **   * A nul-terminated table name.
173444        */
173445        int nByte;
173446        int nVar;
173447        pInput->iNext++;
173448        if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
173449          goto finished_invert;
173450        }
173451        nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
173452        sPK.nBuf = 0;
173453        sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
173454        sessionAppendByte(&sOut, eType, &rc);
173455        sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
173456        if( rc ) goto finished_invert;
173457
173458        pInput->iNext += nByte;
173459        sqlite3_free(apVal);
173460        apVal = 0;
173461        abPK = sPK.aBuf;
173462        break;
173463      }
173464
173465      case SQLITE_INSERT:
173466      case SQLITE_DELETE: {
173467        int nByte;
173468        int bIndirect = pInput->aData[pInput->iNext+1];
173469        int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
173470        pInput->iNext += 2;
173471        assert( rc==SQLITE_OK );
173472        rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
173473        sessionAppendByte(&sOut, eType2, &rc);
173474        sessionAppendByte(&sOut, bIndirect, &rc);
173475        sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
173476        pInput->iNext += nByte;
173477        if( rc ) goto finished_invert;
173478        break;
173479      }
173480
173481      case SQLITE_UPDATE: {
173482        int iCol;
173483
173484        if( 0==apVal ){
173485          apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
173486          if( 0==apVal ){
173487            rc = SQLITE_NOMEM;
173488            goto finished_invert;
173489          }
173490          memset(apVal, 0, sizeof(apVal[0])*nCol*2);
173491        }
173492
173493        /* Write the header for the new UPDATE change. Same as the original. */
173494        sessionAppendByte(&sOut, eType, &rc);
173495        sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
173496
173497        /* Read the old.* and new.* records for the update change. */
173498        pInput->iNext += 2;
173499        rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
173500        if( rc==SQLITE_OK ){
173501          rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
173502        }
173503
173504        /* Write the new old.* record. Consists of the PK columns from the
173505        ** original old.* record, and the other values from the original
173506        ** new.* record. */
173507        for(iCol=0; iCol<nCol; iCol++){
173508          sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
173509          sessionAppendValue(&sOut, pVal, &rc);
173510        }
173511
173512        /* Write the new new.* record. Consists of a copy of all values
173513        ** from the original old.* record, except for the PK columns, which
173514        ** are set to "undefined". */
173515        for(iCol=0; iCol<nCol; iCol++){
173516          sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
173517          sessionAppendValue(&sOut, pVal, &rc);
173518        }
173519
173520        for(iCol=0; iCol<nCol*2; iCol++){
173521          sqlite3ValueFree(apVal[iCol]);
173522        }
173523        memset(apVal, 0, sizeof(apVal[0])*nCol*2);
173524        if( rc!=SQLITE_OK ){
173525          goto finished_invert;
173526        }
173527
173528        break;
173529      }
173530
173531      default:
173532        rc = SQLITE_CORRUPT_BKPT;
173533        goto finished_invert;
173534    }
173535
173536    assert( rc==SQLITE_OK );
173537    if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
173538      rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
173539      sOut.nBuf = 0;
173540      if( rc!=SQLITE_OK ) goto finished_invert;
173541    }
173542  }
173543
173544  assert( rc==SQLITE_OK );
173545  if( pnInverted ){
173546    *pnInverted = sOut.nBuf;
173547    *ppInverted = sOut.aBuf;
173548    sOut.aBuf = 0;
173549  }else if( sOut.nBuf>0 ){
173550    rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
173551  }
173552
173553 finished_invert:
173554  sqlite3_free(sOut.aBuf);
173555  sqlite3_free(apVal);
173556  sqlite3_free(sPK.aBuf);
173557  return rc;
173558}
173559
173560
173561/*
173562** Invert a changeset object.
173563*/
173564SQLITE_API int SQLITE_STDCALL sqlite3changeset_invert(
173565  int nChangeset,                 /* Number of bytes in input */
173566  const void *pChangeset,         /* Input changeset */
173567  int *pnInverted,                /* OUT: Number of bytes in output changeset */
173568  void **ppInverted               /* OUT: Inverse of pChangeset */
173569){
173570  SessionInput sInput;
173571
173572  /* Set up the input stream */
173573  memset(&sInput, 0, sizeof(SessionInput));
173574  sInput.nData = nChangeset;
173575  sInput.aData = (u8*)pChangeset;
173576
173577  return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
173578}
173579
173580/*
173581** Streaming version of sqlite3changeset_invert().
173582*/
173583SQLITE_API int SQLITE_STDCALL sqlite3changeset_invert_strm(
173584  int (*xInput)(void *pIn, void *pData, int *pnData),
173585  void *pIn,
173586  int (*xOutput)(void *pOut, const void *pData, int nData),
173587  void *pOut
173588){
173589  SessionInput sInput;
173590  int rc;
173591
173592  /* Set up the input stream */
173593  memset(&sInput, 0, sizeof(SessionInput));
173594  sInput.xInput = xInput;
173595  sInput.pIn = pIn;
173596
173597  rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
173598  sqlite3_free(sInput.buf.aBuf);
173599  return rc;
173600}
173601
173602typedef struct SessionApplyCtx SessionApplyCtx;
173603struct SessionApplyCtx {
173604  sqlite3 *db;
173605  sqlite3_stmt *pDelete;          /* DELETE statement */
173606  sqlite3_stmt *pUpdate;          /* UPDATE statement */
173607  sqlite3_stmt *pInsert;          /* INSERT statement */
173608  sqlite3_stmt *pSelect;          /* SELECT statement */
173609  int nCol;                       /* Size of azCol[] and abPK[] arrays */
173610  const char **azCol;             /* Array of column names */
173611  u8 *abPK;                       /* Boolean array - true if column is in PK */
173612
173613  int bDeferConstraints;          /* True to defer constraints */
173614  SessionBuffer constraints;      /* Deferred constraints are stored here */
173615};
173616
173617/*
173618** Formulate a statement to DELETE a row from database db. Assuming a table
173619** structure like this:
173620**
173621**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
173622**
173623** The DELETE statement looks like this:
173624**
173625**     DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
173626**
173627** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
173628** matching b and d values, or 1 otherwise. The second case comes up if the
173629** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
173630**
173631** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
173632** pointing to the prepared version of the SQL statement.
173633*/
173634static int sessionDeleteRow(
173635  sqlite3 *db,                    /* Database handle */
173636  const char *zTab,               /* Table name */
173637  SessionApplyCtx *p              /* Session changeset-apply context */
173638){
173639  int i;
173640  const char *zSep = "";
173641  int rc = SQLITE_OK;
173642  SessionBuffer buf = {0, 0, 0};
173643  int nPk = 0;
173644
173645  sessionAppendStr(&buf, "DELETE FROM ", &rc);
173646  sessionAppendIdent(&buf, zTab, &rc);
173647  sessionAppendStr(&buf, " WHERE ", &rc);
173648
173649  for(i=0; i<p->nCol; i++){
173650    if( p->abPK[i] ){
173651      nPk++;
173652      sessionAppendStr(&buf, zSep, &rc);
173653      sessionAppendIdent(&buf, p->azCol[i], &rc);
173654      sessionAppendStr(&buf, " = ?", &rc);
173655      sessionAppendInteger(&buf, i+1, &rc);
173656      zSep = " AND ";
173657    }
173658  }
173659
173660  if( nPk<p->nCol ){
173661    sessionAppendStr(&buf, " AND (?", &rc);
173662    sessionAppendInteger(&buf, p->nCol+1, &rc);
173663    sessionAppendStr(&buf, " OR ", &rc);
173664
173665    zSep = "";
173666    for(i=0; i<p->nCol; i++){
173667      if( !p->abPK[i] ){
173668        sessionAppendStr(&buf, zSep, &rc);
173669        sessionAppendIdent(&buf, p->azCol[i], &rc);
173670        sessionAppendStr(&buf, " IS ?", &rc);
173671        sessionAppendInteger(&buf, i+1, &rc);
173672        zSep = "AND ";
173673      }
173674    }
173675    sessionAppendStr(&buf, ")", &rc);
173676  }
173677
173678  if( rc==SQLITE_OK ){
173679    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
173680  }
173681  sqlite3_free(buf.aBuf);
173682
173683  return rc;
173684}
173685
173686/*
173687** Formulate and prepare a statement to UPDATE a row from database db.
173688** Assuming a table structure like this:
173689**
173690**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
173691**
173692** The UPDATE statement looks like this:
173693**
173694**     UPDATE x SET
173695**     a = CASE WHEN ?2  THEN ?3  ELSE a END,
173696**     b = CASE WHEN ?5  THEN ?6  ELSE b END,
173697**     c = CASE WHEN ?8  THEN ?9  ELSE c END,
173698**     d = CASE WHEN ?11 THEN ?12 ELSE d END
173699**     WHERE a = ?1 AND c = ?7 AND (?13 OR
173700**       (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
173701**     )
173702**
173703** For each column in the table, there are three variables to bind:
173704**
173705**     ?(i*3+1)    The old.* value of the column, if any.
173706**     ?(i*3+2)    A boolean flag indicating that the value is being modified.
173707**     ?(i*3+3)    The new.* value of the column, if any.
173708**
173709** Also, a boolean flag that, if set to true, causes the statement to update
173710** a row even if the non-PK values do not match. This is required if the
173711** conflict-handler is invoked with CHANGESET_DATA and returns
173712** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
173713**
173714** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
173715** pointing to the prepared version of the SQL statement.
173716*/
173717static int sessionUpdateRow(
173718  sqlite3 *db,                    /* Database handle */
173719  const char *zTab,               /* Table name */
173720  SessionApplyCtx *p              /* Session changeset-apply context */
173721){
173722  int rc = SQLITE_OK;
173723  int i;
173724  const char *zSep = "";
173725  SessionBuffer buf = {0, 0, 0};
173726
173727  /* Append "UPDATE tbl SET " */
173728  sessionAppendStr(&buf, "UPDATE ", &rc);
173729  sessionAppendIdent(&buf, zTab, &rc);
173730  sessionAppendStr(&buf, " SET ", &rc);
173731
173732  /* Append the assignments */
173733  for(i=0; i<p->nCol; i++){
173734    sessionAppendStr(&buf, zSep, &rc);
173735    sessionAppendIdent(&buf, p->azCol[i], &rc);
173736    sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
173737    sessionAppendInteger(&buf, i*3+2, &rc);
173738    sessionAppendStr(&buf, " THEN ?", &rc);
173739    sessionAppendInteger(&buf, i*3+3, &rc);
173740    sessionAppendStr(&buf, " ELSE ", &rc);
173741    sessionAppendIdent(&buf, p->azCol[i], &rc);
173742    sessionAppendStr(&buf, " END", &rc);
173743    zSep = ", ";
173744  }
173745
173746  /* Append the PK part of the WHERE clause */
173747  sessionAppendStr(&buf, " WHERE ", &rc);
173748  for(i=0; i<p->nCol; i++){
173749    if( p->abPK[i] ){
173750      sessionAppendIdent(&buf, p->azCol[i], &rc);
173751      sessionAppendStr(&buf, " = ?", &rc);
173752      sessionAppendInteger(&buf, i*3+1, &rc);
173753      sessionAppendStr(&buf, " AND ", &rc);
173754    }
173755  }
173756
173757  /* Append the non-PK part of the WHERE clause */
173758  sessionAppendStr(&buf, " (?", &rc);
173759  sessionAppendInteger(&buf, p->nCol*3+1, &rc);
173760  sessionAppendStr(&buf, " OR 1", &rc);
173761  for(i=0; i<p->nCol; i++){
173762    if( !p->abPK[i] ){
173763      sessionAppendStr(&buf, " AND (?", &rc);
173764      sessionAppendInteger(&buf, i*3+2, &rc);
173765      sessionAppendStr(&buf, "=0 OR ", &rc);
173766      sessionAppendIdent(&buf, p->azCol[i], &rc);
173767      sessionAppendStr(&buf, " IS ?", &rc);
173768      sessionAppendInteger(&buf, i*3+1, &rc);
173769      sessionAppendStr(&buf, ")", &rc);
173770    }
173771  }
173772  sessionAppendStr(&buf, ")", &rc);
173773
173774  if( rc==SQLITE_OK ){
173775    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
173776  }
173777  sqlite3_free(buf.aBuf);
173778
173779  return rc;
173780}
173781
173782/*
173783** Formulate and prepare an SQL statement to query table zTab by primary
173784** key. Assuming the following table structure:
173785**
173786**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
173787**
173788** The SELECT statement looks like this:
173789**
173790**     SELECT * FROM x WHERE a = ?1 AND c = ?3
173791**
173792** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
173793** pointing to the prepared version of the SQL statement.
173794*/
173795static int sessionSelectRow(
173796  sqlite3 *db,                    /* Database handle */
173797  const char *zTab,               /* Table name */
173798  SessionApplyCtx *p              /* Session changeset-apply context */
173799){
173800  return sessionSelectStmt(
173801      db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
173802}
173803
173804/*
173805** Formulate and prepare an INSERT statement to add a record to table zTab.
173806** For example:
173807**
173808**     INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
173809**
173810** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
173811** pointing to the prepared version of the SQL statement.
173812*/
173813static int sessionInsertRow(
173814  sqlite3 *db,                    /* Database handle */
173815  const char *zTab,               /* Table name */
173816  SessionApplyCtx *p              /* Session changeset-apply context */
173817){
173818  int rc = SQLITE_OK;
173819  int i;
173820  SessionBuffer buf = {0, 0, 0};
173821
173822  sessionAppendStr(&buf, "INSERT INTO main.", &rc);
173823  sessionAppendIdent(&buf, zTab, &rc);
173824  sessionAppendStr(&buf, " VALUES(?", &rc);
173825  for(i=1; i<p->nCol; i++){
173826    sessionAppendStr(&buf, ", ?", &rc);
173827  }
173828  sessionAppendStr(&buf, ")", &rc);
173829
173830  if( rc==SQLITE_OK ){
173831    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
173832  }
173833  sqlite3_free(buf.aBuf);
173834  return rc;
173835}
173836
173837/*
173838** A wrapper around sqlite3_bind_value() that detects an extra problem.
173839** See comments in the body of this function for details.
173840*/
173841static int sessionBindValue(
173842  sqlite3_stmt *pStmt,            /* Statement to bind value to */
173843  int i,                          /* Parameter number to bind to */
173844  sqlite3_value *pVal             /* Value to bind */
173845){
173846  int eType = sqlite3_value_type(pVal);
173847  /* COVERAGE: The (pVal->z==0) branch is never true using current versions
173848  ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
173849  ** the (pVal->z) variable remains as it was or the type of the value is
173850  ** set to SQLITE_NULL.  */
173851  if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
173852    /* This condition occurs when an earlier OOM in a call to
173853    ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
173854    ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
173855    return SQLITE_NOMEM;
173856  }
173857  return sqlite3_bind_value(pStmt, i, pVal);
173858}
173859
173860/*
173861** Iterator pIter must point to an SQLITE_INSERT entry. This function
173862** transfers new.* values from the current iterator entry to statement
173863** pStmt. The table being inserted into has nCol columns.
173864**
173865** New.* value $i from the iterator is bound to variable ($i+1) of
173866** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
173867** are transfered to the statement. Otherwise, if abPK is not NULL, it points
173868** to an array nCol elements in size. In this case only those values for
173869** which abPK[$i] is true are read from the iterator and bound to the
173870** statement.
173871**
173872** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
173873*/
173874static int sessionBindRow(
173875  sqlite3_changeset_iter *pIter,  /* Iterator to read values from */
173876  int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
173877  int nCol,                       /* Number of columns */
173878  u8 *abPK,                       /* If not NULL, bind only if true */
173879  sqlite3_stmt *pStmt             /* Bind values to this statement */
173880){
173881  int i;
173882  int rc = SQLITE_OK;
173883
173884  /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
173885  ** argument iterator points to a suitable entry. Make sure that xValue
173886  ** is one of these to guarantee that it is safe to ignore the return
173887  ** in the code below. */
173888  assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
173889
173890  for(i=0; rc==SQLITE_OK && i<nCol; i++){
173891    if( !abPK || abPK[i] ){
173892      sqlite3_value *pVal;
173893      (void)xValue(pIter, i, &pVal);
173894      rc = sessionBindValue(pStmt, i+1, pVal);
173895    }
173896  }
173897  return rc;
173898}
173899
173900/*
173901** SQL statement pSelect is as generated by the sessionSelectRow() function.
173902** This function binds the primary key values from the change that changeset
173903** iterator pIter points to to the SELECT and attempts to seek to the table
173904** entry. If a row is found, the SELECT statement left pointing at the row
173905** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
173906** has occured, the statement is reset and SQLITE_OK is returned. If an
173907** error occurs, the statement is reset and an SQLite error code is returned.
173908**
173909** If this function returns SQLITE_ROW, the caller must eventually reset()
173910** statement pSelect. If any other value is returned, the statement does
173911** not require a reset().
173912**
173913** If the iterator currently points to an INSERT record, bind values from the
173914** new.* record to the SELECT statement. Or, if it points to a DELETE or
173915** UPDATE, bind values from the old.* record.
173916*/
173917static int sessionSeekToRow(
173918  sqlite3 *db,                    /* Database handle */
173919  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
173920  u8 *abPK,                       /* Primary key flags array */
173921  sqlite3_stmt *pSelect           /* SELECT statement from sessionSelectRow() */
173922){
173923  int rc;                         /* Return code */
173924  int nCol;                       /* Number of columns in table */
173925  int op;                         /* Changset operation (SQLITE_UPDATE etc.) */
173926  const char *zDummy;             /* Unused */
173927
173928  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
173929  rc = sessionBindRow(pIter,
173930      op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
173931      nCol, abPK, pSelect
173932  );
173933
173934  if( rc==SQLITE_OK ){
173935    rc = sqlite3_step(pSelect);
173936    if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
173937  }
173938
173939  return rc;
173940}
173941
173942/*
173943** Invoke the conflict handler for the change that the changeset iterator
173944** currently points to.
173945**
173946** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
173947** If argument pbReplace is NULL, then the type of conflict handler invoked
173948** depends solely on eType, as follows:
173949**
173950**    eType value                 Value passed to xConflict
173951**    -------------------------------------------------
173952**    CHANGESET_DATA              CHANGESET_NOTFOUND
173953**    CHANGESET_CONFLICT          CHANGESET_CONSTRAINT
173954**
173955** Or, if pbReplace is not NULL, then an attempt is made to find an existing
173956** record with the same primary key as the record about to be deleted, updated
173957** or inserted. If such a record can be found, it is available to the conflict
173958** handler as the "conflicting" record. In this case the type of conflict
173959** handler invoked is as follows:
173960**
173961**    eType value         PK Record found?   Value passed to xConflict
173962**    ----------------------------------------------------------------
173963**    CHANGESET_DATA      Yes                CHANGESET_DATA
173964**    CHANGESET_DATA      No                 CHANGESET_NOTFOUND
173965**    CHANGESET_CONFLICT  Yes                CHANGESET_CONFLICT
173966**    CHANGESET_CONFLICT  No                 CHANGESET_CONSTRAINT
173967**
173968** If pbReplace is not NULL, and a record with a matching PK is found, and
173969** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
173970** is set to non-zero before returning SQLITE_OK.
173971**
173972** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
173973** returned. Or, if the conflict handler returns an invalid value,
173974** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
173975** this function returns SQLITE_OK.
173976*/
173977static int sessionConflictHandler(
173978  int eType,                      /* Either CHANGESET_DATA or CONFLICT */
173979  SessionApplyCtx *p,             /* changeset_apply() context */
173980  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
173981  int(*xConflict)(void *, int, sqlite3_changeset_iter*),
173982  void *pCtx,                     /* First argument for conflict handler */
173983  int *pbReplace                  /* OUT: Set to true if PK row is found */
173984){
173985  int res = 0;                    /* Value returned by conflict handler */
173986  int rc;
173987  int nCol;
173988  int op;
173989  const char *zDummy;
173990
173991  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
173992
173993  assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
173994  assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
173995  assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
173996
173997  /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
173998  if( pbReplace ){
173999    rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
174000  }else{
174001    rc = SQLITE_OK;
174002  }
174003
174004  if( rc==SQLITE_ROW ){
174005    /* There exists another row with the new.* primary key. */
174006    pIter->pConflict = p->pSelect;
174007    res = xConflict(pCtx, eType, pIter);
174008    pIter->pConflict = 0;
174009    rc = sqlite3_reset(p->pSelect);
174010  }else if( rc==SQLITE_OK ){
174011    if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
174012      /* Instead of invoking the conflict handler, append the change blob
174013      ** to the SessionApplyCtx.constraints buffer. */
174014      u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
174015      int nBlob = pIter->in.iNext - pIter->in.iCurrent;
174016      sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
174017      res = SQLITE_CHANGESET_OMIT;
174018    }else{
174019      /* No other row with the new.* primary key. */
174020      res = xConflict(pCtx, eType+1, pIter);
174021      if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
174022    }
174023  }
174024
174025  if( rc==SQLITE_OK ){
174026    switch( res ){
174027      case SQLITE_CHANGESET_REPLACE:
174028        assert( pbReplace );
174029        *pbReplace = 1;
174030        break;
174031
174032      case SQLITE_CHANGESET_OMIT:
174033        break;
174034
174035      case SQLITE_CHANGESET_ABORT:
174036        rc = SQLITE_ABORT;
174037        break;
174038
174039      default:
174040        rc = SQLITE_MISUSE;
174041        break;
174042    }
174043  }
174044
174045  return rc;
174046}
174047
174048/*
174049** Attempt to apply the change that the iterator passed as the first argument
174050** currently points to to the database. If a conflict is encountered, invoke
174051** the conflict handler callback.
174052**
174053** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
174054** one is encountered, update or delete the row with the matching primary key
174055** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
174056** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
174057** to true before returning. In this case the caller will invoke this function
174058** again, this time with pbRetry set to NULL.
174059**
174060** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
174061** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
174062** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
174063** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
174064** before retrying. In this case the caller attempts to remove the conflicting
174065** row before invoking this function again, this time with pbReplace set
174066** to NULL.
174067**
174068** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
174069** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
174070** returned.
174071*/
174072static int sessionApplyOneOp(
174073  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
174074  SessionApplyCtx *p,             /* changeset_apply() context */
174075  int(*xConflict)(void *, int, sqlite3_changeset_iter *),
174076  void *pCtx,                     /* First argument for the conflict handler */
174077  int *pbReplace,                 /* OUT: True to remove PK row and retry */
174078  int *pbRetry                    /* OUT: True to retry. */
174079){
174080  const char *zDummy;
174081  int op;
174082  int nCol;
174083  int rc = SQLITE_OK;
174084
174085  assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
174086  assert( p->azCol && p->abPK );
174087  assert( !pbReplace || *pbReplace==0 );
174088
174089  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
174090
174091  if( op==SQLITE_DELETE ){
174092
174093    /* Bind values to the DELETE statement. If conflict handling is required,
174094    ** bind values for all columns and set bound variable (nCol+1) to true.
174095    ** Or, if conflict handling is not required, bind just the PK column
174096    ** values and, if it exists, set (nCol+1) to false. Conflict handling
174097    ** is not required if:
174098    **
174099    **   * this is a patchset, or
174100    **   * (pbRetry==0), or
174101    **   * all columns of the table are PK columns (in this case there is
174102    **     no (nCol+1) variable to bind to).
174103    */
174104    u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
174105    rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
174106    if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
174107      rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
174108    }
174109    if( rc!=SQLITE_OK ) return rc;
174110
174111    sqlite3_step(p->pDelete);
174112    rc = sqlite3_reset(p->pDelete);
174113    if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
174114      rc = sessionConflictHandler(
174115          SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
174116      );
174117    }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
174118      rc = sessionConflictHandler(
174119          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
174120      );
174121    }
174122
174123  }else if( op==SQLITE_UPDATE ){
174124    int i;
174125
174126    /* Bind values to the UPDATE statement. */
174127    for(i=0; rc==SQLITE_OK && i<nCol; i++){
174128      sqlite3_value *pOld = sessionChangesetOld(pIter, i);
174129      sqlite3_value *pNew = sessionChangesetNew(pIter, i);
174130
174131      sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
174132      if( pOld ){
174133        rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
174134      }
174135      if( rc==SQLITE_OK && pNew ){
174136        rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
174137      }
174138    }
174139    if( rc==SQLITE_OK ){
174140      sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
174141    }
174142    if( rc!=SQLITE_OK ) return rc;
174143
174144    /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
174145    ** the result will be SQLITE_OK with 0 rows modified. */
174146    sqlite3_step(p->pUpdate);
174147    rc = sqlite3_reset(p->pUpdate);
174148
174149    if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
174150      /* A NOTFOUND or DATA error. Search the table to see if it contains
174151      ** a row with a matching primary key. If so, this is a DATA conflict.
174152      ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
174153
174154      rc = sessionConflictHandler(
174155          SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
174156      );
174157
174158    }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
174159      /* This is always a CONSTRAINT conflict. */
174160      rc = sessionConflictHandler(
174161          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
174162      );
174163    }
174164
174165  }else{
174166    assert( op==SQLITE_INSERT );
174167    rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
174168    if( rc!=SQLITE_OK ) return rc;
174169
174170    sqlite3_step(p->pInsert);
174171    rc = sqlite3_reset(p->pInsert);
174172    if( (rc&0xff)==SQLITE_CONSTRAINT ){
174173      rc = sessionConflictHandler(
174174          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
174175      );
174176    }
174177  }
174178
174179  return rc;
174180}
174181
174182/*
174183** Attempt to apply the change that the iterator passed as the first argument
174184** currently points to to the database. If a conflict is encountered, invoke
174185** the conflict handler callback.
174186**
174187** The difference between this function and sessionApplyOne() is that this
174188** function handles the case where the conflict-handler is invoked and
174189** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
174190** retried in some manner.
174191*/
174192static int sessionApplyOneWithRetry(
174193  sqlite3 *db,                    /* Apply change to "main" db of this handle */
174194  sqlite3_changeset_iter *pIter,  /* Changeset iterator to read change from */
174195  SessionApplyCtx *pApply,        /* Apply context */
174196  int(*xConflict)(void*, int, sqlite3_changeset_iter*),
174197  void *pCtx                      /* First argument passed to xConflict */
174198){
174199  int bReplace = 0;
174200  int bRetry = 0;
174201  int rc;
174202
174203  rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
174204  assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
174205
174206  /* If the bRetry flag is set, the change has not been applied due to an
174207  ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
174208  ** a row with the correct PK is present in the db, but one or more other
174209  ** fields do not contain the expected values) and the conflict handler
174210  ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
174211  ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
174212  ** the SQLITE_CHANGESET_DATA problem.  */
174213  if( bRetry ){
174214    assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
174215    rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
174216  }
174217
174218  /* If the bReplace flag is set, the change is an INSERT that has not
174219  ** been performed because the database already contains a row with the
174220  ** specified primary key and the conflict handler returned
174221  ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
174222  ** before reattempting the INSERT.  */
174223  else if( bReplace ){
174224    assert( pIter->op==SQLITE_INSERT );
174225    rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
174226    if( rc==SQLITE_OK ){
174227      rc = sessionBindRow(pIter,
174228          sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
174229      sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
174230    }
174231    if( rc==SQLITE_OK ){
174232      sqlite3_step(pApply->pDelete);
174233      rc = sqlite3_reset(pApply->pDelete);
174234    }
174235    if( rc==SQLITE_OK ){
174236      rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
174237    }
174238    if( rc==SQLITE_OK ){
174239      rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
174240    }
174241  }
174242
174243  return rc;
174244}
174245
174246/*
174247** Retry the changes accumulated in the pApply->constraints buffer.
174248*/
174249static int sessionRetryConstraints(
174250  sqlite3 *db,
174251  int bPatchset,
174252  const char *zTab,
174253  SessionApplyCtx *pApply,
174254  int(*xConflict)(void*, int, sqlite3_changeset_iter*),
174255  void *pCtx                      /* First argument passed to xConflict */
174256){
174257  int rc = SQLITE_OK;
174258
174259  while( pApply->constraints.nBuf ){
174260    sqlite3_changeset_iter *pIter2 = 0;
174261    SessionBuffer cons = pApply->constraints;
174262    memset(&pApply->constraints, 0, sizeof(SessionBuffer));
174263
174264    rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
174265    if( rc==SQLITE_OK ){
174266      int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
174267      int rc2;
174268      pIter2->bPatchset = bPatchset;
174269      pIter2->zTab = (char*)zTab;
174270      pIter2->nCol = pApply->nCol;
174271      pIter2->abPK = pApply->abPK;
174272      sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
174273      pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
174274      if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
174275
174276      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
174277        rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
174278      }
174279
174280      rc2 = sqlite3changeset_finalize(pIter2);
174281      if( rc==SQLITE_OK ) rc = rc2;
174282    }
174283    assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
174284
174285    sqlite3_free(cons.aBuf);
174286    if( rc!=SQLITE_OK ) break;
174287    if( pApply->constraints.nBuf>=cons.nBuf ){
174288      /* No progress was made on the last round. */
174289      pApply->bDeferConstraints = 0;
174290    }
174291  }
174292
174293  return rc;
174294}
174295
174296/*
174297** Argument pIter is a changeset iterator that has been initialized, but
174298** not yet passed to sqlite3changeset_next(). This function applies the
174299** changeset to the main database attached to handle "db". The supplied
174300** conflict handler callback is invoked to resolve any conflicts encountered
174301** while applying the change.
174302*/
174303static int sessionChangesetApply(
174304  sqlite3 *db,                    /* Apply change to "main" db of this handle */
174305  sqlite3_changeset_iter *pIter,  /* Changeset to apply */
174306  int(*xFilter)(
174307    void *pCtx,                   /* Copy of sixth arg to _apply() */
174308    const char *zTab              /* Table name */
174309  ),
174310  int(*xConflict)(
174311    void *pCtx,                   /* Copy of fifth arg to _apply() */
174312    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
174313    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
174314  ),
174315  void *pCtx                      /* First argument passed to xConflict */
174316){
174317  int schemaMismatch = 0;
174318  int rc;                         /* Return code */
174319  const char *zTab = 0;           /* Name of current table */
174320  int nTab = 0;                   /* Result of sqlite3Strlen30(zTab) */
174321  SessionApplyCtx sApply;         /* changeset_apply() context object */
174322  int bPatchset;
174323
174324  assert( xConflict!=0 );
174325
174326  pIter->in.bNoDiscard = 1;
174327  memset(&sApply, 0, sizeof(sApply));
174328  sqlite3_mutex_enter(sqlite3_db_mutex(db));
174329  rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
174330  if( rc==SQLITE_OK ){
174331    rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
174332  }
174333  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
174334    int nCol;
174335    int op;
174336    const char *zNew;
174337
174338    sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
174339
174340    if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
174341      u8 *abPK;
174342
174343      rc = sessionRetryConstraints(
174344          db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
174345      );
174346      if( rc!=SQLITE_OK ) break;
174347
174348      sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
174349      sqlite3_finalize(sApply.pDelete);
174350      sqlite3_finalize(sApply.pUpdate);
174351      sqlite3_finalize(sApply.pInsert);
174352      sqlite3_finalize(sApply.pSelect);
174353      memset(&sApply, 0, sizeof(sApply));
174354      sApply.db = db;
174355      sApply.bDeferConstraints = 1;
174356
174357      /* If an xFilter() callback was specified, invoke it now. If the
174358      ** xFilter callback returns zero, skip this table. If it returns
174359      ** non-zero, proceed. */
174360      schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
174361      if( schemaMismatch ){
174362        zTab = sqlite3_mprintf("%s", zNew);
174363        if( zTab==0 ){
174364          rc = SQLITE_NOMEM;
174365          break;
174366        }
174367        nTab = (int)strlen(zTab);
174368        sApply.azCol = (const char **)zTab;
174369      }else{
174370        sqlite3changeset_pk(pIter, &abPK, 0);
174371        rc = sessionTableInfo(
174372            db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
174373        );
174374        if( rc!=SQLITE_OK ) break;
174375
174376        if( sApply.nCol==0 ){
174377          schemaMismatch = 1;
174378          sqlite3_log(SQLITE_SCHEMA,
174379              "sqlite3changeset_apply(): no such table: %s", zTab
174380          );
174381        }
174382        else if( sApply.nCol!=nCol ){
174383          schemaMismatch = 1;
174384          sqlite3_log(SQLITE_SCHEMA,
174385              "sqlite3changeset_apply(): table %s has %d columns, expected %d",
174386              zTab, sApply.nCol, nCol
174387          );
174388        }
174389        else if( memcmp(sApply.abPK, abPK, nCol)!=0 ){
174390          schemaMismatch = 1;
174391          sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
174392              "primary key mismatch for table %s", zTab
174393          );
174394        }
174395        else if(
174396            (rc = sessionSelectRow(db, zTab, &sApply))
174397         || (rc = sessionUpdateRow(db, zTab, &sApply))
174398         || (rc = sessionDeleteRow(db, zTab, &sApply))
174399         || (rc = sessionInsertRow(db, zTab, &sApply))
174400        ){
174401          break;
174402        }
174403        nTab = sqlite3Strlen30(zTab);
174404      }
174405    }
174406
174407    /* If there is a schema mismatch on the current table, proceed to the
174408    ** next change. A log message has already been issued. */
174409    if( schemaMismatch ) continue;
174410
174411    rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
174412  }
174413
174414  bPatchset = pIter->bPatchset;
174415  if( rc==SQLITE_OK ){
174416    rc = sqlite3changeset_finalize(pIter);
174417  }else{
174418    sqlite3changeset_finalize(pIter);
174419  }
174420
174421  if( rc==SQLITE_OK ){
174422    rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
174423  }
174424
174425  if( rc==SQLITE_OK ){
174426    int nFk, notUsed;
174427    sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
174428    if( nFk!=0 ){
174429      int res = SQLITE_CHANGESET_ABORT;
174430      sqlite3_changeset_iter sIter;
174431      memset(&sIter, 0, sizeof(sIter));
174432      sIter.nCol = nFk;
174433      res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
174434      if( res!=SQLITE_CHANGESET_OMIT ){
174435        rc = SQLITE_CONSTRAINT;
174436      }
174437    }
174438  }
174439  sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
174440
174441  if( rc==SQLITE_OK ){
174442    rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
174443  }else{
174444    sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
174445    sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
174446  }
174447
174448  sqlite3_finalize(sApply.pInsert);
174449  sqlite3_finalize(sApply.pDelete);
174450  sqlite3_finalize(sApply.pUpdate);
174451  sqlite3_finalize(sApply.pSelect);
174452  sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
174453  sqlite3_free((char*)sApply.constraints.aBuf);
174454  sqlite3_mutex_leave(sqlite3_db_mutex(db));
174455  return rc;
174456}
174457
174458/*
174459** Apply the changeset passed via pChangeset/nChangeset to the main database
174460** attached to handle "db". Invoke the supplied conflict handler callback
174461** to resolve any conflicts encountered while applying the change.
174462*/
174463SQLITE_API int SQLITE_STDCALL sqlite3changeset_apply(
174464  sqlite3 *db,                    /* Apply change to "main" db of this handle */
174465  int nChangeset,                 /* Size of changeset in bytes */
174466  void *pChangeset,               /* Changeset blob */
174467  int(*xFilter)(
174468    void *pCtx,                   /* Copy of sixth arg to _apply() */
174469    const char *zTab              /* Table name */
174470  ),
174471  int(*xConflict)(
174472    void *pCtx,                   /* Copy of fifth arg to _apply() */
174473    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
174474    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
174475  ),
174476  void *pCtx                      /* First argument passed to xConflict */
174477){
174478  sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */
174479  int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
174480  if( rc==SQLITE_OK ){
174481    rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
174482  }
174483  return rc;
174484}
174485
174486/*
174487** Apply the changeset passed via xInput/pIn to the main database
174488** attached to handle "db". Invoke the supplied conflict handler callback
174489** to resolve any conflicts encountered while applying the change.
174490*/
174491SQLITE_API int SQLITE_STDCALL sqlite3changeset_apply_strm(
174492  sqlite3 *db,                    /* Apply change to "main" db of this handle */
174493  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
174494  void *pIn,                                          /* First arg for xInput */
174495  int(*xFilter)(
174496    void *pCtx,                   /* Copy of sixth arg to _apply() */
174497    const char *zTab              /* Table name */
174498  ),
174499  int(*xConflict)(
174500    void *pCtx,                   /* Copy of sixth arg to _apply() */
174501    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
174502    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
174503  ),
174504  void *pCtx                      /* First argument passed to xConflict */
174505){
174506  sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */
174507  int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
174508  if( rc==SQLITE_OK ){
174509    rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
174510  }
174511  return rc;
174512}
174513
174514/*
174515** sqlite3_changegroup handle.
174516*/
174517struct sqlite3_changegroup {
174518  int rc;                         /* Error code */
174519  int bPatch;                     /* True to accumulate patchsets */
174520  SessionTable *pList;            /* List of tables in current patch */
174521};
174522
174523/*
174524** This function is called to merge two changes to the same row together as
174525** part of an sqlite3changeset_concat() operation. A new change object is
174526** allocated and a pointer to it stored in *ppNew.
174527*/
174528static int sessionChangeMerge(
174529  SessionTable *pTab,             /* Table structure */
174530  int bPatchset,                  /* True for patchsets */
174531  SessionChange *pExist,          /* Existing change */
174532  int op2,                        /* Second change operation */
174533  int bIndirect,                  /* True if second change is indirect */
174534  u8 *aRec,                       /* Second change record */
174535  int nRec,                       /* Number of bytes in aRec */
174536  SessionChange **ppNew           /* OUT: Merged change */
174537){
174538  SessionChange *pNew = 0;
174539
174540  if( !pExist ){
174541    pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
174542    if( !pNew ){
174543      return SQLITE_NOMEM;
174544    }
174545    memset(pNew, 0, sizeof(SessionChange));
174546    pNew->op = op2;
174547    pNew->bIndirect = bIndirect;
174548    pNew->nRecord = nRec;
174549    pNew->aRecord = (u8*)&pNew[1];
174550    memcpy(pNew->aRecord, aRec, nRec);
174551  }else{
174552    int op1 = pExist->op;
174553
174554    /*
174555    **   op1=INSERT, op2=INSERT      ->      Unsupported. Discard op2.
174556    **   op1=INSERT, op2=UPDATE      ->      INSERT.
174557    **   op1=INSERT, op2=DELETE      ->      (none)
174558    **
174559    **   op1=UPDATE, op2=INSERT      ->      Unsupported. Discard op2.
174560    **   op1=UPDATE, op2=UPDATE      ->      UPDATE.
174561    **   op1=UPDATE, op2=DELETE      ->      DELETE.
174562    **
174563    **   op1=DELETE, op2=INSERT      ->      UPDATE.
174564    **   op1=DELETE, op2=UPDATE      ->      Unsupported. Discard op2.
174565    **   op1=DELETE, op2=DELETE      ->      Unsupported. Discard op2.
174566    */
174567    if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
174568     || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
174569     || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
174570     || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
174571    ){
174572      pNew = pExist;
174573    }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
174574      sqlite3_free(pExist);
174575      assert( pNew==0 );
174576    }else{
174577      u8 *aExist = pExist->aRecord;
174578      int nByte;
174579      u8 *aCsr;
174580
174581      /* Allocate a new SessionChange object. Ensure that the aRecord[]
174582      ** buffer of the new object is large enough to hold any record that
174583      ** may be generated by combining the input records.  */
174584      nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
174585      pNew = (SessionChange *)sqlite3_malloc(nByte);
174586      if( !pNew ){
174587        sqlite3_free(pExist);
174588        return SQLITE_NOMEM;
174589      }
174590      memset(pNew, 0, sizeof(SessionChange));
174591      pNew->bIndirect = (bIndirect && pExist->bIndirect);
174592      aCsr = pNew->aRecord = (u8 *)&pNew[1];
174593
174594      if( op1==SQLITE_INSERT ){             /* INSERT + UPDATE */
174595        u8 *a1 = aRec;
174596        assert( op2==SQLITE_UPDATE );
174597        pNew->op = SQLITE_INSERT;
174598        if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
174599        sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
174600      }else if( op1==SQLITE_DELETE ){       /* DELETE + INSERT */
174601        assert( op2==SQLITE_INSERT );
174602        pNew->op = SQLITE_UPDATE;
174603        if( bPatchset ){
174604          memcpy(aCsr, aRec, nRec);
174605          aCsr += nRec;
174606        }else{
174607          if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
174608            sqlite3_free(pNew);
174609            pNew = 0;
174610          }
174611        }
174612      }else if( op2==SQLITE_UPDATE ){       /* UPDATE + UPDATE */
174613        u8 *a1 = aExist;
174614        u8 *a2 = aRec;
174615        assert( op1==SQLITE_UPDATE );
174616        if( bPatchset==0 ){
174617          sessionSkipRecord(&a1, pTab->nCol);
174618          sessionSkipRecord(&a2, pTab->nCol);
174619        }
174620        pNew->op = SQLITE_UPDATE;
174621        if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
174622          sqlite3_free(pNew);
174623          pNew = 0;
174624        }
174625      }else{                                /* UPDATE + DELETE */
174626        assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
174627        pNew->op = SQLITE_DELETE;
174628        if( bPatchset ){
174629          memcpy(aCsr, aRec, nRec);
174630          aCsr += nRec;
174631        }else{
174632          sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
174633        }
174634      }
174635
174636      if( pNew ){
174637        pNew->nRecord = (int)(aCsr - pNew->aRecord);
174638      }
174639      sqlite3_free(pExist);
174640    }
174641  }
174642
174643  *ppNew = pNew;
174644  return SQLITE_OK;
174645}
174646
174647/*
174648** Add all changes in the changeset traversed by the iterator passed as
174649** the first argument to the changegroup hash tables.
174650*/
174651static int sessionChangesetToHash(
174652  sqlite3_changeset_iter *pIter,   /* Iterator to read from */
174653  sqlite3_changegroup *pGrp        /* Changegroup object to add changeset to */
174654){
174655  u8 *aRec;
174656  int nRec;
174657  int rc = SQLITE_OK;
174658  SessionTable *pTab = 0;
174659
174660
174661  while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
174662    const char *zNew;
174663    int nCol;
174664    int op;
174665    int iHash;
174666    int bIndirect;
174667    SessionChange *pChange;
174668    SessionChange *pExist = 0;
174669    SessionChange **pp;
174670
174671    if( pGrp->pList==0 ){
174672      pGrp->bPatch = pIter->bPatchset;
174673    }else if( pIter->bPatchset!=pGrp->bPatch ){
174674      rc = SQLITE_ERROR;
174675      break;
174676    }
174677
174678    sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
174679    if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
174680      /* Search the list for a matching table */
174681      int nNew = (int)strlen(zNew);
174682      u8 *abPK;
174683
174684      sqlite3changeset_pk(pIter, &abPK, 0);
174685      for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
174686        if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
174687      }
174688      if( !pTab ){
174689        SessionTable **ppTab;
174690
174691        pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
174692        if( !pTab ){
174693          rc = SQLITE_NOMEM;
174694          break;
174695        }
174696        memset(pTab, 0, sizeof(SessionTable));
174697        pTab->nCol = nCol;
174698        pTab->abPK = (u8*)&pTab[1];
174699        memcpy(pTab->abPK, abPK, nCol);
174700        pTab->zName = (char*)&pTab->abPK[nCol];
174701        memcpy(pTab->zName, zNew, nNew+1);
174702
174703        /* The new object must be linked on to the end of the list, not
174704        ** simply added to the start of it. This is to ensure that the
174705        ** tables within the output of sqlite3changegroup_output() are in
174706        ** the right order.  */
174707        for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
174708        *ppTab = pTab;
174709      }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
174710        rc = SQLITE_SCHEMA;
174711        break;
174712      }
174713    }
174714
174715    if( sessionGrowHash(pIter->bPatchset, pTab) ){
174716      rc = SQLITE_NOMEM;
174717      break;
174718    }
174719    iHash = sessionChangeHash(
174720        pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
174721    );
174722
174723    /* Search for existing entry. If found, remove it from the hash table.
174724    ** Code below may link it back in.
174725    */
174726    for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
174727      int bPkOnly1 = 0;
174728      int bPkOnly2 = 0;
174729      if( pIter->bPatchset ){
174730        bPkOnly1 = (*pp)->op==SQLITE_DELETE;
174731        bPkOnly2 = op==SQLITE_DELETE;
174732      }
174733      if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
174734        pExist = *pp;
174735        *pp = (*pp)->pNext;
174736        pTab->nEntry--;
174737        break;
174738      }
174739    }
174740
174741    rc = sessionChangeMerge(pTab,
174742        pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
174743    );
174744    if( rc ) break;
174745    if( pChange ){
174746      pChange->pNext = pTab->apChange[iHash];
174747      pTab->apChange[iHash] = pChange;
174748      pTab->nEntry++;
174749    }
174750  }
174751
174752  if( rc==SQLITE_OK ) rc = pIter->rc;
174753  return rc;
174754}
174755
174756/*
174757** Serialize a changeset (or patchset) based on all changesets (or patchsets)
174758** added to the changegroup object passed as the first argument.
174759**
174760** If xOutput is not NULL, then the changeset/patchset is returned to the
174761** user via one or more calls to xOutput, as with the other streaming
174762** interfaces.
174763**
174764** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
174765** buffer containing the output changeset before this function returns. In
174766** this case (*pnOut) is set to the size of the output buffer in bytes. It
174767** is the responsibility of the caller to free the output buffer using
174768** sqlite3_free() when it is no longer required.
174769**
174770** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
174771** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
174772** are both set to 0 before returning.
174773*/
174774static int sessionChangegroupOutput(
174775  sqlite3_changegroup *pGrp,
174776  int (*xOutput)(void *pOut, const void *pData, int nData),
174777  void *pOut,
174778  int *pnOut,
174779  void **ppOut
174780){
174781  int rc = SQLITE_OK;
174782  SessionBuffer buf = {0, 0, 0};
174783  SessionTable *pTab;
174784  assert( xOutput==0 || (ppOut==0 && pnOut==0) );
174785
174786  /* Create the serialized output changeset based on the contents of the
174787  ** hash tables attached to the SessionTable objects in list p->pList.
174788  */
174789  for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
174790    int i;
174791    if( pTab->nEntry==0 ) continue;
174792
174793    sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
174794    for(i=0; i<pTab->nChange; i++){
174795      SessionChange *p;
174796      for(p=pTab->apChange[i]; p; p=p->pNext){
174797        sessionAppendByte(&buf, p->op, &rc);
174798        sessionAppendByte(&buf, p->bIndirect, &rc);
174799        sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
174800      }
174801    }
174802
174803    if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
174804      rc = xOutput(pOut, buf.aBuf, buf.nBuf);
174805      buf.nBuf = 0;
174806    }
174807  }
174808
174809  if( rc==SQLITE_OK ){
174810    if( xOutput ){
174811      if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
174812    }else{
174813      *ppOut = buf.aBuf;
174814      *pnOut = buf.nBuf;
174815      buf.aBuf = 0;
174816    }
174817  }
174818  sqlite3_free(buf.aBuf);
174819
174820  return rc;
174821}
174822
174823/*
174824** Allocate a new, empty, sqlite3_changegroup.
174825*/
174826SQLITE_API int SQLITE_STDCALL sqlite3changegroup_new(sqlite3_changegroup **pp){
174827  int rc = SQLITE_OK;             /* Return code */
174828  sqlite3_changegroup *p;         /* New object */
174829  p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
174830  if( p==0 ){
174831    rc = SQLITE_NOMEM;
174832  }else{
174833    memset(p, 0, sizeof(sqlite3_changegroup));
174834  }
174835  *pp = p;
174836  return rc;
174837}
174838
174839/*
174840** Add the changeset currently stored in buffer pData, size nData bytes,
174841** to changeset-group p.
174842*/
174843SQLITE_API int SQLITE_STDCALL sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
174844  sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
174845  int rc;                         /* Return code */
174846
174847  rc = sqlite3changeset_start(&pIter, nData, pData);
174848  if( rc==SQLITE_OK ){
174849    rc = sessionChangesetToHash(pIter, pGrp);
174850  }
174851  sqlite3changeset_finalize(pIter);
174852  return rc;
174853}
174854
174855/*
174856** Obtain a buffer containing a changeset representing the concatenation
174857** of all changesets added to the group so far.
174858*/
174859SQLITE_API int SQLITE_STDCALL sqlite3changegroup_output(
174860    sqlite3_changegroup *pGrp,
174861    int *pnData,
174862    void **ppData
174863){
174864  return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
174865}
174866
174867/*
174868** Streaming versions of changegroup_add().
174869*/
174870SQLITE_API int SQLITE_STDCALL sqlite3changegroup_add_strm(
174871  sqlite3_changegroup *pGrp,
174872  int (*xInput)(void *pIn, void *pData, int *pnData),
174873  void *pIn
174874){
174875  sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
174876  int rc;                         /* Return code */
174877
174878  rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
174879  if( rc==SQLITE_OK ){
174880    rc = sessionChangesetToHash(pIter, pGrp);
174881  }
174882  sqlite3changeset_finalize(pIter);
174883  return rc;
174884}
174885
174886/*
174887** Streaming versions of changegroup_output().
174888*/
174889SQLITE_API int SQLITE_STDCALL sqlite3changegroup_output_strm(
174890  sqlite3_changegroup *pGrp,
174891  int (*xOutput)(void *pOut, const void *pData, int nData),
174892  void *pOut
174893){
174894  return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
174895}
174896
174897/*
174898** Delete a changegroup object.
174899*/
174900SQLITE_API void SQLITE_STDCALL sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
174901  if( pGrp ){
174902    sessionDeleteTable(pGrp->pList);
174903    sqlite3_free(pGrp);
174904  }
174905}
174906
174907/*
174908** Combine two changesets together.
174909*/
174910SQLITE_API int SQLITE_STDCALL sqlite3changeset_concat(
174911  int nLeft,                      /* Number of bytes in lhs input */
174912  void *pLeft,                    /* Lhs input changeset */
174913  int nRight                      /* Number of bytes in rhs input */,
174914  void *pRight,                   /* Rhs input changeset */
174915  int *pnOut,                     /* OUT: Number of bytes in output changeset */
174916  void **ppOut                    /* OUT: changeset (left <concat> right) */
174917){
174918  sqlite3_changegroup *pGrp;
174919  int rc;
174920
174921  rc = sqlite3changegroup_new(&pGrp);
174922  if( rc==SQLITE_OK ){
174923    rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
174924  }
174925  if( rc==SQLITE_OK ){
174926    rc = sqlite3changegroup_add(pGrp, nRight, pRight);
174927  }
174928  if( rc==SQLITE_OK ){
174929    rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
174930  }
174931  sqlite3changegroup_delete(pGrp);
174932
174933  return rc;
174934}
174935
174936/*
174937** Streaming version of sqlite3changeset_concat().
174938*/
174939SQLITE_API int SQLITE_STDCALL sqlite3changeset_concat_strm(
174940  int (*xInputA)(void *pIn, void *pData, int *pnData),
174941  void *pInA,
174942  int (*xInputB)(void *pIn, void *pData, int *pnData),
174943  void *pInB,
174944  int (*xOutput)(void *pOut, const void *pData, int nData),
174945  void *pOut
174946){
174947  sqlite3_changegroup *pGrp;
174948  int rc;
174949
174950  rc = sqlite3changegroup_new(&pGrp);
174951  if( rc==SQLITE_OK ){
174952    rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
174953  }
174954  if( rc==SQLITE_OK ){
174955    rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
174956  }
174957  if( rc==SQLITE_OK ){
174958    rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
174959  }
174960  sqlite3changegroup_delete(pGrp);
174961
174962  return rc;
174963}
174964
174965#endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
174966
174967/************** End of sqlite3session.c **************************************/
174968/************** Begin file json1.c *******************************************/
174969/*
174970** 2015-08-12
174971**
174972** The author disclaims copyright to this source code.  In place of
174973** a legal notice, here is a blessing:
174974**
174975**    May you do good and not evil.
174976**    May you find forgiveness for yourself and forgive others.
174977**    May you share freely, never taking more than you give.
174978**
174979******************************************************************************
174980**
174981** This SQLite extension implements JSON functions.  The interface is
174982** modeled after MySQL JSON functions:
174983**
174984**     https://dev.mysql.com/doc/refman/5.7/en/json.html
174985**
174986** For the time being, all JSON is stored as pure text.  (We might add
174987** a JSONB type in the future which stores a binary encoding of JSON in
174988** a BLOB, but there is no support for JSONB in the current implementation.
174989** This implementation parses JSON text at 250 MB/s, so it is hard to see
174990** how JSONB might improve on that.)
174991*/
174992#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
174993#if !defined(_SQLITEINT_H_)
174994/* #include "sqlite3ext.h" */
174995#endif
174996SQLITE_EXTENSION_INIT1
174997/* #include <assert.h> */
174998/* #include <string.h> */
174999/* #include <stdlib.h> */
175000/* #include <stdarg.h> */
175001
175002/* Mark a function parameter as unused, to suppress nuisance compiler
175003** warnings. */
175004#ifndef UNUSED_PARAM
175005# define UNUSED_PARAM(X)  (void)(X)
175006#endif
175007
175008#ifndef LARGEST_INT64
175009# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
175010# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
175011#endif
175012
175013/*
175014** Versions of isspace(), isalnum() and isdigit() to which it is safe
175015** to pass signed char values.
175016*/
175017#ifdef sqlite3Isdigit
175018   /* Use the SQLite core versions if this routine is part of the
175019   ** SQLite amalgamation */
175020#  define safe_isdigit(x) sqlite3Isdigit(x)
175021#  define safe_isalnum(x) sqlite3Isalnum(x)
175022#else
175023   /* Use the standard library for separate compilation */
175024#include <ctype.h>  /* amalgamator: keep */
175025#  define safe_isdigit(x) isdigit((unsigned char)(x))
175026#  define safe_isalnum(x) isalnum((unsigned char)(x))
175027#endif
175028
175029/*
175030** Growing our own isspace() routine this way is twice as fast as
175031** the library isspace() function, resulting in a 7% overall performance
175032** increase for the parser.  (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
175033*/
175034static const char jsonIsSpace[] = {
175035  0, 0, 0, 0, 0, 0, 0, 0,     0, 1, 1, 0, 0, 1, 0, 0,
175036  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175037  1, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175038  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175039  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175040  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175041  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175042  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175043  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175044  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175045  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175046  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175047  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175048  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175049  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175050  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175051};
175052#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
175053
175054#ifndef SQLITE_AMALGAMATION
175055  /* Unsigned integer types.  These are already defined in the sqliteInt.h,
175056  ** but the definitions need to be repeated for separate compilation. */
175057  typedef sqlite3_uint64 u64;
175058  typedef unsigned int u32;
175059  typedef unsigned char u8;
175060#endif
175061
175062/* Objects */
175063typedef struct JsonString JsonString;
175064typedef struct JsonNode JsonNode;
175065typedef struct JsonParse JsonParse;
175066
175067/* An instance of this object represents a JSON string
175068** under construction.  Really, this is a generic string accumulator
175069** that can be and is used to create strings other than JSON.
175070*/
175071struct JsonString {
175072  sqlite3_context *pCtx;   /* Function context - put error messages here */
175073  char *zBuf;              /* Append JSON content here */
175074  u64 nAlloc;              /* Bytes of storage available in zBuf[] */
175075  u64 nUsed;               /* Bytes of zBuf[] currently used */
175076  u8 bStatic;              /* True if zBuf is static space */
175077  u8 bErr;                 /* True if an error has been encountered */
175078  char zSpace[100];        /* Initial static space */
175079};
175080
175081/* JSON type values
175082*/
175083#define JSON_NULL     0
175084#define JSON_TRUE     1
175085#define JSON_FALSE    2
175086#define JSON_INT      3
175087#define JSON_REAL     4
175088#define JSON_STRING   5
175089#define JSON_ARRAY    6
175090#define JSON_OBJECT   7
175091
175092/* The "subtype" set for JSON values */
175093#define JSON_SUBTYPE  74    /* Ascii for "J" */
175094
175095/*
175096** Names of the various JSON types:
175097*/
175098static const char * const jsonType[] = {
175099  "null", "true", "false", "integer", "real", "text", "array", "object"
175100};
175101
175102/* Bit values for the JsonNode.jnFlag field
175103*/
175104#define JNODE_RAW     0x01         /* Content is raw, not JSON encoded */
175105#define JNODE_ESCAPE  0x02         /* Content is text with \ escapes */
175106#define JNODE_REMOVE  0x04         /* Do not output */
175107#define JNODE_REPLACE 0x08         /* Replace with JsonNode.iVal */
175108#define JNODE_APPEND  0x10         /* More ARRAY/OBJECT entries at u.iAppend */
175109#define JNODE_LABEL   0x20         /* Is a label of an object */
175110
175111
175112/* A single node of parsed JSON
175113*/
175114struct JsonNode {
175115  u8 eType;              /* One of the JSON_ type values */
175116  u8 jnFlags;            /* JNODE flags */
175117  u8 iVal;               /* Replacement value when JNODE_REPLACE */
175118  u32 n;                 /* Bytes of content, or number of sub-nodes */
175119  union {
175120    const char *zJContent; /* Content for INT, REAL, and STRING */
175121    u32 iAppend;           /* More terms for ARRAY and OBJECT */
175122    u32 iKey;              /* Key for ARRAY objects in json_tree() */
175123  } u;
175124};
175125
175126/* A completely parsed JSON string
175127*/
175128struct JsonParse {
175129  u32 nNode;         /* Number of slots of aNode[] used */
175130  u32 nAlloc;        /* Number of slots of aNode[] allocated */
175131  JsonNode *aNode;   /* Array of nodes containing the parse */
175132  const char *zJson; /* Original JSON string */
175133  u32 *aUp;          /* Index of parent of each node */
175134  u8 oom;            /* Set to true if out of memory */
175135  u8 nErr;           /* Number of errors seen */
175136};
175137
175138/**************************************************************************
175139** Utility routines for dealing with JsonString objects
175140**************************************************************************/
175141
175142/* Set the JsonString object to an empty string
175143*/
175144static void jsonZero(JsonString *p){
175145  p->zBuf = p->zSpace;
175146  p->nAlloc = sizeof(p->zSpace);
175147  p->nUsed = 0;
175148  p->bStatic = 1;
175149}
175150
175151/* Initialize the JsonString object
175152*/
175153static void jsonInit(JsonString *p, sqlite3_context *pCtx){
175154  p->pCtx = pCtx;
175155  p->bErr = 0;
175156  jsonZero(p);
175157}
175158
175159
175160/* Free all allocated memory and reset the JsonString object back to its
175161** initial state.
175162*/
175163static void jsonReset(JsonString *p){
175164  if( !p->bStatic ) sqlite3_free(p->zBuf);
175165  jsonZero(p);
175166}
175167
175168
175169/* Report an out-of-memory (OOM) condition
175170*/
175171static void jsonOom(JsonString *p){
175172  p->bErr = 1;
175173  sqlite3_result_error_nomem(p->pCtx);
175174  jsonReset(p);
175175}
175176
175177/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
175178** Return zero on success.  Return non-zero on an OOM error
175179*/
175180static int jsonGrow(JsonString *p, u32 N){
175181  u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
175182  char *zNew;
175183  if( p->bStatic ){
175184    if( p->bErr ) return 1;
175185    zNew = sqlite3_malloc64(nTotal);
175186    if( zNew==0 ){
175187      jsonOom(p);
175188      return SQLITE_NOMEM;
175189    }
175190    memcpy(zNew, p->zBuf, (size_t)p->nUsed);
175191    p->zBuf = zNew;
175192    p->bStatic = 0;
175193  }else{
175194    zNew = sqlite3_realloc64(p->zBuf, nTotal);
175195    if( zNew==0 ){
175196      jsonOom(p);
175197      return SQLITE_NOMEM;
175198    }
175199    p->zBuf = zNew;
175200  }
175201  p->nAlloc = nTotal;
175202  return SQLITE_OK;
175203}
175204
175205/* Append N bytes from zIn onto the end of the JsonString string.
175206*/
175207static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
175208  if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
175209  memcpy(p->zBuf+p->nUsed, zIn, N);
175210  p->nUsed += N;
175211}
175212
175213/* Append formatted text (not to exceed N bytes) to the JsonString.
175214*/
175215static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
175216  va_list ap;
175217  if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
175218  va_start(ap, zFormat);
175219  sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
175220  va_end(ap);
175221  p->nUsed += (int)strlen(p->zBuf+p->nUsed);
175222}
175223
175224/* Append a single character
175225*/
175226static void jsonAppendChar(JsonString *p, char c){
175227  if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
175228  p->zBuf[p->nUsed++] = c;
175229}
175230
175231/* Append a comma separator to the output buffer, if the previous
175232** character is not '[' or '{'.
175233*/
175234static void jsonAppendSeparator(JsonString *p){
175235  char c;
175236  if( p->nUsed==0 ) return;
175237  c = p->zBuf[p->nUsed-1];
175238  if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
175239}
175240
175241/* Append the N-byte string in zIn to the end of the JsonString string
175242** under construction.  Enclose the string in "..." and escape
175243** any double-quotes or backslash characters contained within the
175244** string.
175245*/
175246static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
175247  u32 i;
175248  if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
175249  p->zBuf[p->nUsed++] = '"';
175250  for(i=0; i<N; i++){
175251    unsigned char c = ((unsigned const char*)zIn)[i];
175252    if( c=='"' || c=='\\' ){
175253      json_simple_escape:
175254      if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
175255      p->zBuf[p->nUsed++] = '\\';
175256    }else if( c<=0x1f ){
175257      static const char aSpecial[] = {
175258         0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
175259         0, 0, 0, 0, 0, 0, 0, 0,   0,   0,   0, 0,   0,   0, 0, 0
175260      };
175261      assert( sizeof(aSpecial)==32 );
175262      assert( aSpecial['\b']=='b' );
175263      assert( aSpecial['\f']=='f' );
175264      assert( aSpecial['\n']=='n' );
175265      assert( aSpecial['\r']=='r' );
175266      assert( aSpecial['\t']=='t' );
175267      if( aSpecial[c] ){
175268        c = aSpecial[c];
175269        goto json_simple_escape;
175270      }
175271      if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
175272      p->zBuf[p->nUsed++] = '\\';
175273      p->zBuf[p->nUsed++] = 'u';
175274      p->zBuf[p->nUsed++] = '0';
175275      p->zBuf[p->nUsed++] = '0';
175276      p->zBuf[p->nUsed++] = '0' + (c>>4);
175277      c = "0123456789abcdef"[c&0xf];
175278    }
175279    p->zBuf[p->nUsed++] = c;
175280  }
175281  p->zBuf[p->nUsed++] = '"';
175282  assert( p->nUsed<p->nAlloc );
175283}
175284
175285/*
175286** Append a function parameter value to the JSON string under
175287** construction.
175288*/
175289static void jsonAppendValue(
175290  JsonString *p,                 /* Append to this JSON string */
175291  sqlite3_value *pValue          /* Value to append */
175292){
175293  switch( sqlite3_value_type(pValue) ){
175294    case SQLITE_NULL: {
175295      jsonAppendRaw(p, "null", 4);
175296      break;
175297    }
175298    case SQLITE_INTEGER:
175299    case SQLITE_FLOAT: {
175300      const char *z = (const char*)sqlite3_value_text(pValue);
175301      u32 n = (u32)sqlite3_value_bytes(pValue);
175302      jsonAppendRaw(p, z, n);
175303      break;
175304    }
175305    case SQLITE_TEXT: {
175306      const char *z = (const char*)sqlite3_value_text(pValue);
175307      u32 n = (u32)sqlite3_value_bytes(pValue);
175308      if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
175309        jsonAppendRaw(p, z, n);
175310      }else{
175311        jsonAppendString(p, z, n);
175312      }
175313      break;
175314    }
175315    default: {
175316      if( p->bErr==0 ){
175317        sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
175318        p->bErr = 2;
175319        jsonReset(p);
175320      }
175321      break;
175322    }
175323  }
175324}
175325
175326
175327/* Make the JSON in p the result of the SQL function.
175328*/
175329static void jsonResult(JsonString *p){
175330  if( p->bErr==0 ){
175331    sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
175332                          p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
175333                          SQLITE_UTF8);
175334    jsonZero(p);
175335  }
175336  assert( p->bStatic );
175337}
175338
175339/**************************************************************************
175340** Utility routines for dealing with JsonNode and JsonParse objects
175341**************************************************************************/
175342
175343/*
175344** Return the number of consecutive JsonNode slots need to represent
175345** the parsed JSON at pNode.  The minimum answer is 1.  For ARRAY and
175346** OBJECT types, the number might be larger.
175347**
175348** Appended elements are not counted.  The value returned is the number
175349** by which the JsonNode counter should increment in order to go to the
175350** next peer value.
175351*/
175352static u32 jsonNodeSize(JsonNode *pNode){
175353  return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
175354}
175355
175356/*
175357** Reclaim all memory allocated by a JsonParse object.  But do not
175358** delete the JsonParse object itself.
175359*/
175360static void jsonParseReset(JsonParse *pParse){
175361  sqlite3_free(pParse->aNode);
175362  pParse->aNode = 0;
175363  pParse->nNode = 0;
175364  pParse->nAlloc = 0;
175365  sqlite3_free(pParse->aUp);
175366  pParse->aUp = 0;
175367}
175368
175369/*
175370** Convert the JsonNode pNode into a pure JSON string and
175371** append to pOut.  Subsubstructure is also included.  Return
175372** the number of JsonNode objects that are encoded.
175373*/
175374static void jsonRenderNode(
175375  JsonNode *pNode,               /* The node to render */
175376  JsonString *pOut,              /* Write JSON here */
175377  sqlite3_value **aReplace       /* Replacement values */
175378){
175379  switch( pNode->eType ){
175380    default: {
175381      assert( pNode->eType==JSON_NULL );
175382      jsonAppendRaw(pOut, "null", 4);
175383      break;
175384    }
175385    case JSON_TRUE: {
175386      jsonAppendRaw(pOut, "true", 4);
175387      break;
175388    }
175389    case JSON_FALSE: {
175390      jsonAppendRaw(pOut, "false", 5);
175391      break;
175392    }
175393    case JSON_STRING: {
175394      if( pNode->jnFlags & JNODE_RAW ){
175395        jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
175396        break;
175397      }
175398      /* Fall through into the next case */
175399    }
175400    case JSON_REAL:
175401    case JSON_INT: {
175402      jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
175403      break;
175404    }
175405    case JSON_ARRAY: {
175406      u32 j = 1;
175407      jsonAppendChar(pOut, '[');
175408      for(;;){
175409        while( j<=pNode->n ){
175410          if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
175411            if( pNode[j].jnFlags & JNODE_REPLACE ){
175412              jsonAppendSeparator(pOut);
175413              jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
175414            }
175415          }else{
175416            jsonAppendSeparator(pOut);
175417            jsonRenderNode(&pNode[j], pOut, aReplace);
175418          }
175419          j += jsonNodeSize(&pNode[j]);
175420        }
175421        if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
175422        pNode = &pNode[pNode->u.iAppend];
175423        j = 1;
175424      }
175425      jsonAppendChar(pOut, ']');
175426      break;
175427    }
175428    case JSON_OBJECT: {
175429      u32 j = 1;
175430      jsonAppendChar(pOut, '{');
175431      for(;;){
175432        while( j<=pNode->n ){
175433          if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
175434            jsonAppendSeparator(pOut);
175435            jsonRenderNode(&pNode[j], pOut, aReplace);
175436            jsonAppendChar(pOut, ':');
175437            if( pNode[j+1].jnFlags & JNODE_REPLACE ){
175438              jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
175439            }else{
175440              jsonRenderNode(&pNode[j+1], pOut, aReplace);
175441            }
175442          }
175443          j += 1 + jsonNodeSize(&pNode[j+1]);
175444        }
175445        if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
175446        pNode = &pNode[pNode->u.iAppend];
175447        j = 1;
175448      }
175449      jsonAppendChar(pOut, '}');
175450      break;
175451    }
175452  }
175453}
175454
175455/*
175456** Return a JsonNode and all its descendents as a JSON string.
175457*/
175458static void jsonReturnJson(
175459  JsonNode *pNode,            /* Node to return */
175460  sqlite3_context *pCtx,      /* Return value for this function */
175461  sqlite3_value **aReplace    /* Array of replacement values */
175462){
175463  JsonString s;
175464  jsonInit(&s, pCtx);
175465  jsonRenderNode(pNode, &s, aReplace);
175466  jsonResult(&s);
175467  sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
175468}
175469
175470/*
175471** Make the JsonNode the return value of the function.
175472*/
175473static void jsonReturn(
175474  JsonNode *pNode,            /* Node to return */
175475  sqlite3_context *pCtx,      /* Return value for this function */
175476  sqlite3_value **aReplace    /* Array of replacement values */
175477){
175478  switch( pNode->eType ){
175479    default: {
175480      assert( pNode->eType==JSON_NULL );
175481      sqlite3_result_null(pCtx);
175482      break;
175483    }
175484    case JSON_TRUE: {
175485      sqlite3_result_int(pCtx, 1);
175486      break;
175487    }
175488    case JSON_FALSE: {
175489      sqlite3_result_int(pCtx, 0);
175490      break;
175491    }
175492    case JSON_INT: {
175493      sqlite3_int64 i = 0;
175494      const char *z = pNode->u.zJContent;
175495      if( z[0]=='-' ){ z++; }
175496      while( z[0]>='0' && z[0]<='9' ){
175497        unsigned v = *(z++) - '0';
175498        if( i>=LARGEST_INT64/10 ){
175499          if( i>LARGEST_INT64/10 ) goto int_as_real;
175500          if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
175501          if( v==9 ) goto int_as_real;
175502          if( v==8 ){
175503            if( pNode->u.zJContent[0]=='-' ){
175504              sqlite3_result_int64(pCtx, SMALLEST_INT64);
175505              goto int_done;
175506            }else{
175507              goto int_as_real;
175508            }
175509          }
175510        }
175511        i = i*10 + v;
175512      }
175513      if( pNode->u.zJContent[0]=='-' ){ i = -i; }
175514      sqlite3_result_int64(pCtx, i);
175515      int_done:
175516      break;
175517      int_as_real: /* fall through to real */;
175518    }
175519    case JSON_REAL: {
175520      double r;
175521#ifdef SQLITE_AMALGAMATION
175522      const char *z = pNode->u.zJContent;
175523      sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
175524#else
175525      r = strtod(pNode->u.zJContent, 0);
175526#endif
175527      sqlite3_result_double(pCtx, r);
175528      break;
175529    }
175530    case JSON_STRING: {
175531#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
175532      ** json_insert() and json_replace() and those routines do not
175533      ** call jsonReturn() */
175534      if( pNode->jnFlags & JNODE_RAW ){
175535        sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
175536                            SQLITE_TRANSIENT);
175537      }else
175538#endif
175539      assert( (pNode->jnFlags & JNODE_RAW)==0 );
175540      if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
175541        /* JSON formatted without any backslash-escapes */
175542        sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
175543                            SQLITE_TRANSIENT);
175544      }else{
175545        /* Translate JSON formatted string into raw text */
175546        u32 i;
175547        u32 n = pNode->n;
175548        const char *z = pNode->u.zJContent;
175549        char *zOut;
175550        u32 j;
175551        zOut = sqlite3_malloc( n+1 );
175552        if( zOut==0 ){
175553          sqlite3_result_error_nomem(pCtx);
175554          break;
175555        }
175556        for(i=1, j=0; i<n-1; i++){
175557          char c = z[i];
175558          if( c!='\\' ){
175559            zOut[j++] = c;
175560          }else{
175561            c = z[++i];
175562            if( c=='u' ){
175563              u32 v = 0, k;
175564              for(k=0; k<4 && i<n-2; i++, k++){
175565                c = z[i+1];
175566                if( c>='0' && c<='9' ) v = v*16 + c - '0';
175567                else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
175568                else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
175569                else break;
175570              }
175571              if( v==0 ) break;
175572              if( v<=0x7f ){
175573                zOut[j++] = (char)v;
175574              }else if( v<=0x7ff ){
175575                zOut[j++] = (char)(0xc0 | (v>>6));
175576                zOut[j++] = 0x80 | (v&0x3f);
175577              }else{
175578                zOut[j++] = (char)(0xe0 | (v>>12));
175579                zOut[j++] = 0x80 | ((v>>6)&0x3f);
175580                zOut[j++] = 0x80 | (v&0x3f);
175581              }
175582            }else{
175583              if( c=='b' ){
175584                c = '\b';
175585              }else if( c=='f' ){
175586                c = '\f';
175587              }else if( c=='n' ){
175588                c = '\n';
175589              }else if( c=='r' ){
175590                c = '\r';
175591              }else if( c=='t' ){
175592                c = '\t';
175593              }
175594              zOut[j++] = c;
175595            }
175596          }
175597        }
175598        zOut[j] = 0;
175599        sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
175600      }
175601      break;
175602    }
175603    case JSON_ARRAY:
175604    case JSON_OBJECT: {
175605      jsonReturnJson(pNode, pCtx, aReplace);
175606      break;
175607    }
175608  }
175609}
175610
175611/* Forward reference */
175612static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
175613
175614/*
175615** A macro to hint to the compiler that a function should not be
175616** inlined.
175617*/
175618#if defined(__GNUC__)
175619#  define JSON_NOINLINE  __attribute__((noinline))
175620#elif defined(_MSC_VER) && _MSC_VER>=1310
175621#  define JSON_NOINLINE  __declspec(noinline)
175622#else
175623#  define JSON_NOINLINE
175624#endif
175625
175626
175627static JSON_NOINLINE int jsonParseAddNodeExpand(
175628  JsonParse *pParse,        /* Append the node to this object */
175629  u32 eType,                /* Node type */
175630  u32 n,                    /* Content size or sub-node count */
175631  const char *zContent      /* Content */
175632){
175633  u32 nNew;
175634  JsonNode *pNew;
175635  assert( pParse->nNode>=pParse->nAlloc );
175636  if( pParse->oom ) return -1;
175637  nNew = pParse->nAlloc*2 + 10;
175638  pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
175639  if( pNew==0 ){
175640    pParse->oom = 1;
175641    return -1;
175642  }
175643  pParse->nAlloc = nNew;
175644  pParse->aNode = pNew;
175645  assert( pParse->nNode<pParse->nAlloc );
175646  return jsonParseAddNode(pParse, eType, n, zContent);
175647}
175648
175649/*
175650** Create a new JsonNode instance based on the arguments and append that
175651** instance to the JsonParse.  Return the index in pParse->aNode[] of the
175652** new node, or -1 if a memory allocation fails.
175653*/
175654static int jsonParseAddNode(
175655  JsonParse *pParse,        /* Append the node to this object */
175656  u32 eType,                /* Node type */
175657  u32 n,                    /* Content size or sub-node count */
175658  const char *zContent      /* Content */
175659){
175660  JsonNode *p;
175661  if( pParse->nNode>=pParse->nAlloc ){
175662    return jsonParseAddNodeExpand(pParse, eType, n, zContent);
175663  }
175664  p = &pParse->aNode[pParse->nNode];
175665  p->eType = (u8)eType;
175666  p->jnFlags = 0;
175667  p->iVal = 0;
175668  p->n = n;
175669  p->u.zJContent = zContent;
175670  return pParse->nNode++;
175671}
175672
175673/*
175674** Parse a single JSON value which begins at pParse->zJson[i].  Return the
175675** index of the first character past the end of the value parsed.
175676**
175677** Return negative for a syntax error.  Special cases:  return -2 if the
175678** first non-whitespace character is '}' and return -3 if the first
175679** non-whitespace character is ']'.
175680*/
175681static int jsonParseValue(JsonParse *pParse, u32 i){
175682  char c;
175683  u32 j;
175684  int iThis;
175685  int x;
175686  JsonNode *pNode;
175687  while( safe_isspace(pParse->zJson[i]) ){ i++; }
175688  if( (c = pParse->zJson[i])=='{' ){
175689    /* Parse object */
175690    iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
175691    if( iThis<0 ) return -1;
175692    for(j=i+1;;j++){
175693      while( safe_isspace(pParse->zJson[j]) ){ j++; }
175694      x = jsonParseValue(pParse, j);
175695      if( x<0 ){
175696        if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
175697        return -1;
175698      }
175699      if( pParse->oom ) return -1;
175700      pNode = &pParse->aNode[pParse->nNode-1];
175701      if( pNode->eType!=JSON_STRING ) return -1;
175702      pNode->jnFlags |= JNODE_LABEL;
175703      j = x;
175704      while( safe_isspace(pParse->zJson[j]) ){ j++; }
175705      if( pParse->zJson[j]!=':' ) return -1;
175706      j++;
175707      x = jsonParseValue(pParse, j);
175708      if( x<0 ) return -1;
175709      j = x;
175710      while( safe_isspace(pParse->zJson[j]) ){ j++; }
175711      c = pParse->zJson[j];
175712      if( c==',' ) continue;
175713      if( c!='}' ) return -1;
175714      break;
175715    }
175716    pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
175717    return j+1;
175718  }else if( c=='[' ){
175719    /* Parse array */
175720    iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
175721    if( iThis<0 ) return -1;
175722    for(j=i+1;;j++){
175723      while( safe_isspace(pParse->zJson[j]) ){ j++; }
175724      x = jsonParseValue(pParse, j);
175725      if( x<0 ){
175726        if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
175727        return -1;
175728      }
175729      j = x;
175730      while( safe_isspace(pParse->zJson[j]) ){ j++; }
175731      c = pParse->zJson[j];
175732      if( c==',' ) continue;
175733      if( c!=']' ) return -1;
175734      break;
175735    }
175736    pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
175737    return j+1;
175738  }else if( c=='"' ){
175739    /* Parse string */
175740    u8 jnFlags = 0;
175741    j = i+1;
175742    for(;;){
175743      c = pParse->zJson[j];
175744      if( c==0 ) return -1;
175745      if( c=='\\' ){
175746        c = pParse->zJson[++j];
175747        if( c==0 ) return -1;
175748        jnFlags = JNODE_ESCAPE;
175749      }else if( c=='"' ){
175750        break;
175751      }
175752      j++;
175753    }
175754    jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
175755    if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
175756    return j+1;
175757  }else if( c=='n'
175758         && strncmp(pParse->zJson+i,"null",4)==0
175759         && !safe_isalnum(pParse->zJson[i+4]) ){
175760    jsonParseAddNode(pParse, JSON_NULL, 0, 0);
175761    return i+4;
175762  }else if( c=='t'
175763         && strncmp(pParse->zJson+i,"true",4)==0
175764         && !safe_isalnum(pParse->zJson[i+4]) ){
175765    jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
175766    return i+4;
175767  }else if( c=='f'
175768         && strncmp(pParse->zJson+i,"false",5)==0
175769         && !safe_isalnum(pParse->zJson[i+5]) ){
175770    jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
175771    return i+5;
175772  }else if( c=='-' || (c>='0' && c<='9') ){
175773    /* Parse number */
175774    u8 seenDP = 0;
175775    u8 seenE = 0;
175776    j = i+1;
175777    for(;; j++){
175778      c = pParse->zJson[j];
175779      if( c>='0' && c<='9' ) continue;
175780      if( c=='.' ){
175781        if( pParse->zJson[j-1]=='-' ) return -1;
175782        if( seenDP ) return -1;
175783        seenDP = 1;
175784        continue;
175785      }
175786      if( c=='e' || c=='E' ){
175787        if( pParse->zJson[j-1]<'0' ) return -1;
175788        if( seenE ) return -1;
175789        seenDP = seenE = 1;
175790        c = pParse->zJson[j+1];
175791        if( c=='+' || c=='-' ){
175792          j++;
175793          c = pParse->zJson[j+1];
175794        }
175795        if( c<'0' || c>'9' ) return -1;
175796        continue;
175797      }
175798      break;
175799    }
175800    if( pParse->zJson[j-1]<'0' ) return -1;
175801    jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
175802                        j - i, &pParse->zJson[i]);
175803    return j;
175804  }else if( c=='}' ){
175805    return -2;  /* End of {...} */
175806  }else if( c==']' ){
175807    return -3;  /* End of [...] */
175808  }else if( c==0 ){
175809    return 0;   /* End of file */
175810  }else{
175811    return -1;  /* Syntax error */
175812  }
175813}
175814
175815/*
175816** Parse a complete JSON string.  Return 0 on success or non-zero if there
175817** are any errors.  If an error occurs, free all memory associated with
175818** pParse.
175819**
175820** pParse is uninitialized when this routine is called.
175821*/
175822static int jsonParse(
175823  JsonParse *pParse,           /* Initialize and fill this JsonParse object */
175824  sqlite3_context *pCtx,       /* Report errors here */
175825  const char *zJson            /* Input JSON text to be parsed */
175826){
175827  int i;
175828  memset(pParse, 0, sizeof(*pParse));
175829  if( zJson==0 ) return 1;
175830  pParse->zJson = zJson;
175831  i = jsonParseValue(pParse, 0);
175832  if( pParse->oom ) i = -1;
175833  if( i>0 ){
175834    while( safe_isspace(zJson[i]) ) i++;
175835    if( zJson[i] ) i = -1;
175836  }
175837  if( i<=0 ){
175838    if( pCtx!=0 ){
175839      if( pParse->oom ){
175840        sqlite3_result_error_nomem(pCtx);
175841      }else{
175842        sqlite3_result_error(pCtx, "malformed JSON", -1);
175843      }
175844    }
175845    jsonParseReset(pParse);
175846    return 1;
175847  }
175848  return 0;
175849}
175850
175851/* Mark node i of pParse as being a child of iParent.  Call recursively
175852** to fill in all the descendants of node i.
175853*/
175854static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
175855  JsonNode *pNode = &pParse->aNode[i];
175856  u32 j;
175857  pParse->aUp[i] = iParent;
175858  switch( pNode->eType ){
175859    case JSON_ARRAY: {
175860      for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
175861        jsonParseFillInParentage(pParse, i+j, i);
175862      }
175863      break;
175864    }
175865    case JSON_OBJECT: {
175866      for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
175867        pParse->aUp[i+j] = i;
175868        jsonParseFillInParentage(pParse, i+j+1, i);
175869      }
175870      break;
175871    }
175872    default: {
175873      break;
175874    }
175875  }
175876}
175877
175878/*
175879** Compute the parentage of all nodes in a completed parse.
175880*/
175881static int jsonParseFindParents(JsonParse *pParse){
175882  u32 *aUp;
175883  assert( pParse->aUp==0 );
175884  aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
175885  if( aUp==0 ){
175886    pParse->oom = 1;
175887    return SQLITE_NOMEM;
175888  }
175889  jsonParseFillInParentage(pParse, 0, 0);
175890  return SQLITE_OK;
175891}
175892
175893/*
175894** Compare the OBJECT label at pNode against zKey,nKey.  Return true on
175895** a match.
175896*/
175897static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
175898  if( pNode->jnFlags & JNODE_RAW ){
175899    if( pNode->n!=nKey ) return 0;
175900    return strncmp(pNode->u.zJContent, zKey, nKey)==0;
175901  }else{
175902    if( pNode->n!=nKey+2 ) return 0;
175903    return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
175904  }
175905}
175906
175907/* forward declaration */
175908static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
175909
175910/*
175911** Search along zPath to find the node specified.  Return a pointer
175912** to that node, or NULL if zPath is malformed or if there is no such
175913** node.
175914**
175915** If pApnd!=0, then try to append new nodes to complete zPath if it is
175916** possible to do so and if no existing node corresponds to zPath.  If
175917** new nodes are appended *pApnd is set to 1.
175918*/
175919static JsonNode *jsonLookupStep(
175920  JsonParse *pParse,      /* The JSON to search */
175921  u32 iRoot,              /* Begin the search at this node */
175922  const char *zPath,      /* The path to search */
175923  int *pApnd,             /* Append nodes to complete path if not NULL */
175924  const char **pzErr      /* Make *pzErr point to any syntax error in zPath */
175925){
175926  u32 i, j, nKey;
175927  const char *zKey;
175928  JsonNode *pRoot = &pParse->aNode[iRoot];
175929  if( zPath[0]==0 ) return pRoot;
175930  if( zPath[0]=='.' ){
175931    if( pRoot->eType!=JSON_OBJECT ) return 0;
175932    zPath++;
175933    if( zPath[0]=='"' ){
175934      zKey = zPath + 1;
175935      for(i=1; zPath[i] && zPath[i]!='"'; i++){}
175936      nKey = i-1;
175937      if( zPath[i] ){
175938        i++;
175939      }else{
175940        *pzErr = zPath;
175941        return 0;
175942      }
175943    }else{
175944      zKey = zPath;
175945      for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
175946      nKey = i;
175947    }
175948    if( nKey==0 ){
175949      *pzErr = zPath;
175950      return 0;
175951    }
175952    j = 1;
175953    for(;;){
175954      while( j<=pRoot->n ){
175955        if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
175956          return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
175957        }
175958        j++;
175959        j += jsonNodeSize(&pRoot[j]);
175960      }
175961      if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
175962      iRoot += pRoot->u.iAppend;
175963      pRoot = &pParse->aNode[iRoot];
175964      j = 1;
175965    }
175966    if( pApnd ){
175967      u32 iStart, iLabel;
175968      JsonNode *pNode;
175969      iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
175970      iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
175971      zPath += i;
175972      pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
175973      if( pParse->oom ) return 0;
175974      if( pNode ){
175975        pRoot = &pParse->aNode[iRoot];
175976        pRoot->u.iAppend = iStart - iRoot;
175977        pRoot->jnFlags |= JNODE_APPEND;
175978        pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
175979      }
175980      return pNode;
175981    }
175982  }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
175983    if( pRoot->eType!=JSON_ARRAY ) return 0;
175984    i = 0;
175985    j = 1;
175986    while( safe_isdigit(zPath[j]) ){
175987      i = i*10 + zPath[j] - '0';
175988      j++;
175989    }
175990    if( zPath[j]!=']' ){
175991      *pzErr = zPath;
175992      return 0;
175993    }
175994    zPath += j + 1;
175995    j = 1;
175996    for(;;){
175997      while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
175998        if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
175999        j += jsonNodeSize(&pRoot[j]);
176000      }
176001      if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
176002      iRoot += pRoot->u.iAppend;
176003      pRoot = &pParse->aNode[iRoot];
176004      j = 1;
176005    }
176006    if( j<=pRoot->n ){
176007      return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
176008    }
176009    if( i==0 && pApnd ){
176010      u32 iStart;
176011      JsonNode *pNode;
176012      iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
176013      pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
176014      if( pParse->oom ) return 0;
176015      if( pNode ){
176016        pRoot = &pParse->aNode[iRoot];
176017        pRoot->u.iAppend = iStart - iRoot;
176018        pRoot->jnFlags |= JNODE_APPEND;
176019      }
176020      return pNode;
176021    }
176022  }else{
176023    *pzErr = zPath;
176024  }
176025  return 0;
176026}
176027
176028/*
176029** Append content to pParse that will complete zPath.  Return a pointer
176030** to the inserted node, or return NULL if the append fails.
176031*/
176032static JsonNode *jsonLookupAppend(
176033  JsonParse *pParse,     /* Append content to the JSON parse */
176034  const char *zPath,     /* Description of content to append */
176035  int *pApnd,            /* Set this flag to 1 */
176036  const char **pzErr     /* Make this point to any syntax error */
176037){
176038  *pApnd = 1;
176039  if( zPath[0]==0 ){
176040    jsonParseAddNode(pParse, JSON_NULL, 0, 0);
176041    return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
176042  }
176043  if( zPath[0]=='.' ){
176044    jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
176045  }else if( strncmp(zPath,"[0]",3)==0 ){
176046    jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
176047  }else{
176048    return 0;
176049  }
176050  if( pParse->oom ) return 0;
176051  return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
176052}
176053
176054/*
176055** Return the text of a syntax error message on a JSON path.  Space is
176056** obtained from sqlite3_malloc().
176057*/
176058static char *jsonPathSyntaxError(const char *zErr){
176059  return sqlite3_mprintf("JSON path error near '%q'", zErr);
176060}
176061
176062/*
176063** Do a node lookup using zPath.  Return a pointer to the node on success.
176064** Return NULL if not found or if there is an error.
176065**
176066** On an error, write an error message into pCtx and increment the
176067** pParse->nErr counter.
176068**
176069** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
176070** nodes are appended.
176071*/
176072static JsonNode *jsonLookup(
176073  JsonParse *pParse,      /* The JSON to search */
176074  const char *zPath,      /* The path to search */
176075  int *pApnd,             /* Append nodes to complete path if not NULL */
176076  sqlite3_context *pCtx   /* Report errors here, if not NULL */
176077){
176078  const char *zErr = 0;
176079  JsonNode *pNode = 0;
176080  char *zMsg;
176081
176082  if( zPath==0 ) return 0;
176083  if( zPath[0]!='$' ){
176084    zErr = zPath;
176085    goto lookup_err;
176086  }
176087  zPath++;
176088  pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
176089  if( zErr==0 ) return pNode;
176090
176091lookup_err:
176092  pParse->nErr++;
176093  assert( zErr!=0 && pCtx!=0 );
176094  zMsg = jsonPathSyntaxError(zErr);
176095  if( zMsg ){
176096    sqlite3_result_error(pCtx, zMsg, -1);
176097    sqlite3_free(zMsg);
176098  }else{
176099    sqlite3_result_error_nomem(pCtx);
176100  }
176101  return 0;
176102}
176103
176104
176105/*
176106** Report the wrong number of arguments for json_insert(), json_replace()
176107** or json_set().
176108*/
176109static void jsonWrongNumArgs(
176110  sqlite3_context *pCtx,
176111  const char *zFuncName
176112){
176113  char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
176114                               zFuncName);
176115  sqlite3_result_error(pCtx, zMsg, -1);
176116  sqlite3_free(zMsg);
176117}
176118
176119
176120/****************************************************************************
176121** SQL functions used for testing and debugging
176122****************************************************************************/
176123
176124#ifdef SQLITE_DEBUG
176125/*
176126** The json_parse(JSON) function returns a string which describes
176127** a parse of the JSON provided.  Or it returns NULL if JSON is not
176128** well-formed.
176129*/
176130static void jsonParseFunc(
176131  sqlite3_context *ctx,
176132  int argc,
176133  sqlite3_value **argv
176134){
176135  JsonString s;       /* Output string - not real JSON */
176136  JsonParse x;        /* The parse */
176137  u32 i;
176138
176139  assert( argc==1 );
176140  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176141  jsonParseFindParents(&x);
176142  jsonInit(&s, ctx);
176143  for(i=0; i<x.nNode; i++){
176144    const char *zType;
176145    if( x.aNode[i].jnFlags & JNODE_LABEL ){
176146      assert( x.aNode[i].eType==JSON_STRING );
176147      zType = "label";
176148    }else{
176149      zType = jsonType[x.aNode[i].eType];
176150    }
176151    jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
176152               i, zType, x.aNode[i].n, x.aUp[i]);
176153    if( x.aNode[i].u.zJContent!=0 ){
176154      jsonAppendRaw(&s, " ", 1);
176155      jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
176156    }
176157    jsonAppendRaw(&s, "\n", 1);
176158  }
176159  jsonParseReset(&x);
176160  jsonResult(&s);
176161}
176162
176163/*
176164** The json_test1(JSON) function return true (1) if the input is JSON
176165** text generated by another json function.  It returns (0) if the input
176166** is not known to be JSON.
176167*/
176168static void jsonTest1Func(
176169  sqlite3_context *ctx,
176170  int argc,
176171  sqlite3_value **argv
176172){
176173  UNUSED_PARAM(argc);
176174  sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
176175}
176176#endif /* SQLITE_DEBUG */
176177
176178/****************************************************************************
176179** Scalar SQL function implementations
176180****************************************************************************/
176181
176182/*
176183** Implementation of the json_QUOTE(VALUE) function.  Return a JSON value
176184** corresponding to the SQL value input.  Mostly this means putting
176185** double-quotes around strings and returning the unquoted string "null"
176186** when given a NULL input.
176187*/
176188static void jsonQuoteFunc(
176189  sqlite3_context *ctx,
176190  int argc,
176191  sqlite3_value **argv
176192){
176193  JsonString jx;
176194  UNUSED_PARAM(argc);
176195
176196  jsonInit(&jx, ctx);
176197  jsonAppendValue(&jx, argv[0]);
176198  jsonResult(&jx);
176199  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176200}
176201
176202/*
176203** Implementation of the json_array(VALUE,...) function.  Return a JSON
176204** array that contains all values given in arguments.  Or if any argument
176205** is a BLOB, throw an error.
176206*/
176207static void jsonArrayFunc(
176208  sqlite3_context *ctx,
176209  int argc,
176210  sqlite3_value **argv
176211){
176212  int i;
176213  JsonString jx;
176214
176215  jsonInit(&jx, ctx);
176216  jsonAppendChar(&jx, '[');
176217  for(i=0; i<argc; i++){
176218    jsonAppendSeparator(&jx);
176219    jsonAppendValue(&jx, argv[i]);
176220  }
176221  jsonAppendChar(&jx, ']');
176222  jsonResult(&jx);
176223  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176224}
176225
176226
176227/*
176228** json_array_length(JSON)
176229** json_array_length(JSON, PATH)
176230**
176231** Return the number of elements in the top-level JSON array.
176232** Return 0 if the input is not a well-formed JSON array.
176233*/
176234static void jsonArrayLengthFunc(
176235  sqlite3_context *ctx,
176236  int argc,
176237  sqlite3_value **argv
176238){
176239  JsonParse x;          /* The parse */
176240  sqlite3_int64 n = 0;
176241  u32 i;
176242  JsonNode *pNode;
176243
176244  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176245  assert( x.nNode );
176246  if( argc==2 ){
176247    const char *zPath = (const char*)sqlite3_value_text(argv[1]);
176248    pNode = jsonLookup(&x, zPath, 0, ctx);
176249  }else{
176250    pNode = x.aNode;
176251  }
176252  if( pNode==0 ){
176253    x.nErr = 1;
176254  }else if( pNode->eType==JSON_ARRAY ){
176255    assert( (pNode->jnFlags & JNODE_APPEND)==0 );
176256    for(i=1; i<=pNode->n; n++){
176257      i += jsonNodeSize(&pNode[i]);
176258    }
176259  }
176260  if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
176261  jsonParseReset(&x);
176262}
176263
176264/*
176265** json_extract(JSON, PATH, ...)
176266**
176267** Return the element described by PATH.  Return NULL if there is no
176268** PATH element.  If there are multiple PATHs, then return a JSON array
176269** with the result from each path.  Throw an error if the JSON or any PATH
176270** is malformed.
176271*/
176272static void jsonExtractFunc(
176273  sqlite3_context *ctx,
176274  int argc,
176275  sqlite3_value **argv
176276){
176277  JsonParse x;          /* The parse */
176278  JsonNode *pNode;
176279  const char *zPath;
176280  JsonString jx;
176281  int i;
176282
176283  if( argc<2 ) return;
176284  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176285  jsonInit(&jx, ctx);
176286  jsonAppendChar(&jx, '[');
176287  for(i=1; i<argc; i++){
176288    zPath = (const char*)sqlite3_value_text(argv[i]);
176289    pNode = jsonLookup(&x, zPath, 0, ctx);
176290    if( x.nErr ) break;
176291    if( argc>2 ){
176292      jsonAppendSeparator(&jx);
176293      if( pNode ){
176294        jsonRenderNode(pNode, &jx, 0);
176295      }else{
176296        jsonAppendRaw(&jx, "null", 4);
176297      }
176298    }else if( pNode ){
176299      jsonReturn(pNode, ctx, 0);
176300    }
176301  }
176302  if( argc>2 && i==argc ){
176303    jsonAppendChar(&jx, ']');
176304    jsonResult(&jx);
176305    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176306  }
176307  jsonReset(&jx);
176308  jsonParseReset(&x);
176309}
176310
176311/*
176312** Implementation of the json_object(NAME,VALUE,...) function.  Return a JSON
176313** object that contains all name/value given in arguments.  Or if any name
176314** is not a string or if any value is a BLOB, throw an error.
176315*/
176316static void jsonObjectFunc(
176317  sqlite3_context *ctx,
176318  int argc,
176319  sqlite3_value **argv
176320){
176321  int i;
176322  JsonString jx;
176323  const char *z;
176324  u32 n;
176325
176326  if( argc&1 ){
176327    sqlite3_result_error(ctx, "json_object() requires an even number "
176328                                  "of arguments", -1);
176329    return;
176330  }
176331  jsonInit(&jx, ctx);
176332  jsonAppendChar(&jx, '{');
176333  for(i=0; i<argc; i+=2){
176334    if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
176335      sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
176336      jsonReset(&jx);
176337      return;
176338    }
176339    jsonAppendSeparator(&jx);
176340    z = (const char*)sqlite3_value_text(argv[i]);
176341    n = (u32)sqlite3_value_bytes(argv[i]);
176342    jsonAppendString(&jx, z, n);
176343    jsonAppendChar(&jx, ':');
176344    jsonAppendValue(&jx, argv[i+1]);
176345  }
176346  jsonAppendChar(&jx, '}');
176347  jsonResult(&jx);
176348  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176349}
176350
176351
176352/*
176353** json_remove(JSON, PATH, ...)
176354**
176355** Remove the named elements from JSON and return the result.  malformed
176356** JSON or PATH arguments result in an error.
176357*/
176358static void jsonRemoveFunc(
176359  sqlite3_context *ctx,
176360  int argc,
176361  sqlite3_value **argv
176362){
176363  JsonParse x;          /* The parse */
176364  JsonNode *pNode;
176365  const char *zPath;
176366  u32 i;
176367
176368  if( argc<1 ) return;
176369  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176370  assert( x.nNode );
176371  for(i=1; i<(u32)argc; i++){
176372    zPath = (const char*)sqlite3_value_text(argv[i]);
176373    if( zPath==0 ) goto remove_done;
176374    pNode = jsonLookup(&x, zPath, 0, ctx);
176375    if( x.nErr ) goto remove_done;
176376    if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
176377  }
176378  if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
176379    jsonReturnJson(x.aNode, ctx, 0);
176380  }
176381remove_done:
176382  jsonParseReset(&x);
176383}
176384
176385/*
176386** json_replace(JSON, PATH, VALUE, ...)
176387**
176388** Replace the value at PATH with VALUE.  If PATH does not already exist,
176389** this routine is a no-op.  If JSON or PATH is malformed, throw an error.
176390*/
176391static void jsonReplaceFunc(
176392  sqlite3_context *ctx,
176393  int argc,
176394  sqlite3_value **argv
176395){
176396  JsonParse x;          /* The parse */
176397  JsonNode *pNode;
176398  const char *zPath;
176399  u32 i;
176400
176401  if( argc<1 ) return;
176402  if( (argc&1)==0 ) {
176403    jsonWrongNumArgs(ctx, "replace");
176404    return;
176405  }
176406  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176407  assert( x.nNode );
176408  for(i=1; i<(u32)argc; i+=2){
176409    zPath = (const char*)sqlite3_value_text(argv[i]);
176410    pNode = jsonLookup(&x, zPath, 0, ctx);
176411    if( x.nErr ) goto replace_err;
176412    if( pNode ){
176413      pNode->jnFlags |= (u8)JNODE_REPLACE;
176414      pNode->iVal = (u8)(i+1);
176415    }
176416  }
176417  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
176418    sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
176419  }else{
176420    jsonReturnJson(x.aNode, ctx, argv);
176421  }
176422replace_err:
176423  jsonParseReset(&x);
176424}
176425
176426/*
176427** json_set(JSON, PATH, VALUE, ...)
176428**
176429** Set the value at PATH to VALUE.  Create the PATH if it does not already
176430** exist.  Overwrite existing values that do exist.
176431** If JSON or PATH is malformed, throw an error.
176432**
176433** json_insert(JSON, PATH, VALUE, ...)
176434**
176435** Create PATH and initialize it to VALUE.  If PATH already exists, this
176436** routine is a no-op.  If JSON or PATH is malformed, throw an error.
176437*/
176438static void jsonSetFunc(
176439  sqlite3_context *ctx,
176440  int argc,
176441  sqlite3_value **argv
176442){
176443  JsonParse x;          /* The parse */
176444  JsonNode *pNode;
176445  const char *zPath;
176446  u32 i;
176447  int bApnd;
176448  int bIsSet = *(int*)sqlite3_user_data(ctx);
176449
176450  if( argc<1 ) return;
176451  if( (argc&1)==0 ) {
176452    jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
176453    return;
176454  }
176455  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176456  assert( x.nNode );
176457  for(i=1; i<(u32)argc; i+=2){
176458    zPath = (const char*)sqlite3_value_text(argv[i]);
176459    bApnd = 0;
176460    pNode = jsonLookup(&x, zPath, &bApnd, ctx);
176461    if( x.oom ){
176462      sqlite3_result_error_nomem(ctx);
176463      goto jsonSetDone;
176464    }else if( x.nErr ){
176465      goto jsonSetDone;
176466    }else if( pNode && (bApnd || bIsSet) ){
176467      pNode->jnFlags |= (u8)JNODE_REPLACE;
176468      pNode->iVal = (u8)(i+1);
176469    }
176470  }
176471  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
176472    sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
176473  }else{
176474    jsonReturnJson(x.aNode, ctx, argv);
176475  }
176476jsonSetDone:
176477  jsonParseReset(&x);
176478}
176479
176480/*
176481** json_type(JSON)
176482** json_type(JSON, PATH)
176483**
176484** Return the top-level "type" of a JSON string.  Throw an error if
176485** either the JSON or PATH inputs are not well-formed.
176486*/
176487static void jsonTypeFunc(
176488  sqlite3_context *ctx,
176489  int argc,
176490  sqlite3_value **argv
176491){
176492  JsonParse x;          /* The parse */
176493  const char *zPath;
176494  JsonNode *pNode;
176495
176496  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176497  assert( x.nNode );
176498  if( argc==2 ){
176499    zPath = (const char*)sqlite3_value_text(argv[1]);
176500    pNode = jsonLookup(&x, zPath, 0, ctx);
176501  }else{
176502    pNode = x.aNode;
176503  }
176504  if( pNode ){
176505    sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
176506  }
176507  jsonParseReset(&x);
176508}
176509
176510/*
176511** json_valid(JSON)
176512**
176513** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
176514** Return 0 otherwise.
176515*/
176516static void jsonValidFunc(
176517  sqlite3_context *ctx,
176518  int argc,
176519  sqlite3_value **argv
176520){
176521  JsonParse x;          /* The parse */
176522  int rc = 0;
176523
176524  UNUSED_PARAM(argc);
176525  if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
176526    rc = 1;
176527  }
176528  jsonParseReset(&x);
176529  sqlite3_result_int(ctx, rc);
176530}
176531
176532
176533/****************************************************************************
176534** Aggregate SQL function implementations
176535****************************************************************************/
176536/*
176537** json_group_array(VALUE)
176538**
176539** Return a JSON array composed of all values in the aggregate.
176540*/
176541static void jsonArrayStep(
176542  sqlite3_context *ctx,
176543  int argc,
176544  sqlite3_value **argv
176545){
176546  JsonString *pStr;
176547  UNUSED_PARAM(argc);
176548  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
176549  if( pStr ){
176550    if( pStr->zBuf==0 ){
176551      jsonInit(pStr, ctx);
176552      jsonAppendChar(pStr, '[');
176553    }else{
176554      jsonAppendChar(pStr, ',');
176555      pStr->pCtx = ctx;
176556    }
176557    jsonAppendValue(pStr, argv[0]);
176558  }
176559}
176560static void jsonArrayFinal(sqlite3_context *ctx){
176561  JsonString *pStr;
176562  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
176563  if( pStr ){
176564    pStr->pCtx = ctx;
176565    jsonAppendChar(pStr, ']');
176566    if( pStr->bErr ){
176567      if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
176568      assert( pStr->bStatic );
176569    }else{
176570      sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
176571                          pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
176572      pStr->bStatic = 1;
176573    }
176574  }else{
176575    sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
176576  }
176577  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176578}
176579
176580/*
176581** json_group_obj(NAME,VALUE)
176582**
176583** Return a JSON object composed of all names and values in the aggregate.
176584*/
176585static void jsonObjectStep(
176586  sqlite3_context *ctx,
176587  int argc,
176588  sqlite3_value **argv
176589){
176590  JsonString *pStr;
176591  const char *z;
176592  u32 n;
176593  UNUSED_PARAM(argc);
176594  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
176595  if( pStr ){
176596    if( pStr->zBuf==0 ){
176597      jsonInit(pStr, ctx);
176598      jsonAppendChar(pStr, '{');
176599    }else{
176600      jsonAppendChar(pStr, ',');
176601      pStr->pCtx = ctx;
176602    }
176603    z = (const char*)sqlite3_value_text(argv[0]);
176604    n = (u32)sqlite3_value_bytes(argv[0]);
176605    jsonAppendString(pStr, z, n);
176606    jsonAppendChar(pStr, ':');
176607    jsonAppendValue(pStr, argv[1]);
176608  }
176609}
176610static void jsonObjectFinal(sqlite3_context *ctx){
176611  JsonString *pStr;
176612  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
176613  if( pStr ){
176614    jsonAppendChar(pStr, '}');
176615    if( pStr->bErr ){
176616      if( pStr->bErr==0 ) sqlite3_result_error_nomem(ctx);
176617      assert( pStr->bStatic );
176618    }else{
176619      sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
176620                          pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
176621      pStr->bStatic = 1;
176622    }
176623  }else{
176624    sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
176625  }
176626  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176627}
176628
176629
176630#ifndef SQLITE_OMIT_VIRTUALTABLE
176631/****************************************************************************
176632** The json_each virtual table
176633****************************************************************************/
176634typedef struct JsonEachCursor JsonEachCursor;
176635struct JsonEachCursor {
176636  sqlite3_vtab_cursor base;  /* Base class - must be first */
176637  u32 iRowid;                /* The rowid */
176638  u32 iBegin;                /* The first node of the scan */
176639  u32 i;                     /* Index in sParse.aNode[] of current row */
176640  u32 iEnd;                  /* EOF when i equals or exceeds this value */
176641  u8 eType;                  /* Type of top-level element */
176642  u8 bRecursive;             /* True for json_tree().  False for json_each() */
176643  char *zJson;               /* Input JSON */
176644  char *zRoot;               /* Path by which to filter zJson */
176645  JsonParse sParse;          /* Parse of the input JSON */
176646};
176647
176648/* Constructor for the json_each virtual table */
176649static int jsonEachConnect(
176650  sqlite3 *db,
176651  void *pAux,
176652  int argc, const char *const*argv,
176653  sqlite3_vtab **ppVtab,
176654  char **pzErr
176655){
176656  sqlite3_vtab *pNew;
176657  int rc;
176658
176659/* Column numbers */
176660#define JEACH_KEY     0
176661#define JEACH_VALUE   1
176662#define JEACH_TYPE    2
176663#define JEACH_ATOM    3
176664#define JEACH_ID      4
176665#define JEACH_PARENT  5
176666#define JEACH_FULLKEY 6
176667#define JEACH_PATH    7
176668#define JEACH_JSON    8
176669#define JEACH_ROOT    9
176670
176671  UNUSED_PARAM(pzErr);
176672  UNUSED_PARAM(argv);
176673  UNUSED_PARAM(argc);
176674  UNUSED_PARAM(pAux);
176675  rc = sqlite3_declare_vtab(db,
176676     "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
176677                    "json HIDDEN,root HIDDEN)");
176678  if( rc==SQLITE_OK ){
176679    pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
176680    if( pNew==0 ) return SQLITE_NOMEM;
176681    memset(pNew, 0, sizeof(*pNew));
176682  }
176683  return rc;
176684}
176685
176686/* destructor for json_each virtual table */
176687static int jsonEachDisconnect(sqlite3_vtab *pVtab){
176688  sqlite3_free(pVtab);
176689  return SQLITE_OK;
176690}
176691
176692/* constructor for a JsonEachCursor object for json_each(). */
176693static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
176694  JsonEachCursor *pCur;
176695
176696  UNUSED_PARAM(p);
176697  pCur = sqlite3_malloc( sizeof(*pCur) );
176698  if( pCur==0 ) return SQLITE_NOMEM;
176699  memset(pCur, 0, sizeof(*pCur));
176700  *ppCursor = &pCur->base;
176701  return SQLITE_OK;
176702}
176703
176704/* constructor for a JsonEachCursor object for json_tree(). */
176705static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
176706  int rc = jsonEachOpenEach(p, ppCursor);
176707  if( rc==SQLITE_OK ){
176708    JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
176709    pCur->bRecursive = 1;
176710  }
176711  return rc;
176712}
176713
176714/* Reset a JsonEachCursor back to its original state.  Free any memory
176715** held. */
176716static void jsonEachCursorReset(JsonEachCursor *p){
176717  sqlite3_free(p->zJson);
176718  sqlite3_free(p->zRoot);
176719  jsonParseReset(&p->sParse);
176720  p->iRowid = 0;
176721  p->i = 0;
176722  p->iEnd = 0;
176723  p->eType = 0;
176724  p->zJson = 0;
176725  p->zRoot = 0;
176726}
176727
176728/* Destructor for a jsonEachCursor object */
176729static int jsonEachClose(sqlite3_vtab_cursor *cur){
176730  JsonEachCursor *p = (JsonEachCursor*)cur;
176731  jsonEachCursorReset(p);
176732  sqlite3_free(cur);
176733  return SQLITE_OK;
176734}
176735
176736/* Return TRUE if the jsonEachCursor object has been advanced off the end
176737** of the JSON object */
176738static int jsonEachEof(sqlite3_vtab_cursor *cur){
176739  JsonEachCursor *p = (JsonEachCursor*)cur;
176740  return p->i >= p->iEnd;
176741}
176742
176743/* Advance the cursor to the next element for json_tree() */
176744static int jsonEachNext(sqlite3_vtab_cursor *cur){
176745  JsonEachCursor *p = (JsonEachCursor*)cur;
176746  if( p->bRecursive ){
176747    if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
176748    p->i++;
176749    p->iRowid++;
176750    if( p->i<p->iEnd ){
176751      u32 iUp = p->sParse.aUp[p->i];
176752      JsonNode *pUp = &p->sParse.aNode[iUp];
176753      p->eType = pUp->eType;
176754      if( pUp->eType==JSON_ARRAY ){
176755        if( iUp==p->i-1 ){
176756          pUp->u.iKey = 0;
176757        }else{
176758          pUp->u.iKey++;
176759        }
176760      }
176761    }
176762  }else{
176763    switch( p->eType ){
176764      case JSON_ARRAY: {
176765        p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
176766        p->iRowid++;
176767        break;
176768      }
176769      case JSON_OBJECT: {
176770        p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
176771        p->iRowid++;
176772        break;
176773      }
176774      default: {
176775        p->i = p->iEnd;
176776        break;
176777      }
176778    }
176779  }
176780  return SQLITE_OK;
176781}
176782
176783/* Append the name of the path for element i to pStr
176784*/
176785static void jsonEachComputePath(
176786  JsonEachCursor *p,       /* The cursor */
176787  JsonString *pStr,        /* Write the path here */
176788  u32 i                    /* Path to this element */
176789){
176790  JsonNode *pNode, *pUp;
176791  u32 iUp;
176792  if( i==0 ){
176793    jsonAppendChar(pStr, '$');
176794    return;
176795  }
176796  iUp = p->sParse.aUp[i];
176797  jsonEachComputePath(p, pStr, iUp);
176798  pNode = &p->sParse.aNode[i];
176799  pUp = &p->sParse.aNode[iUp];
176800  if( pUp->eType==JSON_ARRAY ){
176801    jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
176802  }else{
176803    assert( pUp->eType==JSON_OBJECT );
176804    if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
176805    assert( pNode->eType==JSON_STRING );
176806    assert( pNode->jnFlags & JNODE_LABEL );
176807    jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
176808  }
176809}
176810
176811/* Return the value of a column */
176812static int jsonEachColumn(
176813  sqlite3_vtab_cursor *cur,   /* The cursor */
176814  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
176815  int i                       /* Which column to return */
176816){
176817  JsonEachCursor *p = (JsonEachCursor*)cur;
176818  JsonNode *pThis = &p->sParse.aNode[p->i];
176819  switch( i ){
176820    case JEACH_KEY: {
176821      if( p->i==0 ) break;
176822      if( p->eType==JSON_OBJECT ){
176823        jsonReturn(pThis, ctx, 0);
176824      }else if( p->eType==JSON_ARRAY ){
176825        u32 iKey;
176826        if( p->bRecursive ){
176827          if( p->iRowid==0 ) break;
176828          iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
176829        }else{
176830          iKey = p->iRowid;
176831        }
176832        sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
176833      }
176834      break;
176835    }
176836    case JEACH_VALUE: {
176837      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
176838      jsonReturn(pThis, ctx, 0);
176839      break;
176840    }
176841    case JEACH_TYPE: {
176842      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
176843      sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
176844      break;
176845    }
176846    case JEACH_ATOM: {
176847      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
176848      if( pThis->eType>=JSON_ARRAY ) break;
176849      jsonReturn(pThis, ctx, 0);
176850      break;
176851    }
176852    case JEACH_ID: {
176853      sqlite3_result_int64(ctx,
176854         (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
176855      break;
176856    }
176857    case JEACH_PARENT: {
176858      if( p->i>p->iBegin && p->bRecursive ){
176859        sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
176860      }
176861      break;
176862    }
176863    case JEACH_FULLKEY: {
176864      JsonString x;
176865      jsonInit(&x, ctx);
176866      if( p->bRecursive ){
176867        jsonEachComputePath(p, &x, p->i);
176868      }else{
176869        if( p->zRoot ){
176870          jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
176871        }else{
176872          jsonAppendChar(&x, '$');
176873        }
176874        if( p->eType==JSON_ARRAY ){
176875          jsonPrintf(30, &x, "[%d]", p->iRowid);
176876        }else{
176877          jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
176878        }
176879      }
176880      jsonResult(&x);
176881      break;
176882    }
176883    case JEACH_PATH: {
176884      if( p->bRecursive ){
176885        JsonString x;
176886        jsonInit(&x, ctx);
176887        jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
176888        jsonResult(&x);
176889        break;
176890      }
176891      /* For json_each() path and root are the same so fall through
176892      ** into the root case */
176893    }
176894    case JEACH_ROOT: {
176895      const char *zRoot = p->zRoot;
176896       if( zRoot==0 ) zRoot = "$";
176897      sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
176898      break;
176899    }
176900    case JEACH_JSON: {
176901      assert( i==JEACH_JSON );
176902      sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
176903      break;
176904    }
176905  }
176906  return SQLITE_OK;
176907}
176908
176909/* Return the current rowid value */
176910static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
176911  JsonEachCursor *p = (JsonEachCursor*)cur;
176912  *pRowid = p->iRowid;
176913  return SQLITE_OK;
176914}
176915
176916/* The query strategy is to look for an equality constraint on the json
176917** column.  Without such a constraint, the table cannot operate.  idxNum is
176918** 1 if the constraint is found, 3 if the constraint and zRoot are found,
176919** and 0 otherwise.
176920*/
176921static int jsonEachBestIndex(
176922  sqlite3_vtab *tab,
176923  sqlite3_index_info *pIdxInfo
176924){
176925  int i;
176926  int jsonIdx = -1;
176927  int rootIdx = -1;
176928  const struct sqlite3_index_constraint *pConstraint;
176929
176930  UNUSED_PARAM(tab);
176931  pConstraint = pIdxInfo->aConstraint;
176932  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
176933    if( pConstraint->usable==0 ) continue;
176934    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
176935    switch( pConstraint->iColumn ){
176936      case JEACH_JSON:   jsonIdx = i;    break;
176937      case JEACH_ROOT:   rootIdx = i;    break;
176938      default:           /* no-op */     break;
176939    }
176940  }
176941  if( jsonIdx<0 ){
176942    pIdxInfo->idxNum = 0;
176943    pIdxInfo->estimatedCost = 1e99;
176944  }else{
176945    pIdxInfo->estimatedCost = 1.0;
176946    pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
176947    pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
176948    if( rootIdx<0 ){
176949      pIdxInfo->idxNum = 1;
176950    }else{
176951      pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
176952      pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
176953      pIdxInfo->idxNum = 3;
176954    }
176955  }
176956  return SQLITE_OK;
176957}
176958
176959/* Start a search on a new JSON string */
176960static int jsonEachFilter(
176961  sqlite3_vtab_cursor *cur,
176962  int idxNum, const char *idxStr,
176963  int argc, sqlite3_value **argv
176964){
176965  JsonEachCursor *p = (JsonEachCursor*)cur;
176966  const char *z;
176967  const char *zRoot = 0;
176968  sqlite3_int64 n;
176969
176970  UNUSED_PARAM(idxStr);
176971  UNUSED_PARAM(argc);
176972  jsonEachCursorReset(p);
176973  if( idxNum==0 ) return SQLITE_OK;
176974  z = (const char*)sqlite3_value_text(argv[0]);
176975  if( z==0 ) return SQLITE_OK;
176976  n = sqlite3_value_bytes(argv[0]);
176977  p->zJson = sqlite3_malloc64( n+1 );
176978  if( p->zJson==0 ) return SQLITE_NOMEM;
176979  memcpy(p->zJson, z, (size_t)n+1);
176980  if( jsonParse(&p->sParse, 0, p->zJson) ){
176981    int rc = SQLITE_NOMEM;
176982    if( p->sParse.oom==0 ){
176983      sqlite3_free(cur->pVtab->zErrMsg);
176984      cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
176985      if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
176986    }
176987    jsonEachCursorReset(p);
176988    return rc;
176989  }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
176990    jsonEachCursorReset(p);
176991    return SQLITE_NOMEM;
176992  }else{
176993    JsonNode *pNode = 0;
176994    if( idxNum==3 ){
176995      const char *zErr = 0;
176996      zRoot = (const char*)sqlite3_value_text(argv[1]);
176997      if( zRoot==0 ) return SQLITE_OK;
176998      n = sqlite3_value_bytes(argv[1]);
176999      p->zRoot = sqlite3_malloc64( n+1 );
177000      if( p->zRoot==0 ) return SQLITE_NOMEM;
177001      memcpy(p->zRoot, zRoot, (size_t)n+1);
177002      if( zRoot[0]!='$' ){
177003        zErr = zRoot;
177004      }else{
177005        pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
177006      }
177007      if( zErr ){
177008        sqlite3_free(cur->pVtab->zErrMsg);
177009        cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
177010        jsonEachCursorReset(p);
177011        return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
177012      }else if( pNode==0 ){
177013        return SQLITE_OK;
177014      }
177015    }else{
177016      pNode = p->sParse.aNode;
177017    }
177018    p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
177019    p->eType = pNode->eType;
177020    if( p->eType>=JSON_ARRAY ){
177021      pNode->u.iKey = 0;
177022      p->iEnd = p->i + pNode->n + 1;
177023      if( p->bRecursive ){
177024        p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
177025        if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
177026          p->i--;
177027        }
177028      }else{
177029        p->i++;
177030      }
177031    }else{
177032      p->iEnd = p->i+1;
177033    }
177034  }
177035  return SQLITE_OK;
177036}
177037
177038/* The methods of the json_each virtual table */
177039static sqlite3_module jsonEachModule = {
177040  0,                         /* iVersion */
177041  0,                         /* xCreate */
177042  jsonEachConnect,           /* xConnect */
177043  jsonEachBestIndex,         /* xBestIndex */
177044  jsonEachDisconnect,        /* xDisconnect */
177045  0,                         /* xDestroy */
177046  jsonEachOpenEach,          /* xOpen - open a cursor */
177047  jsonEachClose,             /* xClose - close a cursor */
177048  jsonEachFilter,            /* xFilter - configure scan constraints */
177049  jsonEachNext,              /* xNext - advance a cursor */
177050  jsonEachEof,               /* xEof - check for end of scan */
177051  jsonEachColumn,            /* xColumn - read data */
177052  jsonEachRowid,             /* xRowid - read data */
177053  0,                         /* xUpdate */
177054  0,                         /* xBegin */
177055  0,                         /* xSync */
177056  0,                         /* xCommit */
177057  0,                         /* xRollback */
177058  0,                         /* xFindMethod */
177059  0,                         /* xRename */
177060  0,                         /* xSavepoint */
177061  0,                         /* xRelease */
177062  0                          /* xRollbackTo */
177063};
177064
177065/* The methods of the json_tree virtual table. */
177066static sqlite3_module jsonTreeModule = {
177067  0,                         /* iVersion */
177068  0,                         /* xCreate */
177069  jsonEachConnect,           /* xConnect */
177070  jsonEachBestIndex,         /* xBestIndex */
177071  jsonEachDisconnect,        /* xDisconnect */
177072  0,                         /* xDestroy */
177073  jsonEachOpenTree,          /* xOpen - open a cursor */
177074  jsonEachClose,             /* xClose - close a cursor */
177075  jsonEachFilter,            /* xFilter - configure scan constraints */
177076  jsonEachNext,              /* xNext - advance a cursor */
177077  jsonEachEof,               /* xEof - check for end of scan */
177078  jsonEachColumn,            /* xColumn - read data */
177079  jsonEachRowid,             /* xRowid - read data */
177080  0,                         /* xUpdate */
177081  0,                         /* xBegin */
177082  0,                         /* xSync */
177083  0,                         /* xCommit */
177084  0,                         /* xRollback */
177085  0,                         /* xFindMethod */
177086  0,                         /* xRename */
177087  0,                         /* xSavepoint */
177088  0,                         /* xRelease */
177089  0                          /* xRollbackTo */
177090};
177091#endif /* SQLITE_OMIT_VIRTUALTABLE */
177092
177093/****************************************************************************
177094** The following routines are the only publically visible identifiers in this
177095** file.  Call the following routines in order to register the various SQL
177096** functions and the virtual table implemented by this file.
177097****************************************************************************/
177098
177099SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
177100  int rc = SQLITE_OK;
177101  unsigned int i;
177102  static const struct {
177103     const char *zName;
177104     int nArg;
177105     int flag;
177106     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
177107  } aFunc[] = {
177108    { "json",                 1, 0,   jsonRemoveFunc        },
177109    { "json_array",          -1, 0,   jsonArrayFunc         },
177110    { "json_array_length",    1, 0,   jsonArrayLengthFunc   },
177111    { "json_array_length",    2, 0,   jsonArrayLengthFunc   },
177112    { "json_extract",        -1, 0,   jsonExtractFunc       },
177113    { "json_insert",         -1, 0,   jsonSetFunc           },
177114    { "json_object",         -1, 0,   jsonObjectFunc        },
177115    { "json_quote",           1, 0,   jsonQuoteFunc         },
177116    { "json_remove",         -1, 0,   jsonRemoveFunc        },
177117    { "json_replace",        -1, 0,   jsonReplaceFunc       },
177118    { "json_set",            -1, 1,   jsonSetFunc           },
177119    { "json_type",            1, 0,   jsonTypeFunc          },
177120    { "json_type",            2, 0,   jsonTypeFunc          },
177121    { "json_valid",           1, 0,   jsonValidFunc         },
177122
177123#if SQLITE_DEBUG
177124    /* DEBUG and TESTING functions */
177125    { "json_parse",           1, 0,   jsonParseFunc         },
177126    { "json_test1",           1, 0,   jsonTest1Func         },
177127#endif
177128  };
177129  static const struct {
177130     const char *zName;
177131     int nArg;
177132     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
177133     void (*xFinal)(sqlite3_context*);
177134  } aAgg[] = {
177135    { "json_group_array",     1,   jsonArrayStep,   jsonArrayFinal  },
177136    { "json_group_object",    2,   jsonObjectStep,  jsonObjectFinal },
177137  };
177138#ifndef SQLITE_OMIT_VIRTUALTABLE
177139  static const struct {
177140     const char *zName;
177141     sqlite3_module *pModule;
177142  } aMod[] = {
177143    { "json_each",            &jsonEachModule               },
177144    { "json_tree",            &jsonTreeModule               },
177145  };
177146#endif
177147  for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
177148    rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
177149                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
177150                                 (void*)&aFunc[i].flag,
177151                                 aFunc[i].xFunc, 0, 0);
177152  }
177153  for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
177154    rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
177155                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
177156                                 0, aAgg[i].xStep, aAgg[i].xFinal);
177157  }
177158#ifndef SQLITE_OMIT_VIRTUALTABLE
177159  for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
177160    rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
177161  }
177162#endif
177163  return rc;
177164}
177165
177166
177167#ifndef SQLITE_CORE
177168#ifdef _WIN32
177169__declspec(dllexport)
177170#endif
177171SQLITE_API int SQLITE_STDCALL sqlite3_json_init(
177172  sqlite3 *db,
177173  char **pzErrMsg,
177174  const sqlite3_api_routines *pApi
177175){
177176  SQLITE_EXTENSION_INIT2(pApi);
177177  (void)pzErrMsg;  /* Unused parameter */
177178  return sqlite3Json1Init(db);
177179}
177180#endif
177181#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
177182
177183/************** End of json1.c ***********************************************/
177184/************** Begin file fts5.c ********************************************/
177185
177186
177187#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
177188
177189#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
177190# define NDEBUG 1
177191#endif
177192#if defined(NDEBUG) && defined(SQLITE_DEBUG)
177193# undef NDEBUG
177194#endif
177195
177196/*
177197** 2014 May 31
177198**
177199** The author disclaims copyright to this source code.  In place of
177200** a legal notice, here is a blessing:
177201**
177202**    May you do good and not evil.
177203**    May you find forgiveness for yourself and forgive others.
177204**    May you share freely, never taking more than you give.
177205**
177206******************************************************************************
177207**
177208** Interfaces to extend FTS5. Using the interfaces defined in this file,
177209** FTS5 may be extended with:
177210**
177211**     * custom tokenizers, and
177212**     * custom auxiliary functions.
177213*/
177214
177215
177216#ifndef _FTS5_H
177217#define _FTS5_H
177218
177219/* #include "sqlite3.h" */
177220
177221#if 0
177222extern "C" {
177223#endif
177224
177225/*************************************************************************
177226** CUSTOM AUXILIARY FUNCTIONS
177227**
177228** Virtual table implementations may overload SQL functions by implementing
177229** the sqlite3_module.xFindFunction() method.
177230*/
177231
177232typedef struct Fts5ExtensionApi Fts5ExtensionApi;
177233typedef struct Fts5Context Fts5Context;
177234typedef struct Fts5PhraseIter Fts5PhraseIter;
177235
177236typedef void (*fts5_extension_function)(
177237  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
177238  Fts5Context *pFts,              /* First arg to pass to pApi functions */
177239  sqlite3_context *pCtx,          /* Context for returning result/error */
177240  int nVal,                       /* Number of values in apVal[] array */
177241  sqlite3_value **apVal           /* Array of trailing arguments */
177242);
177243
177244struct Fts5PhraseIter {
177245  const unsigned char *a;
177246  const unsigned char *b;
177247};
177248
177249/*
177250** EXTENSION API FUNCTIONS
177251**
177252** xUserData(pFts):
177253**   Return a copy of the context pointer the extension function was
177254**   registered with.
177255**
177256** xColumnTotalSize(pFts, iCol, pnToken):
177257**   If parameter iCol is less than zero, set output variable *pnToken
177258**   to the total number of tokens in the FTS5 table. Or, if iCol is
177259**   non-negative but less than the number of columns in the table, return
177260**   the total number of tokens in column iCol, considering all rows in
177261**   the FTS5 table.
177262**
177263**   If parameter iCol is greater than or equal to the number of columns
177264**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
177265**   an OOM condition or IO error), an appropriate SQLite error code is
177266**   returned.
177267**
177268** xColumnCount(pFts):
177269**   Return the number of columns in the table.
177270**
177271** xColumnSize(pFts, iCol, pnToken):
177272**   If parameter iCol is less than zero, set output variable *pnToken
177273**   to the total number of tokens in the current row. Or, if iCol is
177274**   non-negative but less than the number of columns in the table, set
177275**   *pnToken to the number of tokens in column iCol of the current row.
177276**
177277**   If parameter iCol is greater than or equal to the number of columns
177278**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
177279**   an OOM condition or IO error), an appropriate SQLite error code is
177280**   returned.
177281**
177282**   This function may be quite inefficient if used with an FTS5 table
177283**   created with the "columnsize=0" option.
177284**
177285** xColumnText:
177286**   This function attempts to retrieve the text of column iCol of the
177287**   current document. If successful, (*pz) is set to point to a buffer
177288**   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
177289**   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
177290**   if an error occurs, an SQLite error code is returned and the final values
177291**   of (*pz) and (*pn) are undefined.
177292**
177293** xPhraseCount:
177294**   Returns the number of phrases in the current query expression.
177295**
177296** xPhraseSize:
177297**   Returns the number of tokens in phrase iPhrase of the query. Phrases
177298**   are numbered starting from zero.
177299**
177300** xInstCount:
177301**   Set *pnInst to the total number of occurrences of all phrases within
177302**   the query within the current row. Return SQLITE_OK if successful, or
177303**   an error code (i.e. SQLITE_NOMEM) if an error occurs.
177304**
177305**   This API can be quite slow if used with an FTS5 table created with the
177306**   "detail=none" or "detail=column" option. If the FTS5 table is created
177307**   with either "detail=none" or "detail=column" and "content=" option
177308**   (i.e. if it is a contentless table), then this API always returns 0.
177309**
177310** xInst:
177311**   Query for the details of phrase match iIdx within the current row.
177312**   Phrase matches are numbered starting from zero, so the iIdx argument
177313**   should be greater than or equal to zero and smaller than the value
177314**   output by xInstCount().
177315**
177316**   Usually, output parameter *piPhrase is set to the phrase number, *piCol
177317**   to the column in which it occurs and *piOff the token offset of the
177318**   first token of the phrase. The exception is if the table was created
177319**   with the offsets=0 option specified. In this case *piOff is always
177320**   set to -1.
177321**
177322**   Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
177323**   if an error occurs.
177324**
177325**   This API can be quite slow if used with an FTS5 table created with the
177326**   "detail=none" or "detail=column" option.
177327**
177328** xRowid:
177329**   Returns the rowid of the current row.
177330**
177331** xTokenize:
177332**   Tokenize text using the tokenizer belonging to the FTS5 table.
177333**
177334** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
177335**   This API function is used to query the FTS table for phrase iPhrase
177336**   of the current query. Specifically, a query equivalent to:
177337**
177338**       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
177339**
177340**   with $p set to a phrase equivalent to the phrase iPhrase of the
177341**   current query is executed. Any column filter that applies to
177342**   phrase iPhrase of the current query is included in $p. For each
177343**   row visited, the callback function passed as the fourth argument
177344**   is invoked. The context and API objects passed to the callback
177345**   function may be used to access the properties of each matched row.
177346**   Invoking Api.xUserData() returns a copy of the pointer passed as
177347**   the third argument to pUserData.
177348**
177349**   If the callback function returns any value other than SQLITE_OK, the
177350**   query is abandoned and the xQueryPhrase function returns immediately.
177351**   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
177352**   Otherwise, the error code is propagated upwards.
177353**
177354**   If the query runs to completion without incident, SQLITE_OK is returned.
177355**   Or, if some error occurs before the query completes or is aborted by
177356**   the callback, an SQLite error code is returned.
177357**
177358**
177359** xSetAuxdata(pFts5, pAux, xDelete)
177360**
177361**   Save the pointer passed as the second argument as the extension functions
177362**   "auxiliary data". The pointer may then be retrieved by the current or any
177363**   future invocation of the same fts5 extension function made as part of
177364**   of the same MATCH query using the xGetAuxdata() API.
177365**
177366**   Each extension function is allocated a single auxiliary data slot for
177367**   each FTS query (MATCH expression). If the extension function is invoked
177368**   more than once for a single FTS query, then all invocations share a
177369**   single auxiliary data context.
177370**
177371**   If there is already an auxiliary data pointer when this function is
177372**   invoked, then it is replaced by the new pointer. If an xDelete callback
177373**   was specified along with the original pointer, it is invoked at this
177374**   point.
177375**
177376**   The xDelete callback, if one is specified, is also invoked on the
177377**   auxiliary data pointer after the FTS5 query has finished.
177378**
177379**   If an error (e.g. an OOM condition) occurs within this function, an
177380**   the auxiliary data is set to NULL and an error code returned. If the
177381**   xDelete parameter was not NULL, it is invoked on the auxiliary data
177382**   pointer before returning.
177383**
177384**
177385** xGetAuxdata(pFts5, bClear)
177386**
177387**   Returns the current auxiliary data pointer for the fts5 extension
177388**   function. See the xSetAuxdata() method for details.
177389**
177390**   If the bClear argument is non-zero, then the auxiliary data is cleared
177391**   (set to NULL) before this function returns. In this case the xDelete,
177392**   if any, is not invoked.
177393**
177394**
177395** xRowCount(pFts5, pnRow)
177396**
177397**   This function is used to retrieve the total number of rows in the table.
177398**   In other words, the same value that would be returned by:
177399**
177400**        SELECT count(*) FROM ftstable;
177401**
177402** xPhraseFirst()
177403**   This function is used, along with type Fts5PhraseIter and the xPhraseNext
177404**   method, to iterate through all instances of a single query phrase within
177405**   the current row. This is the same information as is accessible via the
177406**   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
177407**   to use, this API may be faster under some circumstances. To iterate
177408**   through instances of phrase iPhrase, use the following code:
177409**
177410**       Fts5PhraseIter iter;
177411**       int iCol, iOff;
177412**       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
177413**           iCol>=0;
177414**           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
177415**       ){
177416**         // An instance of phrase iPhrase at offset iOff of column iCol
177417**       }
177418**
177419**   The Fts5PhraseIter structure is defined above. Applications should not
177420**   modify this structure directly - it should only be used as shown above
177421**   with the xPhraseFirst() and xPhraseNext() API methods (and by
177422**   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
177423**
177424**   This API can be quite slow if used with an FTS5 table created with the
177425**   "detail=none" or "detail=column" option. If the FTS5 table is created
177426**   with either "detail=none" or "detail=column" and "content=" option
177427**   (i.e. if it is a contentless table), then this API always iterates
177428**   through an empty set (all calls to xPhraseFirst() set iCol to -1).
177429**
177430** xPhraseNext()
177431**   See xPhraseFirst above.
177432**
177433** xPhraseFirstColumn()
177434**   This function and xPhraseNextColumn() are similar to the xPhraseFirst()
177435**   and xPhraseNext() APIs described above. The difference is that instead
177436**   of iterating through all instances of a phrase in the current row, these
177437**   APIs are used to iterate through the set of columns in the current row
177438**   that contain one or more instances of a specified phrase. For example:
177439**
177440**       Fts5PhraseIter iter;
177441**       int iCol;
177442**       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
177443**           iCol>=0;
177444**           pApi->xPhraseNextColumn(pFts, &iter, &iCol)
177445**       ){
177446**         // Column iCol contains at least one instance of phrase iPhrase
177447**       }
177448**
177449**   This API can be quite slow if used with an FTS5 table created with the
177450**   "detail=none" option. If the FTS5 table is created with either
177451**   "detail=none" "content=" option (i.e. if it is a contentless table),
177452**   then this API always iterates through an empty set (all calls to
177453**   xPhraseFirstColumn() set iCol to -1).
177454**
177455**   The information accessed using this API and its companion
177456**   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
177457**   (or xInst/xInstCount). The chief advantage of this API is that it is
177458**   significantly more efficient than those alternatives when used with
177459**   "detail=column" tables.
177460**
177461** xPhraseNextColumn()
177462**   See xPhraseFirstColumn above.
177463*/
177464struct Fts5ExtensionApi {
177465  int iVersion;                   /* Currently always set to 3 */
177466
177467  void *(*xUserData)(Fts5Context*);
177468
177469  int (*xColumnCount)(Fts5Context*);
177470  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
177471  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
177472
177473  int (*xTokenize)(Fts5Context*,
177474    const char *pText, int nText, /* Text to tokenize */
177475    void *pCtx,                   /* Context passed to xToken() */
177476    int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
177477  );
177478
177479  int (*xPhraseCount)(Fts5Context*);
177480  int (*xPhraseSize)(Fts5Context*, int iPhrase);
177481
177482  int (*xInstCount)(Fts5Context*, int *pnInst);
177483  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
177484
177485  sqlite3_int64 (*xRowid)(Fts5Context*);
177486  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
177487  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
177488
177489  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
177490    int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
177491  );
177492  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
177493  void *(*xGetAuxdata)(Fts5Context*, int bClear);
177494
177495  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
177496  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
177497
177498  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
177499  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
177500};
177501
177502/*
177503** CUSTOM AUXILIARY FUNCTIONS
177504*************************************************************************/
177505
177506/*************************************************************************
177507** CUSTOM TOKENIZERS
177508**
177509** Applications may also register custom tokenizer types. A tokenizer
177510** is registered by providing fts5 with a populated instance of the
177511** following structure. All structure methods must be defined, setting
177512** any member of the fts5_tokenizer struct to NULL leads to undefined
177513** behaviour. The structure methods are expected to function as follows:
177514**
177515** xCreate:
177516**   This function is used to allocate and initialize a tokenizer instance.
177517**   A tokenizer instance is required to actually tokenize text.
177518**
177519**   The first argument passed to this function is a copy of the (void*)
177520**   pointer provided by the application when the fts5_tokenizer object
177521**   was registered with FTS5 (the third argument to xCreateTokenizer()).
177522**   The second and third arguments are an array of nul-terminated strings
177523**   containing the tokenizer arguments, if any, specified following the
177524**   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
177525**   to create the FTS5 table.
177526**
177527**   The final argument is an output variable. If successful, (*ppOut)
177528**   should be set to point to the new tokenizer handle and SQLITE_OK
177529**   returned. If an error occurs, some value other than SQLITE_OK should
177530**   be returned. In this case, fts5 assumes that the final value of *ppOut
177531**   is undefined.
177532**
177533** xDelete:
177534**   This function is invoked to delete a tokenizer handle previously
177535**   allocated using xCreate(). Fts5 guarantees that this function will
177536**   be invoked exactly once for each successful call to xCreate().
177537**
177538** xTokenize:
177539**   This function is expected to tokenize the nText byte string indicated
177540**   by argument pText. pText may or may not be nul-terminated. The first
177541**   argument passed to this function is a pointer to an Fts5Tokenizer object
177542**   returned by an earlier call to xCreate().
177543**
177544**   The second argument indicates the reason that FTS5 is requesting
177545**   tokenization of the supplied text. This is always one of the following
177546**   four values:
177547**
177548**   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
177549**            or removed from the FTS table. The tokenizer is being invoked to
177550**            determine the set of tokens to add to (or delete from) the
177551**            FTS index.
177552**
177553**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
177554**            against the FTS index. The tokenizer is being called to tokenize
177555**            a bareword or quoted string specified as part of the query.
177556**
177557**       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
177558**            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
177559**            followed by a "*" character, indicating that the last token
177560**            returned by the tokenizer will be treated as a token prefix.
177561**
177562**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
177563**            satisfy an fts5_api.xTokenize() request made by an auxiliary
177564**            function. Or an fts5_api.xColumnSize() request made by the same
177565**            on a columnsize=0 database.
177566**   </ul>
177567**
177568**   For each token in the input string, the supplied callback xToken() must
177569**   be invoked. The first argument to it should be a copy of the pointer
177570**   passed as the second argument to xTokenize(). The third and fourth
177571**   arguments are a pointer to a buffer containing the token text, and the
177572**   size of the token in bytes. The 4th and 5th arguments are the byte offsets
177573**   of the first byte of and first byte immediately following the text from
177574**   which the token is derived within the input.
177575**
177576**   The second argument passed to the xToken() callback ("tflags") should
177577**   normally be set to 0. The exception is if the tokenizer supports
177578**   synonyms. In this case see the discussion below for details.
177579**
177580**   FTS5 assumes the xToken() callback is invoked for each token in the
177581**   order that they occur within the input text.
177582**
177583**   If an xToken() callback returns any value other than SQLITE_OK, then
177584**   the tokenization should be abandoned and the xTokenize() method should
177585**   immediately return a copy of the xToken() return value. Or, if the
177586**   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
177587**   if an error occurs with the xTokenize() implementation itself, it
177588**   may abandon the tokenization and return any error code other than
177589**   SQLITE_OK or SQLITE_DONE.
177590**
177591** SYNONYM SUPPORT
177592**
177593**   Custom tokenizers may also support synonyms. Consider a case in which a
177594**   user wishes to query for a phrase such as "first place". Using the
177595**   built-in tokenizers, the FTS5 query 'first + place' will match instances
177596**   of "first place" within the document set, but not alternative forms
177597**   such as "1st place". In some applications, it would be better to match
177598**   all instances of "first place" or "1st place" regardless of which form
177599**   the user specified in the MATCH query text.
177600**
177601**   There are several ways to approach this in FTS5:
177602**
177603**   <ol><li> By mapping all synonyms to a single token. In this case, the
177604**            In the above example, this means that the tokenizer returns the
177605**            same token for inputs "first" and "1st". Say that token is in
177606**            fact "first", so that when the user inserts the document "I won
177607**            1st place" entries are added to the index for tokens "i", "won",
177608**            "first" and "place". If the user then queries for '1st + place',
177609**            the tokenizer substitutes "first" for "1st" and the query works
177610**            as expected.
177611**
177612**       <li> By adding multiple synonyms for a single term to the FTS index.
177613**            In this case, when tokenizing query text, the tokenizer may
177614**            provide multiple synonyms for a single term within the document.
177615**            FTS5 then queries the index for each synonym individually. For
177616**            example, faced with the query:
177617**
177618**   <codeblock>
177619**     ... MATCH 'first place'</codeblock>
177620**
177621**            the tokenizer offers both "1st" and "first" as synonyms for the
177622**            first token in the MATCH query and FTS5 effectively runs a query
177623**            similar to:
177624**
177625**   <codeblock>
177626**     ... MATCH '(first OR 1st) place'</codeblock>
177627**
177628**            except that, for the purposes of auxiliary functions, the query
177629**            still appears to contain just two phrases - "(first OR 1st)"
177630**            being treated as a single phrase.
177631**
177632**       <li> By adding multiple synonyms for a single term to the FTS index.
177633**            Using this method, when tokenizing document text, the tokenizer
177634**            provides multiple synonyms for each token. So that when a
177635**            document such as "I won first place" is tokenized, entries are
177636**            added to the FTS index for "i", "won", "first", "1st" and
177637**            "place".
177638**
177639**            This way, even if the tokenizer does not provide synonyms
177640**            when tokenizing query text (it should not - to do would be
177641**            inefficient), it doesn't matter if the user queries for
177642**            'first + place' or '1st + place', as there are entires in the
177643**            FTS index corresponding to both forms of the first token.
177644**   </ol>
177645**
177646**   Whether it is parsing document or query text, any call to xToken that
177647**   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
177648**   is considered to supply a synonym for the previous token. For example,
177649**   when parsing the document "I won first place", a tokenizer that supports
177650**   synonyms would call xToken() 5 times, as follows:
177651**
177652**   <codeblock>
177653**       xToken(pCtx, 0, "i",                      1,  0,  1);
177654**       xToken(pCtx, 0, "won",                    3,  2,  5);
177655**       xToken(pCtx, 0, "first",                  5,  6, 11);
177656**       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
177657**       xToken(pCtx, 0, "place",                  5, 12, 17);
177658**</codeblock>
177659**
177660**   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
177661**   xToken() is called. Multiple synonyms may be specified for a single token
177662**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
177663**   There is no limit to the number of synonyms that may be provided for a
177664**   single token.
177665**
177666**   In many cases, method (1) above is the best approach. It does not add
177667**   extra data to the FTS index or require FTS5 to query for multiple terms,
177668**   so it is efficient in terms of disk space and query speed. However, it
177669**   does not support prefix queries very well. If, as suggested above, the
177670**   token "first" is subsituted for "1st" by the tokenizer, then the query:
177671**
177672**   <codeblock>
177673**     ... MATCH '1s*'</codeblock>
177674**
177675**   will not match documents that contain the token "1st" (as the tokenizer
177676**   will probably not map "1s" to any prefix of "first").
177677**
177678**   For full prefix support, method (3) may be preferred. In this case,
177679**   because the index contains entries for both "first" and "1st", prefix
177680**   queries such as 'fi*' or '1s*' will match correctly. However, because
177681**   extra entries are added to the FTS index, this method uses more space
177682**   within the database.
177683**
177684**   Method (2) offers a midpoint between (1) and (3). Using this method,
177685**   a query such as '1s*' will match documents that contain the literal
177686**   token "1st", but not "first" (assuming the tokenizer is not able to
177687**   provide synonyms for prefixes). However, a non-prefix query like '1st'
177688**   will match against "1st" and "first". This method does not require
177689**   extra disk space, as no extra entries are added to the FTS index.
177690**   On the other hand, it may require more CPU cycles to run MATCH queries,
177691**   as separate queries of the FTS index are required for each synonym.
177692**
177693**   When using methods (2) or (3), it is important that the tokenizer only
177694**   provide synonyms when tokenizing document text (method (2)) or query
177695**   text (method (3)), not both. Doing so will not cause any errors, but is
177696**   inefficient.
177697*/
177698typedef struct Fts5Tokenizer Fts5Tokenizer;
177699typedef struct fts5_tokenizer fts5_tokenizer;
177700struct fts5_tokenizer {
177701  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
177702  void (*xDelete)(Fts5Tokenizer*);
177703  int (*xTokenize)(Fts5Tokenizer*,
177704      void *pCtx,
177705      int flags,            /* Mask of FTS5_TOKENIZE_* flags */
177706      const char *pText, int nText,
177707      int (*xToken)(
177708        void *pCtx,         /* Copy of 2nd argument to xTokenize() */
177709        int tflags,         /* Mask of FTS5_TOKEN_* flags */
177710        const char *pToken, /* Pointer to buffer containing token */
177711        int nToken,         /* Size of token in bytes */
177712        int iStart,         /* Byte offset of token within input text */
177713        int iEnd            /* Byte offset of end of token within input text */
177714      )
177715  );
177716};
177717
177718/* Flags that may be passed as the third argument to xTokenize() */
177719#define FTS5_TOKENIZE_QUERY     0x0001
177720#define FTS5_TOKENIZE_PREFIX    0x0002
177721#define FTS5_TOKENIZE_DOCUMENT  0x0004
177722#define FTS5_TOKENIZE_AUX       0x0008
177723
177724/* Flags that may be passed by the tokenizer implementation back to FTS5
177725** as the third argument to the supplied xToken callback. */
177726#define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
177727
177728/*
177729** END OF CUSTOM TOKENIZERS
177730*************************************************************************/
177731
177732/*************************************************************************
177733** FTS5 EXTENSION REGISTRATION API
177734*/
177735typedef struct fts5_api fts5_api;
177736struct fts5_api {
177737  int iVersion;                   /* Currently always set to 2 */
177738
177739  /* Create a new tokenizer */
177740  int (*xCreateTokenizer)(
177741    fts5_api *pApi,
177742    const char *zName,
177743    void *pContext,
177744    fts5_tokenizer *pTokenizer,
177745    void (*xDestroy)(void*)
177746  );
177747
177748  /* Find an existing tokenizer */
177749  int (*xFindTokenizer)(
177750    fts5_api *pApi,
177751    const char *zName,
177752    void **ppContext,
177753    fts5_tokenizer *pTokenizer
177754  );
177755
177756  /* Create a new auxiliary function */
177757  int (*xCreateFunction)(
177758    fts5_api *pApi,
177759    const char *zName,
177760    void *pContext,
177761    fts5_extension_function xFunction,
177762    void (*xDestroy)(void*)
177763  );
177764};
177765
177766/*
177767** END OF REGISTRATION API
177768*************************************************************************/
177769
177770#if 0
177771}  /* end of the 'extern "C"' block */
177772#endif
177773
177774#endif /* _FTS5_H */
177775
177776/*
177777** 2014 May 31
177778**
177779** The author disclaims copyright to this source code.  In place of
177780** a legal notice, here is a blessing:
177781**
177782**    May you do good and not evil.
177783**    May you find forgiveness for yourself and forgive others.
177784**    May you share freely, never taking more than you give.
177785**
177786******************************************************************************
177787**
177788*/
177789#ifndef _FTS5INT_H
177790#define _FTS5INT_H
177791
177792/* #include "fts5.h" */
177793/* #include "sqlite3ext.h" */
177794SQLITE_EXTENSION_INIT1
177795
177796/* #include <string.h> */
177797/* #include <assert.h> */
177798
177799#ifndef SQLITE_AMALGAMATION
177800
177801typedef unsigned char  u8;
177802typedef unsigned int   u32;
177803typedef unsigned short u16;
177804typedef short i16;
177805typedef sqlite3_int64 i64;
177806typedef sqlite3_uint64 u64;
177807
177808#define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
177809
177810#define testcase(x)
177811#define ALWAYS(x) 1
177812#define NEVER(x) 0
177813
177814#define MIN(x,y) (((x) < (y)) ? (x) : (y))
177815#define MAX(x,y) (((x) > (y)) ? (x) : (y))
177816
177817/*
177818** Constants for the largest and smallest possible 64-bit signed integers.
177819*/
177820# define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
177821# define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
177822
177823#endif
177824
177825/* Truncate very long tokens to this many bytes. Hard limit is
177826** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
177827** field that occurs at the start of each leaf page (see fts5_index.c). */
177828#define FTS5_MAX_TOKEN_SIZE 32768
177829
177830/*
177831** Maximum number of prefix indexes on single FTS5 table. This must be
177832** less than 32. If it is set to anything large than that, an #error
177833** directive in fts5_index.c will cause the build to fail.
177834*/
177835#define FTS5_MAX_PREFIX_INDEXES 31
177836
177837#define FTS5_DEFAULT_NEARDIST 10
177838#define FTS5_DEFAULT_RANK     "bm25"
177839
177840/* Name of rank and rowid columns */
177841#define FTS5_RANK_NAME "rank"
177842#define FTS5_ROWID_NAME "rowid"
177843
177844#ifdef SQLITE_DEBUG
177845# define FTS5_CORRUPT sqlite3Fts5Corrupt()
177846static int sqlite3Fts5Corrupt(void);
177847#else
177848# define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
177849#endif
177850
177851/*
177852** The assert_nc() macro is similar to the assert() macro, except that it
177853** is used for assert() conditions that are true only if it can be
177854** guranteed that the database is not corrupt.
177855*/
177856#ifdef SQLITE_DEBUG
177857SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
177858# define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
177859#else
177860# define assert_nc(x) assert(x)
177861#endif
177862
177863/* Mark a function parameter as unused, to suppress nuisance compiler
177864** warnings. */
177865#ifndef UNUSED_PARAM
177866# define UNUSED_PARAM(X)  (void)(X)
177867#endif
177868
177869#ifndef UNUSED_PARAM2
177870# define UNUSED_PARAM2(X, Y)  (void)(X), (void)(Y)
177871#endif
177872
177873typedef struct Fts5Global Fts5Global;
177874typedef struct Fts5Colset Fts5Colset;
177875
177876/* If a NEAR() clump or phrase may only match a specific set of columns,
177877** then an object of the following type is used to record the set of columns.
177878** Each entry in the aiCol[] array is a column that may be matched.
177879**
177880** This object is used by fts5_expr.c and fts5_index.c.
177881*/
177882struct Fts5Colset {
177883  int nCol;
177884  int aiCol[1];
177885};
177886
177887
177888
177889/**************************************************************************
177890** Interface to code in fts5_config.c. fts5_config.c contains contains code
177891** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
177892*/
177893
177894typedef struct Fts5Config Fts5Config;
177895
177896/*
177897** An instance of the following structure encodes all information that can
177898** be gleaned from the CREATE VIRTUAL TABLE statement.
177899**
177900** And all information loaded from the %_config table.
177901**
177902** nAutomerge:
177903**   The minimum number of segments that an auto-merge operation should
177904**   attempt to merge together. A value of 1 sets the object to use the
177905**   compile time default. Zero disables auto-merge altogether.
177906**
177907** zContent:
177908**
177909** zContentRowid:
177910**   The value of the content_rowid= option, if one was specified. Or
177911**   the string "rowid" otherwise. This text is not quoted - if it is
177912**   used as part of an SQL statement it needs to be quoted appropriately.
177913**
177914** zContentExprlist:
177915**
177916** pzErrmsg:
177917**   This exists in order to allow the fts5_index.c module to return a
177918**   decent error message if it encounters a file-format version it does
177919**   not understand.
177920**
177921** bColumnsize:
177922**   True if the %_docsize table is created.
177923**
177924** bPrefixIndex:
177925**   This is only used for debugging. If set to false, any prefix indexes
177926**   are ignored. This value is configured using:
177927**
177928**       INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
177929**
177930*/
177931struct Fts5Config {
177932  sqlite3 *db;                    /* Database handle */
177933  char *zDb;                      /* Database holding FTS index (e.g. "main") */
177934  char *zName;                    /* Name of FTS index */
177935  int nCol;                       /* Number of columns */
177936  char **azCol;                   /* Column names */
177937  u8 *abUnindexed;                /* True for unindexed columns */
177938  int nPrefix;                    /* Number of prefix indexes */
177939  int *aPrefix;                   /* Sizes in bytes of nPrefix prefix indexes */
177940  int eContent;                   /* An FTS5_CONTENT value */
177941  char *zContent;                 /* content table */
177942  char *zContentRowid;            /* "content_rowid=" option value */
177943  int bColumnsize;                /* "columnsize=" option value (dflt==1) */
177944  int eDetail;                    /* FTS5_DETAIL_XXX value */
177945  char *zContentExprlist;
177946  Fts5Tokenizer *pTok;
177947  fts5_tokenizer *pTokApi;
177948
177949  /* Values loaded from the %_config table */
177950  int iCookie;                    /* Incremented when %_config is modified */
177951  int pgsz;                       /* Approximate page size used in %_data */
177952  int nAutomerge;                 /* 'automerge' setting */
177953  int nCrisisMerge;               /* Maximum allowed segments per level */
177954  int nUsermerge;                 /* 'usermerge' setting */
177955  int nHashSize;                  /* Bytes of memory for in-memory hash */
177956  char *zRank;                    /* Name of rank function */
177957  char *zRankArgs;                /* Arguments to rank function */
177958
177959  /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
177960  char **pzErrmsg;
177961
177962#ifdef SQLITE_DEBUG
177963  int bPrefixIndex;               /* True to use prefix-indexes */
177964#endif
177965};
177966
177967/* Current expected value of %_config table 'version' field */
177968#define FTS5_CURRENT_VERSION 4
177969
177970#define FTS5_CONTENT_NORMAL   0
177971#define FTS5_CONTENT_NONE     1
177972#define FTS5_CONTENT_EXTERNAL 2
177973
177974#define FTS5_DETAIL_FULL    0
177975#define FTS5_DETAIL_NONE    1
177976#define FTS5_DETAIL_COLUMNS 2
177977
177978
177979
177980static int sqlite3Fts5ConfigParse(
177981    Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
177982);
177983static void sqlite3Fts5ConfigFree(Fts5Config*);
177984
177985static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
177986
177987static int sqlite3Fts5Tokenize(
177988  Fts5Config *pConfig,            /* FTS5 Configuration object */
177989  int flags,                      /* FTS5_TOKENIZE_* flags */
177990  const char *pText, int nText,   /* Text to tokenize */
177991  void *pCtx,                     /* Context passed to xToken() */
177992  int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
177993);
177994
177995static void sqlite3Fts5Dequote(char *z);
177996
177997/* Load the contents of the %_config table */
177998static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
177999
178000/* Set the value of a single config attribute */
178001static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
178002
178003static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
178004
178005/*
178006** End of interface to code in fts5_config.c.
178007**************************************************************************/
178008
178009/**************************************************************************
178010** Interface to code in fts5_buffer.c.
178011*/
178012
178013/*
178014** Buffer object for the incremental building of string data.
178015*/
178016typedef struct Fts5Buffer Fts5Buffer;
178017struct Fts5Buffer {
178018  u8 *p;
178019  int n;
178020  int nSpace;
178021};
178022
178023static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
178024static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
178025static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
178026static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
178027static void sqlite3Fts5BufferFree(Fts5Buffer*);
178028static void sqlite3Fts5BufferZero(Fts5Buffer*);
178029static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
178030static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
178031
178032static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
178033
178034#define fts5BufferZero(x)             sqlite3Fts5BufferZero(x)
178035#define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
178036#define fts5BufferFree(a)             sqlite3Fts5BufferFree(a)
178037#define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
178038#define fts5BufferSet(a,b,c,d)        sqlite3Fts5BufferSet(a,b,c,d)
178039
178040#define fts5BufferGrow(pRc,pBuf,nn) ( \
178041  (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
178042    sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
178043)
178044
178045/* Write and decode big-endian 32-bit integer values */
178046static void sqlite3Fts5Put32(u8*, int);
178047static int sqlite3Fts5Get32(const u8*);
178048
178049#define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
178050#define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
178051
178052typedef struct Fts5PoslistReader Fts5PoslistReader;
178053struct Fts5PoslistReader {
178054  /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
178055  const u8 *a;                    /* Position list to iterate through */
178056  int n;                          /* Size of buffer at a[] in bytes */
178057  int i;                          /* Current offset in a[] */
178058
178059  u8 bFlag;                       /* For client use (any custom purpose) */
178060
178061  /* Output variables */
178062  u8 bEof;                        /* Set to true at EOF */
178063  i64 iPos;                       /* (iCol<<32) + iPos */
178064};
178065static int sqlite3Fts5PoslistReaderInit(
178066  const u8 *a, int n,             /* Poslist buffer to iterate through */
178067  Fts5PoslistReader *pIter        /* Iterator object to initialize */
178068);
178069static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
178070
178071typedef struct Fts5PoslistWriter Fts5PoslistWriter;
178072struct Fts5PoslistWriter {
178073  i64 iPrev;
178074};
178075static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
178076static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
178077
178078static int sqlite3Fts5PoslistNext64(
178079  const u8 *a, int n,             /* Buffer containing poslist */
178080  int *pi,                        /* IN/OUT: Offset within a[] */
178081  i64 *piOff                      /* IN/OUT: Current offset */
178082);
178083
178084/* Malloc utility */
178085static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
178086static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
178087
178088/* Character set tests (like isspace(), isalpha() etc.) */
178089static int sqlite3Fts5IsBareword(char t);
178090
178091
178092/* Bucket of terms object used by the integrity-check in offsets=0 mode. */
178093typedef struct Fts5Termset Fts5Termset;
178094static int sqlite3Fts5TermsetNew(Fts5Termset**);
178095static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
178096static void sqlite3Fts5TermsetFree(Fts5Termset*);
178097
178098/*
178099** End of interface to code in fts5_buffer.c.
178100**************************************************************************/
178101
178102/**************************************************************************
178103** Interface to code in fts5_index.c. fts5_index.c contains contains code
178104** to access the data stored in the %_data table.
178105*/
178106
178107typedef struct Fts5Index Fts5Index;
178108typedef struct Fts5IndexIter Fts5IndexIter;
178109
178110struct Fts5IndexIter {
178111  i64 iRowid;
178112  const u8 *pData;
178113  int nData;
178114  u8 bEof;
178115};
178116
178117#define sqlite3Fts5IterEof(x) ((x)->bEof)
178118
178119/*
178120** Values used as part of the flags argument passed to IndexQuery().
178121*/
178122#define FTS5INDEX_QUERY_PREFIX     0x0001   /* Prefix query */
178123#define FTS5INDEX_QUERY_DESC       0x0002   /* Docs in descending rowid order */
178124#define FTS5INDEX_QUERY_TEST_NOIDX 0x0004   /* Do not use prefix index */
178125#define FTS5INDEX_QUERY_SCAN       0x0008   /* Scan query (fts5vocab) */
178126
178127/* The following are used internally by the fts5_index.c module. They are
178128** defined here only to make it easier to avoid clashes with the flags
178129** above. */
178130#define FTS5INDEX_QUERY_SKIPEMPTY  0x0010
178131#define FTS5INDEX_QUERY_NOOUTPUT   0x0020
178132
178133/*
178134** Create/destroy an Fts5Index object.
178135*/
178136static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
178137static int sqlite3Fts5IndexClose(Fts5Index *p);
178138
178139/*
178140** Return a simple checksum value based on the arguments.
178141*/
178142static u64 sqlite3Fts5IndexEntryCksum(
178143  i64 iRowid,
178144  int iCol,
178145  int iPos,
178146  int iIdx,
178147  const char *pTerm,
178148  int nTerm
178149);
178150
178151/*
178152** Argument p points to a buffer containing utf-8 text that is n bytes in
178153** size. Return the number of bytes in the nChar character prefix of the
178154** buffer, or 0 if there are less than nChar characters in total.
178155*/
178156static int sqlite3Fts5IndexCharlenToBytelen(
178157  const char *p,
178158  int nByte,
178159  int nChar
178160);
178161
178162/*
178163** Open a new iterator to iterate though all rowids that match the
178164** specified token or token prefix.
178165*/
178166static int sqlite3Fts5IndexQuery(
178167  Fts5Index *p,                   /* FTS index to query */
178168  const char *pToken, int nToken, /* Token (or prefix) to query for */
178169  int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
178170  Fts5Colset *pColset,            /* Match these columns only */
178171  Fts5IndexIter **ppIter          /* OUT: New iterator object */
178172);
178173
178174/*
178175** The various operations on open token or token prefix iterators opened
178176** using sqlite3Fts5IndexQuery().
178177*/
178178static int sqlite3Fts5IterNext(Fts5IndexIter*);
178179static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
178180
178181/*
178182** Close an iterator opened by sqlite3Fts5IndexQuery().
178183*/
178184static void sqlite3Fts5IterClose(Fts5IndexIter*);
178185
178186/*
178187** This interface is used by the fts5vocab module.
178188*/
178189static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
178190static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
178191
178192
178193/*
178194** Insert or remove data to or from the index. Each time a document is
178195** added to or removed from the index, this function is called one or more
178196** times.
178197**
178198** For an insert, it must be called once for each token in the new document.
178199** If the operation is a delete, it must be called (at least) once for each
178200** unique token in the document with an iCol value less than zero. The iPos
178201** argument is ignored for a delete.
178202*/
178203static int sqlite3Fts5IndexWrite(
178204  Fts5Index *p,                   /* Index to write to */
178205  int iCol,                       /* Column token appears in (-ve -> delete) */
178206  int iPos,                       /* Position of token within column */
178207  const char *pToken, int nToken  /* Token to add or remove to or from index */
178208);
178209
178210/*
178211** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
178212** document iDocid.
178213*/
178214static int sqlite3Fts5IndexBeginWrite(
178215  Fts5Index *p,                   /* Index to write to */
178216  int bDelete,                    /* True if current operation is a delete */
178217  i64 iDocid                      /* Docid to add or remove data from */
178218);
178219
178220/*
178221** Flush any data stored in the in-memory hash tables to the database.
178222** If the bCommit flag is true, also close any open blob handles.
178223*/
178224static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit);
178225
178226/*
178227** Discard any data stored in the in-memory hash tables. Do not write it
178228** to the database. Additionally, assume that the contents of the %_data
178229** table may have changed on disk. So any in-memory caches of %_data
178230** records must be invalidated.
178231*/
178232static int sqlite3Fts5IndexRollback(Fts5Index *p);
178233
178234/*
178235** Get or set the "averages" values.
178236*/
178237static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
178238static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
178239
178240/*
178241** Functions called by the storage module as part of integrity-check.
178242*/
178243static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
178244
178245/*
178246** Called during virtual module initialization to register UDF
178247** fts5_decode() with SQLite
178248*/
178249static int sqlite3Fts5IndexInit(sqlite3*);
178250
178251static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
178252
178253/*
178254** Return the total number of entries read from the %_data table by
178255** this connection since it was created.
178256*/
178257static int sqlite3Fts5IndexReads(Fts5Index *p);
178258
178259static int sqlite3Fts5IndexReinit(Fts5Index *p);
178260static int sqlite3Fts5IndexOptimize(Fts5Index *p);
178261static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
178262static int sqlite3Fts5IndexReset(Fts5Index *p);
178263
178264static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
178265
178266/*
178267** End of interface to code in fts5_index.c.
178268**************************************************************************/
178269
178270/**************************************************************************
178271** Interface to code in fts5_varint.c.
178272*/
178273static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
178274static int sqlite3Fts5GetVarintLen(u32 iVal);
178275static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
178276static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
178277
178278#define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
178279#define fts5GetVarint    sqlite3Fts5GetVarint
178280
178281#define fts5FastGetVarint32(a, iOff, nVal) {      \
178282  nVal = (a)[iOff++];                             \
178283  if( nVal & 0x80 ){                              \
178284    iOff--;                                       \
178285    iOff += fts5GetVarint32(&(a)[iOff], nVal);    \
178286  }                                               \
178287}
178288
178289
178290/*
178291** End of interface to code in fts5_varint.c.
178292**************************************************************************/
178293
178294
178295/**************************************************************************
178296** Interface to code in fts5.c.
178297*/
178298
178299static int sqlite3Fts5GetTokenizer(
178300  Fts5Global*,
178301  const char **azArg,
178302  int nArg,
178303  Fts5Tokenizer**,
178304  fts5_tokenizer**,
178305  char **pzErr
178306);
178307
178308static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
178309
178310/*
178311** End of interface to code in fts5.c.
178312**************************************************************************/
178313
178314/**************************************************************************
178315** Interface to code in fts5_hash.c.
178316*/
178317typedef struct Fts5Hash Fts5Hash;
178318
178319/*
178320** Create a hash table, free a hash table.
178321*/
178322static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
178323static void sqlite3Fts5HashFree(Fts5Hash*);
178324
178325static int sqlite3Fts5HashWrite(
178326  Fts5Hash*,
178327  i64 iRowid,                     /* Rowid for this entry */
178328  int iCol,                       /* Column token appears in (-ve -> delete) */
178329  int iPos,                       /* Position of token within column */
178330  char bByte,
178331  const char *pToken, int nToken  /* Token to add or remove to or from index */
178332);
178333
178334/*
178335** Empty (but do not delete) a hash table.
178336*/
178337static void sqlite3Fts5HashClear(Fts5Hash*);
178338
178339static int sqlite3Fts5HashQuery(
178340  Fts5Hash*,                      /* Hash table to query */
178341  const char *pTerm, int nTerm,   /* Query term */
178342  const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
178343  int *pnDoclist                  /* OUT: Size of doclist in bytes */
178344);
178345
178346static int sqlite3Fts5HashScanInit(
178347  Fts5Hash*,                      /* Hash table to query */
178348  const char *pTerm, int nTerm    /* Query prefix */
178349);
178350static void sqlite3Fts5HashScanNext(Fts5Hash*);
178351static int sqlite3Fts5HashScanEof(Fts5Hash*);
178352static void sqlite3Fts5HashScanEntry(Fts5Hash *,
178353  const char **pzTerm,            /* OUT: term (nul-terminated) */
178354  const u8 **ppDoclist,           /* OUT: pointer to doclist */
178355  int *pnDoclist                  /* OUT: size of doclist in bytes */
178356);
178357
178358
178359/*
178360** End of interface to code in fts5_hash.c.
178361**************************************************************************/
178362
178363/**************************************************************************
178364** Interface to code in fts5_storage.c. fts5_storage.c contains contains
178365** code to access the data stored in the %_content and %_docsize tables.
178366*/
178367
178368#define FTS5_STMT_SCAN_ASC  0     /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
178369#define FTS5_STMT_SCAN_DESC 1     /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
178370#define FTS5_STMT_LOOKUP    2     /* SELECT rowid, * FROM ... WHERE rowid=? */
178371
178372typedef struct Fts5Storage Fts5Storage;
178373
178374static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
178375static int sqlite3Fts5StorageClose(Fts5Storage *p);
178376static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
178377
178378static int sqlite3Fts5DropAll(Fts5Config*);
178379static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
178380
178381static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
178382static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
178383static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
178384
178385static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
178386
178387static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
178388static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
178389
178390static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
178391static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
178392static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
178393
178394static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit);
178395static int sqlite3Fts5StorageRollback(Fts5Storage *p);
178396
178397static int sqlite3Fts5StorageConfigValue(
178398    Fts5Storage *p, const char*, sqlite3_value*, int
178399);
178400
178401static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
178402static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
178403static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
178404static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
178405static int sqlite3Fts5StorageReset(Fts5Storage *p);
178406
178407/*
178408** End of interface to code in fts5_storage.c.
178409**************************************************************************/
178410
178411
178412/**************************************************************************
178413** Interface to code in fts5_expr.c.
178414*/
178415typedef struct Fts5Expr Fts5Expr;
178416typedef struct Fts5ExprNode Fts5ExprNode;
178417typedef struct Fts5Parse Fts5Parse;
178418typedef struct Fts5Token Fts5Token;
178419typedef struct Fts5ExprPhrase Fts5ExprPhrase;
178420typedef struct Fts5ExprNearset Fts5ExprNearset;
178421
178422struct Fts5Token {
178423  const char *p;                  /* Token text (not NULL terminated) */
178424  int n;                          /* Size of buffer p in bytes */
178425};
178426
178427/* Parse a MATCH expression. */
178428static int sqlite3Fts5ExprNew(
178429  Fts5Config *pConfig,
178430  const char *zExpr,
178431  Fts5Expr **ppNew,
178432  char **pzErr
178433);
178434
178435/*
178436** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
178437**     rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
178438**     rc = sqlite3Fts5ExprNext(pExpr)
178439** ){
178440**   // The document with rowid iRowid matches the expression!
178441**   i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
178442** }
178443*/
178444static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
178445static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
178446static int sqlite3Fts5ExprEof(Fts5Expr*);
178447static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
178448
178449static void sqlite3Fts5ExprFree(Fts5Expr*);
178450
178451/* Called during startup to register a UDF with SQLite */
178452static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
178453
178454static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
178455static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
178456static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
178457
178458typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
178459static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
178460static int sqlite3Fts5ExprPopulatePoslists(
178461    Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
178462);
178463static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
178464
178465static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
178466
178467static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
178468
178469/*******************************************
178470** The fts5_expr.c API above this point is used by the other hand-written
178471** C code in this module. The interfaces below this point are called by
178472** the parser code in fts5parse.y.  */
178473
178474static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
178475
178476static Fts5ExprNode *sqlite3Fts5ParseNode(
178477  Fts5Parse *pParse,
178478  int eType,
178479  Fts5ExprNode *pLeft,
178480  Fts5ExprNode *pRight,
178481  Fts5ExprNearset *pNear
178482);
178483
178484static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
178485  Fts5Parse *pParse,
178486  Fts5ExprNode *pLeft,
178487  Fts5ExprNode *pRight
178488);
178489
178490static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
178491  Fts5Parse *pParse,
178492  Fts5ExprPhrase *pPhrase,
178493  Fts5Token *pToken,
178494  int bPrefix
178495);
178496
178497static Fts5ExprNearset *sqlite3Fts5ParseNearset(
178498  Fts5Parse*,
178499  Fts5ExprNearset*,
178500  Fts5ExprPhrase*
178501);
178502
178503static Fts5Colset *sqlite3Fts5ParseColset(
178504  Fts5Parse*,
178505  Fts5Colset*,
178506  Fts5Token *
178507);
178508
178509static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
178510static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
178511static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
178512
178513static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
178514static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNearset*, Fts5Colset*);
178515static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
178516static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
178517
178518/*
178519** End of interface to code in fts5_expr.c.
178520**************************************************************************/
178521
178522
178523
178524/**************************************************************************
178525** Interface to code in fts5_aux.c.
178526*/
178527
178528static int sqlite3Fts5AuxInit(fts5_api*);
178529/*
178530** End of interface to code in fts5_aux.c.
178531**************************************************************************/
178532
178533/**************************************************************************
178534** Interface to code in fts5_tokenizer.c.
178535*/
178536
178537static int sqlite3Fts5TokenizerInit(fts5_api*);
178538/*
178539** End of interface to code in fts5_tokenizer.c.
178540**************************************************************************/
178541
178542/**************************************************************************
178543** Interface to code in fts5_vocab.c.
178544*/
178545
178546static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
178547
178548/*
178549** End of interface to code in fts5_vocab.c.
178550**************************************************************************/
178551
178552
178553/**************************************************************************
178554** Interface to automatically generated code in fts5_unicode2.c.
178555*/
178556static int sqlite3Fts5UnicodeIsalnum(int c);
178557static int sqlite3Fts5UnicodeIsdiacritic(int c);
178558static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
178559/*
178560** End of interface to code in fts5_unicode2.c.
178561**************************************************************************/
178562
178563#endif
178564
178565#define FTS5_OR                               1
178566#define FTS5_AND                              2
178567#define FTS5_NOT                              3
178568#define FTS5_TERM                             4
178569#define FTS5_COLON                            5
178570#define FTS5_LP                               6
178571#define FTS5_RP                               7
178572#define FTS5_LCP                              8
178573#define FTS5_RCP                              9
178574#define FTS5_STRING                          10
178575#define FTS5_COMMA                           11
178576#define FTS5_PLUS                            12
178577#define FTS5_STAR                            13
178578
178579/*
178580** 2000-05-29
178581**
178582** The author disclaims copyright to this source code.  In place of
178583** a legal notice, here is a blessing:
178584**
178585**    May you do good and not evil.
178586**    May you find forgiveness for yourself and forgive others.
178587**    May you share freely, never taking more than you give.
178588**
178589*************************************************************************
178590** Driver template for the LEMON parser generator.
178591**
178592** The "lemon" program processes an LALR(1) input grammar file, then uses
178593** this template to construct a parser.  The "lemon" program inserts text
178594** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
178595** interstitial "-" characters) contained in this template is changed into
178596** the value of the %name directive from the grammar.  Otherwise, the content
178597** of this template is copied straight through into the generate parser
178598** source file.
178599**
178600** The following is the concatenation of all %include directives from the
178601** input grammar file:
178602*/
178603/* #include <stdio.h> */
178604/************ Begin %include sections from the grammar ************************/
178605
178606/* #include "fts5Int.h" */
178607/* #include "fts5parse.h" */
178608
178609/*
178610** Disable all error recovery processing in the parser push-down
178611** automaton.
178612*/
178613#define fts5YYNOERRORRECOVERY 1
178614
178615/*
178616** Make fts5yytestcase() the same as testcase()
178617*/
178618#define fts5yytestcase(X) testcase(X)
178619
178620/*
178621** Indicate that sqlite3ParserFree() will never be called with a null
178622** pointer.
178623*/
178624#define fts5YYPARSEFREENOTNULL 1
178625
178626/*
178627** Alternative datatype for the argument to the malloc() routine passed
178628** into sqlite3ParserAlloc().  The default is size_t.
178629*/
178630#define fts5YYMALLOCARGTYPE  u64
178631
178632/**************** End of %include directives **********************************/
178633/* These constants specify the various numeric values for terminal symbols
178634** in a format understandable to "makeheaders".  This section is blank unless
178635** "lemon" is run with the "-m" command-line option.
178636***************** Begin makeheaders token definitions *************************/
178637/**************** End makeheaders token definitions ***************************/
178638
178639/* The next sections is a series of control #defines.
178640** various aspects of the generated parser.
178641**    fts5YYCODETYPE         is the data type used to store the integer codes
178642**                       that represent terminal and non-terminal symbols.
178643**                       "unsigned char" is used if there are fewer than
178644**                       256 symbols.  Larger types otherwise.
178645**    fts5YYNOCODE           is a number of type fts5YYCODETYPE that is not used for
178646**                       any terminal or nonterminal symbol.
178647**    fts5YYFALLBACK         If defined, this indicates that one or more tokens
178648**                       (also known as: "terminal symbols") have fall-back
178649**                       values which should be used if the original symbol
178650**                       would not parse.  This permits keywords to sometimes
178651**                       be used as identifiers, for example.
178652**    fts5YYACTIONTYPE       is the data type used for "action codes" - numbers
178653**                       that indicate what to do in response to the next
178654**                       token.
178655**    sqlite3Fts5ParserFTS5TOKENTYPE     is the data type used for minor type for terminal
178656**                       symbols.  Background: A "minor type" is a semantic
178657**                       value associated with a terminal or non-terminal
178658**                       symbols.  For example, for an "ID" terminal symbol,
178659**                       the minor type might be the name of the identifier.
178660**                       Each non-terminal can have a different minor type.
178661**                       Terminal symbols all have the same minor type, though.
178662**                       This macros defines the minor type for terminal
178663**                       symbols.
178664**    fts5YYMINORTYPE        is the data type used for all minor types.
178665**                       This is typically a union of many types, one of
178666**                       which is sqlite3Fts5ParserFTS5TOKENTYPE.  The entry in the union
178667**                       for terminal symbols is called "fts5yy0".
178668**    fts5YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
178669**                       zero the stack is dynamically sized using realloc()
178670**    sqlite3Fts5ParserARG_SDECL     A static variable declaration for the %extra_argument
178671**    sqlite3Fts5ParserARG_PDECL     A parameter declaration for the %extra_argument
178672**    sqlite3Fts5ParserARG_STORE     Code to store %extra_argument into fts5yypParser
178673**    sqlite3Fts5ParserARG_FETCH     Code to extract %extra_argument from fts5yypParser
178674**    fts5YYERRORSYMBOL      is the code number of the error symbol.  If not
178675**                       defined, then do no error processing.
178676**    fts5YYNSTATE           the combined number of states.
178677**    fts5YYNRULE            the number of rules in the grammar
178678**    fts5YY_MAX_SHIFT       Maximum value for shift actions
178679**    fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
178680**    fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
178681**    fts5YY_MIN_REDUCE      Maximum value for reduce actions
178682**    fts5YY_ERROR_ACTION    The fts5yy_action[] code for syntax error
178683**    fts5YY_ACCEPT_ACTION   The fts5yy_action[] code for accept
178684**    fts5YY_NO_ACTION       The fts5yy_action[] code for no-op
178685*/
178686#ifndef INTERFACE
178687# define INTERFACE 1
178688#endif
178689/************* Begin control #defines *****************************************/
178690#define fts5YYCODETYPE unsigned char
178691#define fts5YYNOCODE 27
178692#define fts5YYACTIONTYPE unsigned char
178693#define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
178694typedef union {
178695  int fts5yyinit;
178696  sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
178697  Fts5Colset* fts5yy3;
178698  Fts5ExprPhrase* fts5yy11;
178699  Fts5ExprNode* fts5yy18;
178700  int fts5yy20;
178701  Fts5ExprNearset* fts5yy26;
178702} fts5YYMINORTYPE;
178703#ifndef fts5YYSTACKDEPTH
178704#define fts5YYSTACKDEPTH 100
178705#endif
178706#define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
178707#define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
178708#define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
178709#define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
178710#define fts5YYNSTATE             26
178711#define fts5YYNRULE              24
178712#define fts5YY_MAX_SHIFT         25
178713#define fts5YY_MIN_SHIFTREDUCE   40
178714#define fts5YY_MAX_SHIFTREDUCE   63
178715#define fts5YY_MIN_REDUCE        64
178716#define fts5YY_MAX_REDUCE        87
178717#define fts5YY_ERROR_ACTION      88
178718#define fts5YY_ACCEPT_ACTION     89
178719#define fts5YY_NO_ACTION         90
178720/************* End control #defines *******************************************/
178721
178722/* Define the fts5yytestcase() macro to be a no-op if is not already defined
178723** otherwise.
178724**
178725** Applications can choose to define fts5yytestcase() in the %include section
178726** to a macro that can assist in verifying code coverage.  For production
178727** code the fts5yytestcase() macro should be turned off.  But it is useful
178728** for testing.
178729*/
178730#ifndef fts5yytestcase
178731# define fts5yytestcase(X)
178732#endif
178733
178734
178735/* Next are the tables used to determine what action to take based on the
178736** current state and lookahead token.  These tables are used to implement
178737** functions that take a state number and lookahead value and return an
178738** action integer.
178739**
178740** Suppose the action integer is N.  Then the action is determined as
178741** follows
178742**
178743**   0 <= N <= fts5YY_MAX_SHIFT             Shift N.  That is, push the lookahead
178744**                                      token onto the stack and goto state N.
178745**
178746**   N between fts5YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
178747**     and fts5YY_MAX_SHIFTREDUCE           reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
178748**
178749**   N between fts5YY_MIN_REDUCE            Reduce by rule N-fts5YY_MIN_REDUCE
178750**     and fts5YY_MAX_REDUCE
178751
178752**   N == fts5YY_ERROR_ACTION               A syntax error has occurred.
178753**
178754**   N == fts5YY_ACCEPT_ACTION              The parser accepts its input.
178755**
178756**   N == fts5YY_NO_ACTION                  No such action.  Denotes unused
178757**                                      slots in the fts5yy_action[] table.
178758**
178759** The action table is constructed as a single large table named fts5yy_action[].
178760** Given state S and lookahead X, the action is computed as
178761**
178762**      fts5yy_action[ fts5yy_shift_ofst[S] + X ]
178763**
178764** If the index value fts5yy_shift_ofst[S]+X is out of range or if the value
178765** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X or if fts5yy_shift_ofst[S]
178766** is equal to fts5YY_SHIFT_USE_DFLT, it means that the action is not in the table
178767** and that fts5yy_default[S] should be used instead.
178768**
178769** The formula above is for computing the action when the lookahead is
178770** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
178771** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
178772** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
178773** fts5YY_SHIFT_USE_DFLT.
178774**
178775** The following are the tables generated in this section:
178776**
178777**  fts5yy_action[]        A single table containing all actions.
178778**  fts5yy_lookahead[]     A table containing the lookahead for each entry in
178779**                     fts5yy_action.  Used to detect hash collisions.
178780**  fts5yy_shift_ofst[]    For each state, the offset into fts5yy_action for
178781**                     shifting terminals.
178782**  fts5yy_reduce_ofst[]   For each state, the offset into fts5yy_action for
178783**                     shifting non-terminals after a reduce.
178784**  fts5yy_default[]       Default action for each state.
178785**
178786*********** Begin parsing tables **********************************************/
178787#define fts5YY_ACTTAB_COUNT (78)
178788static const fts5YYACTIONTYPE fts5yy_action[] = {
178789 /*     0 */    89,   15,   46,    5,   48,   24,   12,   19,   23,   14,
178790 /*    10 */    46,    5,   48,   24,   20,   21,   23,   43,   46,    5,
178791 /*    20 */    48,   24,    6,   18,   23,   17,   46,    5,   48,   24,
178792 /*    30 */    75,    7,   23,   25,   46,    5,   48,   24,   62,   47,
178793 /*    40 */    23,   48,   24,    7,   11,   23,    9,    3,    4,    2,
178794 /*    50 */    62,   50,   52,   44,   64,    3,    4,    2,   49,    4,
178795 /*    60 */     2,    1,   23,   11,   16,    9,   12,    2,   10,   61,
178796 /*    70 */    53,   59,   62,   60,   22,   13,   55,    8,
178797};
178798static const fts5YYCODETYPE fts5yy_lookahead[] = {
178799 /*     0 */    15,   16,   17,   18,   19,   20,   10,   11,   23,   16,
178800 /*    10 */    17,   18,   19,   20,   23,   24,   23,   16,   17,   18,
178801 /*    20 */    19,   20,   22,   23,   23,   16,   17,   18,   19,   20,
178802 /*    30 */     5,    6,   23,   16,   17,   18,   19,   20,   13,   17,
178803 /*    40 */    23,   19,   20,    6,    8,   23,   10,    1,    2,    3,
178804 /*    50 */    13,    9,   10,    7,    0,    1,    2,    3,   19,    2,
178805 /*    60 */     3,    6,   23,    8,   21,   10,   10,    3,   10,   25,
178806 /*    70 */    10,   10,   13,   25,   12,   10,    7,    5,
178807};
178808#define fts5YY_SHIFT_USE_DFLT (-5)
178809#define fts5YY_SHIFT_COUNT (25)
178810#define fts5YY_SHIFT_MIN   (-4)
178811#define fts5YY_SHIFT_MAX   (72)
178812static const signed char fts5yy_shift_ofst[] = {
178813 /*     0 */    55,   55,   55,   55,   55,   36,   -4,   56,   58,   25,
178814 /*    10 */    37,   60,   59,   59,   46,   54,   42,   57,   62,   61,
178815 /*    20 */    62,   69,   65,   62,   72,   64,
178816};
178817#define fts5YY_REDUCE_USE_DFLT (-16)
178818#define fts5YY_REDUCE_COUNT (13)
178819#define fts5YY_REDUCE_MIN   (-15)
178820#define fts5YY_REDUCE_MAX   (48)
178821static const signed char fts5yy_reduce_ofst[] = {
178822 /*     0 */   -15,   -7,    1,    9,   17,   22,   -9,    0,   39,   44,
178823 /*    10 */    44,   43,   44,   48,
178824};
178825static const fts5YYACTIONTYPE fts5yy_default[] = {
178826 /*     0 */    88,   88,   88,   88,   88,   69,   82,   88,   88,   87,
178827 /*    10 */    87,   88,   87,   87,   88,   88,   88,   66,   80,   88,
178828 /*    20 */    81,   88,   88,   78,   88,   65,
178829};
178830/********** End of lemon-generated parsing tables *****************************/
178831
178832/* The next table maps tokens (terminal symbols) into fallback tokens.
178833** If a construct like the following:
178834**
178835**      %fallback ID X Y Z.
178836**
178837** appears in the grammar, then ID becomes a fallback token for X, Y,
178838** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
178839** but it does not parse, the type of the token is changed to ID and
178840** the parse is retried before an error is thrown.
178841**
178842** This feature can be used, for example, to cause some keywords in a language
178843** to revert to identifiers if they keyword does not apply in the context where
178844** it appears.
178845*/
178846#ifdef fts5YYFALLBACK
178847static const fts5YYCODETYPE fts5yyFallback[] = {
178848};
178849#endif /* fts5YYFALLBACK */
178850
178851/* The following structure represents a single element of the
178852** parser's stack.  Information stored includes:
178853**
178854**   +  The state number for the parser at this level of the stack.
178855**
178856**   +  The value of the token stored at this level of the stack.
178857**      (In other words, the "major" token.)
178858**
178859**   +  The semantic value stored at this level of the stack.  This is
178860**      the information used by the action routines in the grammar.
178861**      It is sometimes called the "minor" token.
178862**
178863** After the "shift" half of a SHIFTREDUCE action, the stateno field
178864** actually contains the reduce action for the second half of the
178865** SHIFTREDUCE.
178866*/
178867struct fts5yyStackEntry {
178868  fts5YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
178869  fts5YYCODETYPE major;      /* The major token value.  This is the code
178870                         ** number for the token at this stack level */
178871  fts5YYMINORTYPE minor;     /* The user-supplied minor token value.  This
178872                         ** is the value of the token  */
178873};
178874typedef struct fts5yyStackEntry fts5yyStackEntry;
178875
178876/* The state of the parser is completely contained in an instance of
178877** the following structure */
178878struct fts5yyParser {
178879  fts5yyStackEntry *fts5yytos;          /* Pointer to top element of the stack */
178880#ifdef fts5YYTRACKMAXSTACKDEPTH
178881  int fts5yyhwm;                    /* High-water mark of the stack */
178882#endif
178883#ifndef fts5YYNOERRORRECOVERY
178884  int fts5yyerrcnt;                 /* Shifts left before out of the error */
178885#endif
178886  sqlite3Fts5ParserARG_SDECL                /* A place to hold %extra_argument */
178887#if fts5YYSTACKDEPTH<=0
178888  int fts5yystksz;                  /* Current side of the stack */
178889  fts5yyStackEntry *fts5yystack;        /* The parser's stack */
178890  fts5yyStackEntry fts5yystk0;          /* First stack entry */
178891#else
178892  fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH];  /* The parser's stack */
178893#endif
178894};
178895typedef struct fts5yyParser fts5yyParser;
178896
178897#ifndef NDEBUG
178898/* #include <stdio.h> */
178899static FILE *fts5yyTraceFILE = 0;
178900static char *fts5yyTracePrompt = 0;
178901#endif /* NDEBUG */
178902
178903#ifndef NDEBUG
178904/*
178905** Turn parser tracing on by giving a stream to which to write the trace
178906** and a prompt to preface each trace message.  Tracing is turned off
178907** by making either argument NULL
178908**
178909** Inputs:
178910** <ul>
178911** <li> A FILE* to which trace output should be written.
178912**      If NULL, then tracing is turned off.
178913** <li> A prefix string written at the beginning of every
178914**      line of trace output.  If NULL, then tracing is
178915**      turned off.
178916** </ul>
178917**
178918** Outputs:
178919** None.
178920*/
178921static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
178922  fts5yyTraceFILE = TraceFILE;
178923  fts5yyTracePrompt = zTracePrompt;
178924  if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
178925  else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
178926}
178927#endif /* NDEBUG */
178928
178929#ifndef NDEBUG
178930/* For tracing shifts, the names of all terminals and nonterminals
178931** are required.  The following table supplies these names */
178932static const char *const fts5yyTokenName[] = {
178933  "$",             "OR",            "AND",           "NOT",
178934  "TERM",          "COLON",         "LP",            "RP",
178935  "LCP",           "RCP",           "STRING",        "COMMA",
178936  "PLUS",          "STAR",          "error",         "input",
178937  "expr",          "cnearset",      "exprlist",      "nearset",
178938  "colset",        "colsetlist",    "nearphrases",   "phrase",
178939  "neardist_opt",  "star_opt",
178940};
178941#endif /* NDEBUG */
178942
178943#ifndef NDEBUG
178944/* For tracing reduce actions, the names of all rules are required.
178945*/
178946static const char *const fts5yyRuleName[] = {
178947 /*   0 */ "input ::= expr",
178948 /*   1 */ "expr ::= expr AND expr",
178949 /*   2 */ "expr ::= expr OR expr",
178950 /*   3 */ "expr ::= expr NOT expr",
178951 /*   4 */ "expr ::= LP expr RP",
178952 /*   5 */ "expr ::= exprlist",
178953 /*   6 */ "exprlist ::= cnearset",
178954 /*   7 */ "exprlist ::= exprlist cnearset",
178955 /*   8 */ "cnearset ::= nearset",
178956 /*   9 */ "cnearset ::= colset COLON nearset",
178957 /*  10 */ "colset ::= LCP colsetlist RCP",
178958 /*  11 */ "colset ::= STRING",
178959 /*  12 */ "colsetlist ::= colsetlist STRING",
178960 /*  13 */ "colsetlist ::= STRING",
178961 /*  14 */ "nearset ::= phrase",
178962 /*  15 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
178963 /*  16 */ "nearphrases ::= phrase",
178964 /*  17 */ "nearphrases ::= nearphrases phrase",
178965 /*  18 */ "neardist_opt ::=",
178966 /*  19 */ "neardist_opt ::= COMMA STRING",
178967 /*  20 */ "phrase ::= phrase PLUS STRING star_opt",
178968 /*  21 */ "phrase ::= STRING star_opt",
178969 /*  22 */ "star_opt ::= STAR",
178970 /*  23 */ "star_opt ::=",
178971};
178972#endif /* NDEBUG */
178973
178974
178975#if fts5YYSTACKDEPTH<=0
178976/*
178977** Try to increase the size of the parser stack.  Return the number
178978** of errors.  Return 0 on success.
178979*/
178980static int fts5yyGrowStack(fts5yyParser *p){
178981  int newSize;
178982  int idx;
178983  fts5yyStackEntry *pNew;
178984
178985  newSize = p->fts5yystksz*2 + 100;
178986  idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
178987  if( p->fts5yystack==&p->fts5yystk0 ){
178988    pNew = malloc(newSize*sizeof(pNew[0]));
178989    if( pNew ) pNew[0] = p->fts5yystk0;
178990  }else{
178991    pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
178992  }
178993  if( pNew ){
178994    p->fts5yystack = pNew;
178995    p->fts5yytos = &p->fts5yystack[idx];
178996#ifndef NDEBUG
178997    if( fts5yyTraceFILE ){
178998      fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
178999              fts5yyTracePrompt, p->fts5yystksz, newSize);
179000    }
179001#endif
179002    p->fts5yystksz = newSize;
179003  }
179004  return pNew==0;
179005}
179006#endif
179007
179008/* Datatype of the argument to the memory allocated passed as the
179009** second argument to sqlite3Fts5ParserAlloc() below.  This can be changed by
179010** putting an appropriate #define in the %include section of the input
179011** grammar.
179012*/
179013#ifndef fts5YYMALLOCARGTYPE
179014# define fts5YYMALLOCARGTYPE size_t
179015#endif
179016
179017/*
179018** This function allocates a new parser.
179019** The only argument is a pointer to a function which works like
179020** malloc.
179021**
179022** Inputs:
179023** A pointer to the function used to allocate memory.
179024**
179025** Outputs:
179026** A pointer to a parser.  This pointer is used in subsequent calls
179027** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
179028*/
179029static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){
179030  fts5yyParser *pParser;
179031  pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
179032  if( pParser ){
179033#ifdef fts5YYTRACKMAXSTACKDEPTH
179034    pParser->fts5yyhwm = 0;
179035#endif
179036#if fts5YYSTACKDEPTH<=0
179037    pParser->fts5yytos = NULL;
179038    pParser->fts5yystack = NULL;
179039    pParser->fts5yystksz = 0;
179040    if( fts5yyGrowStack(pParser) ){
179041      pParser->fts5yystack = &pParser->fts5yystk0;
179042      pParser->fts5yystksz = 1;
179043    }
179044#endif
179045#ifndef fts5YYNOERRORRECOVERY
179046    pParser->fts5yyerrcnt = -1;
179047#endif
179048    pParser->fts5yytos = pParser->fts5yystack;
179049    pParser->fts5yystack[0].stateno = 0;
179050    pParser->fts5yystack[0].major = 0;
179051  }
179052  return pParser;
179053}
179054
179055/* The following function deletes the "minor type" or semantic value
179056** associated with a symbol.  The symbol can be either a terminal
179057** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
179058** a pointer to the value to be deleted.  The code used to do the
179059** deletions is derived from the %destructor and/or %token_destructor
179060** directives of the input grammar.
179061*/
179062static void fts5yy_destructor(
179063  fts5yyParser *fts5yypParser,    /* The parser */
179064  fts5YYCODETYPE fts5yymajor,     /* Type code for object to destroy */
179065  fts5YYMINORTYPE *fts5yypminor   /* The object to be destroyed */
179066){
179067  sqlite3Fts5ParserARG_FETCH;
179068  switch( fts5yymajor ){
179069    /* Here is inserted the actions which take place when a
179070    ** terminal or non-terminal is destroyed.  This can happen
179071    ** when the symbol is popped from the stack during a
179072    ** reduce or during error processing or when a parser is
179073    ** being destroyed before it is finished parsing.
179074    **
179075    ** Note: during a reduce, the only symbols destroyed are those
179076    ** which appear on the RHS of the rule, but which are *not* used
179077    ** inside the C code.
179078    */
179079/********* Begin destructor definitions ***************************************/
179080    case 15: /* input */
179081{
179082 (void)pParse;
179083}
179084      break;
179085    case 16: /* expr */
179086    case 17: /* cnearset */
179087    case 18: /* exprlist */
179088{
179089 sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy18));
179090}
179091      break;
179092    case 19: /* nearset */
179093    case 22: /* nearphrases */
179094{
179095 sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy26));
179096}
179097      break;
179098    case 20: /* colset */
179099    case 21: /* colsetlist */
179100{
179101 sqlite3_free((fts5yypminor->fts5yy3));
179102}
179103      break;
179104    case 23: /* phrase */
179105{
179106 sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy11));
179107}
179108      break;
179109/********* End destructor definitions *****************************************/
179110    default:  break;   /* If no destructor action specified: do nothing */
179111  }
179112}
179113
179114/*
179115** Pop the parser's stack once.
179116**
179117** If there is a destructor routine associated with the token which
179118** is popped from the stack, then call it.
179119*/
179120static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
179121  fts5yyStackEntry *fts5yytos;
179122  assert( pParser->fts5yytos!=0 );
179123  assert( pParser->fts5yytos > pParser->fts5yystack );
179124  fts5yytos = pParser->fts5yytos--;
179125#ifndef NDEBUG
179126  if( fts5yyTraceFILE ){
179127    fprintf(fts5yyTraceFILE,"%sPopping %s\n",
179128      fts5yyTracePrompt,
179129      fts5yyTokenName[fts5yytos->major]);
179130  }
179131#endif
179132  fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
179133}
179134
179135/*
179136** Deallocate and destroy a parser.  Destructors are called for
179137** all stack elements before shutting the parser down.
179138**
179139** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
179140** is defined in a %include section of the input grammar) then it is
179141** assumed that the input pointer is never NULL.
179142*/
179143static void sqlite3Fts5ParserFree(
179144  void *p,                    /* The parser to be deleted */
179145  void (*freeProc)(void*)     /* Function used to reclaim memory */
179146){
179147  fts5yyParser *pParser = (fts5yyParser*)p;
179148#ifndef fts5YYPARSEFREENEVERNULL
179149  if( pParser==0 ) return;
179150#endif
179151  while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
179152#if fts5YYSTACKDEPTH<=0
179153  if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
179154#endif
179155  (*freeProc)((void*)pParser);
179156}
179157
179158/*
179159** Return the peak depth of the stack for a parser.
179160*/
179161#ifdef fts5YYTRACKMAXSTACKDEPTH
179162static int sqlite3Fts5ParserStackPeak(void *p){
179163  fts5yyParser *pParser = (fts5yyParser*)p;
179164  return pParser->fts5yyhwm;
179165}
179166#endif
179167
179168/*
179169** Find the appropriate action for a parser given the terminal
179170** look-ahead token iLookAhead.
179171*/
179172static unsigned int fts5yy_find_shift_action(
179173  fts5yyParser *pParser,        /* The parser */
179174  fts5YYCODETYPE iLookAhead     /* The look-ahead token */
179175){
179176  int i;
179177  int stateno = pParser->fts5yytos->stateno;
179178
179179  if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
179180  assert( stateno <= fts5YY_SHIFT_COUNT );
179181  do{
179182    i = fts5yy_shift_ofst[stateno];
179183    if( i==fts5YY_SHIFT_USE_DFLT ) return fts5yy_default[stateno];
179184    assert( iLookAhead!=fts5YYNOCODE );
179185    i += iLookAhead;
179186    if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
179187      if( iLookAhead>0 ){
179188#ifdef fts5YYFALLBACK
179189        fts5YYCODETYPE iFallback;            /* Fallback token */
179190        if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
179191               && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
179192#ifndef NDEBUG
179193          if( fts5yyTraceFILE ){
179194            fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
179195               fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
179196          }
179197#endif
179198          assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
179199          iLookAhead = iFallback;
179200          continue;
179201        }
179202#endif
179203#ifdef fts5YYWILDCARD
179204        {
179205          int j = i - iLookAhead + fts5YYWILDCARD;
179206          if(
179207#if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
179208            j>=0 &&
179209#endif
179210#if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
179211            j<fts5YY_ACTTAB_COUNT &&
179212#endif
179213            fts5yy_lookahead[j]==fts5YYWILDCARD
179214          ){
179215#ifndef NDEBUG
179216            if( fts5yyTraceFILE ){
179217              fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
179218                 fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
179219                 fts5yyTokenName[fts5YYWILDCARD]);
179220            }
179221#endif /* NDEBUG */
179222            return fts5yy_action[j];
179223          }
179224        }
179225#endif /* fts5YYWILDCARD */
179226      }
179227      return fts5yy_default[stateno];
179228    }else{
179229      return fts5yy_action[i];
179230    }
179231  }while(1);
179232}
179233
179234/*
179235** Find the appropriate action for a parser given the non-terminal
179236** look-ahead token iLookAhead.
179237*/
179238static int fts5yy_find_reduce_action(
179239  int stateno,              /* Current state number */
179240  fts5YYCODETYPE iLookAhead     /* The look-ahead token */
179241){
179242  int i;
179243#ifdef fts5YYERRORSYMBOL
179244  if( stateno>fts5YY_REDUCE_COUNT ){
179245    return fts5yy_default[stateno];
179246  }
179247#else
179248  assert( stateno<=fts5YY_REDUCE_COUNT );
179249#endif
179250  i = fts5yy_reduce_ofst[stateno];
179251  assert( i!=fts5YY_REDUCE_USE_DFLT );
179252  assert( iLookAhead!=fts5YYNOCODE );
179253  i += iLookAhead;
179254#ifdef fts5YYERRORSYMBOL
179255  if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
179256    return fts5yy_default[stateno];
179257  }
179258#else
179259  assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
179260  assert( fts5yy_lookahead[i]==iLookAhead );
179261#endif
179262  return fts5yy_action[i];
179263}
179264
179265/*
179266** The following routine is called if the stack overflows.
179267*/
179268static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
179269   sqlite3Fts5ParserARG_FETCH;
179270   fts5yypParser->fts5yytos--;
179271#ifndef NDEBUG
179272   if( fts5yyTraceFILE ){
179273     fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
179274   }
179275#endif
179276   while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
179277   /* Here code is inserted which will execute if the parser
179278   ** stack every overflows */
179279/******** Begin %stack_overflow code ******************************************/
179280
179281  sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
179282/******** End %stack_overflow code ********************************************/
179283   sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
179284}
179285
179286/*
179287** Print tracing information for a SHIFT action
179288*/
179289#ifndef NDEBUG
179290static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
179291  if( fts5yyTraceFILE ){
179292    if( fts5yyNewState<fts5YYNSTATE ){
179293      fprintf(fts5yyTraceFILE,"%sShift '%s', go to state %d\n",
179294         fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major],
179295         fts5yyNewState);
179296    }else{
179297      fprintf(fts5yyTraceFILE,"%sShift '%s'\n",
179298         fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major]);
179299    }
179300  }
179301}
179302#else
179303# define fts5yyTraceShift(X,Y)
179304#endif
179305
179306/*
179307** Perform a shift action.
179308*/
179309static void fts5yy_shift(
179310  fts5yyParser *fts5yypParser,          /* The parser to be shifted */
179311  int fts5yyNewState,               /* The new state to shift in */
179312  int fts5yyMajor,                  /* The major token to shift in */
179313  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor        /* The minor token to shift in */
179314){
179315  fts5yyStackEntry *fts5yytos;
179316  fts5yypParser->fts5yytos++;
179317#ifdef fts5YYTRACKMAXSTACKDEPTH
179318  if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
179319    fts5yypParser->fts5yyhwm++;
179320    assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
179321  }
179322#endif
179323#if fts5YYSTACKDEPTH>0
179324  if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH] ){
179325    fts5yyStackOverflow(fts5yypParser);
179326    return;
179327  }
179328#else
179329  if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
179330    if( fts5yyGrowStack(fts5yypParser) ){
179331      fts5yyStackOverflow(fts5yypParser);
179332      return;
179333    }
179334  }
179335#endif
179336  if( fts5yyNewState > fts5YY_MAX_SHIFT ){
179337    fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
179338  }
179339  fts5yytos = fts5yypParser->fts5yytos;
179340  fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
179341  fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
179342  fts5yytos->minor.fts5yy0 = fts5yyMinor;
179343  fts5yyTraceShift(fts5yypParser, fts5yyNewState);
179344}
179345
179346/* The following table contains information about every rule that
179347** is used during the reduce.
179348*/
179349static const struct {
179350  fts5YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
179351  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
179352} fts5yyRuleInfo[] = {
179353  { 15, 1 },
179354  { 16, 3 },
179355  { 16, 3 },
179356  { 16, 3 },
179357  { 16, 3 },
179358  { 16, 1 },
179359  { 18, 1 },
179360  { 18, 2 },
179361  { 17, 1 },
179362  { 17, 3 },
179363  { 20, 3 },
179364  { 20, 1 },
179365  { 21, 2 },
179366  { 21, 1 },
179367  { 19, 1 },
179368  { 19, 5 },
179369  { 22, 1 },
179370  { 22, 2 },
179371  { 24, 0 },
179372  { 24, 2 },
179373  { 23, 4 },
179374  { 23, 2 },
179375  { 25, 1 },
179376  { 25, 0 },
179377};
179378
179379static void fts5yy_accept(fts5yyParser*);  /* Forward Declaration */
179380
179381/*
179382** Perform a reduce action and the shift that must immediately
179383** follow the reduce.
179384*/
179385static void fts5yy_reduce(
179386  fts5yyParser *fts5yypParser,         /* The parser */
179387  unsigned int fts5yyruleno        /* Number of the rule by which to reduce */
179388){
179389  int fts5yygoto;                     /* The next state */
179390  int fts5yyact;                      /* The next action */
179391  fts5yyStackEntry *fts5yymsp;            /* The top of the parser's stack */
179392  int fts5yysize;                     /* Amount to pop the stack */
179393  sqlite3Fts5ParserARG_FETCH;
179394  fts5yymsp = fts5yypParser->fts5yytos;
179395#ifndef NDEBUG
179396  if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
179397    fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
179398    fprintf(fts5yyTraceFILE, "%sReduce [%s], go to state %d.\n", fts5yyTracePrompt,
179399      fts5yyRuleName[fts5yyruleno], fts5yymsp[-fts5yysize].stateno);
179400  }
179401#endif /* NDEBUG */
179402
179403  /* Check that the stack is large enough to grow by a single entry
179404  ** if the RHS of the rule is empty.  This ensures that there is room
179405  ** enough on the stack to push the LHS value */
179406  if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
179407#ifdef fts5YYTRACKMAXSTACKDEPTH
179408    if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
179409      fts5yypParser->fts5yyhwm++;
179410      assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
179411    }
179412#endif
179413#if fts5YYSTACKDEPTH>0
179414    if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1] ){
179415      fts5yyStackOverflow(fts5yypParser);
179416      return;
179417    }
179418#else
179419    if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
179420      if( fts5yyGrowStack(fts5yypParser) ){
179421        fts5yyStackOverflow(fts5yypParser);
179422        return;
179423      }
179424      fts5yymsp = fts5yypParser->fts5yytos;
179425    }
179426#endif
179427  }
179428
179429  switch( fts5yyruleno ){
179430  /* Beginning here are the reduction cases.  A typical example
179431  ** follows:
179432  **   case 0:
179433  **  #line <lineno> <grammarfile>
179434  **     { ... }           // User supplied code
179435  **  #line <lineno> <thisfile>
179436  **     break;
179437  */
179438/********** Begin reduce actions **********************************************/
179439        fts5YYMINORTYPE fts5yylhsminor;
179440      case 0: /* input ::= expr */
179441{ sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy18); }
179442        break;
179443      case 1: /* expr ::= expr AND expr */
179444{
179445  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
179446}
179447  fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179448        break;
179449      case 2: /* expr ::= expr OR expr */
179450{
179451  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
179452}
179453  fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179454        break;
179455      case 3: /* expr ::= expr NOT expr */
179456{
179457  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
179458}
179459  fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179460        break;
179461      case 4: /* expr ::= LP expr RP */
179462{fts5yymsp[-2].minor.fts5yy18 = fts5yymsp[-1].minor.fts5yy18;}
179463        break;
179464      case 5: /* expr ::= exprlist */
179465      case 6: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==6);
179466{fts5yylhsminor.fts5yy18 = fts5yymsp[0].minor.fts5yy18;}
179467  fts5yymsp[0].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179468        break;
179469      case 7: /* exprlist ::= exprlist cnearset */
179470{
179471  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18);
179472}
179473  fts5yymsp[-1].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179474        break;
179475      case 8: /* cnearset ::= nearset */
179476{
179477  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26);
179478}
179479  fts5yymsp[0].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179480        break;
179481      case 9: /* cnearset ::= colset COLON nearset */
179482{
179483  sqlite3Fts5ParseSetColset(pParse, fts5yymsp[0].minor.fts5yy26, fts5yymsp[-2].minor.fts5yy3);
179484  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26);
179485}
179486  fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179487        break;
179488      case 10: /* colset ::= LCP colsetlist RCP */
179489{ fts5yymsp[-2].minor.fts5yy3 = fts5yymsp[-1].minor.fts5yy3; }
179490        break;
179491      case 11: /* colset ::= STRING */
179492{
179493  fts5yylhsminor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
179494}
179495  fts5yymsp[0].minor.fts5yy3 = fts5yylhsminor.fts5yy3;
179496        break;
179497      case 12: /* colsetlist ::= colsetlist STRING */
179498{
179499  fts5yylhsminor.fts5yy3 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy3, &fts5yymsp[0].minor.fts5yy0); }
179500  fts5yymsp[-1].minor.fts5yy3 = fts5yylhsminor.fts5yy3;
179501        break;
179502      case 13: /* colsetlist ::= STRING */
179503{
179504  fts5yylhsminor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
179505}
179506  fts5yymsp[0].minor.fts5yy3 = fts5yylhsminor.fts5yy3;
179507        break;
179508      case 14: /* nearset ::= phrase */
179509{ fts5yylhsminor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11); }
179510  fts5yymsp[0].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
179511        break;
179512      case 15: /* nearset ::= STRING LP nearphrases neardist_opt RP */
179513{
179514  sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
179515  sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy26, &fts5yymsp[-1].minor.fts5yy0);
179516  fts5yylhsminor.fts5yy26 = fts5yymsp[-2].minor.fts5yy26;
179517}
179518  fts5yymsp[-4].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
179519        break;
179520      case 16: /* nearphrases ::= phrase */
179521{
179522  fts5yylhsminor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11);
179523}
179524  fts5yymsp[0].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
179525        break;
179526      case 17: /* nearphrases ::= nearphrases phrase */
179527{
179528  fts5yylhsminor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy26, fts5yymsp[0].minor.fts5yy11);
179529}
179530  fts5yymsp[-1].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
179531        break;
179532      case 18: /* neardist_opt ::= */
179533{ fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
179534        break;
179535      case 19: /* neardist_opt ::= COMMA STRING */
179536{ fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
179537        break;
179538      case 20: /* phrase ::= phrase PLUS STRING star_opt */
179539{
179540  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy11, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
179541}
179542  fts5yymsp[-3].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
179543        break;
179544      case 21: /* phrase ::= STRING star_opt */
179545{
179546  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
179547}
179548  fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
179549        break;
179550      case 22: /* star_opt ::= STAR */
179551{ fts5yymsp[0].minor.fts5yy20 = 1; }
179552        break;
179553      case 23: /* star_opt ::= */
179554{ fts5yymsp[1].minor.fts5yy20 = 0; }
179555        break;
179556      default:
179557        break;
179558/********** End reduce actions ************************************************/
179559  };
179560  assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
179561  fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
179562  fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
179563  fts5yyact = fts5yy_find_reduce_action(fts5yymsp[-fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
179564  if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
179565    if( fts5yyact>fts5YY_MAX_SHIFT ){
179566      fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
179567    }
179568    fts5yymsp -= fts5yysize-1;
179569    fts5yypParser->fts5yytos = fts5yymsp;
179570    fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
179571    fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
179572    fts5yyTraceShift(fts5yypParser, fts5yyact);
179573  }else{
179574    assert( fts5yyact == fts5YY_ACCEPT_ACTION );
179575    fts5yypParser->fts5yytos -= fts5yysize;
179576    fts5yy_accept(fts5yypParser);
179577  }
179578}
179579
179580/*
179581** The following code executes when the parse fails
179582*/
179583#ifndef fts5YYNOERRORRECOVERY
179584static void fts5yy_parse_failed(
179585  fts5yyParser *fts5yypParser           /* The parser */
179586){
179587  sqlite3Fts5ParserARG_FETCH;
179588#ifndef NDEBUG
179589  if( fts5yyTraceFILE ){
179590    fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
179591  }
179592#endif
179593  while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
179594  /* Here code is inserted which will be executed whenever the
179595  ** parser fails */
179596/************ Begin %parse_failure code ***************************************/
179597/************ End %parse_failure code *****************************************/
179598  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
179599}
179600#endif /* fts5YYNOERRORRECOVERY */
179601
179602/*
179603** The following code executes when a syntax error first occurs.
179604*/
179605static void fts5yy_syntax_error(
179606  fts5yyParser *fts5yypParser,           /* The parser */
179607  int fts5yymajor,                   /* The major type of the error token */
179608  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor         /* The minor type of the error token */
179609){
179610  sqlite3Fts5ParserARG_FETCH;
179611#define FTS5TOKEN fts5yyminor
179612/************ Begin %syntax_error code ****************************************/
179613
179614  UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
179615  sqlite3Fts5ParseError(
179616    pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
179617  );
179618/************ End %syntax_error code ******************************************/
179619  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
179620}
179621
179622/*
179623** The following is executed when the parser accepts
179624*/
179625static void fts5yy_accept(
179626  fts5yyParser *fts5yypParser           /* The parser */
179627){
179628  sqlite3Fts5ParserARG_FETCH;
179629#ifndef NDEBUG
179630  if( fts5yyTraceFILE ){
179631    fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
179632  }
179633#endif
179634#ifndef fts5YYNOERRORRECOVERY
179635  fts5yypParser->fts5yyerrcnt = -1;
179636#endif
179637  assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
179638  /* Here code is inserted which will be executed whenever the
179639  ** parser accepts */
179640/*********** Begin %parse_accept code *****************************************/
179641/*********** End %parse_accept code *******************************************/
179642  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
179643}
179644
179645/* The main parser program.
179646** The first argument is a pointer to a structure obtained from
179647** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
179648** The second argument is the major token number.  The third is
179649** the minor token.  The fourth optional argument is whatever the
179650** user wants (and specified in the grammar) and is available for
179651** use by the action routines.
179652**
179653** Inputs:
179654** <ul>
179655** <li> A pointer to the parser (an opaque structure.)
179656** <li> The major token number.
179657** <li> The minor token number.
179658** <li> An option argument of a grammar-specified type.
179659** </ul>
179660**
179661** Outputs:
179662** None.
179663*/
179664static void sqlite3Fts5Parser(
179665  void *fts5yyp,                   /* The parser */
179666  int fts5yymajor,                 /* The major token code number */
179667  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor       /* The value for the token */
179668  sqlite3Fts5ParserARG_PDECL               /* Optional %extra_argument parameter */
179669){
179670  fts5YYMINORTYPE fts5yyminorunion;
179671  unsigned int fts5yyact;   /* The parser action. */
179672#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
179673  int fts5yyendofinput;     /* True if we are at the end of input */
179674#endif
179675#ifdef fts5YYERRORSYMBOL
179676  int fts5yyerrorhit = 0;   /* True if fts5yymajor has invoked an error */
179677#endif
179678  fts5yyParser *fts5yypParser;  /* The parser */
179679
179680  fts5yypParser = (fts5yyParser*)fts5yyp;
179681  assert( fts5yypParser->fts5yytos!=0 );
179682#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
179683  fts5yyendofinput = (fts5yymajor==0);
179684#endif
179685  sqlite3Fts5ParserARG_STORE;
179686
179687#ifndef NDEBUG
179688  if( fts5yyTraceFILE ){
179689    fprintf(fts5yyTraceFILE,"%sInput '%s'\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
179690  }
179691#endif
179692
179693  do{
179694    fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
179695    if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
179696      fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor);
179697#ifndef fts5YYNOERRORRECOVERY
179698      fts5yypParser->fts5yyerrcnt--;
179699#endif
179700      fts5yymajor = fts5YYNOCODE;
179701    }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
179702      fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
179703    }else{
179704      assert( fts5yyact == fts5YY_ERROR_ACTION );
179705      fts5yyminorunion.fts5yy0 = fts5yyminor;
179706#ifdef fts5YYERRORSYMBOL
179707      int fts5yymx;
179708#endif
179709#ifndef NDEBUG
179710      if( fts5yyTraceFILE ){
179711        fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
179712      }
179713#endif
179714#ifdef fts5YYERRORSYMBOL
179715      /* A syntax error has occurred.
179716      ** The response to an error depends upon whether or not the
179717      ** grammar defines an error token "ERROR".
179718      **
179719      ** This is what we do if the grammar does define ERROR:
179720      **
179721      **  * Call the %syntax_error function.
179722      **
179723      **  * Begin popping the stack until we enter a state where
179724      **    it is legal to shift the error symbol, then shift
179725      **    the error symbol.
179726      **
179727      **  * Set the error count to three.
179728      **
179729      **  * Begin accepting and shifting new tokens.  No new error
179730      **    processing will occur until three tokens have been
179731      **    shifted successfully.
179732      **
179733      */
179734      if( fts5yypParser->fts5yyerrcnt<0 ){
179735        fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
179736      }
179737      fts5yymx = fts5yypParser->fts5yytos->major;
179738      if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
179739#ifndef NDEBUG
179740        if( fts5yyTraceFILE ){
179741          fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
179742             fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
179743        }
179744#endif
179745        fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
179746        fts5yymajor = fts5YYNOCODE;
179747      }else{
179748        while( fts5yypParser->fts5yytos >= &fts5yypParser->fts5yystack
179749            && fts5yymx != fts5YYERRORSYMBOL
179750            && (fts5yyact = fts5yy_find_reduce_action(
179751                        fts5yypParser->fts5yytos->stateno,
179752                        fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
179753        ){
179754          fts5yy_pop_parser_stack(fts5yypParser);
179755        }
179756        if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
179757          fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
179758          fts5yy_parse_failed(fts5yypParser);
179759#ifndef fts5YYNOERRORRECOVERY
179760          fts5yypParser->fts5yyerrcnt = -1;
179761#endif
179762          fts5yymajor = fts5YYNOCODE;
179763        }else if( fts5yymx!=fts5YYERRORSYMBOL ){
179764          fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
179765        }
179766      }
179767      fts5yypParser->fts5yyerrcnt = 3;
179768      fts5yyerrorhit = 1;
179769#elif defined(fts5YYNOERRORRECOVERY)
179770      /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
179771      ** do any kind of error recovery.  Instead, simply invoke the syntax
179772      ** error routine and continue going as if nothing had happened.
179773      **
179774      ** Applications can set this macro (for example inside %include) if
179775      ** they intend to abandon the parse upon the first syntax error seen.
179776      */
179777      fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
179778      fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
179779      fts5yymajor = fts5YYNOCODE;
179780
179781#else  /* fts5YYERRORSYMBOL is not defined */
179782      /* This is what we do if the grammar does not define ERROR:
179783      **
179784      **  * Report an error message, and throw away the input token.
179785      **
179786      **  * If the input token is $, then fail the parse.
179787      **
179788      ** As before, subsequent error messages are suppressed until
179789      ** three input tokens have been successfully shifted.
179790      */
179791      if( fts5yypParser->fts5yyerrcnt<=0 ){
179792        fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
179793      }
179794      fts5yypParser->fts5yyerrcnt = 3;
179795      fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
179796      if( fts5yyendofinput ){
179797        fts5yy_parse_failed(fts5yypParser);
179798#ifndef fts5YYNOERRORRECOVERY
179799        fts5yypParser->fts5yyerrcnt = -1;
179800#endif
179801      }
179802      fts5yymajor = fts5YYNOCODE;
179803#endif
179804    }
179805  }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
179806#ifndef NDEBUG
179807  if( fts5yyTraceFILE ){
179808    fts5yyStackEntry *i;
179809    char cDiv = '[';
179810    fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
179811    for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
179812      fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
179813      cDiv = ' ';
179814    }
179815    fprintf(fts5yyTraceFILE,"]\n");
179816  }
179817#endif
179818  return;
179819}
179820
179821/*
179822** 2014 May 31
179823**
179824** The author disclaims copyright to this source code.  In place of
179825** a legal notice, here is a blessing:
179826**
179827**    May you do good and not evil.
179828**    May you find forgiveness for yourself and forgive others.
179829**    May you share freely, never taking more than you give.
179830**
179831******************************************************************************
179832*/
179833
179834
179835/* #include "fts5Int.h" */
179836#include <math.h>                 /* amalgamator: keep */
179837
179838/*
179839** Object used to iterate through all "coalesced phrase instances" in
179840** a single column of the current row. If the phrase instances in the
179841** column being considered do not overlap, this object simply iterates
179842** through them. Or, if they do overlap (share one or more tokens in
179843** common), each set of overlapping instances is treated as a single
179844** match. See documentation for the highlight() auxiliary function for
179845** details.
179846**
179847** Usage is:
179848**
179849**   for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
179850**      (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
179851**      rc = fts5CInstIterNext(&iter)
179852**   ){
179853**     printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
179854**   }
179855**
179856*/
179857typedef struct CInstIter CInstIter;
179858struct CInstIter {
179859  const Fts5ExtensionApi *pApi;   /* API offered by current FTS version */
179860  Fts5Context *pFts;              /* First arg to pass to pApi functions */
179861  int iCol;                       /* Column to search */
179862  int iInst;                      /* Next phrase instance index */
179863  int nInst;                      /* Total number of phrase instances */
179864
179865  /* Output variables */
179866  int iStart;                     /* First token in coalesced phrase instance */
179867  int iEnd;                       /* Last token in coalesced phrase instance */
179868};
179869
179870/*
179871** Advance the iterator to the next coalesced phrase instance. Return
179872** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
179873*/
179874static int fts5CInstIterNext(CInstIter *pIter){
179875  int rc = SQLITE_OK;
179876  pIter->iStart = -1;
179877  pIter->iEnd = -1;
179878
179879  while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
179880    int ip; int ic; int io;
179881    rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
179882    if( rc==SQLITE_OK ){
179883      if( ic==pIter->iCol ){
179884        int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
179885        if( pIter->iStart<0 ){
179886          pIter->iStart = io;
179887          pIter->iEnd = iEnd;
179888        }else if( io<=pIter->iEnd ){
179889          if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
179890        }else{
179891          break;
179892        }
179893      }
179894      pIter->iInst++;
179895    }
179896  }
179897
179898  return rc;
179899}
179900
179901/*
179902** Initialize the iterator object indicated by the final parameter to
179903** iterate through coalesced phrase instances in column iCol.
179904*/
179905static int fts5CInstIterInit(
179906  const Fts5ExtensionApi *pApi,
179907  Fts5Context *pFts,
179908  int iCol,
179909  CInstIter *pIter
179910){
179911  int rc;
179912
179913  memset(pIter, 0, sizeof(CInstIter));
179914  pIter->pApi = pApi;
179915  pIter->pFts = pFts;
179916  pIter->iCol = iCol;
179917  rc = pApi->xInstCount(pFts, &pIter->nInst);
179918
179919  if( rc==SQLITE_OK ){
179920    rc = fts5CInstIterNext(pIter);
179921  }
179922
179923  return rc;
179924}
179925
179926
179927
179928/*************************************************************************
179929** Start of highlight() implementation.
179930*/
179931typedef struct HighlightContext HighlightContext;
179932struct HighlightContext {
179933  CInstIter iter;                 /* Coalesced Instance Iterator */
179934  int iPos;                       /* Current token offset in zIn[] */
179935  int iRangeStart;                /* First token to include */
179936  int iRangeEnd;                  /* If non-zero, last token to include */
179937  const char *zOpen;              /* Opening highlight */
179938  const char *zClose;             /* Closing highlight */
179939  const char *zIn;                /* Input text */
179940  int nIn;                        /* Size of input text in bytes */
179941  int iOff;                       /* Current offset within zIn[] */
179942  char *zOut;                     /* Output value */
179943};
179944
179945/*
179946** Append text to the HighlightContext output string - p->zOut. Argument
179947** z points to a buffer containing n bytes of text to append. If n is
179948** negative, everything up until the first '\0' is appended to the output.
179949**
179950** If *pRc is set to any value other than SQLITE_OK when this function is
179951** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
179952** *pRc is set to an error code before returning.
179953*/
179954static void fts5HighlightAppend(
179955  int *pRc,
179956  HighlightContext *p,
179957  const char *z, int n
179958){
179959  if( *pRc==SQLITE_OK ){
179960    if( n<0 ) n = (int)strlen(z);
179961    p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
179962    if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
179963  }
179964}
179965
179966/*
179967** Tokenizer callback used by implementation of highlight() function.
179968*/
179969static int fts5HighlightCb(
179970  void *pContext,                 /* Pointer to HighlightContext object */
179971  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
179972  const char *pToken,             /* Buffer containing token */
179973  int nToken,                     /* Size of token in bytes */
179974  int iStartOff,                  /* Start offset of token */
179975  int iEndOff                     /* End offset of token */
179976){
179977  HighlightContext *p = (HighlightContext*)pContext;
179978  int rc = SQLITE_OK;
179979  int iPos;
179980
179981  UNUSED_PARAM2(pToken, nToken);
179982
179983  if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
179984  iPos = p->iPos++;
179985
179986  if( p->iRangeEnd>0 ){
179987    if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
179988    if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
179989  }
179990
179991  if( iPos==p->iter.iStart ){
179992    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
179993    fts5HighlightAppend(&rc, p, p->zOpen, -1);
179994    p->iOff = iStartOff;
179995  }
179996
179997  if( iPos==p->iter.iEnd ){
179998    if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
179999      fts5HighlightAppend(&rc, p, p->zOpen, -1);
180000    }
180001    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
180002    fts5HighlightAppend(&rc, p, p->zClose, -1);
180003    p->iOff = iEndOff;
180004    if( rc==SQLITE_OK ){
180005      rc = fts5CInstIterNext(&p->iter);
180006    }
180007  }
180008
180009  if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
180010    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
180011    p->iOff = iEndOff;
180012    if( iPos<p->iter.iEnd ){
180013      fts5HighlightAppend(&rc, p, p->zClose, -1);
180014    }
180015  }
180016
180017  return rc;
180018}
180019
180020/*
180021** Implementation of highlight() function.
180022*/
180023static void fts5HighlightFunction(
180024  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
180025  Fts5Context *pFts,              /* First arg to pass to pApi functions */
180026  sqlite3_context *pCtx,          /* Context for returning result/error */
180027  int nVal,                       /* Number of values in apVal[] array */
180028  sqlite3_value **apVal           /* Array of trailing arguments */
180029){
180030  HighlightContext ctx;
180031  int rc;
180032  int iCol;
180033
180034  if( nVal!=3 ){
180035    const char *zErr = "wrong number of arguments to function highlight()";
180036    sqlite3_result_error(pCtx, zErr, -1);
180037    return;
180038  }
180039
180040  iCol = sqlite3_value_int(apVal[0]);
180041  memset(&ctx, 0, sizeof(HighlightContext));
180042  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
180043  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
180044  rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
180045
180046  if( ctx.zIn ){
180047    if( rc==SQLITE_OK ){
180048      rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
180049    }
180050
180051    if( rc==SQLITE_OK ){
180052      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
180053    }
180054    fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
180055
180056    if( rc==SQLITE_OK ){
180057      sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
180058    }
180059    sqlite3_free(ctx.zOut);
180060  }
180061  if( rc!=SQLITE_OK ){
180062    sqlite3_result_error_code(pCtx, rc);
180063  }
180064}
180065/*
180066** End of highlight() implementation.
180067**************************************************************************/
180068
180069/*
180070** Implementation of snippet() function.
180071*/
180072static void fts5SnippetFunction(
180073  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
180074  Fts5Context *pFts,              /* First arg to pass to pApi functions */
180075  sqlite3_context *pCtx,          /* Context for returning result/error */
180076  int nVal,                       /* Number of values in apVal[] array */
180077  sqlite3_value **apVal           /* Array of trailing arguments */
180078){
180079  HighlightContext ctx;
180080  int rc = SQLITE_OK;             /* Return code */
180081  int iCol;                       /* 1st argument to snippet() */
180082  const char *zEllips;            /* 4th argument to snippet() */
180083  int nToken;                     /* 5th argument to snippet() */
180084  int nInst = 0;                  /* Number of instance matches this row */
180085  int i;                          /* Used to iterate through instances */
180086  int nPhrase;                    /* Number of phrases in query */
180087  unsigned char *aSeen;           /* Array of "seen instance" flags */
180088  int iBestCol;                   /* Column containing best snippet */
180089  int iBestStart = 0;             /* First token of best snippet */
180090  int iBestLast;                  /* Last token of best snippet */
180091  int nBestScore = 0;             /* Score of best snippet */
180092  int nColSize = 0;               /* Total size of iBestCol in tokens */
180093
180094  if( nVal!=5 ){
180095    const char *zErr = "wrong number of arguments to function snippet()";
180096    sqlite3_result_error(pCtx, zErr, -1);
180097    return;
180098  }
180099
180100  memset(&ctx, 0, sizeof(HighlightContext));
180101  iCol = sqlite3_value_int(apVal[0]);
180102  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
180103  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
180104  zEllips = (const char*)sqlite3_value_text(apVal[3]);
180105  nToken = sqlite3_value_int(apVal[4]);
180106  iBestLast = nToken-1;
180107
180108  iBestCol = (iCol>=0 ? iCol : 0);
180109  nPhrase = pApi->xPhraseCount(pFts);
180110  aSeen = sqlite3_malloc(nPhrase);
180111  if( aSeen==0 ){
180112    rc = SQLITE_NOMEM;
180113  }
180114
180115  if( rc==SQLITE_OK ){
180116    rc = pApi->xInstCount(pFts, &nInst);
180117  }
180118  for(i=0; rc==SQLITE_OK && i<nInst; i++){
180119    int ip, iSnippetCol, iStart;
180120    memset(aSeen, 0, nPhrase);
180121    rc = pApi->xInst(pFts, i, &ip, &iSnippetCol, &iStart);
180122    if( rc==SQLITE_OK && (iCol<0 || iSnippetCol==iCol) ){
180123      int nScore = 1000;
180124      int iLast = iStart - 1 + pApi->xPhraseSize(pFts, ip);
180125      int j;
180126      aSeen[ip] = 1;
180127
180128      for(j=i+1; rc==SQLITE_OK && j<nInst; j++){
180129        int ic; int io; int iFinal;
180130        rc = pApi->xInst(pFts, j, &ip, &ic, &io);
180131        iFinal = io + pApi->xPhraseSize(pFts, ip) - 1;
180132        if( rc==SQLITE_OK && ic==iSnippetCol && iLast<iStart+nToken ){
180133          nScore += aSeen[ip] ? 1000 : 1;
180134          aSeen[ip] = 1;
180135          if( iFinal>iLast ) iLast = iFinal;
180136        }
180137      }
180138
180139      if( rc==SQLITE_OK && nScore>nBestScore ){
180140        iBestCol = iSnippetCol;
180141        iBestStart = iStart;
180142        iBestLast = iLast;
180143        nBestScore = nScore;
180144      }
180145    }
180146  }
180147
180148  if( rc==SQLITE_OK ){
180149    rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
180150  }
180151  if( rc==SQLITE_OK ){
180152    rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
180153  }
180154  if( ctx.zIn ){
180155    if( rc==SQLITE_OK ){
180156      rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
180157    }
180158
180159    if( (iBestStart+nToken-1)>iBestLast ){
180160      iBestStart -= (iBestStart+nToken-1-iBestLast) / 2;
180161    }
180162    if( iBestStart+nToken>nColSize ){
180163      iBestStart = nColSize - nToken;
180164    }
180165    if( iBestStart<0 ) iBestStart = 0;
180166
180167    ctx.iRangeStart = iBestStart;
180168    ctx.iRangeEnd = iBestStart + nToken - 1;
180169
180170    if( iBestStart>0 ){
180171      fts5HighlightAppend(&rc, &ctx, zEllips, -1);
180172    }
180173    if( rc==SQLITE_OK ){
180174      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
180175    }
180176    if( ctx.iRangeEnd>=(nColSize-1) ){
180177      fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
180178    }else{
180179      fts5HighlightAppend(&rc, &ctx, zEllips, -1);
180180    }
180181
180182    if( rc==SQLITE_OK ){
180183      sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
180184    }else{
180185      sqlite3_result_error_code(pCtx, rc);
180186    }
180187    sqlite3_free(ctx.zOut);
180188  }
180189  sqlite3_free(aSeen);
180190}
180191
180192/************************************************************************/
180193
180194/*
180195** The first time the bm25() function is called for a query, an instance
180196** of the following structure is allocated and populated.
180197*/
180198typedef struct Fts5Bm25Data Fts5Bm25Data;
180199struct Fts5Bm25Data {
180200  int nPhrase;                    /* Number of phrases in query */
180201  double avgdl;                   /* Average number of tokens in each row */
180202  double *aIDF;                   /* IDF for each phrase */
180203  double *aFreq;                  /* Array used to calculate phrase freq. */
180204};
180205
180206/*
180207** Callback used by fts5Bm25GetData() to count the number of rows in the
180208** table matched by each individual phrase within the query.
180209*/
180210static int fts5CountCb(
180211  const Fts5ExtensionApi *pApi,
180212  Fts5Context *pFts,
180213  void *pUserData                 /* Pointer to sqlite3_int64 variable */
180214){
180215  sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
180216  UNUSED_PARAM2(pApi, pFts);
180217  (*pn)++;
180218  return SQLITE_OK;
180219}
180220
180221/*
180222** Set *ppData to point to the Fts5Bm25Data object for the current query.
180223** If the object has not already been allocated, allocate and populate it
180224** now.
180225*/
180226static int fts5Bm25GetData(
180227  const Fts5ExtensionApi *pApi,
180228  Fts5Context *pFts,
180229  Fts5Bm25Data **ppData           /* OUT: bm25-data object for this query */
180230){
180231  int rc = SQLITE_OK;             /* Return code */
180232  Fts5Bm25Data *p;                /* Object to return */
180233
180234  p = pApi->xGetAuxdata(pFts, 0);
180235  if( p==0 ){
180236    int nPhrase;                  /* Number of phrases in query */
180237    sqlite3_int64 nRow = 0;       /* Number of rows in table */
180238    sqlite3_int64 nToken = 0;     /* Number of tokens in table */
180239    int nByte;                    /* Bytes of space to allocate */
180240    int i;
180241
180242    /* Allocate the Fts5Bm25Data object */
180243    nPhrase = pApi->xPhraseCount(pFts);
180244    nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
180245    p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
180246    if( p==0 ){
180247      rc = SQLITE_NOMEM;
180248    }else{
180249      memset(p, 0, nByte);
180250      p->nPhrase = nPhrase;
180251      p->aIDF = (double*)&p[1];
180252      p->aFreq = &p->aIDF[nPhrase];
180253    }
180254
180255    /* Calculate the average document length for this FTS5 table */
180256    if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
180257    if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
180258    if( rc==SQLITE_OK ) p->avgdl = (double)nToken  / (double)nRow;
180259
180260    /* Calculate an IDF for each phrase in the query */
180261    for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
180262      sqlite3_int64 nHit = 0;
180263      rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
180264      if( rc==SQLITE_OK ){
180265        /* Calculate the IDF (Inverse Document Frequency) for phrase i.
180266        ** This is done using the standard BM25 formula as found on wikipedia:
180267        **
180268        **   IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
180269        **
180270        ** where "N" is the total number of documents in the set and nHit
180271        ** is the number that contain at least one instance of the phrase
180272        ** under consideration.
180273        **
180274        ** The problem with this is that if (N < 2*nHit), the IDF is
180275        ** negative. Which is undesirable. So the mimimum allowable IDF is
180276        ** (1e-6) - roughly the same as a term that appears in just over
180277        ** half of set of 5,000,000 documents.  */
180278        double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
180279        if( idf<=0.0 ) idf = 1e-6;
180280        p->aIDF[i] = idf;
180281      }
180282    }
180283
180284    if( rc!=SQLITE_OK ){
180285      sqlite3_free(p);
180286    }else{
180287      rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
180288    }
180289    if( rc!=SQLITE_OK ) p = 0;
180290  }
180291  *ppData = p;
180292  return rc;
180293}
180294
180295/*
180296** Implementation of bm25() function.
180297*/
180298static void fts5Bm25Function(
180299  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
180300  Fts5Context *pFts,              /* First arg to pass to pApi functions */
180301  sqlite3_context *pCtx,          /* Context for returning result/error */
180302  int nVal,                       /* Number of values in apVal[] array */
180303  sqlite3_value **apVal           /* Array of trailing arguments */
180304){
180305  const double k1 = 1.2;          /* Constant "k1" from BM25 formula */
180306  const double b = 0.75;          /* Constant "b" from BM25 formula */
180307  int rc = SQLITE_OK;             /* Error code */
180308  double score = 0.0;             /* SQL function return value */
180309  Fts5Bm25Data *pData;            /* Values allocated/calculated once only */
180310  int i;                          /* Iterator variable */
180311  int nInst = 0;                  /* Value returned by xInstCount() */
180312  double D = 0.0;                 /* Total number of tokens in row */
180313  double *aFreq = 0;              /* Array of phrase freq. for current row */
180314
180315  /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
180316  ** for each phrase in the query for the current row. */
180317  rc = fts5Bm25GetData(pApi, pFts, &pData);
180318  if( rc==SQLITE_OK ){
180319    aFreq = pData->aFreq;
180320    memset(aFreq, 0, sizeof(double) * pData->nPhrase);
180321    rc = pApi->xInstCount(pFts, &nInst);
180322  }
180323  for(i=0; rc==SQLITE_OK && i<nInst; i++){
180324    int ip; int ic; int io;
180325    rc = pApi->xInst(pFts, i, &ip, &ic, &io);
180326    if( rc==SQLITE_OK ){
180327      double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
180328      aFreq[ip] += w;
180329    }
180330  }
180331
180332  /* Figure out the total size of the current row in tokens. */
180333  if( rc==SQLITE_OK ){
180334    int nTok;
180335    rc = pApi->xColumnSize(pFts, -1, &nTok);
180336    D = (double)nTok;
180337  }
180338
180339  /* Determine the BM25 score for the current row. */
180340  for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
180341    score += pData->aIDF[i] * (
180342      ( aFreq[i] * (k1 + 1.0) ) /
180343      ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
180344    );
180345  }
180346
180347  /* If no error has occurred, return the calculated score. Otherwise,
180348  ** throw an SQL exception.  */
180349  if( rc==SQLITE_OK ){
180350    sqlite3_result_double(pCtx, -1.0 * score);
180351  }else{
180352    sqlite3_result_error_code(pCtx, rc);
180353  }
180354}
180355
180356static int sqlite3Fts5AuxInit(fts5_api *pApi){
180357  struct Builtin {
180358    const char *zFunc;            /* Function name (nul-terminated) */
180359    void *pUserData;              /* User-data pointer */
180360    fts5_extension_function xFunc;/* Callback function */
180361    void (*xDestroy)(void*);      /* Destructor function */
180362  } aBuiltin [] = {
180363    { "snippet",   0, fts5SnippetFunction, 0 },
180364    { "highlight", 0, fts5HighlightFunction, 0 },
180365    { "bm25",      0, fts5Bm25Function,    0 },
180366  };
180367  int rc = SQLITE_OK;             /* Return code */
180368  int i;                          /* To iterate through builtin functions */
180369
180370  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
180371    rc = pApi->xCreateFunction(pApi,
180372        aBuiltin[i].zFunc,
180373        aBuiltin[i].pUserData,
180374        aBuiltin[i].xFunc,
180375        aBuiltin[i].xDestroy
180376    );
180377  }
180378
180379  return rc;
180380}
180381
180382
180383
180384/*
180385** 2014 May 31
180386**
180387** The author disclaims copyright to this source code.  In place of
180388** a legal notice, here is a blessing:
180389**
180390**    May you do good and not evil.
180391**    May you find forgiveness for yourself and forgive others.
180392**    May you share freely, never taking more than you give.
180393**
180394******************************************************************************
180395*/
180396
180397
180398
180399/* #include "fts5Int.h" */
180400
180401static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
180402  if( (u32)pBuf->nSpace<nByte ){
180403    u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
180404    u8 *pNew;
180405    while( nNew<nByte ){
180406      nNew = nNew * 2;
180407    }
180408    pNew = sqlite3_realloc(pBuf->p, nNew);
180409    if( pNew==0 ){
180410      *pRc = SQLITE_NOMEM;
180411      return 1;
180412    }else{
180413      pBuf->nSpace = nNew;
180414      pBuf->p = pNew;
180415    }
180416  }
180417  return 0;
180418}
180419
180420
180421/*
180422** Encode value iVal as an SQLite varint and append it to the buffer object
180423** pBuf. If an OOM error occurs, set the error code in p.
180424*/
180425static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
180426  if( fts5BufferGrow(pRc, pBuf, 9) ) return;
180427  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
180428}
180429
180430static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
180431  aBuf[0] = (iVal>>24) & 0x00FF;
180432  aBuf[1] = (iVal>>16) & 0x00FF;
180433  aBuf[2] = (iVal>> 8) & 0x00FF;
180434  aBuf[3] = (iVal>> 0) & 0x00FF;
180435}
180436
180437static int sqlite3Fts5Get32(const u8 *aBuf){
180438  return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
180439}
180440
180441/*
180442** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
180443** the error code in p. If an error has already occurred when this function
180444** is called, it is a no-op.
180445*/
180446static void sqlite3Fts5BufferAppendBlob(
180447  int *pRc,
180448  Fts5Buffer *pBuf,
180449  u32 nData,
180450  const u8 *pData
180451){
180452  assert_nc( *pRc || nData>=0 );
180453  if( fts5BufferGrow(pRc, pBuf, nData) ) return;
180454  memcpy(&pBuf->p[pBuf->n], pData, nData);
180455  pBuf->n += nData;
180456}
180457
180458/*
180459** Append the nul-terminated string zStr to the buffer pBuf. This function
180460** ensures that the byte following the buffer data is set to 0x00, even
180461** though this byte is not included in the pBuf->n count.
180462*/
180463static void sqlite3Fts5BufferAppendString(
180464  int *pRc,
180465  Fts5Buffer *pBuf,
180466  const char *zStr
180467){
180468  int nStr = (int)strlen(zStr);
180469  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
180470  pBuf->n--;
180471}
180472
180473/*
180474** Argument zFmt is a printf() style format string. This function performs
180475** the printf() style processing, then appends the results to buffer pBuf.
180476**
180477** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
180478** following the buffer data is set to 0x00, even though this byte is not
180479** included in the pBuf->n count.
180480*/
180481static void sqlite3Fts5BufferAppendPrintf(
180482  int *pRc,
180483  Fts5Buffer *pBuf,
180484  char *zFmt, ...
180485){
180486  if( *pRc==SQLITE_OK ){
180487    char *zTmp;
180488    va_list ap;
180489    va_start(ap, zFmt);
180490    zTmp = sqlite3_vmprintf(zFmt, ap);
180491    va_end(ap);
180492
180493    if( zTmp==0 ){
180494      *pRc = SQLITE_NOMEM;
180495    }else{
180496      sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
180497      sqlite3_free(zTmp);
180498    }
180499  }
180500}
180501
180502static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
180503  char *zRet = 0;
180504  if( *pRc==SQLITE_OK ){
180505    va_list ap;
180506    va_start(ap, zFmt);
180507    zRet = sqlite3_vmprintf(zFmt, ap);
180508    va_end(ap);
180509    if( zRet==0 ){
180510      *pRc = SQLITE_NOMEM;
180511    }
180512  }
180513  return zRet;
180514}
180515
180516
180517/*
180518** Free any buffer allocated by pBuf. Zero the structure before returning.
180519*/
180520static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
180521  sqlite3_free(pBuf->p);
180522  memset(pBuf, 0, sizeof(Fts5Buffer));
180523}
180524
180525/*
180526** Zero the contents of the buffer object. But do not free the associated
180527** memory allocation.
180528*/
180529static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
180530  pBuf->n = 0;
180531}
180532
180533/*
180534** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
180535** the error code in p. If an error has already occurred when this function
180536** is called, it is a no-op.
180537*/
180538static void sqlite3Fts5BufferSet(
180539  int *pRc,
180540  Fts5Buffer *pBuf,
180541  int nData,
180542  const u8 *pData
180543){
180544  pBuf->n = 0;
180545  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
180546}
180547
180548static int sqlite3Fts5PoslistNext64(
180549  const u8 *a, int n,             /* Buffer containing poslist */
180550  int *pi,                        /* IN/OUT: Offset within a[] */
180551  i64 *piOff                      /* IN/OUT: Current offset */
180552){
180553  int i = *pi;
180554  if( i>=n ){
180555    /* EOF */
180556    *piOff = -1;
180557    return 1;
180558  }else{
180559    i64 iOff = *piOff;
180560    int iVal;
180561    fts5FastGetVarint32(a, i, iVal);
180562    if( iVal==1 ){
180563      fts5FastGetVarint32(a, i, iVal);
180564      iOff = ((i64)iVal) << 32;
180565      fts5FastGetVarint32(a, i, iVal);
180566    }
180567    *piOff = iOff + (iVal-2);
180568    *pi = i;
180569    return 0;
180570  }
180571}
180572
180573
180574/*
180575** Advance the iterator object passed as the only argument. Return true
180576** if the iterator reaches EOF, or false otherwise.
180577*/
180578static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
180579  if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
180580    pIter->bEof = 1;
180581  }
180582  return pIter->bEof;
180583}
180584
180585static int sqlite3Fts5PoslistReaderInit(
180586  const u8 *a, int n,             /* Poslist buffer to iterate through */
180587  Fts5PoslistReader *pIter        /* Iterator object to initialize */
180588){
180589  memset(pIter, 0, sizeof(*pIter));
180590  pIter->a = a;
180591  pIter->n = n;
180592  sqlite3Fts5PoslistReaderNext(pIter);
180593  return pIter->bEof;
180594}
180595
180596/*
180597** Append position iPos to the position list being accumulated in buffer
180598** pBuf, which must be already be large enough to hold the new data.
180599** The previous position written to this list is *piPrev. *piPrev is set
180600** to iPos before returning.
180601*/
180602static void sqlite3Fts5PoslistSafeAppend(
180603  Fts5Buffer *pBuf,
180604  i64 *piPrev,
180605  i64 iPos
180606){
180607  static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
180608  if( (iPos & colmask) != (*piPrev & colmask) ){
180609    pBuf->p[pBuf->n++] = 1;
180610    pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
180611    *piPrev = (iPos & colmask);
180612  }
180613  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
180614  *piPrev = iPos;
180615}
180616
180617static int sqlite3Fts5PoslistWriterAppend(
180618  Fts5Buffer *pBuf,
180619  Fts5PoslistWriter *pWriter,
180620  i64 iPos
180621){
180622  int rc = 0;   /* Initialized only to suppress erroneous warning from Clang */
180623  if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
180624  sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
180625  return SQLITE_OK;
180626}
180627
180628static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
180629  void *pRet = 0;
180630  if( *pRc==SQLITE_OK ){
180631    pRet = sqlite3_malloc(nByte);
180632    if( pRet==0 && nByte>0 ){
180633      *pRc = SQLITE_NOMEM;
180634    }else{
180635      memset(pRet, 0, nByte);
180636    }
180637  }
180638  return pRet;
180639}
180640
180641/*
180642** Return a nul-terminated copy of the string indicated by pIn. If nIn
180643** is non-negative, then it is the length of the string in bytes. Otherwise,
180644** the length of the string is determined using strlen().
180645**
180646** It is the responsibility of the caller to eventually free the returned
180647** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
180648*/
180649static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
180650  char *zRet = 0;
180651  if( *pRc==SQLITE_OK ){
180652    if( nIn<0 ){
180653      nIn = (int)strlen(pIn);
180654    }
180655    zRet = (char*)sqlite3_malloc(nIn+1);
180656    if( zRet ){
180657      memcpy(zRet, pIn, nIn);
180658      zRet[nIn] = '\0';
180659    }else{
180660      *pRc = SQLITE_NOMEM;
180661    }
180662  }
180663  return zRet;
180664}
180665
180666
180667/*
180668** Return true if character 't' may be part of an FTS5 bareword, or false
180669** otherwise. Characters that may be part of barewords:
180670**
180671**   * All non-ASCII characters,
180672**   * The 52 upper and lower case ASCII characters, and
180673**   * The 10 integer ASCII characters.
180674**   * The underscore character "_" (0x5F).
180675**   * The unicode "subsitute" character (0x1A).
180676*/
180677static int sqlite3Fts5IsBareword(char t){
180678  u8 aBareword[128] = {
180679    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00 .. 0x0F */
180680    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 1, 0, 0, 0, 0, 0,   /* 0x10 .. 0x1F */
180681    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20 .. 0x2F */
180682    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30 .. 0x3F */
180683    0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40 .. 0x4F */
180684    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 1,   /* 0x50 .. 0x5F */
180685    0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60 .. 0x6F */
180686    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 0    /* 0x70 .. 0x7F */
180687  };
180688
180689  return (t & 0x80) || aBareword[(int)t];
180690}
180691
180692
180693/*************************************************************************
180694*/
180695typedef struct Fts5TermsetEntry Fts5TermsetEntry;
180696struct Fts5TermsetEntry {
180697  char *pTerm;
180698  int nTerm;
180699  int iIdx;                       /* Index (main or aPrefix[] entry) */
180700  Fts5TermsetEntry *pNext;
180701};
180702
180703struct Fts5Termset {
180704  Fts5TermsetEntry *apHash[512];
180705};
180706
180707static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
180708  int rc = SQLITE_OK;
180709  *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
180710  return rc;
180711}
180712
180713static int sqlite3Fts5TermsetAdd(
180714  Fts5Termset *p,
180715  int iIdx,
180716  const char *pTerm, int nTerm,
180717  int *pbPresent
180718){
180719  int rc = SQLITE_OK;
180720  *pbPresent = 0;
180721  if( p ){
180722    int i;
180723    u32 hash = 13;
180724    Fts5TermsetEntry *pEntry;
180725
180726    /* Calculate a hash value for this term. This is the same hash checksum
180727    ** used by the fts5_hash.c module. This is not important for correct
180728    ** operation of the module, but is necessary to ensure that some tests
180729    ** designed to produce hash table collisions really do work.  */
180730    for(i=nTerm-1; i>=0; i--){
180731      hash = (hash << 3) ^ hash ^ pTerm[i];
180732    }
180733    hash = (hash << 3) ^ hash ^ iIdx;
180734    hash = hash % ArraySize(p->apHash);
180735
180736    for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
180737      if( pEntry->iIdx==iIdx
180738          && pEntry->nTerm==nTerm
180739          && memcmp(pEntry->pTerm, pTerm, nTerm)==0
180740      ){
180741        *pbPresent = 1;
180742        break;
180743      }
180744    }
180745
180746    if( pEntry==0 ){
180747      pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
180748      if( pEntry ){
180749        pEntry->pTerm = (char*)&pEntry[1];
180750        pEntry->nTerm = nTerm;
180751        pEntry->iIdx = iIdx;
180752        memcpy(pEntry->pTerm, pTerm, nTerm);
180753        pEntry->pNext = p->apHash[hash];
180754        p->apHash[hash] = pEntry;
180755      }
180756    }
180757  }
180758
180759  return rc;
180760}
180761
180762static void sqlite3Fts5TermsetFree(Fts5Termset *p){
180763  if( p ){
180764    u32 i;
180765    for(i=0; i<ArraySize(p->apHash); i++){
180766      Fts5TermsetEntry *pEntry = p->apHash[i];
180767      while( pEntry ){
180768        Fts5TermsetEntry *pDel = pEntry;
180769        pEntry = pEntry->pNext;
180770        sqlite3_free(pDel);
180771      }
180772    }
180773    sqlite3_free(p);
180774  }
180775}
180776
180777/*
180778** 2014 Jun 09
180779**
180780** The author disclaims copyright to this source code.  In place of
180781** a legal notice, here is a blessing:
180782**
180783**    May you do good and not evil.
180784**    May you find forgiveness for yourself and forgive others.
180785**    May you share freely, never taking more than you give.
180786**
180787******************************************************************************
180788**
180789** This is an SQLite module implementing full-text search.
180790*/
180791
180792
180793/* #include "fts5Int.h" */
180794
180795#define FTS5_DEFAULT_PAGE_SIZE   4050
180796#define FTS5_DEFAULT_AUTOMERGE      4
180797#define FTS5_DEFAULT_USERMERGE      4
180798#define FTS5_DEFAULT_CRISISMERGE   16
180799#define FTS5_DEFAULT_HASHSIZE    (1024*1024)
180800
180801/* Maximum allowed page size */
180802#define FTS5_MAX_PAGE_SIZE (128*1024)
180803
180804static int fts5_iswhitespace(char x){
180805  return (x==' ');
180806}
180807
180808static int fts5_isopenquote(char x){
180809  return (x=='"' || x=='\'' || x=='[' || x=='`');
180810}
180811
180812/*
180813** Argument pIn points to a character that is part of a nul-terminated
180814** string. Return a pointer to the first character following *pIn in
180815** the string that is not a white-space character.
180816*/
180817static const char *fts5ConfigSkipWhitespace(const char *pIn){
180818  const char *p = pIn;
180819  if( p ){
180820    while( fts5_iswhitespace(*p) ){ p++; }
180821  }
180822  return p;
180823}
180824
180825/*
180826** Argument pIn points to a character that is part of a nul-terminated
180827** string. Return a pointer to the first character following *pIn in
180828** the string that is not a "bareword" character.
180829*/
180830static const char *fts5ConfigSkipBareword(const char *pIn){
180831  const char *p = pIn;
180832  while ( sqlite3Fts5IsBareword(*p) ) p++;
180833  if( p==pIn ) p = 0;
180834  return p;
180835}
180836
180837static int fts5_isdigit(char a){
180838  return (a>='0' && a<='9');
180839}
180840
180841
180842
180843static const char *fts5ConfigSkipLiteral(const char *pIn){
180844  const char *p = pIn;
180845  switch( *p ){
180846    case 'n': case 'N':
180847      if( sqlite3_strnicmp("null", p, 4)==0 ){
180848        p = &p[4];
180849      }else{
180850        p = 0;
180851      }
180852      break;
180853
180854    case 'x': case 'X':
180855      p++;
180856      if( *p=='\'' ){
180857        p++;
180858        while( (*p>='a' && *p<='f')
180859            || (*p>='A' && *p<='F')
180860            || (*p>='0' && *p<='9')
180861            ){
180862          p++;
180863        }
180864        if( *p=='\'' && 0==((p-pIn)%2) ){
180865          p++;
180866        }else{
180867          p = 0;
180868        }
180869      }else{
180870        p = 0;
180871      }
180872      break;
180873
180874    case '\'':
180875      p++;
180876      while( p ){
180877        if( *p=='\'' ){
180878          p++;
180879          if( *p!='\'' ) break;
180880        }
180881        p++;
180882        if( *p==0 ) p = 0;
180883      }
180884      break;
180885
180886    default:
180887      /* maybe a number */
180888      if( *p=='+' || *p=='-' ) p++;
180889      while( fts5_isdigit(*p) ) p++;
180890
180891      /* At this point, if the literal was an integer, the parse is
180892      ** finished. Or, if it is a floating point value, it may continue
180893      ** with either a decimal point or an 'E' character. */
180894      if( *p=='.' && fts5_isdigit(p[1]) ){
180895        p += 2;
180896        while( fts5_isdigit(*p) ) p++;
180897      }
180898      if( p==pIn ) p = 0;
180899
180900      break;
180901  }
180902
180903  return p;
180904}
180905
180906/*
180907** The first character of the string pointed to by argument z is guaranteed
180908** to be an open-quote character (see function fts5_isopenquote()).
180909**
180910** This function searches for the corresponding close-quote character within
180911** the string and, if found, dequotes the string in place and adds a new
180912** nul-terminator byte.
180913**
180914** If the close-quote is found, the value returned is the byte offset of
180915** the character immediately following it. Or, if the close-quote is not
180916** found, -1 is returned. If -1 is returned, the buffer is left in an
180917** undefined state.
180918*/
180919static int fts5Dequote(char *z){
180920  char q;
180921  int iIn = 1;
180922  int iOut = 0;
180923  q = z[0];
180924
180925  /* Set stack variable q to the close-quote character */
180926  assert( q=='[' || q=='\'' || q=='"' || q=='`' );
180927  if( q=='[' ) q = ']';
180928
180929  while( ALWAYS(z[iIn]) ){
180930    if( z[iIn]==q ){
180931      if( z[iIn+1]!=q ){
180932        /* Character iIn was the close quote. */
180933        iIn++;
180934        break;
180935      }else{
180936        /* Character iIn and iIn+1 form an escaped quote character. Skip
180937        ** the input cursor past both and copy a single quote character
180938        ** to the output buffer. */
180939        iIn += 2;
180940        z[iOut++] = q;
180941      }
180942    }else{
180943      z[iOut++] = z[iIn++];
180944    }
180945  }
180946
180947  z[iOut] = '\0';
180948  return iIn;
180949}
180950
180951/*
180952** Convert an SQL-style quoted string into a normal string by removing
180953** the quote characters.  The conversion is done in-place.  If the
180954** input does not begin with a quote character, then this routine
180955** is a no-op.
180956**
180957** Examples:
180958**
180959**     "abc"   becomes   abc
180960**     'xyz'   becomes   xyz
180961**     [pqr]   becomes   pqr
180962**     `mno`   becomes   mno
180963*/
180964static void sqlite3Fts5Dequote(char *z){
180965  char quote;                     /* Quote character (if any ) */
180966
180967  assert( 0==fts5_iswhitespace(z[0]) );
180968  quote = z[0];
180969  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
180970    fts5Dequote(z);
180971  }
180972}
180973
180974
180975struct Fts5Enum {
180976  const char *zName;
180977  int eVal;
180978};
180979typedef struct Fts5Enum Fts5Enum;
180980
180981static int fts5ConfigSetEnum(
180982  const Fts5Enum *aEnum,
180983  const char *zEnum,
180984  int *peVal
180985){
180986  int nEnum = (int)strlen(zEnum);
180987  int i;
180988  int iVal = -1;
180989
180990  for(i=0; aEnum[i].zName; i++){
180991    if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
180992      if( iVal>=0 ) return SQLITE_ERROR;
180993      iVal = aEnum[i].eVal;
180994    }
180995  }
180996
180997  *peVal = iVal;
180998  return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
180999}
181000
181001/*
181002** Parse a "special" CREATE VIRTUAL TABLE directive and update
181003** configuration object pConfig as appropriate.
181004**
181005** If successful, object pConfig is updated and SQLITE_OK returned. If
181006** an error occurs, an SQLite error code is returned and an error message
181007** may be left in *pzErr. It is the responsibility of the caller to
181008** eventually free any such error message using sqlite3_free().
181009*/
181010static int fts5ConfigParseSpecial(
181011  Fts5Global *pGlobal,
181012  Fts5Config *pConfig,            /* Configuration object to update */
181013  const char *zCmd,               /* Special command to parse */
181014  const char *zArg,               /* Argument to parse */
181015  char **pzErr                    /* OUT: Error message */
181016){
181017  int rc = SQLITE_OK;
181018  int nCmd = (int)strlen(zCmd);
181019  if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
181020    const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
181021    const char *p;
181022    int bFirst = 1;
181023    if( pConfig->aPrefix==0 ){
181024      pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
181025      if( rc ) return rc;
181026    }
181027
181028    p = zArg;
181029    while( 1 ){
181030      int nPre = 0;
181031
181032      while( p[0]==' ' ) p++;
181033      if( bFirst==0 && p[0]==',' ){
181034        p++;
181035        while( p[0]==' ' ) p++;
181036      }else if( p[0]=='\0' ){
181037        break;
181038      }
181039      if( p[0]<'0' || p[0]>'9' ){
181040        *pzErr = sqlite3_mprintf("malformed prefix=... directive");
181041        rc = SQLITE_ERROR;
181042        break;
181043      }
181044
181045      if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
181046        *pzErr = sqlite3_mprintf(
181047            "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
181048        );
181049        rc = SQLITE_ERROR;
181050        break;
181051      }
181052
181053      while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
181054        nPre = nPre*10 + (p[0] - '0');
181055        p++;
181056      }
181057
181058      if( nPre<=0 || nPre>=1000 ){
181059        *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
181060        rc = SQLITE_ERROR;
181061        break;
181062      }
181063
181064      pConfig->aPrefix[pConfig->nPrefix] = nPre;
181065      pConfig->nPrefix++;
181066      bFirst = 0;
181067    }
181068    assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
181069    return rc;
181070  }
181071
181072  if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
181073    const char *p = (const char*)zArg;
181074    int nArg = (int)strlen(zArg) + 1;
181075    char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
181076    char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
181077    char *pSpace = pDel;
181078
181079    if( azArg && pSpace ){
181080      if( pConfig->pTok ){
181081        *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
181082        rc = SQLITE_ERROR;
181083      }else{
181084        for(nArg=0; p && *p; nArg++){
181085          const char *p2 = fts5ConfigSkipWhitespace(p);
181086          if( *p2=='\'' ){
181087            p = fts5ConfigSkipLiteral(p2);
181088          }else{
181089            p = fts5ConfigSkipBareword(p2);
181090          }
181091          if( p ){
181092            memcpy(pSpace, p2, p-p2);
181093            azArg[nArg] = pSpace;
181094            sqlite3Fts5Dequote(pSpace);
181095            pSpace += (p - p2) + 1;
181096            p = fts5ConfigSkipWhitespace(p);
181097          }
181098        }
181099        if( p==0 ){
181100          *pzErr = sqlite3_mprintf("parse error in tokenize directive");
181101          rc = SQLITE_ERROR;
181102        }else{
181103          rc = sqlite3Fts5GetTokenizer(pGlobal,
181104              (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
181105              pzErr
181106          );
181107        }
181108      }
181109    }
181110
181111    sqlite3_free(azArg);
181112    sqlite3_free(pDel);
181113    return rc;
181114  }
181115
181116  if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
181117    if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
181118      *pzErr = sqlite3_mprintf("multiple content=... directives");
181119      rc = SQLITE_ERROR;
181120    }else{
181121      if( zArg[0] ){
181122        pConfig->eContent = FTS5_CONTENT_EXTERNAL;
181123        pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
181124      }else{
181125        pConfig->eContent = FTS5_CONTENT_NONE;
181126      }
181127    }
181128    return rc;
181129  }
181130
181131  if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
181132    if( pConfig->zContentRowid ){
181133      *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
181134      rc = SQLITE_ERROR;
181135    }else{
181136      pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
181137    }
181138    return rc;
181139  }
181140
181141  if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
181142    if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
181143      *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
181144      rc = SQLITE_ERROR;
181145    }else{
181146      pConfig->bColumnsize = (zArg[0]=='1');
181147    }
181148    return rc;
181149  }
181150
181151  if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
181152    const Fts5Enum aDetail[] = {
181153      { "none", FTS5_DETAIL_NONE },
181154      { "full", FTS5_DETAIL_FULL },
181155      { "columns", FTS5_DETAIL_COLUMNS },
181156      { 0, 0 }
181157    };
181158
181159    if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
181160      *pzErr = sqlite3_mprintf("malformed detail=... directive");
181161    }
181162    return rc;
181163  }
181164
181165  *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
181166  return SQLITE_ERROR;
181167}
181168
181169/*
181170** Allocate an instance of the default tokenizer ("simple") at
181171** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
181172** code if an error occurs.
181173*/
181174static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
181175  assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
181176  return sqlite3Fts5GetTokenizer(
181177      pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
181178  );
181179}
181180
181181/*
181182** Gobble up the first bareword or quoted word from the input buffer zIn.
181183** Return a pointer to the character immediately following the last in
181184** the gobbled word if successful, or a NULL pointer otherwise (failed
181185** to find close-quote character).
181186**
181187** Before returning, set pzOut to point to a new buffer containing a
181188** nul-terminated, dequoted copy of the gobbled word. If the word was
181189** quoted, *pbQuoted is also set to 1 before returning.
181190**
181191** If *pRc is other than SQLITE_OK when this function is called, it is
181192** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
181193** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
181194** set if a parse error (failed to find close quote) occurs.
181195*/
181196static const char *fts5ConfigGobbleWord(
181197  int *pRc,                       /* IN/OUT: Error code */
181198  const char *zIn,                /* Buffer to gobble string/bareword from */
181199  char **pzOut,                   /* OUT: malloc'd buffer containing str/bw */
181200  int *pbQuoted                   /* OUT: Set to true if dequoting required */
181201){
181202  const char *zRet = 0;
181203
181204  int nIn = (int)strlen(zIn);
181205  char *zOut = sqlite3_malloc(nIn+1);
181206
181207  assert( *pRc==SQLITE_OK );
181208  *pbQuoted = 0;
181209  *pzOut = 0;
181210
181211  if( zOut==0 ){
181212    *pRc = SQLITE_NOMEM;
181213  }else{
181214    memcpy(zOut, zIn, nIn+1);
181215    if( fts5_isopenquote(zOut[0]) ){
181216      int ii = fts5Dequote(zOut);
181217      zRet = &zIn[ii];
181218      *pbQuoted = 1;
181219    }else{
181220      zRet = fts5ConfigSkipBareword(zIn);
181221      if( zRet ){
181222        zOut[zRet-zIn] = '\0';
181223      }
181224    }
181225  }
181226
181227  if( zRet==0 ){
181228    sqlite3_free(zOut);
181229  }else{
181230    *pzOut = zOut;
181231  }
181232
181233  return zRet;
181234}
181235
181236static int fts5ConfigParseColumn(
181237  Fts5Config *p,
181238  char *zCol,
181239  char *zArg,
181240  char **pzErr
181241){
181242  int rc = SQLITE_OK;
181243  if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
181244   || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
181245  ){
181246    *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
181247    rc = SQLITE_ERROR;
181248  }else if( zArg ){
181249    if( 0==sqlite3_stricmp(zArg, "unindexed") ){
181250      p->abUnindexed[p->nCol] = 1;
181251    }else{
181252      *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
181253      rc = SQLITE_ERROR;
181254    }
181255  }
181256
181257  p->azCol[p->nCol++] = zCol;
181258  return rc;
181259}
181260
181261/*
181262** Populate the Fts5Config.zContentExprlist string.
181263*/
181264static int fts5ConfigMakeExprlist(Fts5Config *p){
181265  int i;
181266  int rc = SQLITE_OK;
181267  Fts5Buffer buf = {0, 0, 0};
181268
181269  sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
181270  if( p->eContent!=FTS5_CONTENT_NONE ){
181271    for(i=0; i<p->nCol; i++){
181272      if( p->eContent==FTS5_CONTENT_EXTERNAL ){
181273        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
181274      }else{
181275        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
181276      }
181277    }
181278  }
181279
181280  assert( p->zContentExprlist==0 );
181281  p->zContentExprlist = (char*)buf.p;
181282  return rc;
181283}
181284
181285/*
181286** Arguments nArg/azArg contain the string arguments passed to the xCreate
181287** or xConnect method of the virtual table. This function attempts to
181288** allocate an instance of Fts5Config containing the results of parsing
181289** those arguments.
181290**
181291** If successful, SQLITE_OK is returned and *ppOut is set to point to the
181292** new Fts5Config object. If an error occurs, an SQLite error code is
181293** returned, *ppOut is set to NULL and an error message may be left in
181294** *pzErr. It is the responsibility of the caller to eventually free any
181295** such error message using sqlite3_free().
181296*/
181297static int sqlite3Fts5ConfigParse(
181298  Fts5Global *pGlobal,
181299  sqlite3 *db,
181300  int nArg,                       /* Number of arguments */
181301  const char **azArg,             /* Array of nArg CREATE VIRTUAL TABLE args */
181302  Fts5Config **ppOut,             /* OUT: Results of parse */
181303  char **pzErr                    /* OUT: Error message */
181304){
181305  int rc = SQLITE_OK;             /* Return code */
181306  Fts5Config *pRet;               /* New object to return */
181307  int i;
181308  int nByte;
181309
181310  *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
181311  if( pRet==0 ) return SQLITE_NOMEM;
181312  memset(pRet, 0, sizeof(Fts5Config));
181313  pRet->db = db;
181314  pRet->iCookie = -1;
181315
181316  nByte = nArg * (sizeof(char*) + sizeof(u8));
181317  pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
181318  pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
181319  pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
181320  pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
181321  pRet->bColumnsize = 1;
181322  pRet->eDetail = FTS5_DETAIL_FULL;
181323#ifdef SQLITE_DEBUG
181324  pRet->bPrefixIndex = 1;
181325#endif
181326  if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
181327    *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
181328    rc = SQLITE_ERROR;
181329  }
181330
181331  for(i=3; rc==SQLITE_OK && i<nArg; i++){
181332    const char *zOrig = azArg[i];
181333    const char *z;
181334    char *zOne = 0;
181335    char *zTwo = 0;
181336    int bOption = 0;
181337    int bMustBeCol = 0;
181338
181339    z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
181340    z = fts5ConfigSkipWhitespace(z);
181341    if( z && *z=='=' ){
181342      bOption = 1;
181343      z++;
181344      if( bMustBeCol ) z = 0;
181345    }
181346    z = fts5ConfigSkipWhitespace(z);
181347    if( z && z[0] ){
181348      int bDummy;
181349      z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
181350      if( z && z[0] ) z = 0;
181351    }
181352
181353    if( rc==SQLITE_OK ){
181354      if( z==0 ){
181355        *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
181356        rc = SQLITE_ERROR;
181357      }else{
181358        if( bOption ){
181359          rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
181360        }else{
181361          rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
181362          zOne = 0;
181363        }
181364      }
181365    }
181366
181367    sqlite3_free(zOne);
181368    sqlite3_free(zTwo);
181369  }
181370
181371  /* If a tokenizer= option was successfully parsed, the tokenizer has
181372  ** already been allocated. Otherwise, allocate an instance of the default
181373  ** tokenizer (unicode61) now.  */
181374  if( rc==SQLITE_OK && pRet->pTok==0 ){
181375    rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
181376  }
181377
181378  /* If no zContent option was specified, fill in the default values. */
181379  if( rc==SQLITE_OK && pRet->zContent==0 ){
181380    const char *zTail = 0;
181381    assert( pRet->eContent==FTS5_CONTENT_NORMAL
181382         || pRet->eContent==FTS5_CONTENT_NONE
181383    );
181384    if( pRet->eContent==FTS5_CONTENT_NORMAL ){
181385      zTail = "content";
181386    }else if( pRet->bColumnsize ){
181387      zTail = "docsize";
181388    }
181389
181390    if( zTail ){
181391      pRet->zContent = sqlite3Fts5Mprintf(
181392          &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
181393      );
181394    }
181395  }
181396
181397  if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
181398    pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
181399  }
181400
181401  /* Formulate the zContentExprlist text */
181402  if( rc==SQLITE_OK ){
181403    rc = fts5ConfigMakeExprlist(pRet);
181404  }
181405
181406  if( rc!=SQLITE_OK ){
181407    sqlite3Fts5ConfigFree(pRet);
181408    *ppOut = 0;
181409  }
181410  return rc;
181411}
181412
181413/*
181414** Free the configuration object passed as the only argument.
181415*/
181416static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
181417  if( pConfig ){
181418    int i;
181419    if( pConfig->pTok ){
181420      pConfig->pTokApi->xDelete(pConfig->pTok);
181421    }
181422    sqlite3_free(pConfig->zDb);
181423    sqlite3_free(pConfig->zName);
181424    for(i=0; i<pConfig->nCol; i++){
181425      sqlite3_free(pConfig->azCol[i]);
181426    }
181427    sqlite3_free(pConfig->azCol);
181428    sqlite3_free(pConfig->aPrefix);
181429    sqlite3_free(pConfig->zRank);
181430    sqlite3_free(pConfig->zRankArgs);
181431    sqlite3_free(pConfig->zContent);
181432    sqlite3_free(pConfig->zContentRowid);
181433    sqlite3_free(pConfig->zContentExprlist);
181434    sqlite3_free(pConfig);
181435  }
181436}
181437
181438/*
181439** Call sqlite3_declare_vtab() based on the contents of the configuration
181440** object passed as the only argument. Return SQLITE_OK if successful, or
181441** an SQLite error code if an error occurs.
181442*/
181443static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
181444  int i;
181445  int rc = SQLITE_OK;
181446  char *zSql;
181447
181448  zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
181449  for(i=0; zSql && i<pConfig->nCol; i++){
181450    const char *zSep = (i==0?"":", ");
181451    zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
181452  }
181453  zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
181454      zSql, pConfig->zName, FTS5_RANK_NAME
181455  );
181456
181457  assert( zSql || rc==SQLITE_NOMEM );
181458  if( zSql ){
181459    rc = sqlite3_declare_vtab(pConfig->db, zSql);
181460    sqlite3_free(zSql);
181461  }
181462
181463  return rc;
181464}
181465
181466/*
181467** Tokenize the text passed via the second and third arguments.
181468**
181469** The callback is invoked once for each token in the input text. The
181470** arguments passed to it are, in order:
181471**
181472**     void *pCtx          // Copy of 4th argument to sqlite3Fts5Tokenize()
181473**     const char *pToken  // Pointer to buffer containing token
181474**     int nToken          // Size of token in bytes
181475**     int iStart          // Byte offset of start of token within input text
181476**     int iEnd            // Byte offset of end of token within input text
181477**     int iPos            // Position of token in input (first token is 0)
181478**
181479** If the callback returns a non-zero value the tokenization is abandoned
181480** and no further callbacks are issued.
181481**
181482** This function returns SQLITE_OK if successful or an SQLite error code
181483** if an error occurs. If the tokenization was abandoned early because
181484** the callback returned SQLITE_DONE, this is not an error and this function
181485** still returns SQLITE_OK. Or, if the tokenization was abandoned early
181486** because the callback returned another non-zero value, it is assumed
181487** to be an SQLite error code and returned to the caller.
181488*/
181489static int sqlite3Fts5Tokenize(
181490  Fts5Config *pConfig,            /* FTS5 Configuration object */
181491  int flags,                      /* FTS5_TOKENIZE_* flags */
181492  const char *pText, int nText,   /* Text to tokenize */
181493  void *pCtx,                     /* Context passed to xToken() */
181494  int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
181495){
181496  if( pText==0 ) return SQLITE_OK;
181497  return pConfig->pTokApi->xTokenize(
181498      pConfig->pTok, pCtx, flags, pText, nText, xToken
181499  );
181500}
181501
181502/*
181503** Argument pIn points to the first character in what is expected to be
181504** a comma-separated list of SQL literals followed by a ')' character.
181505** If it actually is this, return a pointer to the ')'. Otherwise, return
181506** NULL to indicate a parse error.
181507*/
181508static const char *fts5ConfigSkipArgs(const char *pIn){
181509  const char *p = pIn;
181510
181511  while( 1 ){
181512    p = fts5ConfigSkipWhitespace(p);
181513    p = fts5ConfigSkipLiteral(p);
181514    p = fts5ConfigSkipWhitespace(p);
181515    if( p==0 || *p==')' ) break;
181516    if( *p!=',' ){
181517      p = 0;
181518      break;
181519    }
181520    p++;
181521  }
181522
181523  return p;
181524}
181525
181526/*
181527** Parameter zIn contains a rank() function specification. The format of
181528** this is:
181529**
181530**   + Bareword (function name)
181531**   + Open parenthesis - "("
181532**   + Zero or more SQL literals in a comma separated list
181533**   + Close parenthesis - ")"
181534*/
181535static int sqlite3Fts5ConfigParseRank(
181536  const char *zIn,                /* Input string */
181537  char **pzRank,                  /* OUT: Rank function name */
181538  char **pzRankArgs               /* OUT: Rank function arguments */
181539){
181540  const char *p = zIn;
181541  const char *pRank;
181542  char *zRank = 0;
181543  char *zRankArgs = 0;
181544  int rc = SQLITE_OK;
181545
181546  *pzRank = 0;
181547  *pzRankArgs = 0;
181548
181549  if( p==0 ){
181550    rc = SQLITE_ERROR;
181551  }else{
181552    p = fts5ConfigSkipWhitespace(p);
181553    pRank = p;
181554    p = fts5ConfigSkipBareword(p);
181555
181556    if( p ){
181557      zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
181558      if( zRank ) memcpy(zRank, pRank, p-pRank);
181559    }else{
181560      rc = SQLITE_ERROR;
181561    }
181562
181563    if( rc==SQLITE_OK ){
181564      p = fts5ConfigSkipWhitespace(p);
181565      if( *p!='(' ) rc = SQLITE_ERROR;
181566      p++;
181567    }
181568    if( rc==SQLITE_OK ){
181569      const char *pArgs;
181570      p = fts5ConfigSkipWhitespace(p);
181571      pArgs = p;
181572      if( *p!=')' ){
181573        p = fts5ConfigSkipArgs(p);
181574        if( p==0 ){
181575          rc = SQLITE_ERROR;
181576        }else{
181577          zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
181578          if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
181579        }
181580      }
181581    }
181582  }
181583
181584  if( rc!=SQLITE_OK ){
181585    sqlite3_free(zRank);
181586    assert( zRankArgs==0 );
181587  }else{
181588    *pzRank = zRank;
181589    *pzRankArgs = zRankArgs;
181590  }
181591  return rc;
181592}
181593
181594static int sqlite3Fts5ConfigSetValue(
181595  Fts5Config *pConfig,
181596  const char *zKey,
181597  sqlite3_value *pVal,
181598  int *pbBadkey
181599){
181600  int rc = SQLITE_OK;
181601
181602  if( 0==sqlite3_stricmp(zKey, "pgsz") ){
181603    int pgsz = 0;
181604    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
181605      pgsz = sqlite3_value_int(pVal);
181606    }
181607    if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
181608      *pbBadkey = 1;
181609    }else{
181610      pConfig->pgsz = pgsz;
181611    }
181612  }
181613
181614  else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
181615    int nHashSize = -1;
181616    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
181617      nHashSize = sqlite3_value_int(pVal);
181618    }
181619    if( nHashSize<=0 ){
181620      *pbBadkey = 1;
181621    }else{
181622      pConfig->nHashSize = nHashSize;
181623    }
181624  }
181625
181626  else if( 0==sqlite3_stricmp(zKey, "automerge") ){
181627    int nAutomerge = -1;
181628    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
181629      nAutomerge = sqlite3_value_int(pVal);
181630    }
181631    if( nAutomerge<0 || nAutomerge>64 ){
181632      *pbBadkey = 1;
181633    }else{
181634      if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
181635      pConfig->nAutomerge = nAutomerge;
181636    }
181637  }
181638
181639  else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
181640    int nUsermerge = -1;
181641    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
181642      nUsermerge = sqlite3_value_int(pVal);
181643    }
181644    if( nUsermerge<2 || nUsermerge>16 ){
181645      *pbBadkey = 1;
181646    }else{
181647      pConfig->nUsermerge = nUsermerge;
181648    }
181649  }
181650
181651  else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
181652    int nCrisisMerge = -1;
181653    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
181654      nCrisisMerge = sqlite3_value_int(pVal);
181655    }
181656    if( nCrisisMerge<0 ){
181657      *pbBadkey = 1;
181658    }else{
181659      if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
181660      pConfig->nCrisisMerge = nCrisisMerge;
181661    }
181662  }
181663
181664  else if( 0==sqlite3_stricmp(zKey, "rank") ){
181665    const char *zIn = (const char*)sqlite3_value_text(pVal);
181666    char *zRank;
181667    char *zRankArgs;
181668    rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
181669    if( rc==SQLITE_OK ){
181670      sqlite3_free(pConfig->zRank);
181671      sqlite3_free(pConfig->zRankArgs);
181672      pConfig->zRank = zRank;
181673      pConfig->zRankArgs = zRankArgs;
181674    }else if( rc==SQLITE_ERROR ){
181675      rc = SQLITE_OK;
181676      *pbBadkey = 1;
181677    }
181678  }else{
181679    *pbBadkey = 1;
181680  }
181681  return rc;
181682}
181683
181684/*
181685** Load the contents of the %_config table into memory.
181686*/
181687static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
181688  const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
181689  char *zSql;
181690  sqlite3_stmt *p = 0;
181691  int rc = SQLITE_OK;
181692  int iVersion = 0;
181693
181694  /* Set default values */
181695  pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
181696  pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
181697  pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
181698  pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
181699  pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
181700
181701  zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
181702  if( zSql ){
181703    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
181704    sqlite3_free(zSql);
181705  }
181706
181707  assert( rc==SQLITE_OK || p==0 );
181708  if( rc==SQLITE_OK ){
181709    while( SQLITE_ROW==sqlite3_step(p) ){
181710      const char *zK = (const char*)sqlite3_column_text(p, 0);
181711      sqlite3_value *pVal = sqlite3_column_value(p, 1);
181712      if( 0==sqlite3_stricmp(zK, "version") ){
181713        iVersion = sqlite3_value_int(pVal);
181714      }else{
181715        int bDummy = 0;
181716        sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
181717      }
181718    }
181719    rc = sqlite3_finalize(p);
181720  }
181721
181722  if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
181723    rc = SQLITE_ERROR;
181724    if( pConfig->pzErrmsg ){
181725      assert( 0==*pConfig->pzErrmsg );
181726      *pConfig->pzErrmsg = sqlite3_mprintf(
181727          "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
181728          iVersion, FTS5_CURRENT_VERSION
181729      );
181730    }
181731  }
181732
181733  if( rc==SQLITE_OK ){
181734    pConfig->iCookie = iCookie;
181735  }
181736  return rc;
181737}
181738
181739/*
181740** 2014 May 31
181741**
181742** The author disclaims copyright to this source code.  In place of
181743** a legal notice, here is a blessing:
181744**
181745**    May you do good and not evil.
181746**    May you find forgiveness for yourself and forgive others.
181747**    May you share freely, never taking more than you give.
181748**
181749******************************************************************************
181750**
181751*/
181752
181753
181754
181755/* #include "fts5Int.h" */
181756/* #include "fts5parse.h" */
181757
181758/*
181759** All token types in the generated fts5parse.h file are greater than 0.
181760*/
181761#define FTS5_EOF 0
181762
181763#define FTS5_LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
181764
181765typedef struct Fts5ExprTerm Fts5ExprTerm;
181766
181767/*
181768** Functions generated by lemon from fts5parse.y.
181769*/
181770static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
181771static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
181772static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
181773#ifndef NDEBUG
181774/* #include <stdio.h> */
181775static void sqlite3Fts5ParserTrace(FILE*, char*);
181776#endif
181777
181778
181779struct Fts5Expr {
181780  Fts5Index *pIndex;
181781  Fts5Config *pConfig;
181782  Fts5ExprNode *pRoot;
181783  int bDesc;                      /* Iterate in descending rowid order */
181784  int nPhrase;                    /* Number of phrases in expression */
181785  Fts5ExprPhrase **apExprPhrase;  /* Pointers to phrase objects */
181786};
181787
181788/*
181789** eType:
181790**   Expression node type. Always one of:
181791**
181792**       FTS5_AND                 (nChild, apChild valid)
181793**       FTS5_OR                  (nChild, apChild valid)
181794**       FTS5_NOT                 (nChild, apChild valid)
181795**       FTS5_STRING              (pNear valid)
181796**       FTS5_TERM                (pNear valid)
181797*/
181798struct Fts5ExprNode {
181799  int eType;                      /* Node type */
181800  int bEof;                       /* True at EOF */
181801  int bNomatch;                   /* True if entry is not a match */
181802
181803  /* Next method for this node. */
181804  int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
181805
181806  i64 iRowid;                     /* Current rowid */
181807  Fts5ExprNearset *pNear;         /* For FTS5_STRING - cluster of phrases */
181808
181809  /* Child nodes. For a NOT node, this array always contains 2 entries. For
181810  ** AND or OR nodes, it contains 2 or more entries.  */
181811  int nChild;                     /* Number of child nodes */
181812  Fts5ExprNode *apChild[1];       /* Array of child nodes */
181813};
181814
181815#define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
181816
181817/*
181818** Invoke the xNext method of an Fts5ExprNode object. This macro should be
181819** used as if it has the same signature as the xNext() methods themselves.
181820*/
181821#define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
181822
181823/*
181824** An instance of the following structure represents a single search term
181825** or term prefix.
181826*/
181827struct Fts5ExprTerm {
181828  int bPrefix;                    /* True for a prefix term */
181829  char *zTerm;                    /* nul-terminated term */
181830  Fts5IndexIter *pIter;           /* Iterator for this term */
181831  Fts5ExprTerm *pSynonym;         /* Pointer to first in list of synonyms */
181832};
181833
181834/*
181835** A phrase. One or more terms that must appear in a contiguous sequence
181836** within a document for it to match.
181837*/
181838struct Fts5ExprPhrase {
181839  Fts5ExprNode *pNode;            /* FTS5_STRING node this phrase is part of */
181840  Fts5Buffer poslist;             /* Current position list */
181841  int nTerm;                      /* Number of entries in aTerm[] */
181842  Fts5ExprTerm aTerm[1];          /* Terms that make up this phrase */
181843};
181844
181845/*
181846** One or more phrases that must appear within a certain token distance of
181847** each other within each matching document.
181848*/
181849struct Fts5ExprNearset {
181850  int nNear;                      /* NEAR parameter */
181851  Fts5Colset *pColset;            /* Columns to search (NULL -> all columns) */
181852  int nPhrase;                    /* Number of entries in aPhrase[] array */
181853  Fts5ExprPhrase *apPhrase[1];    /* Array of phrase pointers */
181854};
181855
181856
181857/*
181858** Parse context.
181859*/
181860struct Fts5Parse {
181861  Fts5Config *pConfig;
181862  char *zErr;
181863  int rc;
181864  int nPhrase;                    /* Size of apPhrase array */
181865  Fts5ExprPhrase **apPhrase;      /* Array of all phrases */
181866  Fts5ExprNode *pExpr;            /* Result of a successful parse */
181867};
181868
181869static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
181870  va_list ap;
181871  va_start(ap, zFmt);
181872  if( pParse->rc==SQLITE_OK ){
181873    pParse->zErr = sqlite3_vmprintf(zFmt, ap);
181874    pParse->rc = SQLITE_ERROR;
181875  }
181876  va_end(ap);
181877}
181878
181879static int fts5ExprIsspace(char t){
181880  return t==' ' || t=='\t' || t=='\n' || t=='\r';
181881}
181882
181883/*
181884** Read the first token from the nul-terminated string at *pz.
181885*/
181886static int fts5ExprGetToken(
181887  Fts5Parse *pParse,
181888  const char **pz,                /* IN/OUT: Pointer into buffer */
181889  Fts5Token *pToken
181890){
181891  const char *z = *pz;
181892  int tok;
181893
181894  /* Skip past any whitespace */
181895  while( fts5ExprIsspace(*z) ) z++;
181896
181897  pToken->p = z;
181898  pToken->n = 1;
181899  switch( *z ){
181900    case '(':  tok = FTS5_LP;    break;
181901    case ')':  tok = FTS5_RP;    break;
181902    case '{':  tok = FTS5_LCP;   break;
181903    case '}':  tok = FTS5_RCP;   break;
181904    case ':':  tok = FTS5_COLON; break;
181905    case ',':  tok = FTS5_COMMA; break;
181906    case '+':  tok = FTS5_PLUS;  break;
181907    case '*':  tok = FTS5_STAR;  break;
181908    case '\0': tok = FTS5_EOF;   break;
181909
181910    case '"': {
181911      const char *z2;
181912      tok = FTS5_STRING;
181913
181914      for(z2=&z[1]; 1; z2++){
181915        if( z2[0]=='"' ){
181916          z2++;
181917          if( z2[0]!='"' ) break;
181918        }
181919        if( z2[0]=='\0' ){
181920          sqlite3Fts5ParseError(pParse, "unterminated string");
181921          return FTS5_EOF;
181922        }
181923      }
181924      pToken->n = (z2 - z);
181925      break;
181926    }
181927
181928    default: {
181929      const char *z2;
181930      if( sqlite3Fts5IsBareword(z[0])==0 ){
181931        sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
181932        return FTS5_EOF;
181933      }
181934      tok = FTS5_STRING;
181935      for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
181936      pToken->n = (z2 - z);
181937      if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 )  tok = FTS5_OR;
181938      if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
181939      if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
181940      break;
181941    }
181942  }
181943
181944  *pz = &pToken->p[pToken->n];
181945  return tok;
181946}
181947
181948static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
181949static void fts5ParseFree(void *p){ sqlite3_free(p); }
181950
181951static int sqlite3Fts5ExprNew(
181952  Fts5Config *pConfig,            /* FTS5 Configuration */
181953  const char *zExpr,              /* Expression text */
181954  Fts5Expr **ppNew,
181955  char **pzErr
181956){
181957  Fts5Parse sParse;
181958  Fts5Token token;
181959  const char *z = zExpr;
181960  int t;                          /* Next token type */
181961  void *pEngine;
181962  Fts5Expr *pNew;
181963
181964  *ppNew = 0;
181965  *pzErr = 0;
181966  memset(&sParse, 0, sizeof(sParse));
181967  pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
181968  if( pEngine==0 ){ return SQLITE_NOMEM; }
181969  sParse.pConfig = pConfig;
181970
181971  do {
181972    t = fts5ExprGetToken(&sParse, &z, &token);
181973    sqlite3Fts5Parser(pEngine, t, token, &sParse);
181974  }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
181975  sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
181976
181977  assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
181978  if( sParse.rc==SQLITE_OK ){
181979    *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
181980    if( pNew==0 ){
181981      sParse.rc = SQLITE_NOMEM;
181982      sqlite3Fts5ParseNodeFree(sParse.pExpr);
181983    }else{
181984      if( !sParse.pExpr ){
181985        const int nByte = sizeof(Fts5ExprNode);
181986        pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
181987        if( pNew->pRoot ){
181988          pNew->pRoot->bEof = 1;
181989        }
181990      }else{
181991        pNew->pRoot = sParse.pExpr;
181992      }
181993      pNew->pIndex = 0;
181994      pNew->pConfig = pConfig;
181995      pNew->apExprPhrase = sParse.apPhrase;
181996      pNew->nPhrase = sParse.nPhrase;
181997      sParse.apPhrase = 0;
181998    }
181999  }else{
182000    sqlite3Fts5ParseNodeFree(sParse.pExpr);
182001  }
182002
182003  sqlite3_free(sParse.apPhrase);
182004  *pzErr = sParse.zErr;
182005  return sParse.rc;
182006}
182007
182008/*
182009** Free the expression node object passed as the only argument.
182010*/
182011static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
182012  if( p ){
182013    int i;
182014    for(i=0; i<p->nChild; i++){
182015      sqlite3Fts5ParseNodeFree(p->apChild[i]);
182016    }
182017    sqlite3Fts5ParseNearsetFree(p->pNear);
182018    sqlite3_free(p);
182019  }
182020}
182021
182022/*
182023** Free the expression object passed as the only argument.
182024*/
182025static void sqlite3Fts5ExprFree(Fts5Expr *p){
182026  if( p ){
182027    sqlite3Fts5ParseNodeFree(p->pRoot);
182028    sqlite3_free(p->apExprPhrase);
182029    sqlite3_free(p);
182030  }
182031}
182032
182033/*
182034** Argument pTerm must be a synonym iterator. Return the current rowid
182035** that it points to.
182036*/
182037static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
182038  i64 iRet = 0;
182039  int bRetValid = 0;
182040  Fts5ExprTerm *p;
182041
182042  assert( pTerm->pSynonym );
182043  assert( bDesc==0 || bDesc==1 );
182044  for(p=pTerm; p; p=p->pSynonym){
182045    if( 0==sqlite3Fts5IterEof(p->pIter) ){
182046      i64 iRowid = p->pIter->iRowid;
182047      if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
182048        iRet = iRowid;
182049        bRetValid = 1;
182050      }
182051    }
182052  }
182053
182054  if( pbEof && bRetValid==0 ) *pbEof = 1;
182055  return iRet;
182056}
182057
182058/*
182059** Argument pTerm must be a synonym iterator.
182060*/
182061static int fts5ExprSynonymList(
182062  Fts5ExprTerm *pTerm,
182063  i64 iRowid,
182064  Fts5Buffer *pBuf,               /* Use this buffer for space if required */
182065  u8 **pa, int *pn
182066){
182067  Fts5PoslistReader aStatic[4];
182068  Fts5PoslistReader *aIter = aStatic;
182069  int nIter = 0;
182070  int nAlloc = 4;
182071  int rc = SQLITE_OK;
182072  Fts5ExprTerm *p;
182073
182074  assert( pTerm->pSynonym );
182075  for(p=pTerm; p; p=p->pSynonym){
182076    Fts5IndexIter *pIter = p->pIter;
182077    if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
182078      if( pIter->nData==0 ) continue;
182079      if( nIter==nAlloc ){
182080        int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
182081        Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
182082        if( aNew==0 ){
182083          rc = SQLITE_NOMEM;
182084          goto synonym_poslist_out;
182085        }
182086        memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
182087        nAlloc = nAlloc*2;
182088        if( aIter!=aStatic ) sqlite3_free(aIter);
182089        aIter = aNew;
182090      }
182091      sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
182092      assert( aIter[nIter].bEof==0 );
182093      nIter++;
182094    }
182095  }
182096
182097  if( nIter==1 ){
182098    *pa = (u8*)aIter[0].a;
182099    *pn = aIter[0].n;
182100  }else{
182101    Fts5PoslistWriter writer = {0};
182102    i64 iPrev = -1;
182103    fts5BufferZero(pBuf);
182104    while( 1 ){
182105      int i;
182106      i64 iMin = FTS5_LARGEST_INT64;
182107      for(i=0; i<nIter; i++){
182108        if( aIter[i].bEof==0 ){
182109          if( aIter[i].iPos==iPrev ){
182110            if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
182111          }
182112          if( aIter[i].iPos<iMin ){
182113            iMin = aIter[i].iPos;
182114          }
182115        }
182116      }
182117      if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
182118      rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
182119      iPrev = iMin;
182120    }
182121    if( rc==SQLITE_OK ){
182122      *pa = pBuf->p;
182123      *pn = pBuf->n;
182124    }
182125  }
182126
182127 synonym_poslist_out:
182128  if( aIter!=aStatic ) sqlite3_free(aIter);
182129  return rc;
182130}
182131
182132
182133/*
182134** All individual term iterators in pPhrase are guaranteed to be valid and
182135** pointing to the same rowid when this function is called. This function
182136** checks if the current rowid really is a match, and if so populates
182137** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
182138** is set to true if this is really a match, or false otherwise.
182139**
182140** SQLITE_OK is returned if an error occurs, or an SQLite error code
182141** otherwise. It is not considered an error code if the current rowid is
182142** not a match.
182143*/
182144static int fts5ExprPhraseIsMatch(
182145  Fts5ExprNode *pNode,            /* Node pPhrase belongs to */
182146  Fts5ExprPhrase *pPhrase,        /* Phrase object to initialize */
182147  int *pbMatch                    /* OUT: Set to true if really a match */
182148){
182149  Fts5PoslistWriter writer = {0};
182150  Fts5PoslistReader aStatic[4];
182151  Fts5PoslistReader *aIter = aStatic;
182152  int i;
182153  int rc = SQLITE_OK;
182154
182155  fts5BufferZero(&pPhrase->poslist);
182156
182157  /* If the aStatic[] array is not large enough, allocate a large array
182158  ** using sqlite3_malloc(). This approach could be improved upon. */
182159  if( pPhrase->nTerm>ArraySize(aStatic) ){
182160    int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
182161    aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
182162    if( !aIter ) return SQLITE_NOMEM;
182163  }
182164  memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
182165
182166  /* Initialize a term iterator for each term in the phrase */
182167  for(i=0; i<pPhrase->nTerm; i++){
182168    Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
182169    int n = 0;
182170    int bFlag = 0;
182171    u8 *a = 0;
182172    if( pTerm->pSynonym ){
182173      Fts5Buffer buf = {0, 0, 0};
182174      rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
182175      if( rc ){
182176        sqlite3_free(a);
182177        goto ismatch_out;
182178      }
182179      if( a==buf.p ) bFlag = 1;
182180    }else{
182181      a = (u8*)pTerm->pIter->pData;
182182      n = pTerm->pIter->nData;
182183    }
182184    sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
182185    aIter[i].bFlag = (u8)bFlag;
182186    if( aIter[i].bEof ) goto ismatch_out;
182187  }
182188
182189  while( 1 ){
182190    int bMatch;
182191    i64 iPos = aIter[0].iPos;
182192    do {
182193      bMatch = 1;
182194      for(i=0; i<pPhrase->nTerm; i++){
182195        Fts5PoslistReader *pPos = &aIter[i];
182196        i64 iAdj = iPos + i;
182197        if( pPos->iPos!=iAdj ){
182198          bMatch = 0;
182199          while( pPos->iPos<iAdj ){
182200            if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
182201          }
182202          if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
182203        }
182204      }
182205    }while( bMatch==0 );
182206
182207    /* Append position iPos to the output */
182208    rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
182209    if( rc!=SQLITE_OK ) goto ismatch_out;
182210
182211    for(i=0; i<pPhrase->nTerm; i++){
182212      if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
182213    }
182214  }
182215
182216 ismatch_out:
182217  *pbMatch = (pPhrase->poslist.n>0);
182218  for(i=0; i<pPhrase->nTerm; i++){
182219    if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
182220  }
182221  if( aIter!=aStatic ) sqlite3_free(aIter);
182222  return rc;
182223}
182224
182225typedef struct Fts5LookaheadReader Fts5LookaheadReader;
182226struct Fts5LookaheadReader {
182227  const u8 *a;                    /* Buffer containing position list */
182228  int n;                          /* Size of buffer a[] in bytes */
182229  int i;                          /* Current offset in position list */
182230  i64 iPos;                       /* Current position */
182231  i64 iLookahead;                 /* Next position */
182232};
182233
182234#define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
182235
182236static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
182237  p->iPos = p->iLookahead;
182238  if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
182239    p->iLookahead = FTS5_LOOKAHEAD_EOF;
182240  }
182241  return (p->iPos==FTS5_LOOKAHEAD_EOF);
182242}
182243
182244static int fts5LookaheadReaderInit(
182245  const u8 *a, int n,             /* Buffer to read position list from */
182246  Fts5LookaheadReader *p          /* Iterator object to initialize */
182247){
182248  memset(p, 0, sizeof(Fts5LookaheadReader));
182249  p->a = a;
182250  p->n = n;
182251  fts5LookaheadReaderNext(p);
182252  return fts5LookaheadReaderNext(p);
182253}
182254
182255typedef struct Fts5NearTrimmer Fts5NearTrimmer;
182256struct Fts5NearTrimmer {
182257  Fts5LookaheadReader reader;     /* Input iterator */
182258  Fts5PoslistWriter writer;       /* Writer context */
182259  Fts5Buffer *pOut;               /* Output poslist */
182260};
182261
182262/*
182263** The near-set object passed as the first argument contains more than
182264** one phrase. All phrases currently point to the same row. The
182265** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
182266** tests if the current row contains instances of each phrase sufficiently
182267** close together to meet the NEAR constraint. Non-zero is returned if it
182268** does, or zero otherwise.
182269**
182270** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
182271** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
182272** occurs within this function (*pRc) is set accordingly before returning.
182273** The return value is undefined in both these cases.
182274**
182275** If no error occurs and non-zero (a match) is returned, the position-list
182276** of each phrase object is edited to contain only those entries that
182277** meet the constraint before returning.
182278*/
182279static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
182280  Fts5NearTrimmer aStatic[4];
182281  Fts5NearTrimmer *a = aStatic;
182282  Fts5ExprPhrase **apPhrase = pNear->apPhrase;
182283
182284  int i;
182285  int rc = *pRc;
182286  int bMatch;
182287
182288  assert( pNear->nPhrase>1 );
182289
182290  /* If the aStatic[] array is not large enough, allocate a large array
182291  ** using sqlite3_malloc(). This approach could be improved upon. */
182292  if( pNear->nPhrase>ArraySize(aStatic) ){
182293    int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
182294    a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
182295  }else{
182296    memset(aStatic, 0, sizeof(aStatic));
182297  }
182298  if( rc!=SQLITE_OK ){
182299    *pRc = rc;
182300    return 0;
182301  }
182302
182303  /* Initialize a lookahead iterator for each phrase. After passing the
182304  ** buffer and buffer size to the lookaside-reader init function, zero
182305  ** the phrase poslist buffer. The new poslist for the phrase (containing
182306  ** the same entries as the original with some entries removed on account
182307  ** of the NEAR constraint) is written over the original even as it is
182308  ** being read. This is safe as the entries for the new poslist are a
182309  ** subset of the old, so it is not possible for data yet to be read to
182310  ** be overwritten.  */
182311  for(i=0; i<pNear->nPhrase; i++){
182312    Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
182313    fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
182314    pPoslist->n = 0;
182315    a[i].pOut = pPoslist;
182316  }
182317
182318  while( 1 ){
182319    int iAdv;
182320    i64 iMin;
182321    i64 iMax;
182322
182323    /* This block advances the phrase iterators until they point to a set of
182324    ** entries that together comprise a match.  */
182325    iMax = a[0].reader.iPos;
182326    do {
182327      bMatch = 1;
182328      for(i=0; i<pNear->nPhrase; i++){
182329        Fts5LookaheadReader *pPos = &a[i].reader;
182330        iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
182331        if( pPos->iPos<iMin || pPos->iPos>iMax ){
182332          bMatch = 0;
182333          while( pPos->iPos<iMin ){
182334            if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
182335          }
182336          if( pPos->iPos>iMax ) iMax = pPos->iPos;
182337        }
182338      }
182339    }while( bMatch==0 );
182340
182341    /* Add an entry to each output position list */
182342    for(i=0; i<pNear->nPhrase; i++){
182343      i64 iPos = a[i].reader.iPos;
182344      Fts5PoslistWriter *pWriter = &a[i].writer;
182345      if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
182346        sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
182347      }
182348    }
182349
182350    iAdv = 0;
182351    iMin = a[0].reader.iLookahead;
182352    for(i=0; i<pNear->nPhrase; i++){
182353      if( a[i].reader.iLookahead < iMin ){
182354        iMin = a[i].reader.iLookahead;
182355        iAdv = i;
182356      }
182357    }
182358    if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
182359  }
182360
182361  ismatch_out: {
182362    int bRet = a[0].pOut->n>0;
182363    *pRc = rc;
182364    if( a!=aStatic ) sqlite3_free(a);
182365    return bRet;
182366  }
182367}
182368
182369/*
182370** Advance iterator pIter until it points to a value equal to or laster
182371** than the initial value of *piLast. If this means the iterator points
182372** to a value laster than *piLast, update *piLast to the new lastest value.
182373**
182374** If the iterator reaches EOF, set *pbEof to true before returning. If
182375** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
182376** are set, return a non-zero value. Otherwise, return zero.
182377*/
182378static int fts5ExprAdvanceto(
182379  Fts5IndexIter *pIter,           /* Iterator to advance */
182380  int bDesc,                      /* True if iterator is "rowid DESC" */
182381  i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
182382  int *pRc,                       /* OUT: Error code */
182383  int *pbEof                      /* OUT: Set to true if EOF */
182384){
182385  i64 iLast = *piLast;
182386  i64 iRowid;
182387
182388  iRowid = pIter->iRowid;
182389  if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
182390    int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
182391    if( rc || sqlite3Fts5IterEof(pIter) ){
182392      *pRc = rc;
182393      *pbEof = 1;
182394      return 1;
182395    }
182396    iRowid = pIter->iRowid;
182397    assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
182398  }
182399  *piLast = iRowid;
182400
182401  return 0;
182402}
182403
182404static int fts5ExprSynonymAdvanceto(
182405  Fts5ExprTerm *pTerm,            /* Term iterator to advance */
182406  int bDesc,                      /* True if iterator is "rowid DESC" */
182407  i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
182408  int *pRc                        /* OUT: Error code */
182409){
182410  int rc = SQLITE_OK;
182411  i64 iLast = *piLast;
182412  Fts5ExprTerm *p;
182413  int bEof = 0;
182414
182415  for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
182416    if( sqlite3Fts5IterEof(p->pIter)==0 ){
182417      i64 iRowid = p->pIter->iRowid;
182418      if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
182419        rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
182420      }
182421    }
182422  }
182423
182424  if( rc!=SQLITE_OK ){
182425    *pRc = rc;
182426    bEof = 1;
182427  }else{
182428    *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
182429  }
182430  return bEof;
182431}
182432
182433
182434static int fts5ExprNearTest(
182435  int *pRc,
182436  Fts5Expr *pExpr,                /* Expression that pNear is a part of */
182437  Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_STRING) */
182438){
182439  Fts5ExprNearset *pNear = pNode->pNear;
182440  int rc = *pRc;
182441
182442  if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
182443    Fts5ExprTerm *pTerm;
182444    Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
182445    pPhrase->poslist.n = 0;
182446    for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
182447      Fts5IndexIter *pIter = pTerm->pIter;
182448      if( sqlite3Fts5IterEof(pIter)==0 ){
182449        if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
182450          pPhrase->poslist.n = 1;
182451        }
182452      }
182453    }
182454    return pPhrase->poslist.n;
182455  }else{
182456    int i;
182457
182458    /* Check that each phrase in the nearset matches the current row.
182459    ** Populate the pPhrase->poslist buffers at the same time. If any
182460    ** phrase is not a match, break out of the loop early.  */
182461    for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
182462      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
182463      if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
182464        int bMatch = 0;
182465        rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
182466        if( bMatch==0 ) break;
182467      }else{
182468        Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
182469        fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
182470      }
182471    }
182472
182473    *pRc = rc;
182474    if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
182475      return 1;
182476    }
182477    return 0;
182478  }
182479}
182480
182481
182482/*
182483** Initialize all term iterators in the pNear object. If any term is found
182484** to match no documents at all, return immediately without initializing any
182485** further iterators.
182486*/
182487static int fts5ExprNearInitAll(
182488  Fts5Expr *pExpr,
182489  Fts5ExprNode *pNode
182490){
182491  Fts5ExprNearset *pNear = pNode->pNear;
182492  int i, j;
182493  int rc = SQLITE_OK;
182494
182495  assert( pNode->bNomatch==0 );
182496  for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
182497    Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
182498    for(j=0; j<pPhrase->nTerm; j++){
182499      Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
182500      Fts5ExprTerm *p;
182501      int bEof = 1;
182502
182503      for(p=pTerm; p && rc==SQLITE_OK; p=p->pSynonym){
182504        if( p->pIter ){
182505          sqlite3Fts5IterClose(p->pIter);
182506          p->pIter = 0;
182507        }
182508        rc = sqlite3Fts5IndexQuery(
182509            pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
182510            (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
182511            (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
182512            pNear->pColset,
182513            &p->pIter
182514        );
182515        assert( rc==SQLITE_OK || p->pIter==0 );
182516        if( p->pIter && 0==sqlite3Fts5IterEof(p->pIter) ){
182517          bEof = 0;
182518        }
182519      }
182520
182521      if( bEof ){
182522        pNode->bEof = 1;
182523        return rc;
182524      }
182525    }
182526  }
182527
182528  return rc;
182529}
182530
182531/*
182532** If pExpr is an ASC iterator, this function returns a value with the
182533** same sign as:
182534**
182535**   (iLhs - iRhs)
182536**
182537** Otherwise, if this is a DESC iterator, the opposite is returned:
182538**
182539**   (iRhs - iLhs)
182540*/
182541static int fts5RowidCmp(
182542  Fts5Expr *pExpr,
182543  i64 iLhs,
182544  i64 iRhs
182545){
182546  assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
182547  if( pExpr->bDesc==0 ){
182548    if( iLhs<iRhs ) return -1;
182549    return (iLhs > iRhs);
182550  }else{
182551    if( iLhs>iRhs ) return -1;
182552    return (iLhs < iRhs);
182553  }
182554}
182555
182556static void fts5ExprSetEof(Fts5ExprNode *pNode){
182557  int i;
182558  pNode->bEof = 1;
182559  pNode->bNomatch = 0;
182560  for(i=0; i<pNode->nChild; i++){
182561    fts5ExprSetEof(pNode->apChild[i]);
182562  }
182563}
182564
182565static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
182566  if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
182567    Fts5ExprNearset *pNear = pNode->pNear;
182568    int i;
182569    for(i=0; i<pNear->nPhrase; i++){
182570      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
182571      pPhrase->poslist.n = 0;
182572    }
182573  }else{
182574    int i;
182575    for(i=0; i<pNode->nChild; i++){
182576      fts5ExprNodeZeroPoslist(pNode->apChild[i]);
182577    }
182578  }
182579}
182580
182581
182582
182583/*
182584** Compare the values currently indicated by the two nodes as follows:
182585**
182586**    res = (*p1) - (*p2)
182587**
182588** Nodes that point to values that come later in the iteration order are
182589** considered to be larger. Nodes at EOF are the largest of all.
182590**
182591** This means that if the iteration order is ASC, then numerically larger
182592** rowids are considered larger. Or if it is the default DESC, numerically
182593** smaller rowids are larger.
182594*/
182595static int fts5NodeCompare(
182596  Fts5Expr *pExpr,
182597  Fts5ExprNode *p1,
182598  Fts5ExprNode *p2
182599){
182600  if( p2->bEof ) return -1;
182601  if( p1->bEof ) return +1;
182602  return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
182603}
182604
182605/*
182606** All individual term iterators in pNear are guaranteed to be valid when
182607** this function is called. This function checks if all term iterators
182608** point to the same rowid, and if not, advances them until they do.
182609** If an EOF is reached before this happens, *pbEof is set to true before
182610** returning.
182611**
182612** SQLITE_OK is returned if an error occurs, or an SQLite error code
182613** otherwise. It is not considered an error code if an iterator reaches
182614** EOF.
182615*/
182616static int fts5ExprNodeTest_STRING(
182617  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
182618  Fts5ExprNode *pNode
182619){
182620  Fts5ExprNearset *pNear = pNode->pNear;
182621  Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
182622  int rc = SQLITE_OK;
182623  i64 iLast;                      /* Lastest rowid any iterator points to */
182624  int i, j;                       /* Phrase and token index, respectively */
182625  int bMatch;                     /* True if all terms are at the same rowid */
182626  const int bDesc = pExpr->bDesc;
182627
182628  /* Check that this node should not be FTS5_TERM */
182629  assert( pNear->nPhrase>1
182630       || pNear->apPhrase[0]->nTerm>1
182631       || pNear->apPhrase[0]->aTerm[0].pSynonym
182632  );
182633
182634  /* Initialize iLast, the "lastest" rowid any iterator points to. If the
182635  ** iterator skips through rowids in the default ascending order, this means
182636  ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
182637  ** means the minimum rowid.  */
182638  if( pLeft->aTerm[0].pSynonym ){
182639    iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
182640  }else{
182641    iLast = pLeft->aTerm[0].pIter->iRowid;
182642  }
182643
182644  do {
182645    bMatch = 1;
182646    for(i=0; i<pNear->nPhrase; i++){
182647      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
182648      for(j=0; j<pPhrase->nTerm; j++){
182649        Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
182650        if( pTerm->pSynonym ){
182651          i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
182652          if( iRowid==iLast ) continue;
182653          bMatch = 0;
182654          if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
182655            pNode->bNomatch = 0;
182656            pNode->bEof = 1;
182657            return rc;
182658          }
182659        }else{
182660          Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
182661          if( pIter->iRowid==iLast ) continue;
182662          bMatch = 0;
182663          if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
182664            return rc;
182665          }
182666        }
182667      }
182668    }
182669  }while( bMatch==0 );
182670
182671  pNode->iRowid = iLast;
182672  pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
182673  assert( pNode->bEof==0 || pNode->bNomatch==0 );
182674
182675  return rc;
182676}
182677
182678/*
182679** Advance the first term iterator in the first phrase of pNear. Set output
182680** variable *pbEof to true if it reaches EOF or if an error occurs.
182681**
182682** Return SQLITE_OK if successful, or an SQLite error code if an error
182683** occurs.
182684*/
182685static int fts5ExprNodeNext_STRING(
182686  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
182687  Fts5ExprNode *pNode,            /* FTS5_STRING or FTS5_TERM node */
182688  int bFromValid,
182689  i64 iFrom
182690){
182691  Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
182692  int rc = SQLITE_OK;
182693
182694  pNode->bNomatch = 0;
182695  if( pTerm->pSynonym ){
182696    int bEof = 1;
182697    Fts5ExprTerm *p;
182698
182699    /* Find the firstest rowid any synonym points to. */
182700    i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
182701
182702    /* Advance each iterator that currently points to iRowid. Or, if iFrom
182703    ** is valid - each iterator that points to a rowid before iFrom.  */
182704    for(p=pTerm; p; p=p->pSynonym){
182705      if( sqlite3Fts5IterEof(p->pIter)==0 ){
182706        i64 ii = p->pIter->iRowid;
182707        if( ii==iRowid
182708         || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
182709        ){
182710          if( bFromValid ){
182711            rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
182712          }else{
182713            rc = sqlite3Fts5IterNext(p->pIter);
182714          }
182715          if( rc!=SQLITE_OK ) break;
182716          if( sqlite3Fts5IterEof(p->pIter)==0 ){
182717            bEof = 0;
182718          }
182719        }else{
182720          bEof = 0;
182721        }
182722      }
182723    }
182724
182725    /* Set the EOF flag if either all synonym iterators are at EOF or an
182726    ** error has occurred.  */
182727    pNode->bEof = (rc || bEof);
182728  }else{
182729    Fts5IndexIter *pIter = pTerm->pIter;
182730
182731    assert( Fts5NodeIsString(pNode) );
182732    if( bFromValid ){
182733      rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
182734    }else{
182735      rc = sqlite3Fts5IterNext(pIter);
182736    }
182737
182738    pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
182739  }
182740
182741  if( pNode->bEof==0 ){
182742    assert( rc==SQLITE_OK );
182743    rc = fts5ExprNodeTest_STRING(pExpr, pNode);
182744  }
182745
182746  return rc;
182747}
182748
182749
182750static int fts5ExprNodeTest_TERM(
182751  Fts5Expr *pExpr,                /* Expression that pNear is a part of */
182752  Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_TERM) */
182753){
182754  /* As this "NEAR" object is actually a single phrase that consists
182755  ** of a single term only, grab pointers into the poslist managed by the
182756  ** fts5_index.c iterator object. This is much faster than synthesizing
182757  ** a new poslist the way we have to for more complicated phrase or NEAR
182758  ** expressions.  */
182759  Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
182760  Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
182761
182762  assert( pNode->eType==FTS5_TERM );
182763  assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
182764  assert( pPhrase->aTerm[0].pSynonym==0 );
182765
182766  pPhrase->poslist.n = pIter->nData;
182767  if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
182768    pPhrase->poslist.p = (u8*)pIter->pData;
182769  }
182770  pNode->iRowid = pIter->iRowid;
182771  pNode->bNomatch = (pPhrase->poslist.n==0);
182772  return SQLITE_OK;
182773}
182774
182775/*
182776** xNext() method for a node of type FTS5_TERM.
182777*/
182778static int fts5ExprNodeNext_TERM(
182779  Fts5Expr *pExpr,
182780  Fts5ExprNode *pNode,
182781  int bFromValid,
182782  i64 iFrom
182783){
182784  int rc;
182785  Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
182786
182787  assert( pNode->bEof==0 );
182788  if( bFromValid ){
182789    rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
182790  }else{
182791    rc = sqlite3Fts5IterNext(pIter);
182792  }
182793  if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
182794    rc = fts5ExprNodeTest_TERM(pExpr, pNode);
182795  }else{
182796    pNode->bEof = 1;
182797    pNode->bNomatch = 0;
182798  }
182799  return rc;
182800}
182801
182802static void fts5ExprNodeTest_OR(
182803  Fts5Expr *pExpr,                /* Expression of which pNode is a part */
182804  Fts5ExprNode *pNode             /* Expression node to test */
182805){
182806  Fts5ExprNode *pNext = pNode->apChild[0];
182807  int i;
182808
182809  for(i=1; i<pNode->nChild; i++){
182810    Fts5ExprNode *pChild = pNode->apChild[i];
182811    int cmp = fts5NodeCompare(pExpr, pNext, pChild);
182812    if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
182813      pNext = pChild;
182814    }
182815  }
182816  pNode->iRowid = pNext->iRowid;
182817  pNode->bEof = pNext->bEof;
182818  pNode->bNomatch = pNext->bNomatch;
182819}
182820
182821static int fts5ExprNodeNext_OR(
182822  Fts5Expr *pExpr,
182823  Fts5ExprNode *pNode,
182824  int bFromValid,
182825  i64 iFrom
182826){
182827  int i;
182828  i64 iLast = pNode->iRowid;
182829
182830  for(i=0; i<pNode->nChild; i++){
182831    Fts5ExprNode *p1 = pNode->apChild[i];
182832    assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
182833    if( p1->bEof==0 ){
182834      if( (p1->iRowid==iLast)
182835       || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
182836      ){
182837        int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
182838        if( rc!=SQLITE_OK ) return rc;
182839      }
182840    }
182841  }
182842
182843  fts5ExprNodeTest_OR(pExpr, pNode);
182844  return SQLITE_OK;
182845}
182846
182847/*
182848** Argument pNode is an FTS5_AND node.
182849*/
182850static int fts5ExprNodeTest_AND(
182851  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
182852  Fts5ExprNode *pAnd              /* FTS5_AND node to advance */
182853){
182854  int iChild;
182855  i64 iLast = pAnd->iRowid;
182856  int rc = SQLITE_OK;
182857  int bMatch;
182858
182859  assert( pAnd->bEof==0 );
182860  do {
182861    pAnd->bNomatch = 0;
182862    bMatch = 1;
182863    for(iChild=0; iChild<pAnd->nChild; iChild++){
182864      Fts5ExprNode *pChild = pAnd->apChild[iChild];
182865      int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
182866      if( cmp>0 ){
182867        /* Advance pChild until it points to iLast or laster */
182868        rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
182869        if( rc!=SQLITE_OK ) return rc;
182870      }
182871
182872      /* If the child node is now at EOF, so is the parent AND node. Otherwise,
182873      ** the child node is guaranteed to have advanced at least as far as
182874      ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
182875      ** new lastest rowid seen so far.  */
182876      assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
182877      if( pChild->bEof ){
182878        fts5ExprSetEof(pAnd);
182879        bMatch = 1;
182880        break;
182881      }else if( iLast!=pChild->iRowid ){
182882        bMatch = 0;
182883        iLast = pChild->iRowid;
182884      }
182885
182886      if( pChild->bNomatch ){
182887        pAnd->bNomatch = 1;
182888      }
182889    }
182890  }while( bMatch==0 );
182891
182892  if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
182893    fts5ExprNodeZeroPoslist(pAnd);
182894  }
182895  pAnd->iRowid = iLast;
182896  return SQLITE_OK;
182897}
182898
182899static int fts5ExprNodeNext_AND(
182900  Fts5Expr *pExpr,
182901  Fts5ExprNode *pNode,
182902  int bFromValid,
182903  i64 iFrom
182904){
182905  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
182906  if( rc==SQLITE_OK ){
182907    rc = fts5ExprNodeTest_AND(pExpr, pNode);
182908  }
182909  return rc;
182910}
182911
182912static int fts5ExprNodeTest_NOT(
182913  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
182914  Fts5ExprNode *pNode             /* FTS5_NOT node to advance */
182915){
182916  int rc = SQLITE_OK;
182917  Fts5ExprNode *p1 = pNode->apChild[0];
182918  Fts5ExprNode *p2 = pNode->apChild[1];
182919  assert( pNode->nChild==2 );
182920
182921  while( rc==SQLITE_OK && p1->bEof==0 ){
182922    int cmp = fts5NodeCompare(pExpr, p1, p2);
182923    if( cmp>0 ){
182924      rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
182925      cmp = fts5NodeCompare(pExpr, p1, p2);
182926    }
182927    assert( rc!=SQLITE_OK || cmp<=0 );
182928    if( cmp || p2->bNomatch ) break;
182929    rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
182930  }
182931  pNode->bEof = p1->bEof;
182932  pNode->bNomatch = p1->bNomatch;
182933  pNode->iRowid = p1->iRowid;
182934  if( p1->bEof ){
182935    fts5ExprNodeZeroPoslist(p2);
182936  }
182937  return rc;
182938}
182939
182940static int fts5ExprNodeNext_NOT(
182941  Fts5Expr *pExpr,
182942  Fts5ExprNode *pNode,
182943  int bFromValid,
182944  i64 iFrom
182945){
182946  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
182947  if( rc==SQLITE_OK ){
182948    rc = fts5ExprNodeTest_NOT(pExpr, pNode);
182949  }
182950  return rc;
182951}
182952
182953/*
182954** If pNode currently points to a match, this function returns SQLITE_OK
182955** without modifying it. Otherwise, pNode is advanced until it does point
182956** to a match or EOF is reached.
182957*/
182958static int fts5ExprNodeTest(
182959  Fts5Expr *pExpr,                /* Expression of which pNode is a part */
182960  Fts5ExprNode *pNode             /* Expression node to test */
182961){
182962  int rc = SQLITE_OK;
182963  if( pNode->bEof==0 ){
182964    switch( pNode->eType ){
182965
182966      case FTS5_STRING: {
182967        rc = fts5ExprNodeTest_STRING(pExpr, pNode);
182968        break;
182969      }
182970
182971      case FTS5_TERM: {
182972        rc = fts5ExprNodeTest_TERM(pExpr, pNode);
182973        break;
182974      }
182975
182976      case FTS5_AND: {
182977        rc = fts5ExprNodeTest_AND(pExpr, pNode);
182978        break;
182979      }
182980
182981      case FTS5_OR: {
182982        fts5ExprNodeTest_OR(pExpr, pNode);
182983        break;
182984      }
182985
182986      default: assert( pNode->eType==FTS5_NOT ); {
182987        rc = fts5ExprNodeTest_NOT(pExpr, pNode);
182988        break;
182989      }
182990    }
182991  }
182992  return rc;
182993}
182994
182995
182996/*
182997** Set node pNode, which is part of expression pExpr, to point to the first
182998** match. If there are no matches, set the Node.bEof flag to indicate EOF.
182999**
183000** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
183001** It is not an error if there are no matches.
183002*/
183003static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
183004  int rc = SQLITE_OK;
183005  pNode->bEof = 0;
183006  pNode->bNomatch = 0;
183007
183008  if( Fts5NodeIsString(pNode) ){
183009    /* Initialize all term iterators in the NEAR object. */
183010    rc = fts5ExprNearInitAll(pExpr, pNode);
183011  }else if( pNode->xNext==0 ){
183012    pNode->bEof = 1;
183013  }else{
183014    int i;
183015    int nEof = 0;
183016    for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
183017      Fts5ExprNode *pChild = pNode->apChild[i];
183018      rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
183019      assert( pChild->bEof==0 || pChild->bEof==1 );
183020      nEof += pChild->bEof;
183021    }
183022    pNode->iRowid = pNode->apChild[0]->iRowid;
183023
183024    switch( pNode->eType ){
183025      case FTS5_AND:
183026        if( nEof>0 ) fts5ExprSetEof(pNode);
183027        break;
183028
183029      case FTS5_OR:
183030        if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
183031        break;
183032
183033      default:
183034        assert( pNode->eType==FTS5_NOT );
183035        pNode->bEof = pNode->apChild[0]->bEof;
183036        break;
183037    }
183038  }
183039
183040  if( rc==SQLITE_OK ){
183041    rc = fts5ExprNodeTest(pExpr, pNode);
183042  }
183043  return rc;
183044}
183045
183046
183047/*
183048** Begin iterating through the set of documents in index pIdx matched by
183049** the MATCH expression passed as the first argument. If the "bDesc"
183050** parameter is passed a non-zero value, iteration is in descending rowid
183051** order. Or, if it is zero, in ascending order.
183052**
183053** If iterating in ascending rowid order (bDesc==0), the first document
183054** visited is that with the smallest rowid that is larger than or equal
183055** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
183056** then the first document visited must have a rowid smaller than or
183057** equal to iFirst.
183058**
183059** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
183060** is not considered an error if the query does not match any documents.
183061*/
183062static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
183063  Fts5ExprNode *pRoot = p->pRoot;
183064  int rc;                         /* Return code */
183065
183066  p->pIndex = pIdx;
183067  p->bDesc = bDesc;
183068  rc = fts5ExprNodeFirst(p, pRoot);
183069
183070  /* If not at EOF but the current rowid occurs earlier than iFirst in
183071  ** the iteration order, move to document iFirst or later. */
183072  if( pRoot->bEof==0 && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 ){
183073    rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
183074  }
183075
183076  /* If the iterator is not at a real match, skip forward until it is. */
183077  while( pRoot->bNomatch ){
183078    assert( pRoot->bEof==0 && rc==SQLITE_OK );
183079    rc = fts5ExprNodeNext(p, pRoot, 0, 0);
183080  }
183081  return rc;
183082}
183083
183084/*
183085** Move to the next document
183086**
183087** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
183088** is not considered an error if the query does not match any documents.
183089*/
183090static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
183091  int rc;
183092  Fts5ExprNode *pRoot = p->pRoot;
183093  assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
183094  do {
183095    rc = fts5ExprNodeNext(p, pRoot, 0, 0);
183096    assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
183097  }while( pRoot->bNomatch );
183098  if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
183099    pRoot->bEof = 1;
183100  }
183101  return rc;
183102}
183103
183104static int sqlite3Fts5ExprEof(Fts5Expr *p){
183105  return p->pRoot->bEof;
183106}
183107
183108static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
183109  return p->pRoot->iRowid;
183110}
183111
183112static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
183113  int rc = SQLITE_OK;
183114  *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
183115  return rc;
183116}
183117
183118/*
183119** Free the phrase object passed as the only argument.
183120*/
183121static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
183122  if( pPhrase ){
183123    int i;
183124    for(i=0; i<pPhrase->nTerm; i++){
183125      Fts5ExprTerm *pSyn;
183126      Fts5ExprTerm *pNext;
183127      Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
183128      sqlite3_free(pTerm->zTerm);
183129      sqlite3Fts5IterClose(pTerm->pIter);
183130      for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
183131        pNext = pSyn->pSynonym;
183132        sqlite3Fts5IterClose(pSyn->pIter);
183133        fts5BufferFree((Fts5Buffer*)&pSyn[1]);
183134        sqlite3_free(pSyn);
183135      }
183136    }
183137    if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
183138    sqlite3_free(pPhrase);
183139  }
183140}
183141
183142/*
183143** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
183144** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
183145** appended to it and the results returned.
183146**
183147** If an OOM error occurs, both the pNear and pPhrase objects are freed and
183148** NULL returned.
183149*/
183150static Fts5ExprNearset *sqlite3Fts5ParseNearset(
183151  Fts5Parse *pParse,              /* Parse context */
183152  Fts5ExprNearset *pNear,         /* Existing nearset, or NULL */
183153  Fts5ExprPhrase *pPhrase         /* Recently parsed phrase */
183154){
183155  const int SZALLOC = 8;
183156  Fts5ExprNearset *pRet = 0;
183157
183158  if( pParse->rc==SQLITE_OK ){
183159    if( pPhrase==0 ){
183160      return pNear;
183161    }
183162    if( pNear==0 ){
183163      int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
183164      pRet = sqlite3_malloc(nByte);
183165      if( pRet==0 ){
183166        pParse->rc = SQLITE_NOMEM;
183167      }else{
183168        memset(pRet, 0, nByte);
183169      }
183170    }else if( (pNear->nPhrase % SZALLOC)==0 ){
183171      int nNew = pNear->nPhrase + SZALLOC;
183172      int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
183173
183174      pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
183175      if( pRet==0 ){
183176        pParse->rc = SQLITE_NOMEM;
183177      }
183178    }else{
183179      pRet = pNear;
183180    }
183181  }
183182
183183  if( pRet==0 ){
183184    assert( pParse->rc!=SQLITE_OK );
183185    sqlite3Fts5ParseNearsetFree(pNear);
183186    sqlite3Fts5ParsePhraseFree(pPhrase);
183187  }else{
183188    if( pRet->nPhrase>0 ){
183189      Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
183190      assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
183191      if( pPhrase->nTerm==0 ){
183192        fts5ExprPhraseFree(pPhrase);
183193        pRet->nPhrase--;
183194        pParse->nPhrase--;
183195        pPhrase = pLast;
183196      }else if( pLast->nTerm==0 ){
183197        fts5ExprPhraseFree(pLast);
183198        pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
183199        pParse->nPhrase--;
183200        pRet->nPhrase--;
183201      }
183202    }
183203    pRet->apPhrase[pRet->nPhrase++] = pPhrase;
183204  }
183205  return pRet;
183206}
183207
183208typedef struct TokenCtx TokenCtx;
183209struct TokenCtx {
183210  Fts5ExprPhrase *pPhrase;
183211  int rc;
183212};
183213
183214/*
183215** Callback for tokenizing terms used by ParseTerm().
183216*/
183217static int fts5ParseTokenize(
183218  void *pContext,                 /* Pointer to Fts5InsertCtx object */
183219  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
183220  const char *pToken,             /* Buffer containing token */
183221  int nToken,                     /* Size of token in bytes */
183222  int iUnused1,                   /* Start offset of token */
183223  int iUnused2                    /* End offset of token */
183224){
183225  int rc = SQLITE_OK;
183226  const int SZALLOC = 8;
183227  TokenCtx *pCtx = (TokenCtx*)pContext;
183228  Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
183229
183230  UNUSED_PARAM2(iUnused1, iUnused2);
183231
183232  /* If an error has already occurred, this is a no-op */
183233  if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
183234  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
183235
183236  if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
183237    Fts5ExprTerm *pSyn;
183238    int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
183239    pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
183240    if( pSyn==0 ){
183241      rc = SQLITE_NOMEM;
183242    }else{
183243      memset(pSyn, 0, nByte);
183244      pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
183245      memcpy(pSyn->zTerm, pToken, nToken);
183246      pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
183247      pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
183248    }
183249  }else{
183250    Fts5ExprTerm *pTerm;
183251    if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
183252      Fts5ExprPhrase *pNew;
183253      int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
183254
183255      pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
183256          sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
183257      );
183258      if( pNew==0 ){
183259        rc = SQLITE_NOMEM;
183260      }else{
183261        if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
183262        pCtx->pPhrase = pPhrase = pNew;
183263        pNew->nTerm = nNew - SZALLOC;
183264      }
183265    }
183266
183267    if( rc==SQLITE_OK ){
183268      pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
183269      memset(pTerm, 0, sizeof(Fts5ExprTerm));
183270      pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
183271    }
183272  }
183273
183274  pCtx->rc = rc;
183275  return rc;
183276}
183277
183278
183279/*
183280** Free the phrase object passed as the only argument.
183281*/
183282static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
183283  fts5ExprPhraseFree(pPhrase);
183284}
183285
183286/*
183287** Free the phrase object passed as the second argument.
183288*/
183289static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
183290  if( pNear ){
183291    int i;
183292    for(i=0; i<pNear->nPhrase; i++){
183293      fts5ExprPhraseFree(pNear->apPhrase[i]);
183294    }
183295    sqlite3_free(pNear->pColset);
183296    sqlite3_free(pNear);
183297  }
183298}
183299
183300static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
183301  assert( pParse->pExpr==0 );
183302  pParse->pExpr = p;
183303}
183304
183305/*
183306** This function is called by the parser to process a string token. The
183307** string may or may not be quoted. In any case it is tokenized and a
183308** phrase object consisting of all tokens returned.
183309*/
183310static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
183311  Fts5Parse *pParse,              /* Parse context */
183312  Fts5ExprPhrase *pAppend,        /* Phrase to append to */
183313  Fts5Token *pToken,              /* String to tokenize */
183314  int bPrefix                     /* True if there is a trailing "*" */
183315){
183316  Fts5Config *pConfig = pParse->pConfig;
183317  TokenCtx sCtx;                  /* Context object passed to callback */
183318  int rc;                         /* Tokenize return code */
183319  char *z = 0;
183320
183321  memset(&sCtx, 0, sizeof(TokenCtx));
183322  sCtx.pPhrase = pAppend;
183323
183324  rc = fts5ParseStringFromToken(pToken, &z);
183325  if( rc==SQLITE_OK ){
183326    int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_QUERY : 0);
183327    int n;
183328    sqlite3Fts5Dequote(z);
183329    n = (int)strlen(z);
183330    rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
183331  }
183332  sqlite3_free(z);
183333  if( rc || (rc = sCtx.rc) ){
183334    pParse->rc = rc;
183335    fts5ExprPhraseFree(sCtx.pPhrase);
183336    sCtx.pPhrase = 0;
183337  }else{
183338
183339    if( pAppend==0 ){
183340      if( (pParse->nPhrase % 8)==0 ){
183341        int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
183342        Fts5ExprPhrase **apNew;
183343        apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
183344        if( apNew==0 ){
183345          pParse->rc = SQLITE_NOMEM;
183346          fts5ExprPhraseFree(sCtx.pPhrase);
183347          return 0;
183348        }
183349        pParse->apPhrase = apNew;
183350      }
183351      pParse->nPhrase++;
183352    }
183353
183354    if( sCtx.pPhrase==0 ){
183355      /* This happens when parsing a token or quoted phrase that contains
183356      ** no token characters at all. (e.g ... MATCH '""'). */
183357      sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
183358    }else if( sCtx.pPhrase->nTerm ){
183359      sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
183360    }
183361    pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
183362  }
183363
183364  return sCtx.pPhrase;
183365}
183366
183367/*
183368** Create a new FTS5 expression by cloning phrase iPhrase of the
183369** expression passed as the second argument.
183370*/
183371static int sqlite3Fts5ExprClonePhrase(
183372  Fts5Expr *pExpr,
183373  int iPhrase,
183374  Fts5Expr **ppNew
183375){
183376  int rc = SQLITE_OK;             /* Return code */
183377  Fts5ExprPhrase *pOrig;          /* The phrase extracted from pExpr */
183378  int i;                          /* Used to iterate through phrase terms */
183379  Fts5Expr *pNew = 0;             /* Expression to return via *ppNew */
183380  TokenCtx sCtx = {0,0};          /* Context object for fts5ParseTokenize */
183381
183382  pOrig = pExpr->apExprPhrase[iPhrase];
183383  pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
183384  if( rc==SQLITE_OK ){
183385    pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
183386        sizeof(Fts5ExprPhrase*));
183387  }
183388  if( rc==SQLITE_OK ){
183389    pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
183390        sizeof(Fts5ExprNode));
183391  }
183392  if( rc==SQLITE_OK ){
183393    pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
183394        sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
183395  }
183396  if( rc==SQLITE_OK ){
183397    Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
183398    if( pColsetOrig ){
183399      int nByte = sizeof(Fts5Colset) + pColsetOrig->nCol * sizeof(int);
183400      Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
183401      if( pColset ){
183402        memcpy(pColset, pColsetOrig, nByte);
183403      }
183404      pNew->pRoot->pNear->pColset = pColset;
183405    }
183406  }
183407
183408  for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
183409    int tflags = 0;
183410    Fts5ExprTerm *p;
183411    for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
183412      const char *zTerm = p->zTerm;
183413      rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
183414          0, 0);
183415      tflags = FTS5_TOKEN_COLOCATED;
183416    }
183417    if( rc==SQLITE_OK ){
183418      sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
183419    }
183420  }
183421
183422  if( rc==SQLITE_OK ){
183423    /* All the allocations succeeded. Put the expression object together. */
183424    pNew->pIndex = pExpr->pIndex;
183425    pNew->pConfig = pExpr->pConfig;
183426    pNew->nPhrase = 1;
183427    pNew->apExprPhrase[0] = sCtx.pPhrase;
183428    pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
183429    pNew->pRoot->pNear->nPhrase = 1;
183430    sCtx.pPhrase->pNode = pNew->pRoot;
183431
183432    if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
183433      pNew->pRoot->eType = FTS5_TERM;
183434      pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
183435    }else{
183436      pNew->pRoot->eType = FTS5_STRING;
183437      pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
183438    }
183439  }else{
183440    sqlite3Fts5ExprFree(pNew);
183441    fts5ExprPhraseFree(sCtx.pPhrase);
183442    pNew = 0;
183443  }
183444
183445  *ppNew = pNew;
183446  return rc;
183447}
183448
183449
183450/*
183451** Token pTok has appeared in a MATCH expression where the NEAR operator
183452** is expected. If token pTok does not contain "NEAR", store an error
183453** in the pParse object.
183454*/
183455static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
183456  if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
183457    sqlite3Fts5ParseError(
183458        pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
183459    );
183460  }
183461}
183462
183463static void sqlite3Fts5ParseSetDistance(
183464  Fts5Parse *pParse,
183465  Fts5ExprNearset *pNear,
183466  Fts5Token *p
183467){
183468  if( pNear ){
183469    int nNear = 0;
183470    int i;
183471    if( p->n ){
183472      for(i=0; i<p->n; i++){
183473        char c = (char)p->p[i];
183474        if( c<'0' || c>'9' ){
183475          sqlite3Fts5ParseError(
183476              pParse, "expected integer, got \"%.*s\"", p->n, p->p
183477              );
183478          return;
183479        }
183480        nNear = nNear * 10 + (p->p[i] - '0');
183481      }
183482    }else{
183483      nNear = FTS5_DEFAULT_NEARDIST;
183484    }
183485    pNear->nNear = nNear;
183486  }
183487}
183488
183489/*
183490** The second argument passed to this function may be NULL, or it may be
183491** an existing Fts5Colset object. This function returns a pointer to
183492** a new colset object containing the contents of (p) with new value column
183493** number iCol appended.
183494**
183495** If an OOM error occurs, store an error code in pParse and return NULL.
183496** The old colset object (if any) is not freed in this case.
183497*/
183498static Fts5Colset *fts5ParseColset(
183499  Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
183500  Fts5Colset *p,                  /* Existing colset object */
183501  int iCol                        /* New column to add to colset object */
183502){
183503  int nCol = p ? p->nCol : 0;     /* Num. columns already in colset object */
183504  Fts5Colset *pNew;               /* New colset object to return */
183505
183506  assert( pParse->rc==SQLITE_OK );
183507  assert( iCol>=0 && iCol<pParse->pConfig->nCol );
183508
183509  pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
183510  if( pNew==0 ){
183511    pParse->rc = SQLITE_NOMEM;
183512  }else{
183513    int *aiCol = pNew->aiCol;
183514    int i, j;
183515    for(i=0; i<nCol; i++){
183516      if( aiCol[i]==iCol ) return pNew;
183517      if( aiCol[i]>iCol ) break;
183518    }
183519    for(j=nCol; j>i; j--){
183520      aiCol[j] = aiCol[j-1];
183521    }
183522    aiCol[i] = iCol;
183523    pNew->nCol = nCol+1;
183524
183525#ifndef NDEBUG
183526    /* Check that the array is in order and contains no duplicate entries. */
183527    for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
183528#endif
183529  }
183530
183531  return pNew;
183532}
183533
183534static Fts5Colset *sqlite3Fts5ParseColset(
183535  Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
183536  Fts5Colset *pColset,            /* Existing colset object */
183537  Fts5Token *p
183538){
183539  Fts5Colset *pRet = 0;
183540  int iCol;
183541  char *z;                        /* Dequoted copy of token p */
183542
183543  z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
183544  if( pParse->rc==SQLITE_OK ){
183545    Fts5Config *pConfig = pParse->pConfig;
183546    sqlite3Fts5Dequote(z);
183547    for(iCol=0; iCol<pConfig->nCol; iCol++){
183548      if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
183549    }
183550    if( iCol==pConfig->nCol ){
183551      sqlite3Fts5ParseError(pParse, "no such column: %s", z);
183552    }else{
183553      pRet = fts5ParseColset(pParse, pColset, iCol);
183554    }
183555    sqlite3_free(z);
183556  }
183557
183558  if( pRet==0 ){
183559    assert( pParse->rc!=SQLITE_OK );
183560    sqlite3_free(pColset);
183561  }
183562
183563  return pRet;
183564}
183565
183566static void sqlite3Fts5ParseSetColset(
183567  Fts5Parse *pParse,
183568  Fts5ExprNearset *pNear,
183569  Fts5Colset *pColset
183570){
183571  if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
183572    pParse->rc = SQLITE_ERROR;
183573    pParse->zErr = sqlite3_mprintf(
183574      "fts5: column queries are not supported (detail=none)"
183575    );
183576    sqlite3_free(pColset);
183577    return;
183578  }
183579
183580  if( pNear ){
183581    pNear->pColset = pColset;
183582  }else{
183583    sqlite3_free(pColset);
183584  }
183585}
183586
183587static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
183588  switch( pNode->eType ){
183589    case FTS5_STRING: {
183590      Fts5ExprNearset *pNear = pNode->pNear;
183591      if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
183592       && pNear->apPhrase[0]->aTerm[0].pSynonym==0
183593      ){
183594        pNode->eType = FTS5_TERM;
183595        pNode->xNext = fts5ExprNodeNext_TERM;
183596      }else{
183597        pNode->xNext = fts5ExprNodeNext_STRING;
183598      }
183599      break;
183600    };
183601
183602    case FTS5_OR: {
183603      pNode->xNext = fts5ExprNodeNext_OR;
183604      break;
183605    };
183606
183607    case FTS5_AND: {
183608      pNode->xNext = fts5ExprNodeNext_AND;
183609      break;
183610    };
183611
183612    default: assert( pNode->eType==FTS5_NOT ); {
183613      pNode->xNext = fts5ExprNodeNext_NOT;
183614      break;
183615    };
183616  }
183617}
183618
183619static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
183620  if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
183621    int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
183622    memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
183623    p->nChild += pSub->nChild;
183624    sqlite3_free(pSub);
183625  }else{
183626    p->apChild[p->nChild++] = pSub;
183627  }
183628}
183629
183630/*
183631** Allocate and return a new expression object. If anything goes wrong (i.e.
183632** OOM error), leave an error code in pParse and return NULL.
183633*/
183634static Fts5ExprNode *sqlite3Fts5ParseNode(
183635  Fts5Parse *pParse,              /* Parse context */
183636  int eType,                      /* FTS5_STRING, AND, OR or NOT */
183637  Fts5ExprNode *pLeft,            /* Left hand child expression */
183638  Fts5ExprNode *pRight,           /* Right hand child expression */
183639  Fts5ExprNearset *pNear          /* For STRING expressions, the near cluster */
183640){
183641  Fts5ExprNode *pRet = 0;
183642
183643  if( pParse->rc==SQLITE_OK ){
183644    int nChild = 0;               /* Number of children of returned node */
183645    int nByte;                    /* Bytes of space to allocate for this node */
183646
183647    assert( (eType!=FTS5_STRING && !pNear)
183648         || (eType==FTS5_STRING && !pLeft && !pRight)
183649    );
183650    if( eType==FTS5_STRING && pNear==0 ) return 0;
183651    if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
183652    if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
183653
183654    if( eType==FTS5_NOT ){
183655      nChild = 2;
183656    }else if( eType==FTS5_AND || eType==FTS5_OR ){
183657      nChild = 2;
183658      if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
183659      if( pRight->eType==eType ) nChild += pRight->nChild-1;
183660    }
183661
183662    nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
183663    pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
183664
183665    if( pRet ){
183666      pRet->eType = eType;
183667      pRet->pNear = pNear;
183668      fts5ExprAssignXNext(pRet);
183669      if( eType==FTS5_STRING ){
183670        int iPhrase;
183671        for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
183672          pNear->apPhrase[iPhrase]->pNode = pRet;
183673          if( pNear->apPhrase[iPhrase]->nTerm==0 ){
183674            pRet->xNext = 0;
183675            pRet->eType = FTS5_EOF;
183676          }
183677        }
183678
183679        if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL
183680         && (pNear->nPhrase!=1 || pNear->apPhrase[0]->nTerm>1)
183681        ){
183682          assert( pParse->rc==SQLITE_OK );
183683          pParse->rc = SQLITE_ERROR;
183684          assert( pParse->zErr==0 );
183685          pParse->zErr = sqlite3_mprintf(
183686              "fts5: %s queries are not supported (detail!=full)",
183687              pNear->nPhrase==1 ? "phrase": "NEAR"
183688          );
183689          sqlite3_free(pRet);
183690          pRet = 0;
183691        }
183692
183693      }else{
183694        fts5ExprAddChildren(pRet, pLeft);
183695        fts5ExprAddChildren(pRet, pRight);
183696      }
183697    }
183698  }
183699
183700  if( pRet==0 ){
183701    assert( pParse->rc!=SQLITE_OK );
183702    sqlite3Fts5ParseNodeFree(pLeft);
183703    sqlite3Fts5ParseNodeFree(pRight);
183704    sqlite3Fts5ParseNearsetFree(pNear);
183705  }
183706  return pRet;
183707}
183708
183709static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
183710  Fts5Parse *pParse,              /* Parse context */
183711  Fts5ExprNode *pLeft,            /* Left hand child expression */
183712  Fts5ExprNode *pRight            /* Right hand child expression */
183713){
183714  Fts5ExprNode *pRet = 0;
183715  Fts5ExprNode *pPrev;
183716
183717  if( pParse->rc ){
183718    sqlite3Fts5ParseNodeFree(pLeft);
183719    sqlite3Fts5ParseNodeFree(pRight);
183720  }else{
183721
183722    assert( pLeft->eType==FTS5_STRING
183723        || pLeft->eType==FTS5_TERM
183724        || pLeft->eType==FTS5_EOF
183725        || pLeft->eType==FTS5_AND
183726    );
183727    assert( pRight->eType==FTS5_STRING
183728        || pRight->eType==FTS5_TERM
183729        || pRight->eType==FTS5_EOF
183730    );
183731
183732    if( pLeft->eType==FTS5_AND ){
183733      pPrev = pLeft->apChild[pLeft->nChild-1];
183734    }else{
183735      pPrev = pLeft;
183736    }
183737    assert( pPrev->eType==FTS5_STRING
183738        || pPrev->eType==FTS5_TERM
183739        || pPrev->eType==FTS5_EOF
183740        );
183741
183742    if( pRight->eType==FTS5_EOF ){
183743      assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
183744      sqlite3Fts5ParseNodeFree(pRight);
183745      pRet = pLeft;
183746      pParse->nPhrase--;
183747    }
183748    else if( pPrev->eType==FTS5_EOF ){
183749      Fts5ExprPhrase **ap;
183750
183751      if( pPrev==pLeft ){
183752        pRet = pRight;
183753      }else{
183754        pLeft->apChild[pLeft->nChild-1] = pRight;
183755        pRet = pLeft;
183756      }
183757
183758      ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
183759      assert( ap[0]==pPrev->pNear->apPhrase[0] );
183760      memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
183761      pParse->nPhrase--;
183762
183763      sqlite3Fts5ParseNodeFree(pPrev);
183764    }
183765    else{
183766      pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
183767    }
183768  }
183769
183770  return pRet;
183771}
183772
183773static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
183774  int nByte = 0;
183775  Fts5ExprTerm *p;
183776  char *zQuoted;
183777
183778  /* Determine the maximum amount of space required. */
183779  for(p=pTerm; p; p=p->pSynonym){
183780    nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
183781  }
183782  zQuoted = sqlite3_malloc(nByte);
183783
183784  if( zQuoted ){
183785    int i = 0;
183786    for(p=pTerm; p; p=p->pSynonym){
183787      char *zIn = p->zTerm;
183788      zQuoted[i++] = '"';
183789      while( *zIn ){
183790        if( *zIn=='"' ) zQuoted[i++] = '"';
183791        zQuoted[i++] = *zIn++;
183792      }
183793      zQuoted[i++] = '"';
183794      if( p->pSynonym ) zQuoted[i++] = '|';
183795    }
183796    if( pTerm->bPrefix ){
183797      zQuoted[i++] = ' ';
183798      zQuoted[i++] = '*';
183799    }
183800    zQuoted[i++] = '\0';
183801  }
183802  return zQuoted;
183803}
183804
183805static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
183806  char *zNew;
183807  va_list ap;
183808  va_start(ap, zFmt);
183809  zNew = sqlite3_vmprintf(zFmt, ap);
183810  va_end(ap);
183811  if( zApp && zNew ){
183812    char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
183813    sqlite3_free(zNew);
183814    zNew = zNew2;
183815  }
183816  sqlite3_free(zApp);
183817  return zNew;
183818}
183819
183820/*
183821** Compose a tcl-readable representation of expression pExpr. Return a
183822** pointer to a buffer containing that representation. It is the
183823** responsibility of the caller to at some point free the buffer using
183824** sqlite3_free().
183825*/
183826static char *fts5ExprPrintTcl(
183827  Fts5Config *pConfig,
183828  const char *zNearsetCmd,
183829  Fts5ExprNode *pExpr
183830){
183831  char *zRet = 0;
183832  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
183833    Fts5ExprNearset *pNear = pExpr->pNear;
183834    int i;
183835    int iTerm;
183836
183837    zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
183838    if( zRet==0 ) return 0;
183839    if( pNear->pColset ){
183840      int *aiCol = pNear->pColset->aiCol;
183841      int nCol = pNear->pColset->nCol;
183842      if( nCol==1 ){
183843        zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
183844      }else{
183845        zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
183846        for(i=1; i<pNear->pColset->nCol; i++){
183847          zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
183848        }
183849        zRet = fts5PrintfAppend(zRet, "} ");
183850      }
183851      if( zRet==0 ) return 0;
183852    }
183853
183854    if( pNear->nPhrase>1 ){
183855      zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
183856      if( zRet==0 ) return 0;
183857    }
183858
183859    zRet = fts5PrintfAppend(zRet, "--");
183860    if( zRet==0 ) return 0;
183861
183862    for(i=0; i<pNear->nPhrase; i++){
183863      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
183864
183865      zRet = fts5PrintfAppend(zRet, " {");
183866      for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
183867        char *zTerm = pPhrase->aTerm[iTerm].zTerm;
183868        zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
183869        if( pPhrase->aTerm[iTerm].bPrefix ){
183870          zRet = fts5PrintfAppend(zRet, "*");
183871        }
183872      }
183873
183874      if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
183875      if( zRet==0 ) return 0;
183876    }
183877
183878  }else{
183879    char const *zOp = 0;
183880    int i;
183881    switch( pExpr->eType ){
183882      case FTS5_AND: zOp = "AND"; break;
183883      case FTS5_NOT: zOp = "NOT"; break;
183884      default:
183885        assert( pExpr->eType==FTS5_OR );
183886        zOp = "OR";
183887        break;
183888    }
183889
183890    zRet = sqlite3_mprintf("%s", zOp);
183891    for(i=0; zRet && i<pExpr->nChild; i++){
183892      char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
183893      if( !z ){
183894        sqlite3_free(zRet);
183895        zRet = 0;
183896      }else{
183897        zRet = fts5PrintfAppend(zRet, " [%z]", z);
183898      }
183899    }
183900  }
183901
183902  return zRet;
183903}
183904
183905static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
183906  char *zRet = 0;
183907  if( pExpr->eType==0 ){
183908    return sqlite3_mprintf("\"\"");
183909  }else
183910  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
183911    Fts5ExprNearset *pNear = pExpr->pNear;
183912    int i;
183913    int iTerm;
183914
183915    if( pNear->pColset ){
183916      int iCol = pNear->pColset->aiCol[0];
183917      zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
183918      if( zRet==0 ) return 0;
183919    }
183920
183921    if( pNear->nPhrase>1 ){
183922      zRet = fts5PrintfAppend(zRet, "NEAR(");
183923      if( zRet==0 ) return 0;
183924    }
183925
183926    for(i=0; i<pNear->nPhrase; i++){
183927      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
183928      if( i!=0 ){
183929        zRet = fts5PrintfAppend(zRet, " ");
183930        if( zRet==0 ) return 0;
183931      }
183932      for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
183933        char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
183934        if( zTerm ){
183935          zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
183936          sqlite3_free(zTerm);
183937        }
183938        if( zTerm==0 || zRet==0 ){
183939          sqlite3_free(zRet);
183940          return 0;
183941        }
183942      }
183943    }
183944
183945    if( pNear->nPhrase>1 ){
183946      zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
183947      if( zRet==0 ) return 0;
183948    }
183949
183950  }else{
183951    char const *zOp = 0;
183952    int i;
183953
183954    switch( pExpr->eType ){
183955      case FTS5_AND: zOp = " AND "; break;
183956      case FTS5_NOT: zOp = " NOT "; break;
183957      default:
183958        assert( pExpr->eType==FTS5_OR );
183959        zOp = " OR ";
183960        break;
183961    }
183962
183963    for(i=0; i<pExpr->nChild; i++){
183964      char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
183965      if( z==0 ){
183966        sqlite3_free(zRet);
183967        zRet = 0;
183968      }else{
183969        int e = pExpr->apChild[i]->eType;
183970        int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
183971        zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
183972            (i==0 ? "" : zOp),
183973            (b?"(":""), z, (b?")":"")
183974        );
183975      }
183976      if( zRet==0 ) break;
183977    }
183978  }
183979
183980  return zRet;
183981}
183982
183983/*
183984** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
183985** and fts5_expr_tcl() (bTcl!=0).
183986*/
183987static void fts5ExprFunction(
183988  sqlite3_context *pCtx,          /* Function call context */
183989  int nArg,                       /* Number of args */
183990  sqlite3_value **apVal,          /* Function arguments */
183991  int bTcl
183992){
183993  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
183994  sqlite3 *db = sqlite3_context_db_handle(pCtx);
183995  const char *zExpr = 0;
183996  char *zErr = 0;
183997  Fts5Expr *pExpr = 0;
183998  int rc;
183999  int i;
184000
184001  const char **azConfig;          /* Array of arguments for Fts5Config */
184002  const char *zNearsetCmd = "nearset";
184003  int nConfig;                    /* Size of azConfig[] */
184004  Fts5Config *pConfig = 0;
184005  int iArg = 1;
184006
184007  if( nArg<1 ){
184008    zErr = sqlite3_mprintf("wrong number of arguments to function %s",
184009        bTcl ? "fts5_expr_tcl" : "fts5_expr"
184010    );
184011    sqlite3_result_error(pCtx, zErr, -1);
184012    sqlite3_free(zErr);
184013    return;
184014  }
184015
184016  if( bTcl && nArg>1 ){
184017    zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
184018    iArg = 2;
184019  }
184020
184021  nConfig = 3 + (nArg-iArg);
184022  azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
184023  if( azConfig==0 ){
184024    sqlite3_result_error_nomem(pCtx);
184025    return;
184026  }
184027  azConfig[0] = 0;
184028  azConfig[1] = "main";
184029  azConfig[2] = "tbl";
184030  for(i=3; iArg<nArg; iArg++){
184031    azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
184032  }
184033
184034  zExpr = (const char*)sqlite3_value_text(apVal[0]);
184035
184036  rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
184037  if( rc==SQLITE_OK ){
184038    rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pExpr, &zErr);
184039  }
184040  if( rc==SQLITE_OK ){
184041    char *zText;
184042    if( pExpr->pRoot->xNext==0 ){
184043      zText = sqlite3_mprintf("");
184044    }else if( bTcl ){
184045      zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
184046    }else{
184047      zText = fts5ExprPrint(pConfig, pExpr->pRoot);
184048    }
184049    if( zText==0 ){
184050      rc = SQLITE_NOMEM;
184051    }else{
184052      sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
184053      sqlite3_free(zText);
184054    }
184055  }
184056
184057  if( rc!=SQLITE_OK ){
184058    if( zErr ){
184059      sqlite3_result_error(pCtx, zErr, -1);
184060      sqlite3_free(zErr);
184061    }else{
184062      sqlite3_result_error_code(pCtx, rc);
184063    }
184064  }
184065  sqlite3_free((void *)azConfig);
184066  sqlite3Fts5ConfigFree(pConfig);
184067  sqlite3Fts5ExprFree(pExpr);
184068}
184069
184070static void fts5ExprFunctionHr(
184071  sqlite3_context *pCtx,          /* Function call context */
184072  int nArg,                       /* Number of args */
184073  sqlite3_value **apVal           /* Function arguments */
184074){
184075  fts5ExprFunction(pCtx, nArg, apVal, 0);
184076}
184077static void fts5ExprFunctionTcl(
184078  sqlite3_context *pCtx,          /* Function call context */
184079  int nArg,                       /* Number of args */
184080  sqlite3_value **apVal           /* Function arguments */
184081){
184082  fts5ExprFunction(pCtx, nArg, apVal, 1);
184083}
184084
184085/*
184086** The implementation of an SQLite user-defined-function that accepts a
184087** single integer as an argument. If the integer is an alpha-numeric
184088** unicode code point, 1 is returned. Otherwise 0.
184089*/
184090static void fts5ExprIsAlnum(
184091  sqlite3_context *pCtx,          /* Function call context */
184092  int nArg,                       /* Number of args */
184093  sqlite3_value **apVal           /* Function arguments */
184094){
184095  int iCode;
184096  if( nArg!=1 ){
184097    sqlite3_result_error(pCtx,
184098        "wrong number of arguments to function fts5_isalnum", -1
184099    );
184100    return;
184101  }
184102  iCode = sqlite3_value_int(apVal[0]);
184103  sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
184104}
184105
184106static void fts5ExprFold(
184107  sqlite3_context *pCtx,          /* Function call context */
184108  int nArg,                       /* Number of args */
184109  sqlite3_value **apVal           /* Function arguments */
184110){
184111  if( nArg!=1 && nArg!=2 ){
184112    sqlite3_result_error(pCtx,
184113        "wrong number of arguments to function fts5_fold", -1
184114    );
184115  }else{
184116    int iCode;
184117    int bRemoveDiacritics = 0;
184118    iCode = sqlite3_value_int(apVal[0]);
184119    if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
184120    sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
184121  }
184122}
184123
184124/*
184125** This is called during initialization to register the fts5_expr() scalar
184126** UDF with the SQLite handle passed as the only argument.
184127*/
184128static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
184129  struct Fts5ExprFunc {
184130    const char *z;
184131    void (*x)(sqlite3_context*,int,sqlite3_value**);
184132  } aFunc[] = {
184133    { "fts5_expr",     fts5ExprFunctionHr },
184134    { "fts5_expr_tcl", fts5ExprFunctionTcl },
184135    { "fts5_isalnum",  fts5ExprIsAlnum },
184136    { "fts5_fold",     fts5ExprFold },
184137  };
184138  int i;
184139  int rc = SQLITE_OK;
184140  void *pCtx = (void*)pGlobal;
184141
184142  for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
184143    struct Fts5ExprFunc *p = &aFunc[i];
184144    rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
184145  }
184146
184147  /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
184148#ifndef NDEBUG
184149  (void)sqlite3Fts5ParserTrace;
184150#endif
184151
184152  return rc;
184153}
184154
184155/*
184156** Return the number of phrases in expression pExpr.
184157*/
184158static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
184159  return (pExpr ? pExpr->nPhrase : 0);
184160}
184161
184162/*
184163** Return the number of terms in the iPhrase'th phrase in pExpr.
184164*/
184165static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
184166  if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
184167  return pExpr->apExprPhrase[iPhrase]->nTerm;
184168}
184169
184170/*
184171** This function is used to access the current position list for phrase
184172** iPhrase.
184173*/
184174static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
184175  int nRet;
184176  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
184177  Fts5ExprNode *pNode = pPhrase->pNode;
184178  if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
184179    *pa = pPhrase->poslist.p;
184180    nRet = pPhrase->poslist.n;
184181  }else{
184182    *pa = 0;
184183    nRet = 0;
184184  }
184185  return nRet;
184186}
184187
184188struct Fts5PoslistPopulator {
184189  Fts5PoslistWriter writer;
184190  int bOk;                        /* True if ok to populate */
184191  int bMiss;
184192};
184193
184194static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
184195  Fts5PoslistPopulator *pRet;
184196  pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
184197  if( pRet ){
184198    int i;
184199    memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
184200    for(i=0; i<pExpr->nPhrase; i++){
184201      Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
184202      Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
184203      assert( pExpr->apExprPhrase[i]->nTerm==1 );
184204      if( bLive &&
184205          (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
184206      ){
184207        pRet[i].bMiss = 1;
184208      }else{
184209        pBuf->n = 0;
184210      }
184211    }
184212  }
184213  return pRet;
184214}
184215
184216struct Fts5ExprCtx {
184217  Fts5Expr *pExpr;
184218  Fts5PoslistPopulator *aPopulator;
184219  i64 iOff;
184220};
184221typedef struct Fts5ExprCtx Fts5ExprCtx;
184222
184223/*
184224** TODO: Make this more efficient!
184225*/
184226static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
184227  int i;
184228  for(i=0; i<pColset->nCol; i++){
184229    if( pColset->aiCol[i]==iCol ) return 1;
184230  }
184231  return 0;
184232}
184233
184234static int fts5ExprPopulatePoslistsCb(
184235  void *pCtx,                /* Copy of 2nd argument to xTokenize() */
184236  int tflags,                /* Mask of FTS5_TOKEN_* flags */
184237  const char *pToken,        /* Pointer to buffer containing token */
184238  int nToken,                /* Size of token in bytes */
184239  int iUnused1,              /* Byte offset of token within input text */
184240  int iUnused2               /* Byte offset of end of token within input text */
184241){
184242  Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
184243  Fts5Expr *pExpr = p->pExpr;
184244  int i;
184245
184246  UNUSED_PARAM2(iUnused1, iUnused2);
184247
184248  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
184249  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
184250  for(i=0; i<pExpr->nPhrase; i++){
184251    Fts5ExprTerm *pTerm;
184252    if( p->aPopulator[i].bOk==0 ) continue;
184253    for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
184254      int nTerm = (int)strlen(pTerm->zTerm);
184255      if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
184256       && memcmp(pTerm->zTerm, pToken, nTerm)==0
184257      ){
184258        int rc = sqlite3Fts5PoslistWriterAppend(
184259            &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
184260        );
184261        if( rc ) return rc;
184262        break;
184263      }
184264    }
184265  }
184266  return SQLITE_OK;
184267}
184268
184269static int sqlite3Fts5ExprPopulatePoslists(
184270  Fts5Config *pConfig,
184271  Fts5Expr *pExpr,
184272  Fts5PoslistPopulator *aPopulator,
184273  int iCol,
184274  const char *z, int n
184275){
184276  int i;
184277  Fts5ExprCtx sCtx;
184278  sCtx.pExpr = pExpr;
184279  sCtx.aPopulator = aPopulator;
184280  sCtx.iOff = (((i64)iCol) << 32) - 1;
184281
184282  for(i=0; i<pExpr->nPhrase; i++){
184283    Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
184284    Fts5Colset *pColset = pNode->pNear->pColset;
184285    if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
184286     || aPopulator[i].bMiss
184287    ){
184288      aPopulator[i].bOk = 0;
184289    }else{
184290      aPopulator[i].bOk = 1;
184291    }
184292  }
184293
184294  return sqlite3Fts5Tokenize(pConfig,
184295      FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
184296  );
184297}
184298
184299static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
184300  if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
184301    pNode->pNear->apPhrase[0]->poslist.n = 0;
184302  }else{
184303    int i;
184304    for(i=0; i<pNode->nChild; i++){
184305      fts5ExprClearPoslists(pNode->apChild[i]);
184306    }
184307  }
184308}
184309
184310static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
184311  pNode->iRowid = iRowid;
184312  pNode->bEof = 0;
184313  switch( pNode->eType ){
184314    case FTS5_TERM:
184315    case FTS5_STRING:
184316      return (pNode->pNear->apPhrase[0]->poslist.n>0);
184317
184318    case FTS5_AND: {
184319      int i;
184320      for(i=0; i<pNode->nChild; i++){
184321        if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
184322          fts5ExprClearPoslists(pNode);
184323          return 0;
184324        }
184325      }
184326      break;
184327    }
184328
184329    case FTS5_OR: {
184330      int i;
184331      int bRet = 0;
184332      for(i=0; i<pNode->nChild; i++){
184333        if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
184334          bRet = 1;
184335        }
184336      }
184337      return bRet;
184338    }
184339
184340    default: {
184341      assert( pNode->eType==FTS5_NOT );
184342      if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
184343          || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
184344        ){
184345        fts5ExprClearPoslists(pNode);
184346        return 0;
184347      }
184348      break;
184349    }
184350  }
184351  return 1;
184352}
184353
184354static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
184355  fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
184356}
184357
184358/*
184359** This function is only called for detail=columns tables.
184360*/
184361static int sqlite3Fts5ExprPhraseCollist(
184362  Fts5Expr *pExpr,
184363  int iPhrase,
184364  const u8 **ppCollist,
184365  int *pnCollist
184366){
184367  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
184368  Fts5ExprNode *pNode = pPhrase->pNode;
184369  int rc = SQLITE_OK;
184370
184371  assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
184372  assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
184373
184374  if( pNode->bEof==0
184375   && pNode->iRowid==pExpr->pRoot->iRowid
184376   && pPhrase->poslist.n>0
184377  ){
184378    Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
184379    if( pTerm->pSynonym ){
184380      Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
184381      rc = fts5ExprSynonymList(
184382          pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
184383      );
184384    }else{
184385      *ppCollist = pPhrase->aTerm[0].pIter->pData;
184386      *pnCollist = pPhrase->aTerm[0].pIter->nData;
184387    }
184388  }else{
184389    *ppCollist = 0;
184390    *pnCollist = 0;
184391  }
184392
184393  return rc;
184394}
184395
184396
184397/*
184398** 2014 August 11
184399**
184400** The author disclaims copyright to this source code.  In place of
184401** a legal notice, here is a blessing:
184402**
184403**    May you do good and not evil.
184404**    May you find forgiveness for yourself and forgive others.
184405**    May you share freely, never taking more than you give.
184406**
184407******************************************************************************
184408**
184409*/
184410
184411
184412
184413/* #include "fts5Int.h" */
184414
184415typedef struct Fts5HashEntry Fts5HashEntry;
184416
184417/*
184418** This file contains the implementation of an in-memory hash table used
184419** to accumuluate "term -> doclist" content before it is flused to a level-0
184420** segment.
184421*/
184422
184423
184424struct Fts5Hash {
184425  int eDetail;                    /* Copy of Fts5Config.eDetail */
184426  int *pnByte;                    /* Pointer to bytes counter */
184427  int nEntry;                     /* Number of entries currently in hash */
184428  int nSlot;                      /* Size of aSlot[] array */
184429  Fts5HashEntry *pScan;           /* Current ordered scan item */
184430  Fts5HashEntry **aSlot;          /* Array of hash slots */
184431};
184432
184433/*
184434** Each entry in the hash table is represented by an object of the
184435** following type. Each object, its key (zKey[]) and its current data
184436** are stored in a single memory allocation. The position list data
184437** immediately follows the key data in memory.
184438**
184439** The data that follows the key is in a similar, but not identical format
184440** to the doclist data stored in the database. It is:
184441**
184442**   * Rowid, as a varint
184443**   * Position list, without 0x00 terminator.
184444**   * Size of previous position list and rowid, as a 4 byte
184445**     big-endian integer.
184446**
184447** iRowidOff:
184448**   Offset of last rowid written to data area. Relative to first byte of
184449**   structure.
184450**
184451** nData:
184452**   Bytes of data written since iRowidOff.
184453*/
184454struct Fts5HashEntry {
184455  Fts5HashEntry *pHashNext;       /* Next hash entry with same hash-key */
184456  Fts5HashEntry *pScanNext;       /* Next entry in sorted order */
184457
184458  int nAlloc;                     /* Total size of allocation */
184459  int iSzPoslist;                 /* Offset of space for 4-byte poslist size */
184460  int nData;                      /* Total bytes of data (incl. structure) */
184461  int nKey;                       /* Length of zKey[] in bytes */
184462  u8 bDel;                        /* Set delete-flag @ iSzPoslist */
184463  u8 bContent;                    /* Set content-flag (detail=none mode) */
184464  i16 iCol;                       /* Column of last value written */
184465  int iPos;                       /* Position of last value written */
184466  i64 iRowid;                     /* Rowid of last value written */
184467  char zKey[8];                   /* Nul-terminated entry key */
184468};
184469
184470/*
184471** Size of Fts5HashEntry without the zKey[] array.
184472*/
184473#define FTS5_HASHENTRYSIZE (sizeof(Fts5HashEntry)-8)
184474
184475
184476
184477/*
184478** Allocate a new hash table.
184479*/
184480static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
184481  int rc = SQLITE_OK;
184482  Fts5Hash *pNew;
184483
184484  *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
184485  if( pNew==0 ){
184486    rc = SQLITE_NOMEM;
184487  }else{
184488    int nByte;
184489    memset(pNew, 0, sizeof(Fts5Hash));
184490    pNew->pnByte = pnByte;
184491    pNew->eDetail = pConfig->eDetail;
184492
184493    pNew->nSlot = 1024;
184494    nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
184495    pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
184496    if( pNew->aSlot==0 ){
184497      sqlite3_free(pNew);
184498      *ppNew = 0;
184499      rc = SQLITE_NOMEM;
184500    }else{
184501      memset(pNew->aSlot, 0, nByte);
184502    }
184503  }
184504  return rc;
184505}
184506
184507/*
184508** Free a hash table object.
184509*/
184510static void sqlite3Fts5HashFree(Fts5Hash *pHash){
184511  if( pHash ){
184512    sqlite3Fts5HashClear(pHash);
184513    sqlite3_free(pHash->aSlot);
184514    sqlite3_free(pHash);
184515  }
184516}
184517
184518/*
184519** Empty (but do not delete) a hash table.
184520*/
184521static void sqlite3Fts5HashClear(Fts5Hash *pHash){
184522  int i;
184523  for(i=0; i<pHash->nSlot; i++){
184524    Fts5HashEntry *pNext;
184525    Fts5HashEntry *pSlot;
184526    for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
184527      pNext = pSlot->pHashNext;
184528      sqlite3_free(pSlot);
184529    }
184530  }
184531  memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
184532  pHash->nEntry = 0;
184533}
184534
184535static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
184536  int i;
184537  unsigned int h = 13;
184538  for(i=n-1; i>=0; i--){
184539    h = (h << 3) ^ h ^ p[i];
184540  }
184541  return (h % nSlot);
184542}
184543
184544static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
184545  int i;
184546  unsigned int h = 13;
184547  for(i=n-1; i>=0; i--){
184548    h = (h << 3) ^ h ^ p[i];
184549  }
184550  h = (h << 3) ^ h ^ b;
184551  return (h % nSlot);
184552}
184553
184554/*
184555** Resize the hash table by doubling the number of slots.
184556*/
184557static int fts5HashResize(Fts5Hash *pHash){
184558  int nNew = pHash->nSlot*2;
184559  int i;
184560  Fts5HashEntry **apNew;
184561  Fts5HashEntry **apOld = pHash->aSlot;
184562
184563  apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
184564  if( !apNew ) return SQLITE_NOMEM;
184565  memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
184566
184567  for(i=0; i<pHash->nSlot; i++){
184568    while( apOld[i] ){
184569      int iHash;
184570      Fts5HashEntry *p = apOld[i];
184571      apOld[i] = p->pHashNext;
184572      iHash = fts5HashKey(nNew, (u8*)p->zKey, (int)strlen(p->zKey));
184573      p->pHashNext = apNew[iHash];
184574      apNew[iHash] = p;
184575    }
184576  }
184577
184578  sqlite3_free(apOld);
184579  pHash->nSlot = nNew;
184580  pHash->aSlot = apNew;
184581  return SQLITE_OK;
184582}
184583
184584static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
184585  if( p->iSzPoslist ){
184586    u8 *pPtr = (u8*)p;
184587    if( pHash->eDetail==FTS5_DETAIL_NONE ){
184588      assert( p->nData==p->iSzPoslist );
184589      if( p->bDel ){
184590        pPtr[p->nData++] = 0x00;
184591        if( p->bContent ){
184592          pPtr[p->nData++] = 0x00;
184593        }
184594      }
184595    }else{
184596      int nSz = (p->nData - p->iSzPoslist - 1);       /* Size in bytes */
184597      int nPos = nSz*2 + p->bDel;                     /* Value of nPos field */
184598
184599      assert( p->bDel==0 || p->bDel==1 );
184600      if( nPos<=127 ){
184601        pPtr[p->iSzPoslist] = (u8)nPos;
184602      }else{
184603        int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
184604        memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
184605        sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
184606        p->nData += (nByte-1);
184607      }
184608    }
184609
184610    p->iSzPoslist = 0;
184611    p->bDel = 0;
184612    p->bContent = 0;
184613  }
184614}
184615
184616/*
184617** Add an entry to the in-memory hash table. The key is the concatenation
184618** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
184619**
184620**     (bByte || pToken) -> (iRowid,iCol,iPos)
184621**
184622** Or, if iCol is negative, then the value is a delete marker.
184623*/
184624static int sqlite3Fts5HashWrite(
184625  Fts5Hash *pHash,
184626  i64 iRowid,                     /* Rowid for this entry */
184627  int iCol,                       /* Column token appears in (-ve -> delete) */
184628  int iPos,                       /* Position of token within column */
184629  char bByte,                     /* First byte of token */
184630  const char *pToken, int nToken  /* Token to add or remove to or from index */
184631){
184632  unsigned int iHash;
184633  Fts5HashEntry *p;
184634  u8 *pPtr;
184635  int nIncr = 0;                  /* Amount to increment (*pHash->pnByte) by */
184636  int bNew;                       /* If non-delete entry should be written */
184637
184638  bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
184639
184640  /* Attempt to locate an existing hash entry */
184641  iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
184642  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
184643    if( p->zKey[0]==bByte
184644     && p->nKey==nToken
184645     && memcmp(&p->zKey[1], pToken, nToken)==0
184646    ){
184647      break;
184648    }
184649  }
184650
184651  /* If an existing hash entry cannot be found, create a new one. */
184652  if( p==0 ){
184653    /* Figure out how much space to allocate */
184654    int nByte = FTS5_HASHENTRYSIZE + (nToken+1) + 1 + 64;
184655    if( nByte<128 ) nByte = 128;
184656
184657    /* Grow the Fts5Hash.aSlot[] array if necessary. */
184658    if( (pHash->nEntry*2)>=pHash->nSlot ){
184659      int rc = fts5HashResize(pHash);
184660      if( rc!=SQLITE_OK ) return rc;
184661      iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
184662    }
184663
184664    /* Allocate new Fts5HashEntry and add it to the hash table. */
184665    p = (Fts5HashEntry*)sqlite3_malloc(nByte);
184666    if( !p ) return SQLITE_NOMEM;
184667    memset(p, 0, FTS5_HASHENTRYSIZE);
184668    p->nAlloc = nByte;
184669    p->zKey[0] = bByte;
184670    memcpy(&p->zKey[1], pToken, nToken);
184671    assert( iHash==fts5HashKey(pHash->nSlot, (u8*)p->zKey, nToken+1) );
184672    p->nKey = nToken;
184673    p->zKey[nToken+1] = '\0';
184674    p->nData = nToken+1 + 1 + FTS5_HASHENTRYSIZE;
184675    p->pHashNext = pHash->aSlot[iHash];
184676    pHash->aSlot[iHash] = p;
184677    pHash->nEntry++;
184678
184679    /* Add the first rowid field to the hash-entry */
184680    p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
184681    p->iRowid = iRowid;
184682
184683    p->iSzPoslist = p->nData;
184684    if( pHash->eDetail!=FTS5_DETAIL_NONE ){
184685      p->nData += 1;
184686      p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
184687    }
184688
184689    nIncr += p->nData;
184690  }else{
184691
184692    /* Appending to an existing hash-entry. Check that there is enough
184693    ** space to append the largest possible new entry. Worst case scenario
184694    ** is:
184695    **
184696    **     + 9 bytes for a new rowid,
184697    **     + 4 byte reserved for the "poslist size" varint.
184698    **     + 1 byte for a "new column" byte,
184699    **     + 3 bytes for a new column number (16-bit max) as a varint,
184700    **     + 5 bytes for the new position offset (32-bit max).
184701    */
184702    if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
184703      int nNew = p->nAlloc * 2;
184704      Fts5HashEntry *pNew;
184705      Fts5HashEntry **pp;
184706      pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
184707      if( pNew==0 ) return SQLITE_NOMEM;
184708      pNew->nAlloc = nNew;
184709      for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
184710      *pp = pNew;
184711      p = pNew;
184712    }
184713    nIncr -= p->nData;
184714  }
184715  assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
184716
184717  pPtr = (u8*)p;
184718
184719  /* If this is a new rowid, append the 4-byte size field for the previous
184720  ** entry, and the new rowid for this entry.  */
184721  if( iRowid!=p->iRowid ){
184722    fts5HashAddPoslistSize(pHash, p);
184723    p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
184724    p->iRowid = iRowid;
184725    bNew = 1;
184726    p->iSzPoslist = p->nData;
184727    if( pHash->eDetail!=FTS5_DETAIL_NONE ){
184728      p->nData += 1;
184729      p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
184730      p->iPos = 0;
184731    }
184732  }
184733
184734  if( iCol>=0 ){
184735    if( pHash->eDetail==FTS5_DETAIL_NONE ){
184736      p->bContent = 1;
184737    }else{
184738      /* Append a new column value, if necessary */
184739      assert( iCol>=p->iCol );
184740      if( iCol!=p->iCol ){
184741        if( pHash->eDetail==FTS5_DETAIL_FULL ){
184742          pPtr[p->nData++] = 0x01;
184743          p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
184744          p->iCol = (i16)iCol;
184745          p->iPos = 0;
184746        }else{
184747          bNew = 1;
184748          p->iCol = (i16)(iPos = iCol);
184749        }
184750      }
184751
184752      /* Append the new position offset, if necessary */
184753      if( bNew ){
184754        p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
184755        p->iPos = iPos;
184756      }
184757    }
184758  }else{
184759    /* This is a delete. Set the delete flag. */
184760    p->bDel = 1;
184761  }
184762
184763  nIncr += p->nData;
184764  *pHash->pnByte += nIncr;
184765  return SQLITE_OK;
184766}
184767
184768
184769/*
184770** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
184771** each sorted in key order. This function merges the two lists into a
184772** single list and returns a pointer to its first element.
184773*/
184774static Fts5HashEntry *fts5HashEntryMerge(
184775  Fts5HashEntry *pLeft,
184776  Fts5HashEntry *pRight
184777){
184778  Fts5HashEntry *p1 = pLeft;
184779  Fts5HashEntry *p2 = pRight;
184780  Fts5HashEntry *pRet = 0;
184781  Fts5HashEntry **ppOut = &pRet;
184782
184783  while( p1 || p2 ){
184784    if( p1==0 ){
184785      *ppOut = p2;
184786      p2 = 0;
184787    }else if( p2==0 ){
184788      *ppOut = p1;
184789      p1 = 0;
184790    }else{
184791      int i = 0;
184792      while( p1->zKey[i]==p2->zKey[i] ) i++;
184793
184794      if( ((u8)p1->zKey[i])>((u8)p2->zKey[i]) ){
184795        /* p2 is smaller */
184796        *ppOut = p2;
184797        ppOut = &p2->pScanNext;
184798        p2 = p2->pScanNext;
184799      }else{
184800        /* p1 is smaller */
184801        *ppOut = p1;
184802        ppOut = &p1->pScanNext;
184803        p1 = p1->pScanNext;
184804      }
184805      *ppOut = 0;
184806    }
184807  }
184808
184809  return pRet;
184810}
184811
184812/*
184813** Extract all tokens from hash table iHash and link them into a list
184814** in sorted order. The hash table is cleared before returning. It is
184815** the responsibility of the caller to free the elements of the returned
184816** list.
184817*/
184818static int fts5HashEntrySort(
184819  Fts5Hash *pHash,
184820  const char *pTerm, int nTerm,   /* Query prefix, if any */
184821  Fts5HashEntry **ppSorted
184822){
184823  const int nMergeSlot = 32;
184824  Fts5HashEntry **ap;
184825  Fts5HashEntry *pList;
184826  int iSlot;
184827  int i;
184828
184829  *ppSorted = 0;
184830  ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
184831  if( !ap ) return SQLITE_NOMEM;
184832  memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
184833
184834  for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
184835    Fts5HashEntry *pIter;
184836    for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
184837      if( pTerm==0 || 0==memcmp(pIter->zKey, pTerm, nTerm) ){
184838        Fts5HashEntry *pEntry = pIter;
184839        pEntry->pScanNext = 0;
184840        for(i=0; ap[i]; i++){
184841          pEntry = fts5HashEntryMerge(pEntry, ap[i]);
184842          ap[i] = 0;
184843        }
184844        ap[i] = pEntry;
184845      }
184846    }
184847  }
184848
184849  pList = 0;
184850  for(i=0; i<nMergeSlot; i++){
184851    pList = fts5HashEntryMerge(pList, ap[i]);
184852  }
184853
184854  pHash->nEntry = 0;
184855  sqlite3_free(ap);
184856  *ppSorted = pList;
184857  return SQLITE_OK;
184858}
184859
184860/*
184861** Query the hash table for a doclist associated with term pTerm/nTerm.
184862*/
184863static int sqlite3Fts5HashQuery(
184864  Fts5Hash *pHash,                /* Hash table to query */
184865  const char *pTerm, int nTerm,   /* Query term */
184866  const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
184867  int *pnDoclist                  /* OUT: Size of doclist in bytes */
184868){
184869  unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
184870  Fts5HashEntry *p;
184871
184872  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
184873    if( memcmp(p->zKey, pTerm, nTerm)==0 && p->zKey[nTerm]==0 ) break;
184874  }
184875
184876  if( p ){
184877    fts5HashAddPoslistSize(pHash, p);
184878    *ppDoclist = (const u8*)&p->zKey[nTerm+1];
184879    *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
184880  }else{
184881    *ppDoclist = 0;
184882    *pnDoclist = 0;
184883  }
184884
184885  return SQLITE_OK;
184886}
184887
184888static int sqlite3Fts5HashScanInit(
184889  Fts5Hash *p,                    /* Hash table to query */
184890  const char *pTerm, int nTerm    /* Query prefix */
184891){
184892  return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
184893}
184894
184895static void sqlite3Fts5HashScanNext(Fts5Hash *p){
184896  assert( !sqlite3Fts5HashScanEof(p) );
184897  p->pScan = p->pScan->pScanNext;
184898}
184899
184900static int sqlite3Fts5HashScanEof(Fts5Hash *p){
184901  return (p->pScan==0);
184902}
184903
184904static void sqlite3Fts5HashScanEntry(
184905  Fts5Hash *pHash,
184906  const char **pzTerm,            /* OUT: term (nul-terminated) */
184907  const u8 **ppDoclist,           /* OUT: pointer to doclist */
184908  int *pnDoclist                  /* OUT: size of doclist in bytes */
184909){
184910  Fts5HashEntry *p;
184911  if( (p = pHash->pScan) ){
184912    int nTerm = (int)strlen(p->zKey);
184913    fts5HashAddPoslistSize(pHash, p);
184914    *pzTerm = p->zKey;
184915    *ppDoclist = (const u8*)&p->zKey[nTerm+1];
184916    *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
184917  }else{
184918    *pzTerm = 0;
184919    *ppDoclist = 0;
184920    *pnDoclist = 0;
184921  }
184922}
184923
184924
184925/*
184926** 2014 May 31
184927**
184928** The author disclaims copyright to this source code.  In place of
184929** a legal notice, here is a blessing:
184930**
184931**    May you do good and not evil.
184932**    May you find forgiveness for yourself and forgive others.
184933**    May you share freely, never taking more than you give.
184934**
184935******************************************************************************
184936**
184937** Low level access to the FTS index stored in the database file. The
184938** routines in this file file implement all read and write access to the
184939** %_data table. Other parts of the system access this functionality via
184940** the interface defined in fts5Int.h.
184941*/
184942
184943
184944/* #include "fts5Int.h" */
184945
184946/*
184947** Overview:
184948**
184949** The %_data table contains all the FTS indexes for an FTS5 virtual table.
184950** As well as the main term index, there may be up to 31 prefix indexes.
184951** The format is similar to FTS3/4, except that:
184952**
184953**   * all segment b-tree leaf data is stored in fixed size page records
184954**     (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
184955**     taken to ensure it is possible to iterate in either direction through
184956**     the entries in a doclist, or to seek to a specific entry within a
184957**     doclist, without loading it into memory.
184958**
184959**   * large doclists that span many pages have associated "doclist index"
184960**     records that contain a copy of the first rowid on each page spanned by
184961**     the doclist. This is used to speed up seek operations, and merges of
184962**     large doclists with very small doclists.
184963**
184964**   * extra fields in the "structure record" record the state of ongoing
184965**     incremental merge operations.
184966**
184967*/
184968
184969
184970#define FTS5_OPT_WORK_UNIT  1000  /* Number of leaf pages per optimize step */
184971#define FTS5_WORK_UNIT      64    /* Number of leaf pages in unit of work */
184972
184973#define FTS5_MIN_DLIDX_SIZE 4     /* Add dlidx if this many empty pages */
184974
184975#define FTS5_MAIN_PREFIX '0'
184976
184977#if FTS5_MAX_PREFIX_INDEXES > 31
184978# error "FTS5_MAX_PREFIX_INDEXES is too large"
184979#endif
184980
184981/*
184982** Details:
184983**
184984** The %_data table managed by this module,
184985**
184986**     CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
184987**
184988** , contains the following 5 types of records. See the comments surrounding
184989** the FTS5_*_ROWID macros below for a description of how %_data rowids are
184990** assigned to each fo them.
184991**
184992** 1. Structure Records:
184993**
184994**   The set of segments that make up an index - the index structure - are
184995**   recorded in a single record within the %_data table. The record consists
184996**   of a single 32-bit configuration cookie value followed by a list of
184997**   SQLite varints. If the FTS table features more than one index (because
184998**   there are one or more prefix indexes), it is guaranteed that all share
184999**   the same cookie value.
185000**
185001**   Immediately following the configuration cookie, the record begins with
185002**   three varints:
185003**
185004**     + number of levels,
185005**     + total number of segments on all levels,
185006**     + value of write counter.
185007**
185008**   Then, for each level from 0 to nMax:
185009**
185010**     + number of input segments in ongoing merge.
185011**     + total number of segments in level.
185012**     + for each segment from oldest to newest:
185013**         + segment id (always > 0)
185014**         + first leaf page number (often 1, always greater than 0)
185015**         + final leaf page number
185016**
185017** 2. The Averages Record:
185018**
185019**   A single record within the %_data table. The data is a list of varints.
185020**   The first value is the number of rows in the index. Then, for each column
185021**   from left to right, the total number of tokens in the column for all
185022**   rows of the table.
185023**
185024** 3. Segment leaves:
185025**
185026**   TERM/DOCLIST FORMAT:
185027**
185028**     Most of each segment leaf is taken up by term/doclist data. The
185029**     general format of term/doclist, starting with the first term
185030**     on the leaf page, is:
185031**
185032**         varint : size of first term
185033**         blob:    first term data
185034**         doclist: first doclist
185035**         zero-or-more {
185036**           varint:  number of bytes in common with previous term
185037**           varint:  number of bytes of new term data (nNew)
185038**           blob:    nNew bytes of new term data
185039**           doclist: next doclist
185040**         }
185041**
185042**     doclist format:
185043**
185044**         varint:  first rowid
185045**         poslist: first poslist
185046**         zero-or-more {
185047**           varint:  rowid delta (always > 0)
185048**           poslist: next poslist
185049**         }
185050**
185051**     poslist format:
185052**
185053**         varint: size of poslist in bytes multiplied by 2, not including
185054**                 this field. Plus 1 if this entry carries the "delete" flag.
185055**         collist: collist for column 0
185056**         zero-or-more {
185057**           0x01 byte
185058**           varint: column number (I)
185059**           collist: collist for column I
185060**         }
185061**
185062**     collist format:
185063**
185064**         varint: first offset + 2
185065**         zero-or-more {
185066**           varint: offset delta + 2
185067**         }
185068**
185069**   PAGE FORMAT
185070**
185071**     Each leaf page begins with a 4-byte header containing 2 16-bit
185072**     unsigned integer fields in big-endian format. They are:
185073**
185074**       * The byte offset of the first rowid on the page, if it exists
185075**         and occurs before the first term (otherwise 0).
185076**
185077**       * The byte offset of the start of the page footer. If the page
185078**         footer is 0 bytes in size, then this field is the same as the
185079**         size of the leaf page in bytes.
185080**
185081**     The page footer consists of a single varint for each term located
185082**     on the page. Each varint is the byte offset of the current term
185083**     within the page, delta-compressed against the previous value. In
185084**     other words, the first varint in the footer is the byte offset of
185085**     the first term, the second is the byte offset of the second less that
185086**     of the first, and so on.
185087**
185088**     The term/doclist format described above is accurate if the entire
185089**     term/doclist data fits on a single leaf page. If this is not the case,
185090**     the format is changed in two ways:
185091**
185092**       + if the first rowid on a page occurs before the first term, it
185093**         is stored as a literal value:
185094**
185095**             varint:  first rowid
185096**
185097**       + the first term on each page is stored in the same way as the
185098**         very first term of the segment:
185099**
185100**             varint : size of first term
185101**             blob:    first term data
185102**
185103** 5. Segment doclist indexes:
185104**
185105**   Doclist indexes are themselves b-trees, however they usually consist of
185106**   a single leaf record only. The format of each doclist index leaf page
185107**   is:
185108**
185109**     * Flags byte. Bits are:
185110**         0x01: Clear if leaf is also the root page, otherwise set.
185111**
185112**     * Page number of fts index leaf page. As a varint.
185113**
185114**     * First rowid on page indicated by previous field. As a varint.
185115**
185116**     * A list of varints, one for each subsequent termless page. A
185117**       positive delta if the termless page contains at least one rowid,
185118**       or an 0x00 byte otherwise.
185119**
185120**   Internal doclist index nodes are:
185121**
185122**     * Flags byte. Bits are:
185123**         0x01: Clear for root page, otherwise set.
185124**
185125**     * Page number of first child page. As a varint.
185126**
185127**     * Copy of first rowid on page indicated by previous field. As a varint.
185128**
185129**     * A list of delta-encoded varints - the first rowid on each subsequent
185130**       child page.
185131**
185132*/
185133
185134/*
185135** Rowids for the averages and structure records in the %_data table.
185136*/
185137#define FTS5_AVERAGES_ROWID     1    /* Rowid used for the averages record */
185138#define FTS5_STRUCTURE_ROWID   10    /* The structure record */
185139
185140/*
185141** Macros determining the rowids used by segment leaves and dlidx leaves
185142** and nodes. All nodes and leaves are stored in the %_data table with large
185143** positive rowids.
185144**
185145** Each segment has a unique non-zero 16-bit id.
185146**
185147** The rowid for each segment leaf is found by passing the segment id and
185148** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
185149** sequentially starting from 1.
185150*/
185151#define FTS5_DATA_ID_B     16     /* Max seg id number 65535 */
185152#define FTS5_DATA_DLI_B     1     /* Doclist-index flag (1 bit) */
185153#define FTS5_DATA_HEIGHT_B  5     /* Max dlidx tree height of 32 */
185154#define FTS5_DATA_PAGE_B   31     /* Max page number of 2147483648 */
185155
185156#define fts5_dri(segid, dlidx, height, pgno) (                                 \
185157 ((i64)(segid)  << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) +    \
185158 ((i64)(dlidx)  << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) +                  \
185159 ((i64)(height) << (FTS5_DATA_PAGE_B)) +                                       \
185160 ((i64)(pgno))                                                                 \
185161)
185162
185163#define FTS5_SEGMENT_ROWID(segid, pgno)       fts5_dri(segid, 0, 0, pgno)
185164#define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
185165
185166/*
185167** Maximum segments permitted in a single index
185168*/
185169#define FTS5_MAX_SEGMENT 2000
185170
185171#ifdef SQLITE_DEBUG
185172static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
185173#endif
185174
185175
185176/*
185177** Each time a blob is read from the %_data table, it is padded with this
185178** many zero bytes. This makes it easier to decode the various record formats
185179** without overreading if the records are corrupt.
185180*/
185181#define FTS5_DATA_ZERO_PADDING 8
185182#define FTS5_DATA_PADDING 20
185183
185184typedef struct Fts5Data Fts5Data;
185185typedef struct Fts5DlidxIter Fts5DlidxIter;
185186typedef struct Fts5DlidxLvl Fts5DlidxLvl;
185187typedef struct Fts5DlidxWriter Fts5DlidxWriter;
185188typedef struct Fts5Iter Fts5Iter;
185189typedef struct Fts5PageWriter Fts5PageWriter;
185190typedef struct Fts5SegIter Fts5SegIter;
185191typedef struct Fts5DoclistIter Fts5DoclistIter;
185192typedef struct Fts5SegWriter Fts5SegWriter;
185193typedef struct Fts5Structure Fts5Structure;
185194typedef struct Fts5StructureLevel Fts5StructureLevel;
185195typedef struct Fts5StructureSegment Fts5StructureSegment;
185196
185197struct Fts5Data {
185198  u8 *p;                          /* Pointer to buffer containing record */
185199  int nn;                         /* Size of record in bytes */
185200  int szLeaf;                     /* Size of leaf without page-index */
185201};
185202
185203/*
185204** One object per %_data table.
185205*/
185206struct Fts5Index {
185207  Fts5Config *pConfig;            /* Virtual table configuration */
185208  char *zDataTbl;                 /* Name of %_data table */
185209  int nWorkUnit;                  /* Leaf pages in a "unit" of work */
185210
185211  /*
185212  ** Variables related to the accumulation of tokens and doclists within the
185213  ** in-memory hash tables before they are flushed to disk.
185214  */
185215  Fts5Hash *pHash;                /* Hash table for in-memory data */
185216  int nPendingData;               /* Current bytes of pending data */
185217  i64 iWriteRowid;                /* Rowid for current doc being written */
185218  int bDelete;                    /* Current write is a delete */
185219
185220  /* Error state. */
185221  int rc;                         /* Current error code */
185222
185223  /* State used by the fts5DataXXX() functions. */
185224  sqlite3_blob *pReader;          /* RO incr-blob open on %_data table */
185225  sqlite3_stmt *pWriter;          /* "INSERT ... %_data VALUES(?,?)" */
185226  sqlite3_stmt *pDeleter;         /* "DELETE FROM %_data ... id>=? AND id<=?" */
185227  sqlite3_stmt *pIdxWriter;       /* "INSERT ... %_idx VALUES(?,?,?,?)" */
185228  sqlite3_stmt *pIdxDeleter;      /* "DELETE FROM %_idx WHERE segid=? */
185229  sqlite3_stmt *pIdxSelect;
185230  int nRead;                      /* Total number of blocks read */
185231
185232  sqlite3_stmt *pDataVersion;
185233  i64 iStructVersion;             /* data_version when pStruct read */
185234  Fts5Structure *pStruct;         /* Current db structure (or NULL) */
185235};
185236
185237struct Fts5DoclistIter {
185238  u8 *aEof;                       /* Pointer to 1 byte past end of doclist */
185239
185240  /* Output variables. aPoslist==0 at EOF */
185241  i64 iRowid;
185242  u8 *aPoslist;
185243  int nPoslist;
185244  int nSize;
185245};
185246
185247/*
185248** The contents of the "structure" record for each index are represented
185249** using an Fts5Structure record in memory. Which uses instances of the
185250** other Fts5StructureXXX types as components.
185251*/
185252struct Fts5StructureSegment {
185253  int iSegid;                     /* Segment id */
185254  int pgnoFirst;                  /* First leaf page number in segment */
185255  int pgnoLast;                   /* Last leaf page number in segment */
185256};
185257struct Fts5StructureLevel {
185258  int nMerge;                     /* Number of segments in incr-merge */
185259  int nSeg;                       /* Total number of segments on level */
185260  Fts5StructureSegment *aSeg;     /* Array of segments. aSeg[0] is oldest. */
185261};
185262struct Fts5Structure {
185263  int nRef;                       /* Object reference count */
185264  u64 nWriteCounter;              /* Total leaves written to level 0 */
185265  int nSegment;                   /* Total segments in this structure */
185266  int nLevel;                     /* Number of levels in this index */
185267  Fts5StructureLevel aLevel[1];   /* Array of nLevel level objects */
185268};
185269
185270/*
185271** An object of type Fts5SegWriter is used to write to segments.
185272*/
185273struct Fts5PageWriter {
185274  int pgno;                       /* Page number for this page */
185275  int iPrevPgidx;                 /* Previous value written into pgidx */
185276  Fts5Buffer buf;                 /* Buffer containing leaf data */
185277  Fts5Buffer pgidx;               /* Buffer containing page-index */
185278  Fts5Buffer term;                /* Buffer containing previous term on page */
185279};
185280struct Fts5DlidxWriter {
185281  int pgno;                       /* Page number for this page */
185282  int bPrevValid;                 /* True if iPrev is valid */
185283  i64 iPrev;                      /* Previous rowid value written to page */
185284  Fts5Buffer buf;                 /* Buffer containing page data */
185285};
185286struct Fts5SegWriter {
185287  int iSegid;                     /* Segid to write to */
185288  Fts5PageWriter writer;          /* PageWriter object */
185289  i64 iPrevRowid;                 /* Previous rowid written to current leaf */
185290  u8 bFirstRowidInDoclist;        /* True if next rowid is first in doclist */
185291  u8 bFirstRowidInPage;           /* True if next rowid is first in page */
185292  /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
185293  u8 bFirstTermInPage;            /* True if next term will be first in leaf */
185294  int nLeafWritten;               /* Number of leaf pages written */
185295  int nEmpty;                     /* Number of contiguous term-less nodes */
185296
185297  int nDlidx;                     /* Allocated size of aDlidx[] array */
185298  Fts5DlidxWriter *aDlidx;        /* Array of Fts5DlidxWriter objects */
185299
185300  /* Values to insert into the %_idx table */
185301  Fts5Buffer btterm;              /* Next term to insert into %_idx table */
185302  int iBtPage;                    /* Page number corresponding to btterm */
185303};
185304
185305typedef struct Fts5CResult Fts5CResult;
185306struct Fts5CResult {
185307  u16 iFirst;                     /* aSeg[] index of firstest iterator */
185308  u8 bTermEq;                     /* True if the terms are equal */
185309};
185310
185311/*
185312** Object for iterating through a single segment, visiting each term/rowid
185313** pair in the segment.
185314**
185315** pSeg:
185316**   The segment to iterate through.
185317**
185318** iLeafPgno:
185319**   Current leaf page number within segment.
185320**
185321** iLeafOffset:
185322**   Byte offset within the current leaf that is the first byte of the
185323**   position list data (one byte passed the position-list size field).
185324**   rowid field of the current entry. Usually this is the size field of the
185325**   position list data. The exception is if the rowid for the current entry
185326**   is the last thing on the leaf page.
185327**
185328** pLeaf:
185329**   Buffer containing current leaf page data. Set to NULL at EOF.
185330**
185331** iTermLeafPgno, iTermLeafOffset:
185332**   Leaf page number containing the last term read from the segment. And
185333**   the offset immediately following the term data.
185334**
185335** flags:
185336**   Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
185337**
185338**   FTS5_SEGITER_ONETERM:
185339**     If set, set the iterator to point to EOF after the current doclist
185340**     has been exhausted. Do not proceed to the next term in the segment.
185341**
185342**   FTS5_SEGITER_REVERSE:
185343**     This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
185344**     it is set, iterate through rowid in descending order instead of the
185345**     default ascending order.
185346**
185347** iRowidOffset/nRowidOffset/aRowidOffset:
185348**     These are used if the FTS5_SEGITER_REVERSE flag is set.
185349**
185350**     For each rowid on the page corresponding to the current term, the
185351**     corresponding aRowidOffset[] entry is set to the byte offset of the
185352**     start of the "position-list-size" field within the page.
185353**
185354** iTermIdx:
185355**     Index of current term on iTermLeafPgno.
185356*/
185357struct Fts5SegIter {
185358  Fts5StructureSegment *pSeg;     /* Segment to iterate through */
185359  int flags;                      /* Mask of configuration flags */
185360  int iLeafPgno;                  /* Current leaf page number */
185361  Fts5Data *pLeaf;                /* Current leaf data */
185362  Fts5Data *pNextLeaf;            /* Leaf page (iLeafPgno+1) */
185363  int iLeafOffset;                /* Byte offset within current leaf */
185364
185365  /* Next method */
185366  void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
185367
185368  /* The page and offset from which the current term was read. The offset
185369  ** is the offset of the first rowid in the current doclist.  */
185370  int iTermLeafPgno;
185371  int iTermLeafOffset;
185372
185373  int iPgidxOff;                  /* Next offset in pgidx */
185374  int iEndofDoclist;
185375
185376  /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
185377  int iRowidOffset;               /* Current entry in aRowidOffset[] */
185378  int nRowidOffset;               /* Allocated size of aRowidOffset[] array */
185379  int *aRowidOffset;              /* Array of offset to rowid fields */
185380
185381  Fts5DlidxIter *pDlidx;          /* If there is a doclist-index */
185382
185383  /* Variables populated based on current entry. */
185384  Fts5Buffer term;                /* Current term */
185385  i64 iRowid;                     /* Current rowid */
185386  int nPos;                       /* Number of bytes in current position list */
185387  u8 bDel;                        /* True if the delete flag is set */
185388};
185389
185390/*
185391** Argument is a pointer to an Fts5Data structure that contains a
185392** leaf page.
185393*/
185394#define ASSERT_SZLEAF_OK(x) assert( \
185395    (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
185396)
185397
185398#define FTS5_SEGITER_ONETERM 0x01
185399#define FTS5_SEGITER_REVERSE 0x02
185400
185401/*
185402** Argument is a pointer to an Fts5Data structure that contains a leaf
185403** page. This macro evaluates to true if the leaf contains no terms, or
185404** false if it contains at least one term.
185405*/
185406#define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
185407
185408#define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
185409
185410#define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
185411
185412/*
185413** Object for iterating through the merged results of one or more segments,
185414** visiting each term/rowid pair in the merged data.
185415**
185416** nSeg is always a power of two greater than or equal to the number of
185417** segments that this object is merging data from. Both the aSeg[] and
185418** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
185419** with zeroed objects - these are handled as if they were iterators opened
185420** on empty segments.
185421**
185422** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
185423** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
185424** comparison in this context is the index of the iterator that currently
185425** points to the smaller term/rowid combination. Iterators at EOF are
185426** considered to be greater than all other iterators.
185427**
185428** aFirst[1] contains the index in aSeg[] of the iterator that points to
185429** the smallest key overall. aFirst[0] is unused.
185430**
185431** poslist:
185432**   Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
185433**   There is no way to tell if this is populated or not.
185434*/
185435struct Fts5Iter {
185436  Fts5IndexIter base;             /* Base class containing output vars */
185437
185438  Fts5Index *pIndex;              /* Index that owns this iterator */
185439  Fts5Structure *pStruct;         /* Database structure for this iterator */
185440  Fts5Buffer poslist;             /* Buffer containing current poslist */
185441  Fts5Colset *pColset;            /* Restrict matches to these columns */
185442
185443  /* Invoked to set output variables. */
185444  void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
185445
185446  int nSeg;                       /* Size of aSeg[] array */
185447  int bRev;                       /* True to iterate in reverse order */
185448  u8 bSkipEmpty;                  /* True to skip deleted entries */
185449
185450  i64 iSwitchRowid;               /* Firstest rowid of other than aFirst[1] */
185451  Fts5CResult *aFirst;            /* Current merge state (see above) */
185452  Fts5SegIter aSeg[1];            /* Array of segment iterators */
185453};
185454
185455
185456/*
185457** An instance of the following type is used to iterate through the contents
185458** of a doclist-index record.
185459**
185460** pData:
185461**   Record containing the doclist-index data.
185462**
185463** bEof:
185464**   Set to true once iterator has reached EOF.
185465**
185466** iOff:
185467**   Set to the current offset within record pData.
185468*/
185469struct Fts5DlidxLvl {
185470  Fts5Data *pData;              /* Data for current page of this level */
185471  int iOff;                     /* Current offset into pData */
185472  int bEof;                     /* At EOF already */
185473  int iFirstOff;                /* Used by reverse iterators */
185474
185475  /* Output variables */
185476  int iLeafPgno;                /* Page number of current leaf page */
185477  i64 iRowid;                   /* First rowid on leaf iLeafPgno */
185478};
185479struct Fts5DlidxIter {
185480  int nLvl;
185481  int iSegid;
185482  Fts5DlidxLvl aLvl[1];
185483};
185484
185485static void fts5PutU16(u8 *aOut, u16 iVal){
185486  aOut[0] = (iVal>>8);
185487  aOut[1] = (iVal&0xFF);
185488}
185489
185490static u16 fts5GetU16(const u8 *aIn){
185491  return ((u16)aIn[0] << 8) + aIn[1];
185492}
185493
185494/*
185495** Allocate and return a buffer at least nByte bytes in size.
185496**
185497** If an OOM error is encountered, return NULL and set the error code in
185498** the Fts5Index handle passed as the first argument.
185499*/
185500static void *fts5IdxMalloc(Fts5Index *p, int nByte){
185501  return sqlite3Fts5MallocZero(&p->rc, nByte);
185502}
185503
185504/*
185505** Compare the contents of the pLeft buffer with the pRight/nRight blob.
185506**
185507** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
185508** +ve if pRight is smaller than pLeft. In other words:
185509**
185510**     res = *pLeft - *pRight
185511*/
185512#ifdef SQLITE_DEBUG
185513static int fts5BufferCompareBlob(
185514  Fts5Buffer *pLeft,              /* Left hand side of comparison */
185515  const u8 *pRight, int nRight    /* Right hand side of comparison */
185516){
185517  int nCmp = MIN(pLeft->n, nRight);
185518  int res = memcmp(pLeft->p, pRight, nCmp);
185519  return (res==0 ? (pLeft->n - nRight) : res);
185520}
185521#endif
185522
185523/*
185524** Compare the contents of the two buffers using memcmp(). If one buffer
185525** is a prefix of the other, it is considered the lesser.
185526**
185527** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
185528** +ve if pRight is smaller than pLeft. In other words:
185529**
185530**     res = *pLeft - *pRight
185531*/
185532static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
185533  int nCmp = MIN(pLeft->n, pRight->n);
185534  int res = memcmp(pLeft->p, pRight->p, nCmp);
185535  return (res==0 ? (pLeft->n - pRight->n) : res);
185536}
185537
185538static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
185539  int ret;
185540  fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
185541  return ret;
185542}
185543
185544/*
185545** Close the read-only blob handle, if it is open.
185546*/
185547static void fts5CloseReader(Fts5Index *p){
185548  if( p->pReader ){
185549    sqlite3_blob *pReader = p->pReader;
185550    p->pReader = 0;
185551    sqlite3_blob_close(pReader);
185552  }
185553}
185554
185555
185556/*
185557** Retrieve a record from the %_data table.
185558**
185559** If an error occurs, NULL is returned and an error left in the
185560** Fts5Index object.
185561*/
185562static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
185563  Fts5Data *pRet = 0;
185564  if( p->rc==SQLITE_OK ){
185565    int rc = SQLITE_OK;
185566
185567    if( p->pReader ){
185568      /* This call may return SQLITE_ABORT if there has been a savepoint
185569      ** rollback since it was last used. In this case a new blob handle
185570      ** is required.  */
185571      sqlite3_blob *pBlob = p->pReader;
185572      p->pReader = 0;
185573      rc = sqlite3_blob_reopen(pBlob, iRowid);
185574      assert( p->pReader==0 );
185575      p->pReader = pBlob;
185576      if( rc!=SQLITE_OK ){
185577        fts5CloseReader(p);
185578      }
185579      if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
185580    }
185581
185582    /* If the blob handle is not open at this point, open it and seek
185583    ** to the requested entry.  */
185584    if( p->pReader==0 && rc==SQLITE_OK ){
185585      Fts5Config *pConfig = p->pConfig;
185586      rc = sqlite3_blob_open(pConfig->db,
185587          pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
185588      );
185589    }
185590
185591    /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
185592    ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
185593    ** All the reasons those functions might return SQLITE_ERROR - missing
185594    ** table, missing row, non-blob/text in block column - indicate
185595    ** backing store corruption.  */
185596    if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
185597
185598    if( rc==SQLITE_OK ){
185599      u8 *aOut = 0;               /* Read blob data into this buffer */
185600      int nByte = sqlite3_blob_bytes(p->pReader);
185601      int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
185602      pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
185603      if( pRet ){
185604        pRet->nn = nByte;
185605        aOut = pRet->p = (u8*)&pRet[1];
185606      }else{
185607        rc = SQLITE_NOMEM;
185608      }
185609
185610      if( rc==SQLITE_OK ){
185611        rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
185612      }
185613      if( rc!=SQLITE_OK ){
185614        sqlite3_free(pRet);
185615        pRet = 0;
185616      }else{
185617        /* TODO1: Fix this */
185618        pRet->szLeaf = fts5GetU16(&pRet->p[2]);
185619      }
185620    }
185621    p->rc = rc;
185622    p->nRead++;
185623  }
185624
185625  assert( (pRet==0)==(p->rc!=SQLITE_OK) );
185626  return pRet;
185627}
185628
185629
185630/*
185631** Release a reference to data record returned by an earlier call to
185632** fts5DataRead().
185633*/
185634static void fts5DataRelease(Fts5Data *pData){
185635  sqlite3_free(pData);
185636}
185637
185638static int fts5IndexPrepareStmt(
185639  Fts5Index *p,
185640  sqlite3_stmt **ppStmt,
185641  char *zSql
185642){
185643  if( p->rc==SQLITE_OK ){
185644    if( zSql ){
185645      p->rc = sqlite3_prepare_v2(p->pConfig->db, zSql, -1, ppStmt, 0);
185646    }else{
185647      p->rc = SQLITE_NOMEM;
185648    }
185649  }
185650  sqlite3_free(zSql);
185651  return p->rc;
185652}
185653
185654
185655/*
185656** INSERT OR REPLACE a record into the %_data table.
185657*/
185658static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
185659  if( p->rc!=SQLITE_OK ) return;
185660
185661  if( p->pWriter==0 ){
185662    Fts5Config *pConfig = p->pConfig;
185663    fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
185664          "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
185665          pConfig->zDb, pConfig->zName
185666    ));
185667    if( p->rc ) return;
185668  }
185669
185670  sqlite3_bind_int64(p->pWriter, 1, iRowid);
185671  sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
185672  sqlite3_step(p->pWriter);
185673  p->rc = sqlite3_reset(p->pWriter);
185674}
185675
185676/*
185677** Execute the following SQL:
185678**
185679**     DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
185680*/
185681static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
185682  if( p->rc!=SQLITE_OK ) return;
185683
185684  if( p->pDeleter==0 ){
185685    int rc;
185686    Fts5Config *pConfig = p->pConfig;
185687    char *zSql = sqlite3_mprintf(
185688        "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
185689          pConfig->zDb, pConfig->zName
185690    );
185691    if( zSql==0 ){
185692      rc = SQLITE_NOMEM;
185693    }else{
185694      rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p->pDeleter, 0);
185695      sqlite3_free(zSql);
185696    }
185697    if( rc!=SQLITE_OK ){
185698      p->rc = rc;
185699      return;
185700    }
185701  }
185702
185703  sqlite3_bind_int64(p->pDeleter, 1, iFirst);
185704  sqlite3_bind_int64(p->pDeleter, 2, iLast);
185705  sqlite3_step(p->pDeleter);
185706  p->rc = sqlite3_reset(p->pDeleter);
185707}
185708
185709/*
185710** Remove all records associated with segment iSegid.
185711*/
185712static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
185713  i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
185714  i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
185715  fts5DataDelete(p, iFirst, iLast);
185716  if( p->pIdxDeleter==0 ){
185717    Fts5Config *pConfig = p->pConfig;
185718    fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
185719          "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
185720          pConfig->zDb, pConfig->zName
185721    ));
185722  }
185723  if( p->rc==SQLITE_OK ){
185724    sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
185725    sqlite3_step(p->pIdxDeleter);
185726    p->rc = sqlite3_reset(p->pIdxDeleter);
185727  }
185728}
185729
185730/*
185731** Release a reference to an Fts5Structure object returned by an earlier
185732** call to fts5StructureRead() or fts5StructureDecode().
185733*/
185734static void fts5StructureRelease(Fts5Structure *pStruct){
185735  if( pStruct && 0>=(--pStruct->nRef) ){
185736    int i;
185737    assert( pStruct->nRef==0 );
185738    for(i=0; i<pStruct->nLevel; i++){
185739      sqlite3_free(pStruct->aLevel[i].aSeg);
185740    }
185741    sqlite3_free(pStruct);
185742  }
185743}
185744
185745static void fts5StructureRef(Fts5Structure *pStruct){
185746  pStruct->nRef++;
185747}
185748
185749/*
185750** Deserialize and return the structure record currently stored in serialized
185751** form within buffer pData/nData.
185752**
185753** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
185754** are over-allocated by one slot. This allows the structure contents
185755** to be more easily edited.
185756**
185757** If an error occurs, *ppOut is set to NULL and an SQLite error code
185758** returned. Otherwise, *ppOut is set to point to the new object and
185759** SQLITE_OK returned.
185760*/
185761static int fts5StructureDecode(
185762  const u8 *pData,                /* Buffer containing serialized structure */
185763  int nData,                      /* Size of buffer pData in bytes */
185764  int *piCookie,                  /* Configuration cookie value */
185765  Fts5Structure **ppOut           /* OUT: Deserialized object */
185766){
185767  int rc = SQLITE_OK;
185768  int i = 0;
185769  int iLvl;
185770  int nLevel = 0;
185771  int nSegment = 0;
185772  int nByte;                      /* Bytes of space to allocate at pRet */
185773  Fts5Structure *pRet = 0;        /* Structure object to return */
185774
185775  /* Grab the cookie value */
185776  if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
185777  i = 4;
185778
185779  /* Read the total number of levels and segments from the start of the
185780  ** structure record.  */
185781  i += fts5GetVarint32(&pData[i], nLevel);
185782  i += fts5GetVarint32(&pData[i], nSegment);
185783  nByte = (
185784      sizeof(Fts5Structure) +                    /* Main structure */
185785      sizeof(Fts5StructureLevel) * (nLevel-1)    /* aLevel[] array */
185786  );
185787  pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
185788
185789  if( pRet ){
185790    pRet->nRef = 1;
185791    pRet->nLevel = nLevel;
185792    pRet->nSegment = nSegment;
185793    i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
185794
185795    for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
185796      Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
185797      int nTotal = 0;
185798      int iSeg;
185799
185800      if( i>=nData ){
185801        rc = FTS5_CORRUPT;
185802      }else{
185803        i += fts5GetVarint32(&pData[i], pLvl->nMerge);
185804        i += fts5GetVarint32(&pData[i], nTotal);
185805        assert( nTotal>=pLvl->nMerge );
185806        pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
185807            nTotal * sizeof(Fts5StructureSegment)
185808        );
185809      }
185810
185811      if( rc==SQLITE_OK ){
185812        pLvl->nSeg = nTotal;
185813        for(iSeg=0; iSeg<nTotal; iSeg++){
185814          if( i>=nData ){
185815            rc = FTS5_CORRUPT;
185816            break;
185817          }
185818          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
185819          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
185820          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
185821        }
185822      }
185823    }
185824    if( rc!=SQLITE_OK ){
185825      fts5StructureRelease(pRet);
185826      pRet = 0;
185827    }
185828  }
185829
185830  *ppOut = pRet;
185831  return rc;
185832}
185833
185834/*
185835**
185836*/
185837static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
185838  if( *pRc==SQLITE_OK ){
185839    Fts5Structure *pStruct = *ppStruct;
185840    int nLevel = pStruct->nLevel;
185841    int nByte = (
185842        sizeof(Fts5Structure) +                  /* Main structure */
185843        sizeof(Fts5StructureLevel) * (nLevel+1)  /* aLevel[] array */
185844    );
185845
185846    pStruct = sqlite3_realloc(pStruct, nByte);
185847    if( pStruct ){
185848      memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
185849      pStruct->nLevel++;
185850      *ppStruct = pStruct;
185851    }else{
185852      *pRc = SQLITE_NOMEM;
185853    }
185854  }
185855}
185856
185857/*
185858** Extend level iLvl so that there is room for at least nExtra more
185859** segments.
185860*/
185861static void fts5StructureExtendLevel(
185862  int *pRc,
185863  Fts5Structure *pStruct,
185864  int iLvl,
185865  int nExtra,
185866  int bInsert
185867){
185868  if( *pRc==SQLITE_OK ){
185869    Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
185870    Fts5StructureSegment *aNew;
185871    int nByte;
185872
185873    nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
185874    aNew = sqlite3_realloc(pLvl->aSeg, nByte);
185875    if( aNew ){
185876      if( bInsert==0 ){
185877        memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
185878      }else{
185879        int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
185880        memmove(&aNew[nExtra], aNew, nMove);
185881        memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
185882      }
185883      pLvl->aSeg = aNew;
185884    }else{
185885      *pRc = SQLITE_NOMEM;
185886    }
185887  }
185888}
185889
185890static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
185891  Fts5Structure *pRet = 0;
185892  Fts5Config *pConfig = p->pConfig;
185893  int iCookie;                    /* Configuration cookie */
185894  Fts5Data *pData;
185895
185896  pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
185897  if( p->rc==SQLITE_OK ){
185898    /* TODO: Do we need this if the leaf-index is appended? Probably... */
185899    memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
185900    p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
185901    if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
185902      p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
185903    }
185904    fts5DataRelease(pData);
185905    if( p->rc!=SQLITE_OK ){
185906      fts5StructureRelease(pRet);
185907      pRet = 0;
185908    }
185909  }
185910
185911  return pRet;
185912}
185913
185914static i64 fts5IndexDataVersion(Fts5Index *p){
185915  i64 iVersion = 0;
185916
185917  if( p->rc==SQLITE_OK ){
185918    if( p->pDataVersion==0 ){
185919      p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
185920          sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
185921          );
185922      if( p->rc ) return 0;
185923    }
185924
185925    if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
185926      iVersion = sqlite3_column_int64(p->pDataVersion, 0);
185927    }
185928    p->rc = sqlite3_reset(p->pDataVersion);
185929  }
185930
185931  return iVersion;
185932}
185933
185934/*
185935** Read, deserialize and return the structure record.
185936**
185937** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
185938** are over-allocated as described for function fts5StructureDecode()
185939** above.
185940**
185941** If an error occurs, NULL is returned and an error code left in the
185942** Fts5Index handle. If an error has already occurred when this function
185943** is called, it is a no-op.
185944*/
185945static Fts5Structure *fts5StructureRead(Fts5Index *p){
185946
185947  if( p->pStruct==0 ){
185948    p->iStructVersion = fts5IndexDataVersion(p);
185949    if( p->rc==SQLITE_OK ){
185950      p->pStruct = fts5StructureReadUncached(p);
185951    }
185952  }
185953
185954#if 0
185955  else{
185956    Fts5Structure *pTest = fts5StructureReadUncached(p);
185957    if( pTest ){
185958      int i, j;
185959      assert_nc( p->pStruct->nSegment==pTest->nSegment );
185960      assert_nc( p->pStruct->nLevel==pTest->nLevel );
185961      for(i=0; i<pTest->nLevel; i++){
185962        assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
185963        assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
185964        for(j=0; j<pTest->aLevel[i].nSeg; j++){
185965          Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
185966          Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
185967          assert_nc( p1->iSegid==p2->iSegid );
185968          assert_nc( p1->pgnoFirst==p2->pgnoFirst );
185969          assert_nc( p1->pgnoLast==p2->pgnoLast );
185970        }
185971      }
185972      fts5StructureRelease(pTest);
185973    }
185974  }
185975#endif
185976
185977  if( p->rc!=SQLITE_OK ) return 0;
185978  assert( p->iStructVersion!=0 );
185979  assert( p->pStruct!=0 );
185980  fts5StructureRef(p->pStruct);
185981  return p->pStruct;
185982}
185983
185984static void fts5StructureInvalidate(Fts5Index *p){
185985  if( p->pStruct ){
185986    fts5StructureRelease(p->pStruct);
185987    p->pStruct = 0;
185988  }
185989}
185990
185991/*
185992** Return the total number of segments in index structure pStruct. This
185993** function is only ever used as part of assert() conditions.
185994*/
185995#ifdef SQLITE_DEBUG
185996static int fts5StructureCountSegments(Fts5Structure *pStruct){
185997  int nSegment = 0;               /* Total number of segments */
185998  if( pStruct ){
185999    int iLvl;                     /* Used to iterate through levels */
186000    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
186001      nSegment += pStruct->aLevel[iLvl].nSeg;
186002    }
186003  }
186004
186005  return nSegment;
186006}
186007#endif
186008
186009#define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) {     \
186010  assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) );             \
186011  memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob);             \
186012  (pBuf)->n += nBlob;                                      \
186013}
186014
186015#define fts5BufferSafeAppendVarint(pBuf, iVal) {                \
186016  (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal));  \
186017  assert( (pBuf)->nSpace>=(pBuf)->n );                          \
186018}
186019
186020
186021/*
186022** Serialize and store the "structure" record.
186023**
186024** If an error occurs, leave an error code in the Fts5Index object. If an
186025** error has already occurred, this function is a no-op.
186026*/
186027static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
186028  if( p->rc==SQLITE_OK ){
186029    Fts5Buffer buf;               /* Buffer to serialize record into */
186030    int iLvl;                     /* Used to iterate through levels */
186031    int iCookie;                  /* Cookie value to store */
186032
186033    assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
186034    memset(&buf, 0, sizeof(Fts5Buffer));
186035
186036    /* Append the current configuration cookie */
186037    iCookie = p->pConfig->iCookie;
186038    if( iCookie<0 ) iCookie = 0;
186039
186040    if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
186041      sqlite3Fts5Put32(buf.p, iCookie);
186042      buf.n = 4;
186043      fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
186044      fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
186045      fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
186046    }
186047
186048    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
186049      int iSeg;                     /* Used to iterate through segments */
186050      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
186051      fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
186052      fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
186053      assert( pLvl->nMerge<=pLvl->nSeg );
186054
186055      for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
186056        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
186057        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
186058        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
186059      }
186060    }
186061
186062    fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
186063    fts5BufferFree(&buf);
186064  }
186065}
186066
186067#if 0
186068static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
186069static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
186070  int rc = SQLITE_OK;
186071  Fts5Buffer buf;
186072  memset(&buf, 0, sizeof(buf));
186073  fts5DebugStructure(&rc, &buf, pStruct);
186074  fprintf(stdout, "%s: %s\n", zCaption, buf.p);
186075  fflush(stdout);
186076  fts5BufferFree(&buf);
186077}
186078#else
186079# define fts5PrintStructure(x,y)
186080#endif
186081
186082static int fts5SegmentSize(Fts5StructureSegment *pSeg){
186083  return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
186084}
186085
186086/*
186087** Return a copy of index structure pStruct. Except, promote as many
186088** segments as possible to level iPromote. If an OOM occurs, NULL is
186089** returned.
186090*/
186091static void fts5StructurePromoteTo(
186092  Fts5Index *p,
186093  int iPromote,
186094  int szPromote,
186095  Fts5Structure *pStruct
186096){
186097  int il, is;
186098  Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
186099
186100  if( pOut->nMerge==0 ){
186101    for(il=iPromote+1; il<pStruct->nLevel; il++){
186102      Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
186103      if( pLvl->nMerge ) return;
186104      for(is=pLvl->nSeg-1; is>=0; is--){
186105        int sz = fts5SegmentSize(&pLvl->aSeg[is]);
186106        if( sz>szPromote ) return;
186107        fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
186108        if( p->rc ) return;
186109        memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
186110        pOut->nSeg++;
186111        pLvl->nSeg--;
186112      }
186113    }
186114  }
186115}
186116
186117/*
186118** A new segment has just been written to level iLvl of index structure
186119** pStruct. This function determines if any segments should be promoted
186120** as a result. Segments are promoted in two scenarios:
186121**
186122**   a) If the segment just written is smaller than one or more segments
186123**      within the previous populated level, it is promoted to the previous
186124**      populated level.
186125**
186126**   b) If the segment just written is larger than the newest segment on
186127**      the next populated level, then that segment, and any other adjacent
186128**      segments that are also smaller than the one just written, are
186129**      promoted.
186130**
186131** If one or more segments are promoted, the structure object is updated
186132** to reflect this.
186133*/
186134static void fts5StructurePromote(
186135  Fts5Index *p,                   /* FTS5 backend object */
186136  int iLvl,                       /* Index level just updated */
186137  Fts5Structure *pStruct          /* Index structure */
186138){
186139  if( p->rc==SQLITE_OK ){
186140    int iTst;
186141    int iPromote = -1;
186142    int szPromote = 0;            /* Promote anything this size or smaller */
186143    Fts5StructureSegment *pSeg;   /* Segment just written */
186144    int szSeg;                    /* Size of segment just written */
186145    int nSeg = pStruct->aLevel[iLvl].nSeg;
186146
186147    if( nSeg==0 ) return;
186148    pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
186149    szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
186150
186151    /* Check for condition (a) */
186152    for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
186153    if( iTst>=0 ){
186154      int i;
186155      int szMax = 0;
186156      Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
186157      assert( pTst->nMerge==0 );
186158      for(i=0; i<pTst->nSeg; i++){
186159        int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
186160        if( sz>szMax ) szMax = sz;
186161      }
186162      if( szMax>=szSeg ){
186163        /* Condition (a) is true. Promote the newest segment on level
186164        ** iLvl to level iTst.  */
186165        iPromote = iTst;
186166        szPromote = szMax;
186167      }
186168    }
186169
186170    /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
186171    ** is a no-op if it is not.  */
186172    if( iPromote<0 ){
186173      iPromote = iLvl;
186174      szPromote = szSeg;
186175    }
186176    fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
186177  }
186178}
186179
186180
186181/*
186182** Advance the iterator passed as the only argument. If the end of the
186183** doclist-index page is reached, return non-zero.
186184*/
186185static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
186186  Fts5Data *pData = pLvl->pData;
186187
186188  if( pLvl->iOff==0 ){
186189    assert( pLvl->bEof==0 );
186190    pLvl->iOff = 1;
186191    pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
186192    pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
186193    pLvl->iFirstOff = pLvl->iOff;
186194  }else{
186195    int iOff;
186196    for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
186197      if( pData->p[iOff] ) break;
186198    }
186199
186200    if( iOff<pData->nn ){
186201      i64 iVal;
186202      pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
186203      iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
186204      pLvl->iRowid += iVal;
186205      pLvl->iOff = iOff;
186206    }else{
186207      pLvl->bEof = 1;
186208    }
186209  }
186210
186211  return pLvl->bEof;
186212}
186213
186214/*
186215** Advance the iterator passed as the only argument.
186216*/
186217static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
186218  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
186219
186220  assert( iLvl<pIter->nLvl );
186221  if( fts5DlidxLvlNext(pLvl) ){
186222    if( (iLvl+1) < pIter->nLvl ){
186223      fts5DlidxIterNextR(p, pIter, iLvl+1);
186224      if( pLvl[1].bEof==0 ){
186225        fts5DataRelease(pLvl->pData);
186226        memset(pLvl, 0, sizeof(Fts5DlidxLvl));
186227        pLvl->pData = fts5DataRead(p,
186228            FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
186229        );
186230        if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
186231      }
186232    }
186233  }
186234
186235  return pIter->aLvl[0].bEof;
186236}
186237static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
186238  return fts5DlidxIterNextR(p, pIter, 0);
186239}
186240
186241/*
186242** The iterator passed as the first argument has the following fields set
186243** as follows. This function sets up the rest of the iterator so that it
186244** points to the first rowid in the doclist-index.
186245**
186246**   pData:
186247**     pointer to doclist-index record,
186248**
186249** When this function is called pIter->iLeafPgno is the page number the
186250** doclist is associated with (the one featuring the term).
186251*/
186252static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
186253  int i;
186254  for(i=0; i<pIter->nLvl; i++){
186255    fts5DlidxLvlNext(&pIter->aLvl[i]);
186256  }
186257  return pIter->aLvl[0].bEof;
186258}
186259
186260
186261static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
186262  return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
186263}
186264
186265static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
186266  int i;
186267
186268  /* Advance each level to the last entry on the last page */
186269  for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
186270    Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
186271    while( fts5DlidxLvlNext(pLvl)==0 );
186272    pLvl->bEof = 0;
186273
186274    if( i>0 ){
186275      Fts5DlidxLvl *pChild = &pLvl[-1];
186276      fts5DataRelease(pChild->pData);
186277      memset(pChild, 0, sizeof(Fts5DlidxLvl));
186278      pChild->pData = fts5DataRead(p,
186279          FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
186280      );
186281    }
186282  }
186283}
186284
186285/*
186286** Move the iterator passed as the only argument to the previous entry.
186287*/
186288static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
186289  int iOff = pLvl->iOff;
186290
186291  assert( pLvl->bEof==0 );
186292  if( iOff<=pLvl->iFirstOff ){
186293    pLvl->bEof = 1;
186294  }else{
186295    u8 *a = pLvl->pData->p;
186296    i64 iVal;
186297    int iLimit;
186298    int ii;
186299    int nZero = 0;
186300
186301    /* Currently iOff points to the first byte of a varint. This block
186302    ** decrements iOff until it points to the first byte of the previous
186303    ** varint. Taking care not to read any memory locations that occur
186304    ** before the buffer in memory.  */
186305    iLimit = (iOff>9 ? iOff-9 : 0);
186306    for(iOff--; iOff>iLimit; iOff--){
186307      if( (a[iOff-1] & 0x80)==0 ) break;
186308    }
186309
186310    fts5GetVarint(&a[iOff], (u64*)&iVal);
186311    pLvl->iRowid -= iVal;
186312    pLvl->iLeafPgno--;
186313
186314    /* Skip backwards past any 0x00 varints. */
186315    for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
186316      nZero++;
186317    }
186318    if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
186319      /* The byte immediately before the last 0x00 byte has the 0x80 bit
186320      ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
186321      ** bytes before a[ii]. */
186322      int bZero = 0;              /* True if last 0x00 counts */
186323      if( (ii-8)>=pLvl->iFirstOff ){
186324        int j;
186325        for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
186326        bZero = (j>8);
186327      }
186328      if( bZero==0 ) nZero--;
186329    }
186330    pLvl->iLeafPgno -= nZero;
186331    pLvl->iOff = iOff - nZero;
186332  }
186333
186334  return pLvl->bEof;
186335}
186336
186337static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
186338  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
186339
186340  assert( iLvl<pIter->nLvl );
186341  if( fts5DlidxLvlPrev(pLvl) ){
186342    if( (iLvl+1) < pIter->nLvl ){
186343      fts5DlidxIterPrevR(p, pIter, iLvl+1);
186344      if( pLvl[1].bEof==0 ){
186345        fts5DataRelease(pLvl->pData);
186346        memset(pLvl, 0, sizeof(Fts5DlidxLvl));
186347        pLvl->pData = fts5DataRead(p,
186348            FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
186349        );
186350        if( pLvl->pData ){
186351          while( fts5DlidxLvlNext(pLvl)==0 );
186352          pLvl->bEof = 0;
186353        }
186354      }
186355    }
186356  }
186357
186358  return pIter->aLvl[0].bEof;
186359}
186360static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
186361  return fts5DlidxIterPrevR(p, pIter, 0);
186362}
186363
186364/*
186365** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
186366*/
186367static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
186368  if( pIter ){
186369    int i;
186370    for(i=0; i<pIter->nLvl; i++){
186371      fts5DataRelease(pIter->aLvl[i].pData);
186372    }
186373    sqlite3_free(pIter);
186374  }
186375}
186376
186377static Fts5DlidxIter *fts5DlidxIterInit(
186378  Fts5Index *p,                   /* Fts5 Backend to iterate within */
186379  int bRev,                       /* True for ORDER BY ASC */
186380  int iSegid,                     /* Segment id */
186381  int iLeafPg                     /* Leaf page number to load dlidx for */
186382){
186383  Fts5DlidxIter *pIter = 0;
186384  int i;
186385  int bDone = 0;
186386
186387  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
186388    int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
186389    Fts5DlidxIter *pNew;
186390
186391    pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
186392    if( pNew==0 ){
186393      p->rc = SQLITE_NOMEM;
186394    }else{
186395      i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
186396      Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
186397      pIter = pNew;
186398      memset(pLvl, 0, sizeof(Fts5DlidxLvl));
186399      pLvl->pData = fts5DataRead(p, iRowid);
186400      if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
186401        bDone = 1;
186402      }
186403      pIter->nLvl = i+1;
186404    }
186405  }
186406
186407  if( p->rc==SQLITE_OK ){
186408    pIter->iSegid = iSegid;
186409    if( bRev==0 ){
186410      fts5DlidxIterFirst(pIter);
186411    }else{
186412      fts5DlidxIterLast(p, pIter);
186413    }
186414  }
186415
186416  if( p->rc!=SQLITE_OK ){
186417    fts5DlidxIterFree(pIter);
186418    pIter = 0;
186419  }
186420
186421  return pIter;
186422}
186423
186424static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
186425  return pIter->aLvl[0].iRowid;
186426}
186427static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
186428  return pIter->aLvl[0].iLeafPgno;
186429}
186430
186431/*
186432** Load the next leaf page into the segment iterator.
186433*/
186434static void fts5SegIterNextPage(
186435  Fts5Index *p,                   /* FTS5 backend object */
186436  Fts5SegIter *pIter              /* Iterator to advance to next page */
186437){
186438  Fts5Data *pLeaf;
186439  Fts5StructureSegment *pSeg = pIter->pSeg;
186440  fts5DataRelease(pIter->pLeaf);
186441  pIter->iLeafPgno++;
186442  if( pIter->pNextLeaf ){
186443    pIter->pLeaf = pIter->pNextLeaf;
186444    pIter->pNextLeaf = 0;
186445  }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
186446    pIter->pLeaf = fts5DataRead(p,
186447        FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
186448    );
186449  }else{
186450    pIter->pLeaf = 0;
186451  }
186452  pLeaf = pIter->pLeaf;
186453
186454  if( pLeaf ){
186455    pIter->iPgidxOff = pLeaf->szLeaf;
186456    if( fts5LeafIsTermless(pLeaf) ){
186457      pIter->iEndofDoclist = pLeaf->nn+1;
186458    }else{
186459      pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
186460          pIter->iEndofDoclist
186461      );
186462    }
186463  }
186464}
186465
186466/*
186467** Argument p points to a buffer containing a varint to be interpreted as a
186468** position list size field. Read the varint and return the number of bytes
186469** read. Before returning, set *pnSz to the number of bytes in the position
186470** list, and *pbDel to true if the delete flag is set, or false otherwise.
186471*/
186472static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
186473  int nSz;
186474  int n = 0;
186475  fts5FastGetVarint32(p, n, nSz);
186476  assert_nc( nSz>=0 );
186477  *pnSz = nSz/2;
186478  *pbDel = nSz & 0x0001;
186479  return n;
186480}
186481
186482/*
186483** Fts5SegIter.iLeafOffset currently points to the first byte of a
186484** position-list size field. Read the value of the field and store it
186485** in the following variables:
186486**
186487**   Fts5SegIter.nPos
186488**   Fts5SegIter.bDel
186489**
186490** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
186491** position list content (if any).
186492*/
186493static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
186494  if( p->rc==SQLITE_OK ){
186495    int iOff = pIter->iLeafOffset;  /* Offset to read at */
186496    ASSERT_SZLEAF_OK(pIter->pLeaf);
186497    if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
186498      int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
186499      pIter->bDel = 0;
186500      pIter->nPos = 1;
186501      if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
186502        pIter->bDel = 1;
186503        iOff++;
186504        if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
186505          pIter->nPos = 1;
186506          iOff++;
186507        }else{
186508          pIter->nPos = 0;
186509        }
186510      }
186511    }else{
186512      int nSz;
186513      fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
186514      pIter->bDel = (nSz & 0x0001);
186515      pIter->nPos = nSz>>1;
186516      assert_nc( pIter->nPos>=0 );
186517    }
186518    pIter->iLeafOffset = iOff;
186519  }
186520}
186521
186522static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
186523  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
186524  int iOff = pIter->iLeafOffset;
186525
186526  ASSERT_SZLEAF_OK(pIter->pLeaf);
186527  if( iOff>=pIter->pLeaf->szLeaf ){
186528    fts5SegIterNextPage(p, pIter);
186529    if( pIter->pLeaf==0 ){
186530      if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
186531      return;
186532    }
186533    iOff = 4;
186534    a = pIter->pLeaf->p;
186535  }
186536  iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
186537  pIter->iLeafOffset = iOff;
186538}
186539
186540/*
186541** Fts5SegIter.iLeafOffset currently points to the first byte of the
186542** "nSuffix" field of a term. Function parameter nKeep contains the value
186543** of the "nPrefix" field (if there was one - it is passed 0 if this is
186544** the first term in the segment).
186545**
186546** This function populates:
186547**
186548**   Fts5SegIter.term
186549**   Fts5SegIter.rowid
186550**
186551** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
186552** the first position list. The position list belonging to document
186553** (Fts5SegIter.iRowid).
186554*/
186555static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
186556  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
186557  int iOff = pIter->iLeafOffset;  /* Offset to read at */
186558  int nNew;                       /* Bytes of new data */
186559
186560  iOff += fts5GetVarint32(&a[iOff], nNew);
186561  if( iOff+nNew>pIter->pLeaf->nn ){
186562    p->rc = FTS5_CORRUPT;
186563    return;
186564  }
186565  pIter->term.n = nKeep;
186566  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
186567  iOff += nNew;
186568  pIter->iTermLeafOffset = iOff;
186569  pIter->iTermLeafPgno = pIter->iLeafPgno;
186570  pIter->iLeafOffset = iOff;
186571
186572  if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
186573    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
186574  }else{
186575    int nExtra;
186576    pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
186577    pIter->iEndofDoclist += nExtra;
186578  }
186579
186580  fts5SegIterLoadRowid(p, pIter);
186581}
186582
186583static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
186584static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
186585static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
186586
186587static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
186588  if( pIter->flags & FTS5_SEGITER_REVERSE ){
186589    pIter->xNext = fts5SegIterNext_Reverse;
186590  }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
186591    pIter->xNext = fts5SegIterNext_None;
186592  }else{
186593    pIter->xNext = fts5SegIterNext;
186594  }
186595}
186596
186597/*
186598** Initialize the iterator object pIter to iterate through the entries in
186599** segment pSeg. The iterator is left pointing to the first entry when
186600** this function returns.
186601**
186602** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
186603** an error has already occurred when this function is called, it is a no-op.
186604*/
186605static void fts5SegIterInit(
186606  Fts5Index *p,                   /* FTS index object */
186607  Fts5StructureSegment *pSeg,     /* Description of segment */
186608  Fts5SegIter *pIter              /* Object to populate */
186609){
186610  if( pSeg->pgnoFirst==0 ){
186611    /* This happens if the segment is being used as an input to an incremental
186612    ** merge and all data has already been "trimmed". See function
186613    ** fts5TrimSegments() for details. In this case leave the iterator empty.
186614    ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
186615    ** at EOF already. */
186616    assert( pIter->pLeaf==0 );
186617    return;
186618  }
186619
186620  if( p->rc==SQLITE_OK ){
186621    memset(pIter, 0, sizeof(*pIter));
186622    fts5SegIterSetNext(p, pIter);
186623    pIter->pSeg = pSeg;
186624    pIter->iLeafPgno = pSeg->pgnoFirst-1;
186625    fts5SegIterNextPage(p, pIter);
186626  }
186627
186628  if( p->rc==SQLITE_OK ){
186629    pIter->iLeafOffset = 4;
186630    assert_nc( pIter->pLeaf->nn>4 );
186631    assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
186632    pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
186633    fts5SegIterLoadTerm(p, pIter, 0);
186634    fts5SegIterLoadNPos(p, pIter);
186635  }
186636}
186637
186638/*
186639** This function is only ever called on iterators created by calls to
186640** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
186641**
186642** The iterator is in an unusual state when this function is called: the
186643** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
186644** the position-list size field for the first relevant rowid on the page.
186645** Fts5SegIter.rowid is set, but nPos and bDel are not.
186646**
186647** This function advances the iterator so that it points to the last
186648** relevant rowid on the page and, if necessary, initializes the
186649** aRowidOffset[] and iRowidOffset variables. At this point the iterator
186650** is in its regular state - Fts5SegIter.iLeafOffset points to the first
186651** byte of the position list content associated with said rowid.
186652*/
186653static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
186654  int eDetail = p->pConfig->eDetail;
186655  int n = pIter->pLeaf->szLeaf;
186656  int i = pIter->iLeafOffset;
186657  u8 *a = pIter->pLeaf->p;
186658  int iRowidOffset = 0;
186659
186660  if( n>pIter->iEndofDoclist ){
186661    n = pIter->iEndofDoclist;
186662  }
186663
186664  ASSERT_SZLEAF_OK(pIter->pLeaf);
186665  while( 1 ){
186666    i64 iDelta = 0;
186667
186668    if( eDetail==FTS5_DETAIL_NONE ){
186669      /* todo */
186670      if( i<n && a[i]==0 ){
186671        i++;
186672        if( i<n && a[i]==0 ) i++;
186673      }
186674    }else{
186675      int nPos;
186676      int bDummy;
186677      i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
186678      i += nPos;
186679    }
186680    if( i>=n ) break;
186681    i += fts5GetVarint(&a[i], (u64*)&iDelta);
186682    pIter->iRowid += iDelta;
186683
186684    /* If necessary, grow the pIter->aRowidOffset[] array. */
186685    if( iRowidOffset>=pIter->nRowidOffset ){
186686      int nNew = pIter->nRowidOffset + 8;
186687      int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
186688      if( aNew==0 ){
186689        p->rc = SQLITE_NOMEM;
186690        break;
186691      }
186692      pIter->aRowidOffset = aNew;
186693      pIter->nRowidOffset = nNew;
186694    }
186695
186696    pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
186697    pIter->iLeafOffset = i;
186698  }
186699  pIter->iRowidOffset = iRowidOffset;
186700  fts5SegIterLoadNPos(p, pIter);
186701}
186702
186703/*
186704**
186705*/
186706static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
186707  assert( pIter->flags & FTS5_SEGITER_REVERSE );
186708  assert( pIter->flags & FTS5_SEGITER_ONETERM );
186709
186710  fts5DataRelease(pIter->pLeaf);
186711  pIter->pLeaf = 0;
186712  while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
186713    Fts5Data *pNew;
186714    pIter->iLeafPgno--;
186715    pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
186716          pIter->pSeg->iSegid, pIter->iLeafPgno
186717    ));
186718    if( pNew ){
186719      /* iTermLeafOffset may be equal to szLeaf if the term is the last
186720      ** thing on the page - i.e. the first rowid is on the following page.
186721      ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
186722      if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
186723        assert( pIter->pLeaf==0 );
186724        if( pIter->iTermLeafOffset<pNew->szLeaf ){
186725          pIter->pLeaf = pNew;
186726          pIter->iLeafOffset = pIter->iTermLeafOffset;
186727        }
186728      }else{
186729        int iRowidOff;
186730        iRowidOff = fts5LeafFirstRowidOff(pNew);
186731        if( iRowidOff ){
186732          pIter->pLeaf = pNew;
186733          pIter->iLeafOffset = iRowidOff;
186734        }
186735      }
186736
186737      if( pIter->pLeaf ){
186738        u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
186739        pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
186740        break;
186741      }else{
186742        fts5DataRelease(pNew);
186743      }
186744    }
186745  }
186746
186747  if( pIter->pLeaf ){
186748    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
186749    fts5SegIterReverseInitPage(p, pIter);
186750  }
186751}
186752
186753/*
186754** Return true if the iterator passed as the second argument currently
186755** points to a delete marker. A delete marker is an entry with a 0 byte
186756** position-list.
186757*/
186758static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
186759  Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
186760  return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
186761}
186762
186763/*
186764** Advance iterator pIter to the next entry.
186765**
186766** This version of fts5SegIterNext() is only used by reverse iterators.
186767*/
186768static void fts5SegIterNext_Reverse(
186769  Fts5Index *p,                   /* FTS5 backend object */
186770  Fts5SegIter *pIter,             /* Iterator to advance */
186771  int *pbUnused                   /* Unused */
186772){
186773  assert( pIter->flags & FTS5_SEGITER_REVERSE );
186774  assert( pIter->pNextLeaf==0 );
186775  UNUSED_PARAM(pbUnused);
186776
186777  if( pIter->iRowidOffset>0 ){
186778    u8 *a = pIter->pLeaf->p;
186779    int iOff;
186780    i64 iDelta;
186781
186782    pIter->iRowidOffset--;
186783    pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
186784    fts5SegIterLoadNPos(p, pIter);
186785    iOff = pIter->iLeafOffset;
186786    if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
186787      iOff += pIter->nPos;
186788    }
186789    fts5GetVarint(&a[iOff], (u64*)&iDelta);
186790    pIter->iRowid -= iDelta;
186791  }else{
186792    fts5SegIterReverseNewPage(p, pIter);
186793  }
186794}
186795
186796/*
186797** Advance iterator pIter to the next entry.
186798**
186799** This version of fts5SegIterNext() is only used if detail=none and the
186800** iterator is not a reverse direction iterator.
186801*/
186802static void fts5SegIterNext_None(
186803  Fts5Index *p,                   /* FTS5 backend object */
186804  Fts5SegIter *pIter,             /* Iterator to advance */
186805  int *pbNewTerm                  /* OUT: Set for new term */
186806){
186807  int iOff;
186808
186809  assert( p->rc==SQLITE_OK );
186810  assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
186811  assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
186812
186813  ASSERT_SZLEAF_OK(pIter->pLeaf);
186814  iOff = pIter->iLeafOffset;
186815
186816  /* Next entry is on the next page */
186817  if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
186818    fts5SegIterNextPage(p, pIter);
186819    if( p->rc || pIter->pLeaf==0 ) return;
186820    pIter->iRowid = 0;
186821    iOff = 4;
186822  }
186823
186824  if( iOff<pIter->iEndofDoclist ){
186825    /* Next entry is on the current page */
186826    i64 iDelta;
186827    iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
186828    pIter->iLeafOffset = iOff;
186829    pIter->iRowid += iDelta;
186830  }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
186831    if( pIter->pSeg ){
186832      int nKeep = 0;
186833      if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
186834        iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
186835      }
186836      pIter->iLeafOffset = iOff;
186837      fts5SegIterLoadTerm(p, pIter, nKeep);
186838    }else{
186839      const u8 *pList = 0;
186840      const char *zTerm = 0;
186841      int nList;
186842      sqlite3Fts5HashScanNext(p->pHash);
186843      sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
186844      if( pList==0 ) goto next_none_eof;
186845      pIter->pLeaf->p = (u8*)pList;
186846      pIter->pLeaf->nn = nList;
186847      pIter->pLeaf->szLeaf = nList;
186848      pIter->iEndofDoclist = nList;
186849      sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
186850      pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
186851    }
186852
186853    if( pbNewTerm ) *pbNewTerm = 1;
186854  }else{
186855    goto next_none_eof;
186856  }
186857
186858  fts5SegIterLoadNPos(p, pIter);
186859
186860  return;
186861 next_none_eof:
186862  fts5DataRelease(pIter->pLeaf);
186863  pIter->pLeaf = 0;
186864}
186865
186866
186867/*
186868** Advance iterator pIter to the next entry.
186869**
186870** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
186871** is not considered an error if the iterator reaches EOF. If an error has
186872** already occurred when this function is called, it is a no-op.
186873*/
186874static void fts5SegIterNext(
186875  Fts5Index *p,                   /* FTS5 backend object */
186876  Fts5SegIter *pIter,             /* Iterator to advance */
186877  int *pbNewTerm                  /* OUT: Set for new term */
186878){
186879  Fts5Data *pLeaf = pIter->pLeaf;
186880  int iOff;
186881  int bNewTerm = 0;
186882  int nKeep = 0;
186883  u8 *a;
186884  int n;
186885
186886  assert( pbNewTerm==0 || *pbNewTerm==0 );
186887  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
186888
186889  /* Search for the end of the position list within the current page. */
186890  a = pLeaf->p;
186891  n = pLeaf->szLeaf;
186892
186893  ASSERT_SZLEAF_OK(pLeaf);
186894  iOff = pIter->iLeafOffset + pIter->nPos;
186895
186896  if( iOff<n ){
186897    /* The next entry is on the current page. */
186898    assert_nc( iOff<=pIter->iEndofDoclist );
186899    if( iOff>=pIter->iEndofDoclist ){
186900      bNewTerm = 1;
186901      if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
186902        iOff += fts5GetVarint32(&a[iOff], nKeep);
186903      }
186904    }else{
186905      u64 iDelta;
186906      iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
186907      pIter->iRowid += iDelta;
186908      assert_nc( iDelta>0 );
186909    }
186910    pIter->iLeafOffset = iOff;
186911
186912  }else if( pIter->pSeg==0 ){
186913    const u8 *pList = 0;
186914    const char *zTerm = 0;
186915    int nList = 0;
186916    assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
186917    if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
186918      sqlite3Fts5HashScanNext(p->pHash);
186919      sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
186920    }
186921    if( pList==0 ){
186922      fts5DataRelease(pIter->pLeaf);
186923      pIter->pLeaf = 0;
186924    }else{
186925      pIter->pLeaf->p = (u8*)pList;
186926      pIter->pLeaf->nn = nList;
186927      pIter->pLeaf->szLeaf = nList;
186928      pIter->iEndofDoclist = nList+1;
186929      sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
186930          (u8*)zTerm);
186931      pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
186932      *pbNewTerm = 1;
186933    }
186934  }else{
186935    iOff = 0;
186936    /* Next entry is not on the current page */
186937    while( iOff==0 ){
186938      fts5SegIterNextPage(p, pIter);
186939      pLeaf = pIter->pLeaf;
186940      if( pLeaf==0 ) break;
186941      ASSERT_SZLEAF_OK(pLeaf);
186942      if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
186943        iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
186944        pIter->iLeafOffset = iOff;
186945
186946        if( pLeaf->nn>pLeaf->szLeaf ){
186947          pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
186948              &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
186949              );
186950        }
186951
186952      }
186953      else if( pLeaf->nn>pLeaf->szLeaf ){
186954        pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
186955            &pLeaf->p[pLeaf->szLeaf], iOff
186956            );
186957        pIter->iLeafOffset = iOff;
186958        pIter->iEndofDoclist = iOff;
186959        bNewTerm = 1;
186960      }
186961      assert_nc( iOff<pLeaf->szLeaf );
186962      if( iOff>pLeaf->szLeaf ){
186963        p->rc = FTS5_CORRUPT;
186964        return;
186965      }
186966    }
186967  }
186968
186969  /* Check if the iterator is now at EOF. If so, return early. */
186970  if( pIter->pLeaf ){
186971    if( bNewTerm ){
186972      if( pIter->flags & FTS5_SEGITER_ONETERM ){
186973        fts5DataRelease(pIter->pLeaf);
186974        pIter->pLeaf = 0;
186975      }else{
186976        fts5SegIterLoadTerm(p, pIter, nKeep);
186977        fts5SegIterLoadNPos(p, pIter);
186978        if( pbNewTerm ) *pbNewTerm = 1;
186979      }
186980    }else{
186981      /* The following could be done by calling fts5SegIterLoadNPos(). But
186982      ** this block is particularly performance critical, so equivalent
186983      ** code is inlined.
186984      **
186985      ** Later: Switched back to fts5SegIterLoadNPos() because it supports
186986      ** detail=none mode. Not ideal.
186987      */
186988      int nSz;
186989      assert( p->rc==SQLITE_OK );
186990      fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
186991      pIter->bDel = (nSz & 0x0001);
186992      pIter->nPos = nSz>>1;
186993      assert_nc( pIter->nPos>=0 );
186994    }
186995  }
186996}
186997
186998#define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
186999
187000#define fts5IndexSkipVarint(a, iOff) {            \
187001  int iEnd = iOff+9;                              \
187002  while( (a[iOff++] & 0x80) && iOff<iEnd );       \
187003}
187004
187005/*
187006** Iterator pIter currently points to the first rowid in a doclist. This
187007** function sets the iterator up so that iterates in reverse order through
187008** the doclist.
187009*/
187010static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
187011  Fts5DlidxIter *pDlidx = pIter->pDlidx;
187012  Fts5Data *pLast = 0;
187013  int pgnoLast = 0;
187014
187015  if( pDlidx ){
187016    int iSegid = pIter->pSeg->iSegid;
187017    pgnoLast = fts5DlidxIterPgno(pDlidx);
187018    pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
187019  }else{
187020    Fts5Data *pLeaf = pIter->pLeaf;         /* Current leaf data */
187021
187022    /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
187023    ** position-list content for the current rowid. Back it up so that it
187024    ** points to the start of the position-list size field. */
187025    int iPoslist;
187026    if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
187027      iPoslist = pIter->iTermLeafOffset;
187028    }else{
187029      iPoslist = 4;
187030    }
187031    fts5IndexSkipVarint(pLeaf->p, iPoslist);
187032    pIter->iLeafOffset = iPoslist;
187033
187034    /* If this condition is true then the largest rowid for the current
187035    ** term may not be stored on the current page. So search forward to
187036    ** see where said rowid really is.  */
187037    if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
187038      int pgno;
187039      Fts5StructureSegment *pSeg = pIter->pSeg;
187040
187041      /* The last rowid in the doclist may not be on the current page. Search
187042      ** forward to find the page containing the last rowid.  */
187043      for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
187044        i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
187045        Fts5Data *pNew = fts5DataRead(p, iAbs);
187046        if( pNew ){
187047          int iRowid, bTermless;
187048          iRowid = fts5LeafFirstRowidOff(pNew);
187049          bTermless = fts5LeafIsTermless(pNew);
187050          if( iRowid ){
187051            SWAPVAL(Fts5Data*, pNew, pLast);
187052            pgnoLast = pgno;
187053          }
187054          fts5DataRelease(pNew);
187055          if( bTermless==0 ) break;
187056        }
187057      }
187058    }
187059  }
187060
187061  /* If pLast is NULL at this point, then the last rowid for this doclist
187062  ** lies on the page currently indicated by the iterator. In this case
187063  ** pIter->iLeafOffset is already set to point to the position-list size
187064  ** field associated with the first relevant rowid on the page.
187065  **
187066  ** Or, if pLast is non-NULL, then it is the page that contains the last
187067  ** rowid. In this case configure the iterator so that it points to the
187068  ** first rowid on this page.
187069  */
187070  if( pLast ){
187071    int iOff;
187072    fts5DataRelease(pIter->pLeaf);
187073    pIter->pLeaf = pLast;
187074    pIter->iLeafPgno = pgnoLast;
187075    iOff = fts5LeafFirstRowidOff(pLast);
187076    iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
187077    pIter->iLeafOffset = iOff;
187078
187079    if( fts5LeafIsTermless(pLast) ){
187080      pIter->iEndofDoclist = pLast->nn+1;
187081    }else{
187082      pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
187083    }
187084
187085  }
187086
187087  fts5SegIterReverseInitPage(p, pIter);
187088}
187089
187090/*
187091** Iterator pIter currently points to the first rowid of a doclist.
187092** There is a doclist-index associated with the final term on the current
187093** page. If the current term is the last term on the page, load the
187094** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
187095*/
187096static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
187097  int iSeg = pIter->pSeg->iSegid;
187098  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
187099  Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
187100
187101  assert( pIter->flags & FTS5_SEGITER_ONETERM );
187102  assert( pIter->pDlidx==0 );
187103
187104  /* Check if the current doclist ends on this page. If it does, return
187105  ** early without loading the doclist-index (as it belongs to a different
187106  ** term. */
187107  if( pIter->iTermLeafPgno==pIter->iLeafPgno
187108   && pIter->iEndofDoclist<pLeaf->szLeaf
187109  ){
187110    return;
187111  }
187112
187113  pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
187114}
187115
187116/*
187117** The iterator object passed as the second argument currently contains
187118** no valid values except for the Fts5SegIter.pLeaf member variable. This
187119** function searches the leaf page for a term matching (pTerm/nTerm).
187120**
187121** If the specified term is found on the page, then the iterator is left
187122** pointing to it. If argument bGe is zero and the term is not found,
187123** the iterator is left pointing at EOF.
187124**
187125** If bGe is non-zero and the specified term is not found, then the
187126** iterator is left pointing to the smallest term in the segment that
187127** is larger than the specified term, even if this term is not on the
187128** current page.
187129*/
187130static void fts5LeafSeek(
187131  Fts5Index *p,                   /* Leave any error code here */
187132  int bGe,                        /* True for a >= search */
187133  Fts5SegIter *pIter,             /* Iterator to seek */
187134  const u8 *pTerm, int nTerm      /* Term to search for */
187135){
187136  int iOff;
187137  const u8 *a = pIter->pLeaf->p;
187138  int szLeaf = pIter->pLeaf->szLeaf;
187139  int n = pIter->pLeaf->nn;
187140
187141  int nMatch = 0;
187142  int nKeep = 0;
187143  int nNew = 0;
187144  int iTermOff;
187145  int iPgidx;                     /* Current offset in pgidx */
187146  int bEndOfPage = 0;
187147
187148  assert( p->rc==SQLITE_OK );
187149
187150  iPgidx = szLeaf;
187151  iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
187152  iOff = iTermOff;
187153  if( iOff>n ){
187154    p->rc = FTS5_CORRUPT;
187155    return;
187156  }
187157
187158  while( 1 ){
187159
187160    /* Figure out how many new bytes are in this term */
187161    fts5FastGetVarint32(a, iOff, nNew);
187162    if( nKeep<nMatch ){
187163      goto search_failed;
187164    }
187165
187166    assert( nKeep>=nMatch );
187167    if( nKeep==nMatch ){
187168      int nCmp;
187169      int i;
187170      nCmp = MIN(nNew, nTerm-nMatch);
187171      for(i=0; i<nCmp; i++){
187172        if( a[iOff+i]!=pTerm[nMatch+i] ) break;
187173      }
187174      nMatch += i;
187175
187176      if( nTerm==nMatch ){
187177        if( i==nNew ){
187178          goto search_success;
187179        }else{
187180          goto search_failed;
187181        }
187182      }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
187183        goto search_failed;
187184      }
187185    }
187186
187187    if( iPgidx>=n ){
187188      bEndOfPage = 1;
187189      break;
187190    }
187191
187192    iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
187193    iTermOff += nKeep;
187194    iOff = iTermOff;
187195
187196    /* Read the nKeep field of the next term. */
187197    fts5FastGetVarint32(a, iOff, nKeep);
187198  }
187199
187200 search_failed:
187201  if( bGe==0 ){
187202    fts5DataRelease(pIter->pLeaf);
187203    pIter->pLeaf = 0;
187204    return;
187205  }else if( bEndOfPage ){
187206    do {
187207      fts5SegIterNextPage(p, pIter);
187208      if( pIter->pLeaf==0 ) return;
187209      a = pIter->pLeaf->p;
187210      if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
187211        iPgidx = pIter->pLeaf->szLeaf;
187212        iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
187213        if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
187214          p->rc = FTS5_CORRUPT;
187215        }else{
187216          nKeep = 0;
187217          iTermOff = iOff;
187218          n = pIter->pLeaf->nn;
187219          iOff += fts5GetVarint32(&a[iOff], nNew);
187220          break;
187221        }
187222      }
187223    }while( 1 );
187224  }
187225
187226 search_success:
187227
187228  pIter->iLeafOffset = iOff + nNew;
187229  pIter->iTermLeafOffset = pIter->iLeafOffset;
187230  pIter->iTermLeafPgno = pIter->iLeafPgno;
187231
187232  fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
187233  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
187234
187235  if( iPgidx>=n ){
187236    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
187237  }else{
187238    int nExtra;
187239    iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
187240    pIter->iEndofDoclist = iTermOff + nExtra;
187241  }
187242  pIter->iPgidxOff = iPgidx;
187243
187244  fts5SegIterLoadRowid(p, pIter);
187245  fts5SegIterLoadNPos(p, pIter);
187246}
187247
187248static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
187249  if( p->pIdxSelect==0 ){
187250    Fts5Config *pConfig = p->pConfig;
187251    fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
187252          "SELECT pgno FROM '%q'.'%q_idx' WHERE "
187253          "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
187254          pConfig->zDb, pConfig->zName
187255    ));
187256  }
187257  return p->pIdxSelect;
187258}
187259
187260/*
187261** Initialize the object pIter to point to term pTerm/nTerm within segment
187262** pSeg. If there is no such term in the index, the iterator is set to EOF.
187263**
187264** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
187265** an error has already occurred when this function is called, it is a no-op.
187266*/
187267static void fts5SegIterSeekInit(
187268  Fts5Index *p,                   /* FTS5 backend */
187269  const u8 *pTerm, int nTerm,     /* Term to seek to */
187270  int flags,                      /* Mask of FTS5INDEX_XXX flags */
187271  Fts5StructureSegment *pSeg,     /* Description of segment */
187272  Fts5SegIter *pIter              /* Object to populate */
187273){
187274  int iPg = 1;
187275  int bGe = (flags & FTS5INDEX_QUERY_SCAN);
187276  int bDlidx = 0;                 /* True if there is a doclist-index */
187277  sqlite3_stmt *pIdxSelect = 0;
187278
187279  assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
187280  assert( pTerm && nTerm );
187281  memset(pIter, 0, sizeof(*pIter));
187282  pIter->pSeg = pSeg;
187283
187284  /* This block sets stack variable iPg to the leaf page number that may
187285  ** contain term (pTerm/nTerm), if it is present in the segment. */
187286  pIdxSelect = fts5IdxSelectStmt(p);
187287  if( p->rc ) return;
187288  sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
187289  sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
187290  if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
187291    i64 val = sqlite3_column_int(pIdxSelect, 0);
187292    iPg = (int)(val>>1);
187293    bDlidx = (val & 0x0001);
187294  }
187295  p->rc = sqlite3_reset(pIdxSelect);
187296
187297  if( iPg<pSeg->pgnoFirst ){
187298    iPg = pSeg->pgnoFirst;
187299    bDlidx = 0;
187300  }
187301
187302  pIter->iLeafPgno = iPg - 1;
187303  fts5SegIterNextPage(p, pIter);
187304
187305  if( pIter->pLeaf ){
187306    fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
187307  }
187308
187309  if( p->rc==SQLITE_OK && bGe==0 ){
187310    pIter->flags |= FTS5_SEGITER_ONETERM;
187311    if( pIter->pLeaf ){
187312      if( flags & FTS5INDEX_QUERY_DESC ){
187313        pIter->flags |= FTS5_SEGITER_REVERSE;
187314      }
187315      if( bDlidx ){
187316        fts5SegIterLoadDlidx(p, pIter);
187317      }
187318      if( flags & FTS5INDEX_QUERY_DESC ){
187319        fts5SegIterReverse(p, pIter);
187320      }
187321    }
187322  }
187323
187324  fts5SegIterSetNext(p, pIter);
187325
187326  /* Either:
187327  **
187328  **   1) an error has occurred, or
187329  **   2) the iterator points to EOF, or
187330  **   3) the iterator points to an entry with term (pTerm/nTerm), or
187331  **   4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
187332  **      to an entry with a term greater than or equal to (pTerm/nTerm).
187333  */
187334  assert( p->rc!=SQLITE_OK                                          /* 1 */
187335   || pIter->pLeaf==0                                               /* 2 */
187336   || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0          /* 3 */
187337   || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0)  /* 4 */
187338  );
187339}
187340
187341/*
187342** Initialize the object pIter to point to term pTerm/nTerm within the
187343** in-memory hash table. If there is no such term in the hash-table, the
187344** iterator is set to EOF.
187345**
187346** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
187347** an error has already occurred when this function is called, it is a no-op.
187348*/
187349static void fts5SegIterHashInit(
187350  Fts5Index *p,                   /* FTS5 backend */
187351  const u8 *pTerm, int nTerm,     /* Term to seek to */
187352  int flags,                      /* Mask of FTS5INDEX_XXX flags */
187353  Fts5SegIter *pIter              /* Object to populate */
187354){
187355  const u8 *pList = 0;
187356  int nList = 0;
187357  const u8 *z = 0;
187358  int n = 0;
187359
187360  assert( p->pHash );
187361  assert( p->rc==SQLITE_OK );
187362
187363  if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
187364    p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
187365    sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
187366    n = (z ? (int)strlen((const char*)z) : 0);
187367  }else{
187368    pIter->flags |= FTS5_SEGITER_ONETERM;
187369    sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
187370    z = pTerm;
187371    n = nTerm;
187372  }
187373
187374  if( pList ){
187375    Fts5Data *pLeaf;
187376    sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
187377    pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
187378    if( pLeaf==0 ) return;
187379    pLeaf->p = (u8*)pList;
187380    pLeaf->nn = pLeaf->szLeaf = nList;
187381    pIter->pLeaf = pLeaf;
187382    pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
187383    pIter->iEndofDoclist = pLeaf->nn;
187384
187385    if( flags & FTS5INDEX_QUERY_DESC ){
187386      pIter->flags |= FTS5_SEGITER_REVERSE;
187387      fts5SegIterReverseInitPage(p, pIter);
187388    }else{
187389      fts5SegIterLoadNPos(p, pIter);
187390    }
187391  }
187392
187393  fts5SegIterSetNext(p, pIter);
187394}
187395
187396/*
187397** Zero the iterator passed as the only argument.
187398*/
187399static void fts5SegIterClear(Fts5SegIter *pIter){
187400  fts5BufferFree(&pIter->term);
187401  fts5DataRelease(pIter->pLeaf);
187402  fts5DataRelease(pIter->pNextLeaf);
187403  fts5DlidxIterFree(pIter->pDlidx);
187404  sqlite3_free(pIter->aRowidOffset);
187405  memset(pIter, 0, sizeof(Fts5SegIter));
187406}
187407
187408#ifdef SQLITE_DEBUG
187409
187410/*
187411** This function is used as part of the big assert() procedure implemented by
187412** fts5AssertMultiIterSetup(). It ensures that the result currently stored
187413** in *pRes is the correct result of comparing the current positions of the
187414** two iterators.
187415*/
187416static void fts5AssertComparisonResult(
187417  Fts5Iter *pIter,
187418  Fts5SegIter *p1,
187419  Fts5SegIter *p2,
187420  Fts5CResult *pRes
187421){
187422  int i1 = p1 - pIter->aSeg;
187423  int i2 = p2 - pIter->aSeg;
187424
187425  if( p1->pLeaf || p2->pLeaf ){
187426    if( p1->pLeaf==0 ){
187427      assert( pRes->iFirst==i2 );
187428    }else if( p2->pLeaf==0 ){
187429      assert( pRes->iFirst==i1 );
187430    }else{
187431      int nMin = MIN(p1->term.n, p2->term.n);
187432      int res = memcmp(p1->term.p, p2->term.p, nMin);
187433      if( res==0 ) res = p1->term.n - p2->term.n;
187434
187435      if( res==0 ){
187436        assert( pRes->bTermEq==1 );
187437        assert( p1->iRowid!=p2->iRowid );
187438        res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
187439      }else{
187440        assert( pRes->bTermEq==0 );
187441      }
187442
187443      if( res<0 ){
187444        assert( pRes->iFirst==i1 );
187445      }else{
187446        assert( pRes->iFirst==i2 );
187447      }
187448    }
187449  }
187450}
187451
187452/*
187453** This function is a no-op unless SQLITE_DEBUG is defined when this module
187454** is compiled. In that case, this function is essentially an assert()
187455** statement used to verify that the contents of the pIter->aFirst[] array
187456** are correct.
187457*/
187458static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
187459  if( p->rc==SQLITE_OK ){
187460    Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
187461    int i;
187462
187463    assert( (pFirst->pLeaf==0)==pIter->base.bEof );
187464
187465    /* Check that pIter->iSwitchRowid is set correctly. */
187466    for(i=0; i<pIter->nSeg; i++){
187467      Fts5SegIter *p1 = &pIter->aSeg[i];
187468      assert( p1==pFirst
187469           || p1->pLeaf==0
187470           || fts5BufferCompare(&pFirst->term, &p1->term)
187471           || p1->iRowid==pIter->iSwitchRowid
187472           || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
187473      );
187474    }
187475
187476    for(i=0; i<pIter->nSeg; i+=2){
187477      Fts5SegIter *p1 = &pIter->aSeg[i];
187478      Fts5SegIter *p2 = &pIter->aSeg[i+1];
187479      Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
187480      fts5AssertComparisonResult(pIter, p1, p2, pRes);
187481    }
187482
187483    for(i=1; i<(pIter->nSeg / 2); i+=2){
187484      Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
187485      Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
187486      Fts5CResult *pRes = &pIter->aFirst[i];
187487      fts5AssertComparisonResult(pIter, p1, p2, pRes);
187488    }
187489  }
187490}
187491#else
187492# define fts5AssertMultiIterSetup(x,y)
187493#endif
187494
187495/*
187496** Do the comparison necessary to populate pIter->aFirst[iOut].
187497**
187498** If the returned value is non-zero, then it is the index of an entry
187499** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
187500** to a key that is a duplicate of another, higher priority,
187501** segment-iterator in the pSeg->aSeg[] array.
187502*/
187503static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
187504  int i1;                         /* Index of left-hand Fts5SegIter */
187505  int i2;                         /* Index of right-hand Fts5SegIter */
187506  int iRes;
187507  Fts5SegIter *p1;                /* Left-hand Fts5SegIter */
187508  Fts5SegIter *p2;                /* Right-hand Fts5SegIter */
187509  Fts5CResult *pRes = &pIter->aFirst[iOut];
187510
187511  assert( iOut<pIter->nSeg && iOut>0 );
187512  assert( pIter->bRev==0 || pIter->bRev==1 );
187513
187514  if( iOut>=(pIter->nSeg/2) ){
187515    i1 = (iOut - pIter->nSeg/2) * 2;
187516    i2 = i1 + 1;
187517  }else{
187518    i1 = pIter->aFirst[iOut*2].iFirst;
187519    i2 = pIter->aFirst[iOut*2+1].iFirst;
187520  }
187521  p1 = &pIter->aSeg[i1];
187522  p2 = &pIter->aSeg[i2];
187523
187524  pRes->bTermEq = 0;
187525  if( p1->pLeaf==0 ){           /* If p1 is at EOF */
187526    iRes = i2;
187527  }else if( p2->pLeaf==0 ){     /* If p2 is at EOF */
187528    iRes = i1;
187529  }else{
187530    int res = fts5BufferCompare(&p1->term, &p2->term);
187531    if( res==0 ){
187532      assert( i2>i1 );
187533      assert( i2!=0 );
187534      pRes->bTermEq = 1;
187535      if( p1->iRowid==p2->iRowid ){
187536        p1->bDel = p2->bDel;
187537        return i2;
187538      }
187539      res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
187540    }
187541    assert( res!=0 );
187542    if( res<0 ){
187543      iRes = i1;
187544    }else{
187545      iRes = i2;
187546    }
187547  }
187548
187549  pRes->iFirst = (u16)iRes;
187550  return 0;
187551}
187552
187553/*
187554** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
187555** It is an error if leaf iLeafPgno does not exist or contains no rowids.
187556*/
187557static void fts5SegIterGotoPage(
187558  Fts5Index *p,                   /* FTS5 backend object */
187559  Fts5SegIter *pIter,             /* Iterator to advance */
187560  int iLeafPgno
187561){
187562  assert( iLeafPgno>pIter->iLeafPgno );
187563
187564  if( iLeafPgno>pIter->pSeg->pgnoLast ){
187565    p->rc = FTS5_CORRUPT;
187566  }else{
187567    fts5DataRelease(pIter->pNextLeaf);
187568    pIter->pNextLeaf = 0;
187569    pIter->iLeafPgno = iLeafPgno-1;
187570    fts5SegIterNextPage(p, pIter);
187571    assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
187572
187573    if( p->rc==SQLITE_OK ){
187574      int iOff;
187575      u8 *a = pIter->pLeaf->p;
187576      int n = pIter->pLeaf->szLeaf;
187577
187578      iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
187579      if( iOff<4 || iOff>=n ){
187580        p->rc = FTS5_CORRUPT;
187581      }else{
187582        iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
187583        pIter->iLeafOffset = iOff;
187584        fts5SegIterLoadNPos(p, pIter);
187585      }
187586    }
187587  }
187588}
187589
187590/*
187591** Advance the iterator passed as the second argument until it is at or
187592** past rowid iFrom. Regardless of the value of iFrom, the iterator is
187593** always advanced at least once.
187594*/
187595static void fts5SegIterNextFrom(
187596  Fts5Index *p,                   /* FTS5 backend object */
187597  Fts5SegIter *pIter,             /* Iterator to advance */
187598  i64 iMatch                      /* Advance iterator at least this far */
187599){
187600  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
187601  Fts5DlidxIter *pDlidx = pIter->pDlidx;
187602  int iLeafPgno = pIter->iLeafPgno;
187603  int bMove = 1;
187604
187605  assert( pIter->flags & FTS5_SEGITER_ONETERM );
187606  assert( pIter->pDlidx );
187607  assert( pIter->pLeaf );
187608
187609  if( bRev==0 ){
187610    while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
187611      iLeafPgno = fts5DlidxIterPgno(pDlidx);
187612      fts5DlidxIterNext(p, pDlidx);
187613    }
187614    assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
187615    if( iLeafPgno>pIter->iLeafPgno ){
187616      fts5SegIterGotoPage(p, pIter, iLeafPgno);
187617      bMove = 0;
187618    }
187619  }else{
187620    assert( pIter->pNextLeaf==0 );
187621    assert( iMatch<pIter->iRowid );
187622    while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
187623      fts5DlidxIterPrev(p, pDlidx);
187624    }
187625    iLeafPgno = fts5DlidxIterPgno(pDlidx);
187626
187627    assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
187628
187629    if( iLeafPgno<pIter->iLeafPgno ){
187630      pIter->iLeafPgno = iLeafPgno+1;
187631      fts5SegIterReverseNewPage(p, pIter);
187632      bMove = 0;
187633    }
187634  }
187635
187636  do{
187637    if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
187638    if( pIter->pLeaf==0 ) break;
187639    if( bRev==0 && pIter->iRowid>=iMatch ) break;
187640    if( bRev!=0 && pIter->iRowid<=iMatch ) break;
187641    bMove = 1;
187642  }while( p->rc==SQLITE_OK );
187643}
187644
187645
187646/*
187647** Free the iterator object passed as the second argument.
187648*/
187649static void fts5MultiIterFree(Fts5Iter *pIter){
187650  if( pIter ){
187651    int i;
187652    for(i=0; i<pIter->nSeg; i++){
187653      fts5SegIterClear(&pIter->aSeg[i]);
187654    }
187655    fts5StructureRelease(pIter->pStruct);
187656    fts5BufferFree(&pIter->poslist);
187657    sqlite3_free(pIter);
187658  }
187659}
187660
187661static void fts5MultiIterAdvanced(
187662  Fts5Index *p,                   /* FTS5 backend to iterate within */
187663  Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
187664  int iChanged,                   /* Index of sub-iterator just advanced */
187665  int iMinset                     /* Minimum entry in aFirst[] to set */
187666){
187667  int i;
187668  for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
187669    int iEq;
187670    if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
187671      Fts5SegIter *pSeg = &pIter->aSeg[iEq];
187672      assert( p->rc==SQLITE_OK );
187673      pSeg->xNext(p, pSeg, 0);
187674      i = pIter->nSeg + iEq;
187675    }
187676  }
187677}
187678
187679/*
187680** Sub-iterator iChanged of iterator pIter has just been advanced. It still
187681** points to the same term though - just a different rowid. This function
187682** attempts to update the contents of the pIter->aFirst[] accordingly.
187683** If it does so successfully, 0 is returned. Otherwise 1.
187684**
187685** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
187686** on the iterator instead. That function does the same as this one, except
187687** that it deals with more complicated cases as well.
187688*/
187689static int fts5MultiIterAdvanceRowid(
187690  Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
187691  int iChanged,                   /* Index of sub-iterator just advanced */
187692  Fts5SegIter **ppFirst
187693){
187694  Fts5SegIter *pNew = &pIter->aSeg[iChanged];
187695
187696  if( pNew->iRowid==pIter->iSwitchRowid
187697   || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
187698  ){
187699    int i;
187700    Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
187701    pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
187702    for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
187703      Fts5CResult *pRes = &pIter->aFirst[i];
187704
187705      assert( pNew->pLeaf );
187706      assert( pRes->bTermEq==0 || pOther->pLeaf );
187707
187708      if( pRes->bTermEq ){
187709        if( pNew->iRowid==pOther->iRowid ){
187710          return 1;
187711        }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
187712          pIter->iSwitchRowid = pOther->iRowid;
187713          pNew = pOther;
187714        }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
187715          pIter->iSwitchRowid = pOther->iRowid;
187716        }
187717      }
187718      pRes->iFirst = (u16)(pNew - pIter->aSeg);
187719      if( i==1 ) break;
187720
187721      pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
187722    }
187723  }
187724
187725  *ppFirst = pNew;
187726  return 0;
187727}
187728
187729/*
187730** Set the pIter->bEof variable based on the state of the sub-iterators.
187731*/
187732static void fts5MultiIterSetEof(Fts5Iter *pIter){
187733  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
187734  pIter->base.bEof = pSeg->pLeaf==0;
187735  pIter->iSwitchRowid = pSeg->iRowid;
187736}
187737
187738/*
187739** Move the iterator to the next entry.
187740**
187741** If an error occurs, an error code is left in Fts5Index.rc. It is not
187742** considered an error if the iterator reaches EOF, or if it is already at
187743** EOF when this function is called.
187744*/
187745static void fts5MultiIterNext(
187746  Fts5Index *p,
187747  Fts5Iter *pIter,
187748  int bFrom,                      /* True if argument iFrom is valid */
187749  i64 iFrom                       /* Advance at least as far as this */
187750){
187751  int bUseFrom = bFrom;
187752  while( p->rc==SQLITE_OK ){
187753    int iFirst = pIter->aFirst[1].iFirst;
187754    int bNewTerm = 0;
187755    Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
187756    assert( p->rc==SQLITE_OK );
187757    if( bUseFrom && pSeg->pDlidx ){
187758      fts5SegIterNextFrom(p, pSeg, iFrom);
187759    }else{
187760      pSeg->xNext(p, pSeg, &bNewTerm);
187761    }
187762
187763    if( pSeg->pLeaf==0 || bNewTerm
187764     || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
187765    ){
187766      fts5MultiIterAdvanced(p, pIter, iFirst, 1);
187767      fts5MultiIterSetEof(pIter);
187768      pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
187769      if( pSeg->pLeaf==0 ) return;
187770    }
187771
187772    fts5AssertMultiIterSetup(p, pIter);
187773    assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
187774    if( pIter->bSkipEmpty==0 || pSeg->nPos ){
187775      pIter->xSetOutputs(pIter, pSeg);
187776      return;
187777    }
187778    bUseFrom = 0;
187779  }
187780}
187781
187782static void fts5MultiIterNext2(
187783  Fts5Index *p,
187784  Fts5Iter *pIter,
187785  int *pbNewTerm                  /* OUT: True if *might* be new term */
187786){
187787  assert( pIter->bSkipEmpty );
187788  if( p->rc==SQLITE_OK ){
187789    do {
187790      int iFirst = pIter->aFirst[1].iFirst;
187791      Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
187792      int bNewTerm = 0;
187793
187794      assert( p->rc==SQLITE_OK );
187795      pSeg->xNext(p, pSeg, &bNewTerm);
187796      if( pSeg->pLeaf==0 || bNewTerm
187797       || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
187798      ){
187799        fts5MultiIterAdvanced(p, pIter, iFirst, 1);
187800        fts5MultiIterSetEof(pIter);
187801        *pbNewTerm = 1;
187802      }else{
187803        *pbNewTerm = 0;
187804      }
187805      fts5AssertMultiIterSetup(p, pIter);
187806
187807    }while( fts5MultiIterIsEmpty(p, pIter) );
187808  }
187809}
187810
187811static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
187812  UNUSED_PARAM2(pUnused1, pUnused2);
187813}
187814
187815static Fts5Iter *fts5MultiIterAlloc(
187816  Fts5Index *p,                   /* FTS5 backend to iterate within */
187817  int nSeg
187818){
187819  Fts5Iter *pNew;
187820  int nSlot;                      /* Power of two >= nSeg */
187821
187822  for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
187823  pNew = fts5IdxMalloc(p,
187824      sizeof(Fts5Iter) +                  /* pNew */
187825      sizeof(Fts5SegIter) * (nSlot-1) +   /* pNew->aSeg[] */
187826      sizeof(Fts5CResult) * nSlot         /* pNew->aFirst[] */
187827  );
187828  if( pNew ){
187829    pNew->nSeg = nSlot;
187830    pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
187831    pNew->pIndex = p;
187832    pNew->xSetOutputs = fts5IterSetOutputs_Noop;
187833  }
187834  return pNew;
187835}
187836
187837static void fts5PoslistCallback(
187838  Fts5Index *pUnused,
187839  void *pContext,
187840  const u8 *pChunk, int nChunk
187841){
187842  UNUSED_PARAM(pUnused);
187843  assert_nc( nChunk>=0 );
187844  if( nChunk>0 ){
187845    fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
187846  }
187847}
187848
187849typedef struct PoslistCallbackCtx PoslistCallbackCtx;
187850struct PoslistCallbackCtx {
187851  Fts5Buffer *pBuf;               /* Append to this buffer */
187852  Fts5Colset *pColset;            /* Restrict matches to this column */
187853  int eState;                     /* See above */
187854};
187855
187856typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
187857struct PoslistOffsetsCtx {
187858  Fts5Buffer *pBuf;               /* Append to this buffer */
187859  Fts5Colset *pColset;            /* Restrict matches to this column */
187860  int iRead;
187861  int iWrite;
187862};
187863
187864/*
187865** TODO: Make this more efficient!
187866*/
187867static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
187868  int i;
187869  for(i=0; i<pColset->nCol; i++){
187870    if( pColset->aiCol[i]==iCol ) return 1;
187871  }
187872  return 0;
187873}
187874
187875static void fts5PoslistOffsetsCallback(
187876  Fts5Index *pUnused,
187877  void *pContext,
187878  const u8 *pChunk, int nChunk
187879){
187880  PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
187881  UNUSED_PARAM(pUnused);
187882  assert_nc( nChunk>=0 );
187883  if( nChunk>0 ){
187884    int i = 0;
187885    while( i<nChunk ){
187886      int iVal;
187887      i += fts5GetVarint32(&pChunk[i], iVal);
187888      iVal += pCtx->iRead - 2;
187889      pCtx->iRead = iVal;
187890      if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
187891        fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
187892        pCtx->iWrite = iVal;
187893      }
187894    }
187895  }
187896}
187897
187898static void fts5PoslistFilterCallback(
187899  Fts5Index *pUnused,
187900  void *pContext,
187901  const u8 *pChunk, int nChunk
187902){
187903  PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
187904  UNUSED_PARAM(pUnused);
187905  assert_nc( nChunk>=0 );
187906  if( nChunk>0 ){
187907    /* Search through to find the first varint with value 1. This is the
187908    ** start of the next columns hits. */
187909    int i = 0;
187910    int iStart = 0;
187911
187912    if( pCtx->eState==2 ){
187913      int iCol;
187914      fts5FastGetVarint32(pChunk, i, iCol);
187915      if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
187916        pCtx->eState = 1;
187917        fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
187918      }else{
187919        pCtx->eState = 0;
187920      }
187921    }
187922
187923    do {
187924      while( i<nChunk && pChunk[i]!=0x01 ){
187925        while( pChunk[i] & 0x80 ) i++;
187926        i++;
187927      }
187928      if( pCtx->eState ){
187929        fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
187930      }
187931      if( i<nChunk ){
187932        int iCol;
187933        iStart = i;
187934        i++;
187935        if( i>=nChunk ){
187936          pCtx->eState = 2;
187937        }else{
187938          fts5FastGetVarint32(pChunk, i, iCol);
187939          pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
187940          if( pCtx->eState ){
187941            fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
187942            iStart = i;
187943          }
187944        }
187945      }
187946    }while( i<nChunk );
187947  }
187948}
187949
187950static void fts5ChunkIterate(
187951  Fts5Index *p,                   /* Index object */
187952  Fts5SegIter *pSeg,              /* Poslist of this iterator */
187953  void *pCtx,                     /* Context pointer for xChunk callback */
187954  void (*xChunk)(Fts5Index*, void*, const u8*, int)
187955){
187956  int nRem = pSeg->nPos;          /* Number of bytes still to come */
187957  Fts5Data *pData = 0;
187958  u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
187959  int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
187960  int pgno = pSeg->iLeafPgno;
187961  int pgnoSave = 0;
187962
187963  /* This function does notmwork with detail=none databases. */
187964  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
187965
187966  if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
187967    pgnoSave = pgno+1;
187968  }
187969
187970  while( 1 ){
187971    xChunk(p, pCtx, pChunk, nChunk);
187972    nRem -= nChunk;
187973    fts5DataRelease(pData);
187974    if( nRem<=0 ){
187975      break;
187976    }else{
187977      pgno++;
187978      pData = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
187979      if( pData==0 ) break;
187980      pChunk = &pData->p[4];
187981      nChunk = MIN(nRem, pData->szLeaf - 4);
187982      if( pgno==pgnoSave ){
187983        assert( pSeg->pNextLeaf==0 );
187984        pSeg->pNextLeaf = pData;
187985        pData = 0;
187986      }
187987    }
187988  }
187989}
187990
187991/*
187992** Iterator pIter currently points to a valid entry (not EOF). This
187993** function appends the position list data for the current entry to
187994** buffer pBuf. It does not make a copy of the position-list size
187995** field.
187996*/
187997static void fts5SegiterPoslist(
187998  Fts5Index *p,
187999  Fts5SegIter *pSeg,
188000  Fts5Colset *pColset,
188001  Fts5Buffer *pBuf
188002){
188003  if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
188004    if( pColset==0 ){
188005      fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
188006    }else{
188007      if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
188008        PoslistCallbackCtx sCtx;
188009        sCtx.pBuf = pBuf;
188010        sCtx.pColset = pColset;
188011        sCtx.eState = fts5IndexColsetTest(pColset, 0);
188012        assert( sCtx.eState==0 || sCtx.eState==1 );
188013        fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
188014      }else{
188015        PoslistOffsetsCtx sCtx;
188016        memset(&sCtx, 0, sizeof(sCtx));
188017        sCtx.pBuf = pBuf;
188018        sCtx.pColset = pColset;
188019        fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
188020      }
188021    }
188022  }
188023}
188024
188025/*
188026** IN/OUT parameter (*pa) points to a position list n bytes in size. If
188027** the position list contains entries for column iCol, then (*pa) is set
188028** to point to the sub-position-list for that column and the number of
188029** bytes in it returned. Or, if the argument position list does not
188030** contain any entries for column iCol, return 0.
188031*/
188032static int fts5IndexExtractCol(
188033  const u8 **pa,                  /* IN/OUT: Pointer to poslist */
188034  int n,                          /* IN: Size of poslist in bytes */
188035  int iCol                        /* Column to extract from poslist */
188036){
188037  int iCurrent = 0;               /* Anything before the first 0x01 is col 0 */
188038  const u8 *p = *pa;
188039  const u8 *pEnd = &p[n];         /* One byte past end of position list */
188040
188041  while( iCol>iCurrent ){
188042    /* Advance pointer p until it points to pEnd or an 0x01 byte that is
188043    ** not part of a varint. Note that it is not possible for a negative
188044    ** or extremely large varint to occur within an uncorrupted position
188045    ** list. So the last byte of each varint may be assumed to have a clear
188046    ** 0x80 bit.  */
188047    while( *p!=0x01 ){
188048      while( *p++ & 0x80 );
188049      if( p>=pEnd ) return 0;
188050    }
188051    *pa = p++;
188052    iCurrent = *p++;
188053    if( iCurrent & 0x80 ){
188054      p--;
188055      p += fts5GetVarint32(p, iCurrent);
188056    }
188057  }
188058  if( iCol!=iCurrent ) return 0;
188059
188060  /* Advance pointer p until it points to pEnd or an 0x01 byte that is
188061  ** not part of a varint */
188062  while( p<pEnd && *p!=0x01 ){
188063    while( *p++ & 0x80 );
188064  }
188065
188066  return p - (*pa);
188067}
188068
188069static int fts5IndexExtractColset (
188070  Fts5Colset *pColset,            /* Colset to filter on */
188071  const u8 *pPos, int nPos,       /* Position list */
188072  Fts5Buffer *pBuf                /* Output buffer */
188073){
188074  int rc = SQLITE_OK;
188075  int i;
188076
188077  fts5BufferZero(pBuf);
188078  for(i=0; i<pColset->nCol; i++){
188079    const u8 *pSub = pPos;
188080    int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
188081    if( nSub ){
188082      fts5BufferAppendBlob(&rc, pBuf, nSub, pSub);
188083    }
188084  }
188085  return rc;
188086}
188087
188088/*
188089** xSetOutputs callback used by detail=none tables.
188090*/
188091static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
188092  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
188093  pIter->base.iRowid = pSeg->iRowid;
188094  pIter->base.nData = pSeg->nPos;
188095}
188096
188097/*
188098** xSetOutputs callback used by detail=full and detail=col tables when no
188099** column filters are specified.
188100*/
188101static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
188102  pIter->base.iRowid = pSeg->iRowid;
188103  pIter->base.nData = pSeg->nPos;
188104
188105  assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
188106  assert( pIter->pColset==0 );
188107
188108  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
188109    /* All data is stored on the current page. Populate the output
188110    ** variables to point into the body of the page object. */
188111    pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
188112  }else{
188113    /* The data is distributed over two or more pages. Copy it into the
188114    ** Fts5Iter.poslist buffer and then set the output pointer to point
188115    ** to this buffer.  */
188116    fts5BufferZero(&pIter->poslist);
188117    fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
188118    pIter->base.pData = pIter->poslist.p;
188119  }
188120}
188121
188122/*
188123** xSetOutputs callback used by detail=col when there is a column filter
188124** and there are 100 or more columns. Also called as a fallback from
188125** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
188126*/
188127static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
188128  fts5BufferZero(&pIter->poslist);
188129  fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
188130  pIter->base.iRowid = pSeg->iRowid;
188131  pIter->base.pData = pIter->poslist.p;
188132  pIter->base.nData = pIter->poslist.n;
188133}
188134
188135/*
188136** xSetOutputs callback used when:
188137**
188138**   * detail=col,
188139**   * there is a column filter, and
188140**   * the table contains 100 or fewer columns.
188141**
188142** The last point is to ensure all column numbers are stored as
188143** single-byte varints.
188144*/
188145static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
188146
188147  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
188148  assert( pIter->pColset );
188149
188150  if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
188151    fts5IterSetOutputs_Col(pIter, pSeg);
188152  }else{
188153    u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
188154    u8 *pEnd = (u8*)&a[pSeg->nPos];
188155    int iPrev = 0;
188156    int *aiCol = pIter->pColset->aiCol;
188157    int *aiColEnd = &aiCol[pIter->pColset->nCol];
188158
188159    u8 *aOut = pIter->poslist.p;
188160    int iPrevOut = 0;
188161
188162    pIter->base.iRowid = pSeg->iRowid;
188163
188164    while( a<pEnd ){
188165      iPrev += (int)a++[0] - 2;
188166      while( *aiCol<iPrev ){
188167        aiCol++;
188168        if( aiCol==aiColEnd ) goto setoutputs_col_out;
188169      }
188170      if( *aiCol==iPrev ){
188171        *aOut++ = (u8)((iPrev - iPrevOut) + 2);
188172        iPrevOut = iPrev;
188173      }
188174    }
188175
188176setoutputs_col_out:
188177    pIter->base.pData = pIter->poslist.p;
188178    pIter->base.nData = aOut - pIter->poslist.p;
188179  }
188180}
188181
188182/*
188183** xSetOutputs callback used by detail=full when there is a column filter.
188184*/
188185static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
188186  Fts5Colset *pColset = pIter->pColset;
188187  pIter->base.iRowid = pSeg->iRowid;
188188
188189  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
188190  assert( pColset );
188191
188192  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
188193    /* All data is stored on the current page. Populate the output
188194    ** variables to point into the body of the page object. */
188195    const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
188196    if( pColset->nCol==1 ){
188197      pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
188198      pIter->base.pData = a;
188199    }else{
188200      fts5BufferZero(&pIter->poslist);
188201      fts5IndexExtractColset(pColset, a, pSeg->nPos, &pIter->poslist);
188202      pIter->base.pData = pIter->poslist.p;
188203      pIter->base.nData = pIter->poslist.n;
188204    }
188205  }else{
188206    /* The data is distributed over two or more pages. Copy it into the
188207    ** Fts5Iter.poslist buffer and then set the output pointer to point
188208    ** to this buffer.  */
188209    fts5BufferZero(&pIter->poslist);
188210    fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
188211    pIter->base.pData = pIter->poslist.p;
188212    pIter->base.nData = pIter->poslist.n;
188213  }
188214}
188215
188216static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
188217  if( *pRc==SQLITE_OK ){
188218    Fts5Config *pConfig = pIter->pIndex->pConfig;
188219    if( pConfig->eDetail==FTS5_DETAIL_NONE ){
188220      pIter->xSetOutputs = fts5IterSetOutputs_None;
188221    }
188222
188223    else if( pIter->pColset==0 ){
188224      pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
188225    }
188226
188227    else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
188228      pIter->xSetOutputs = fts5IterSetOutputs_Full;
188229    }
188230
188231    else{
188232      assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
188233      if( pConfig->nCol<=100 ){
188234        pIter->xSetOutputs = fts5IterSetOutputs_Col100;
188235        sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
188236      }else{
188237        pIter->xSetOutputs = fts5IterSetOutputs_Col;
188238      }
188239    }
188240  }
188241}
188242
188243
188244/*
188245** Allocate a new Fts5Iter object.
188246**
188247** The new object will be used to iterate through data in structure pStruct.
188248** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
188249** is zero or greater, data from the first nSegment segments on level iLevel
188250** is merged.
188251**
188252** The iterator initially points to the first term/rowid entry in the
188253** iterated data.
188254*/
188255static void fts5MultiIterNew(
188256  Fts5Index *p,                   /* FTS5 backend to iterate within */
188257  Fts5Structure *pStruct,         /* Structure of specific index */
188258  int flags,                      /* FTS5INDEX_QUERY_XXX flags */
188259  Fts5Colset *pColset,            /* Colset to filter on (or NULL) */
188260  const u8 *pTerm, int nTerm,     /* Term to seek to (or NULL/0) */
188261  int iLevel,                     /* Level to iterate (-1 for all) */
188262  int nSegment,                   /* Number of segments to merge (iLevel>=0) */
188263  Fts5Iter **ppOut                /* New object */
188264){
188265  int nSeg = 0;                   /* Number of segment-iters in use */
188266  int iIter = 0;                  /* */
188267  int iSeg;                       /* Used to iterate through segments */
188268  Fts5StructureLevel *pLvl;
188269  Fts5Iter *pNew;
188270
188271  assert( (pTerm==0 && nTerm==0) || iLevel<0 );
188272
188273  /* Allocate space for the new multi-seg-iterator. */
188274  if( p->rc==SQLITE_OK ){
188275    if( iLevel<0 ){
188276      assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
188277      nSeg = pStruct->nSegment;
188278      nSeg += (p->pHash ? 1 : 0);
188279    }else{
188280      nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
188281    }
188282  }
188283  *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
188284  if( pNew==0 ) return;
188285  pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
188286  pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
188287  pNew->pStruct = pStruct;
188288  pNew->pColset = pColset;
188289  fts5StructureRef(pStruct);
188290  if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
188291    fts5IterSetOutputCb(&p->rc, pNew);
188292  }
188293
188294  /* Initialize each of the component segment iterators. */
188295  if( p->rc==SQLITE_OK ){
188296    if( iLevel<0 ){
188297      Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
188298      if( p->pHash ){
188299        /* Add a segment iterator for the current contents of the hash table. */
188300        Fts5SegIter *pIter = &pNew->aSeg[iIter++];
188301        fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
188302      }
188303      for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
188304        for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
188305          Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
188306          Fts5SegIter *pIter = &pNew->aSeg[iIter++];
188307          if( pTerm==0 ){
188308            fts5SegIterInit(p, pSeg, pIter);
188309          }else{
188310            fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
188311          }
188312        }
188313      }
188314    }else{
188315      pLvl = &pStruct->aLevel[iLevel];
188316      for(iSeg=nSeg-1; iSeg>=0; iSeg--){
188317        fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
188318      }
188319    }
188320    assert( iIter==nSeg );
188321  }
188322
188323  /* If the above was successful, each component iterators now points
188324  ** to the first entry in its segment. In this case initialize the
188325  ** aFirst[] array. Or, if an error has occurred, free the iterator
188326  ** object and set the output variable to NULL.  */
188327  if( p->rc==SQLITE_OK ){
188328    for(iIter=pNew->nSeg-1; iIter>0; iIter--){
188329      int iEq;
188330      if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
188331        Fts5SegIter *pSeg = &pNew->aSeg[iEq];
188332        if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
188333        fts5MultiIterAdvanced(p, pNew, iEq, iIter);
188334      }
188335    }
188336    fts5MultiIterSetEof(pNew);
188337    fts5AssertMultiIterSetup(p, pNew);
188338
188339    if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
188340      fts5MultiIterNext(p, pNew, 0, 0);
188341    }else if( pNew->base.bEof==0 ){
188342      Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
188343      pNew->xSetOutputs(pNew, pSeg);
188344    }
188345
188346  }else{
188347    fts5MultiIterFree(pNew);
188348    *ppOut = 0;
188349  }
188350}
188351
188352/*
188353** Create an Fts5Iter that iterates through the doclist provided
188354** as the second argument.
188355*/
188356static void fts5MultiIterNew2(
188357  Fts5Index *p,                   /* FTS5 backend to iterate within */
188358  Fts5Data *pData,                /* Doclist to iterate through */
188359  int bDesc,                      /* True for descending rowid order */
188360  Fts5Iter **ppOut                /* New object */
188361){
188362  Fts5Iter *pNew;
188363  pNew = fts5MultiIterAlloc(p, 2);
188364  if( pNew ){
188365    Fts5SegIter *pIter = &pNew->aSeg[1];
188366
188367    pIter->flags = FTS5_SEGITER_ONETERM;
188368    if( pData->szLeaf>0 ){
188369      pIter->pLeaf = pData;
188370      pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
188371      pIter->iEndofDoclist = pData->nn;
188372      pNew->aFirst[1].iFirst = 1;
188373      if( bDesc ){
188374        pNew->bRev = 1;
188375        pIter->flags |= FTS5_SEGITER_REVERSE;
188376        fts5SegIterReverseInitPage(p, pIter);
188377      }else{
188378        fts5SegIterLoadNPos(p, pIter);
188379      }
188380      pData = 0;
188381    }else{
188382      pNew->base.bEof = 1;
188383    }
188384    fts5SegIterSetNext(p, pIter);
188385
188386    *ppOut = pNew;
188387  }
188388
188389  fts5DataRelease(pData);
188390}
188391
188392/*
188393** Return true if the iterator is at EOF or if an error has occurred.
188394** False otherwise.
188395*/
188396static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
188397  assert( p->rc
188398      || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
188399  );
188400  return (p->rc || pIter->base.bEof);
188401}
188402
188403/*
188404** Return the rowid of the entry that the iterator currently points
188405** to. If the iterator points to EOF when this function is called the
188406** results are undefined.
188407*/
188408static i64 fts5MultiIterRowid(Fts5Iter *pIter){
188409  assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
188410  return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
188411}
188412
188413/*
188414** Move the iterator to the next entry at or following iMatch.
188415*/
188416static void fts5MultiIterNextFrom(
188417  Fts5Index *p,
188418  Fts5Iter *pIter,
188419  i64 iMatch
188420){
188421  while( 1 ){
188422    i64 iRowid;
188423    fts5MultiIterNext(p, pIter, 1, iMatch);
188424    if( fts5MultiIterEof(p, pIter) ) break;
188425    iRowid = fts5MultiIterRowid(pIter);
188426    if( pIter->bRev==0 && iRowid>=iMatch ) break;
188427    if( pIter->bRev!=0 && iRowid<=iMatch ) break;
188428  }
188429}
188430
188431/*
188432** Return a pointer to a buffer containing the term associated with the
188433** entry that the iterator currently points to.
188434*/
188435static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
188436  Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
188437  *pn = p->term.n;
188438  return p->term.p;
188439}
188440
188441/*
188442** Allocate a new segment-id for the structure pStruct. The new segment
188443** id must be between 1 and 65335 inclusive, and must not be used by
188444** any currently existing segment. If a free segment id cannot be found,
188445** SQLITE_FULL is returned.
188446**
188447** If an error has already occurred, this function is a no-op. 0 is
188448** returned in this case.
188449*/
188450static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
188451  int iSegid = 0;
188452
188453  if( p->rc==SQLITE_OK ){
188454    if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
188455      p->rc = SQLITE_FULL;
188456    }else{
188457      /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
188458      ** array is 63 elements, or 252 bytes, in size.  */
188459      u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
188460      int iLvl, iSeg;
188461      int i;
188462      u32 mask;
188463      memset(aUsed, 0, sizeof(aUsed));
188464      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
188465        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
188466          int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
188467          if( iId<=FTS5_MAX_SEGMENT ){
188468            aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
188469          }
188470        }
188471      }
188472
188473      for(i=0; aUsed[i]==0xFFFFFFFF; i++);
188474      mask = aUsed[i];
188475      for(iSegid=0; mask & (1 << iSegid); iSegid++);
188476      iSegid += 1 + i*32;
188477
188478#ifdef SQLITE_DEBUG
188479      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
188480        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
188481          assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
188482        }
188483      }
188484      assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
188485
188486      {
188487        sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
188488        if( p->rc==SQLITE_OK ){
188489          u8 aBlob[2] = {0xff, 0xff};
188490          sqlite3_bind_int(pIdxSelect, 1, iSegid);
188491          sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
188492          assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
188493          p->rc = sqlite3_reset(pIdxSelect);
188494        }
188495      }
188496#endif
188497    }
188498  }
188499
188500  return iSegid;
188501}
188502
188503/*
188504** Discard all data currently cached in the hash-tables.
188505*/
188506static void fts5IndexDiscardData(Fts5Index *p){
188507  assert( p->pHash || p->nPendingData==0 );
188508  if( p->pHash ){
188509    sqlite3Fts5HashClear(p->pHash);
188510    p->nPendingData = 0;
188511  }
188512}
188513
188514/*
188515** Return the size of the prefix, in bytes, that buffer
188516** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
188517**
188518** Buffer (pNew/<length-unknown>) is guaranteed to be greater
188519** than buffer (pOld/nOld).
188520*/
188521static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
188522  int i;
188523  for(i=0; i<nOld; i++){
188524    if( pOld[i]!=pNew[i] ) break;
188525  }
188526  return i;
188527}
188528
188529static void fts5WriteDlidxClear(
188530  Fts5Index *p,
188531  Fts5SegWriter *pWriter,
188532  int bFlush                      /* If true, write dlidx to disk */
188533){
188534  int i;
188535  assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
188536  for(i=0; i<pWriter->nDlidx; i++){
188537    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
188538    if( pDlidx->buf.n==0 ) break;
188539    if( bFlush ){
188540      assert( pDlidx->pgno!=0 );
188541      fts5DataWrite(p,
188542          FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
188543          pDlidx->buf.p, pDlidx->buf.n
188544      );
188545    }
188546    sqlite3Fts5BufferZero(&pDlidx->buf);
188547    pDlidx->bPrevValid = 0;
188548  }
188549}
188550
188551/*
188552** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
188553** Any new array elements are zeroed before returning.
188554*/
188555static int fts5WriteDlidxGrow(
188556  Fts5Index *p,
188557  Fts5SegWriter *pWriter,
188558  int nLvl
188559){
188560  if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
188561    Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
188562        pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
188563    );
188564    if( aDlidx==0 ){
188565      p->rc = SQLITE_NOMEM;
188566    }else{
188567      int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
188568      memset(&aDlidx[pWriter->nDlidx], 0, nByte);
188569      pWriter->aDlidx = aDlidx;
188570      pWriter->nDlidx = nLvl;
188571    }
188572  }
188573  return p->rc;
188574}
188575
188576/*
188577** If the current doclist-index accumulating in pWriter->aDlidx[] is large
188578** enough, flush it to disk and return 1. Otherwise discard it and return
188579** zero.
188580*/
188581static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
188582  int bFlag = 0;
188583
188584  /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
188585  ** to the database, also write the doclist-index to disk.  */
188586  if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
188587    bFlag = 1;
188588  }
188589  fts5WriteDlidxClear(p, pWriter, bFlag);
188590  pWriter->nEmpty = 0;
188591  return bFlag;
188592}
188593
188594/*
188595** This function is called whenever processing of the doclist for the
188596** last term on leaf page (pWriter->iBtPage) is completed.
188597**
188598** The doclist-index for that term is currently stored in-memory within the
188599** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
188600** writes it out to disk. Or, if it is too small to bother with, discards
188601** it.
188602**
188603** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
188604*/
188605static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
188606  int bFlag;
188607
188608  assert( pWriter->iBtPage || pWriter->nEmpty==0 );
188609  if( pWriter->iBtPage==0 ) return;
188610  bFlag = fts5WriteFlushDlidx(p, pWriter);
188611
188612  if( p->rc==SQLITE_OK ){
188613    const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
188614    /* The following was already done in fts5WriteInit(): */
188615    /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
188616    sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
188617    sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
188618    sqlite3_step(p->pIdxWriter);
188619    p->rc = sqlite3_reset(p->pIdxWriter);
188620  }
188621  pWriter->iBtPage = 0;
188622}
188623
188624/*
188625** This is called once for each leaf page except the first that contains
188626** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
188627** is larger than all terms written to earlier leaves, and equal to or
188628** smaller than the first term on the new leaf.
188629**
188630** If an error occurs, an error code is left in Fts5Index.rc. If an error
188631** has already occurred when this function is called, it is a no-op.
188632*/
188633static void fts5WriteBtreeTerm(
188634  Fts5Index *p,                   /* FTS5 backend object */
188635  Fts5SegWriter *pWriter,         /* Writer object */
188636  int nTerm, const u8 *pTerm      /* First term on new page */
188637){
188638  fts5WriteFlushBtree(p, pWriter);
188639  fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
188640  pWriter->iBtPage = pWriter->writer.pgno;
188641}
188642
188643/*
188644** This function is called when flushing a leaf page that contains no
188645** terms at all to disk.
188646*/
188647static void fts5WriteBtreeNoTerm(
188648  Fts5Index *p,                   /* FTS5 backend object */
188649  Fts5SegWriter *pWriter          /* Writer object */
188650){
188651  /* If there were no rowids on the leaf page either and the doclist-index
188652  ** has already been started, append an 0x00 byte to it.  */
188653  if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
188654    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
188655    assert( pDlidx->bPrevValid );
188656    sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
188657  }
188658
188659  /* Increment the "number of sequential leaves without a term" counter. */
188660  pWriter->nEmpty++;
188661}
188662
188663static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
188664  i64 iRowid;
188665  int iOff;
188666
188667  iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
188668  fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
188669  return iRowid;
188670}
188671
188672/*
188673** Rowid iRowid has just been appended to the current leaf page. It is the
188674** first on the page. This function appends an appropriate entry to the current
188675** doclist-index.
188676*/
188677static void fts5WriteDlidxAppend(
188678  Fts5Index *p,
188679  Fts5SegWriter *pWriter,
188680  i64 iRowid
188681){
188682  int i;
188683  int bDone = 0;
188684
188685  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
188686    i64 iVal;
188687    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
188688
188689    if( pDlidx->buf.n>=p->pConfig->pgsz ){
188690      /* The current doclist-index page is full. Write it to disk and push
188691      ** a copy of iRowid (which will become the first rowid on the next
188692      ** doclist-index leaf page) up into the next level of the b-tree
188693      ** hierarchy. If the node being flushed is currently the root node,
188694      ** also push its first rowid upwards. */
188695      pDlidx->buf.p[0] = 0x01;    /* Not the root node */
188696      fts5DataWrite(p,
188697          FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
188698          pDlidx->buf.p, pDlidx->buf.n
188699      );
188700      fts5WriteDlidxGrow(p, pWriter, i+2);
188701      pDlidx = &pWriter->aDlidx[i];
188702      if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
188703        i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
188704
188705        /* This was the root node. Push its first rowid up to the new root. */
188706        pDlidx[1].pgno = pDlidx->pgno;
188707        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
188708        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
188709        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
188710        pDlidx[1].bPrevValid = 1;
188711        pDlidx[1].iPrev = iFirst;
188712      }
188713
188714      sqlite3Fts5BufferZero(&pDlidx->buf);
188715      pDlidx->bPrevValid = 0;
188716      pDlidx->pgno++;
188717    }else{
188718      bDone = 1;
188719    }
188720
188721    if( pDlidx->bPrevValid ){
188722      iVal = iRowid - pDlidx->iPrev;
188723    }else{
188724      i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
188725      assert( pDlidx->buf.n==0 );
188726      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
188727      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
188728      iVal = iRowid;
188729    }
188730
188731    sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
188732    pDlidx->bPrevValid = 1;
188733    pDlidx->iPrev = iRowid;
188734  }
188735}
188736
188737static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
188738  static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
188739  Fts5PageWriter *pPage = &pWriter->writer;
188740  i64 iRowid;
188741
188742static int nCall = 0;
188743nCall++;
188744
188745  assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
188746
188747  /* Set the szLeaf header field. */
188748  assert( 0==fts5GetU16(&pPage->buf.p[2]) );
188749  fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
188750
188751  if( pWriter->bFirstTermInPage ){
188752    /* No term was written to this page. */
188753    assert( pPage->pgidx.n==0 );
188754    fts5WriteBtreeNoTerm(p, pWriter);
188755  }else{
188756    /* Append the pgidx to the page buffer. Set the szLeaf header field. */
188757    fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
188758  }
188759
188760  /* Write the page out to disk */
188761  iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
188762  fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
188763
188764  /* Initialize the next page. */
188765  fts5BufferZero(&pPage->buf);
188766  fts5BufferZero(&pPage->pgidx);
188767  fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
188768  pPage->iPrevPgidx = 0;
188769  pPage->pgno++;
188770
188771  /* Increase the leaves written counter */
188772  pWriter->nLeafWritten++;
188773
188774  /* The new leaf holds no terms or rowids */
188775  pWriter->bFirstTermInPage = 1;
188776  pWriter->bFirstRowidInPage = 1;
188777}
188778
188779/*
188780** Append term pTerm/nTerm to the segment being written by the writer passed
188781** as the second argument.
188782**
188783** If an error occurs, set the Fts5Index.rc error code. If an error has
188784** already occurred, this function is a no-op.
188785*/
188786static void fts5WriteAppendTerm(
188787  Fts5Index *p,
188788  Fts5SegWriter *pWriter,
188789  int nTerm, const u8 *pTerm
188790){
188791  int nPrefix;                    /* Bytes of prefix compression for term */
188792  Fts5PageWriter *pPage = &pWriter->writer;
188793  Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
188794
188795  assert( p->rc==SQLITE_OK );
188796  assert( pPage->buf.n>=4 );
188797  assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
188798
188799  /* If the current leaf page is full, flush it to disk. */
188800  if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
188801    if( pPage->buf.n>4 ){
188802      fts5WriteFlushLeaf(p, pWriter);
188803    }
188804    fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
188805  }
188806
188807  /* TODO1: Updating pgidx here. */
188808  pPgidx->n += sqlite3Fts5PutVarint(
188809      &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
188810  );
188811  pPage->iPrevPgidx = pPage->buf.n;
188812#if 0
188813  fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
188814  pPgidx->n += 2;
188815#endif
188816
188817  if( pWriter->bFirstTermInPage ){
188818    nPrefix = 0;
188819    if( pPage->pgno!=1 ){
188820      /* This is the first term on a leaf that is not the leftmost leaf in
188821      ** the segment b-tree. In this case it is necessary to add a term to
188822      ** the b-tree hierarchy that is (a) larger than the largest term
188823      ** already written to the segment and (b) smaller than or equal to
188824      ** this term. In other words, a prefix of (pTerm/nTerm) that is one
188825      ** byte longer than the longest prefix (pTerm/nTerm) shares with the
188826      ** previous term.
188827      **
188828      ** Usually, the previous term is available in pPage->term. The exception
188829      ** is if this is the first term written in an incremental-merge step.
188830      ** In this case the previous term is not available, so just write a
188831      ** copy of (pTerm/nTerm) into the parent node. This is slightly
188832      ** inefficient, but still correct.  */
188833      int n = nTerm;
188834      if( pPage->term.n ){
188835        n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
188836      }
188837      fts5WriteBtreeTerm(p, pWriter, n, pTerm);
188838      pPage = &pWriter->writer;
188839    }
188840  }else{
188841    nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
188842    fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
188843  }
188844
188845  /* Append the number of bytes of new data, then the term data itself
188846  ** to the page. */
188847  fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
188848  fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
188849
188850  /* Update the Fts5PageWriter.term field. */
188851  fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
188852  pWriter->bFirstTermInPage = 0;
188853
188854  pWriter->bFirstRowidInPage = 0;
188855  pWriter->bFirstRowidInDoclist = 1;
188856
188857  assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
188858  pWriter->aDlidx[0].pgno = pPage->pgno;
188859}
188860
188861/*
188862** Append a rowid and position-list size field to the writers output.
188863*/
188864static void fts5WriteAppendRowid(
188865  Fts5Index *p,
188866  Fts5SegWriter *pWriter,
188867  i64 iRowid
188868){
188869  if( p->rc==SQLITE_OK ){
188870    Fts5PageWriter *pPage = &pWriter->writer;
188871
188872    if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
188873      fts5WriteFlushLeaf(p, pWriter);
188874    }
188875
188876    /* If this is to be the first rowid written to the page, set the
188877    ** rowid-pointer in the page-header. Also append a value to the dlidx
188878    ** buffer, in case a doclist-index is required.  */
188879    if( pWriter->bFirstRowidInPage ){
188880      fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
188881      fts5WriteDlidxAppend(p, pWriter, iRowid);
188882    }
188883
188884    /* Write the rowid. */
188885    if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
188886      fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
188887    }else{
188888      assert( p->rc || iRowid>pWriter->iPrevRowid );
188889      fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
188890    }
188891    pWriter->iPrevRowid = iRowid;
188892    pWriter->bFirstRowidInDoclist = 0;
188893    pWriter->bFirstRowidInPage = 0;
188894  }
188895}
188896
188897static void fts5WriteAppendPoslistData(
188898  Fts5Index *p,
188899  Fts5SegWriter *pWriter,
188900  const u8 *aData,
188901  int nData
188902){
188903  Fts5PageWriter *pPage = &pWriter->writer;
188904  const u8 *a = aData;
188905  int n = nData;
188906
188907  assert( p->pConfig->pgsz>0 );
188908  while( p->rc==SQLITE_OK
188909     && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
188910  ){
188911    int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
188912    int nCopy = 0;
188913    while( nCopy<nReq ){
188914      i64 dummy;
188915      nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
188916    }
188917    fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
188918    a += nCopy;
188919    n -= nCopy;
188920    fts5WriteFlushLeaf(p, pWriter);
188921  }
188922  if( n>0 ){
188923    fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
188924  }
188925}
188926
188927/*
188928** Flush any data cached by the writer object to the database. Free any
188929** allocations associated with the writer.
188930*/
188931static void fts5WriteFinish(
188932  Fts5Index *p,
188933  Fts5SegWriter *pWriter,         /* Writer object */
188934  int *pnLeaf                     /* OUT: Number of leaf pages in b-tree */
188935){
188936  int i;
188937  Fts5PageWriter *pLeaf = &pWriter->writer;
188938  if( p->rc==SQLITE_OK ){
188939    assert( pLeaf->pgno>=1 );
188940    if( pLeaf->buf.n>4 ){
188941      fts5WriteFlushLeaf(p, pWriter);
188942    }
188943    *pnLeaf = pLeaf->pgno-1;
188944    if( pLeaf->pgno>1 ){
188945      fts5WriteFlushBtree(p, pWriter);
188946    }
188947  }
188948  fts5BufferFree(&pLeaf->term);
188949  fts5BufferFree(&pLeaf->buf);
188950  fts5BufferFree(&pLeaf->pgidx);
188951  fts5BufferFree(&pWriter->btterm);
188952
188953  for(i=0; i<pWriter->nDlidx; i++){
188954    sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
188955  }
188956  sqlite3_free(pWriter->aDlidx);
188957}
188958
188959static void fts5WriteInit(
188960  Fts5Index *p,
188961  Fts5SegWriter *pWriter,
188962  int iSegid
188963){
188964  const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
188965
188966  memset(pWriter, 0, sizeof(Fts5SegWriter));
188967  pWriter->iSegid = iSegid;
188968
188969  fts5WriteDlidxGrow(p, pWriter, 1);
188970  pWriter->writer.pgno = 1;
188971  pWriter->bFirstTermInPage = 1;
188972  pWriter->iBtPage = 1;
188973
188974  assert( pWriter->writer.buf.n==0 );
188975  assert( pWriter->writer.pgidx.n==0 );
188976
188977  /* Grow the two buffers to pgsz + padding bytes in size. */
188978  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
188979  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
188980
188981  if( p->pIdxWriter==0 ){
188982    Fts5Config *pConfig = p->pConfig;
188983    fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
188984          "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
188985          pConfig->zDb, pConfig->zName
188986    ));
188987  }
188988
188989  if( p->rc==SQLITE_OK ){
188990    /* Initialize the 4-byte leaf-page header to 0x00. */
188991    memset(pWriter->writer.buf.p, 0, 4);
188992    pWriter->writer.buf.n = 4;
188993
188994    /* Bind the current output segment id to the index-writer. This is an
188995    ** optimization over binding the same value over and over as rows are
188996    ** inserted into %_idx by the current writer.  */
188997    sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
188998  }
188999}
189000
189001/*
189002** Iterator pIter was used to iterate through the input segments of on an
189003** incremental merge operation. This function is called if the incremental
189004** merge step has finished but the input has not been completely exhausted.
189005*/
189006static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
189007  int i;
189008  Fts5Buffer buf;
189009  memset(&buf, 0, sizeof(Fts5Buffer));
189010  for(i=0; i<pIter->nSeg; i++){
189011    Fts5SegIter *pSeg = &pIter->aSeg[i];
189012    if( pSeg->pSeg==0 ){
189013      /* no-op */
189014    }else if( pSeg->pLeaf==0 ){
189015      /* All keys from this input segment have been transfered to the output.
189016      ** Set both the first and last page-numbers to 0 to indicate that the
189017      ** segment is now empty. */
189018      pSeg->pSeg->pgnoLast = 0;
189019      pSeg->pSeg->pgnoFirst = 0;
189020    }else{
189021      int iOff = pSeg->iTermLeafOffset;     /* Offset on new first leaf page */
189022      i64 iLeafRowid;
189023      Fts5Data *pData;
189024      int iId = pSeg->pSeg->iSegid;
189025      u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
189026
189027      iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
189028      pData = fts5DataRead(p, iLeafRowid);
189029      if( pData ){
189030        fts5BufferZero(&buf);
189031        fts5BufferGrow(&p->rc, &buf, pData->nn);
189032        fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
189033        fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
189034        fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
189035        fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
189036        if( p->rc==SQLITE_OK ){
189037          /* Set the szLeaf field */
189038          fts5PutU16(&buf.p[2], (u16)buf.n);
189039        }
189040
189041        /* Set up the new page-index array */
189042        fts5BufferAppendVarint(&p->rc, &buf, 4);
189043        if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
189044         && pSeg->iEndofDoclist<pData->szLeaf
189045        ){
189046          int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
189047          fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
189048          fts5BufferAppendBlob(&p->rc, &buf,
189049              pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
189050          );
189051        }
189052
189053        fts5DataRelease(pData);
189054        pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
189055        fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
189056        fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
189057      }
189058    }
189059  }
189060  fts5BufferFree(&buf);
189061}
189062
189063static void fts5MergeChunkCallback(
189064  Fts5Index *p,
189065  void *pCtx,
189066  const u8 *pChunk, int nChunk
189067){
189068  Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
189069  fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
189070}
189071
189072/*
189073**
189074*/
189075static void fts5IndexMergeLevel(
189076  Fts5Index *p,                   /* FTS5 backend object */
189077  Fts5Structure **ppStruct,       /* IN/OUT: Stucture of index */
189078  int iLvl,                       /* Level to read input from */
189079  int *pnRem                      /* Write up to this many output leaves */
189080){
189081  Fts5Structure *pStruct = *ppStruct;
189082  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
189083  Fts5StructureLevel *pLvlOut;
189084  Fts5Iter *pIter = 0;       /* Iterator to read input data */
189085  int nRem = pnRem ? *pnRem : 0;  /* Output leaf pages left to write */
189086  int nInput;                     /* Number of input segments */
189087  Fts5SegWriter writer;           /* Writer object */
189088  Fts5StructureSegment *pSeg;     /* Output segment */
189089  Fts5Buffer term;
189090  int bOldest;                    /* True if the output segment is the oldest */
189091  int eDetail = p->pConfig->eDetail;
189092  const int flags = FTS5INDEX_QUERY_NOOUTPUT;
189093
189094  assert( iLvl<pStruct->nLevel );
189095  assert( pLvl->nMerge<=pLvl->nSeg );
189096
189097  memset(&writer, 0, sizeof(Fts5SegWriter));
189098  memset(&term, 0, sizeof(Fts5Buffer));
189099  if( pLvl->nMerge ){
189100    pLvlOut = &pStruct->aLevel[iLvl+1];
189101    assert( pLvlOut->nSeg>0 );
189102    nInput = pLvl->nMerge;
189103    pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
189104
189105    fts5WriteInit(p, &writer, pSeg->iSegid);
189106    writer.writer.pgno = pSeg->pgnoLast+1;
189107    writer.iBtPage = 0;
189108  }else{
189109    int iSegid = fts5AllocateSegid(p, pStruct);
189110
189111    /* Extend the Fts5Structure object as required to ensure the output
189112    ** segment exists. */
189113    if( iLvl==pStruct->nLevel-1 ){
189114      fts5StructureAddLevel(&p->rc, ppStruct);
189115      pStruct = *ppStruct;
189116    }
189117    fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
189118    if( p->rc ) return;
189119    pLvl = &pStruct->aLevel[iLvl];
189120    pLvlOut = &pStruct->aLevel[iLvl+1];
189121
189122    fts5WriteInit(p, &writer, iSegid);
189123
189124    /* Add the new segment to the output level */
189125    pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
189126    pLvlOut->nSeg++;
189127    pSeg->pgnoFirst = 1;
189128    pSeg->iSegid = iSegid;
189129    pStruct->nSegment++;
189130
189131    /* Read input from all segments in the input level */
189132    nInput = pLvl->nSeg;
189133  }
189134  bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
189135
189136  assert( iLvl>=0 );
189137  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
189138      fts5MultiIterEof(p, pIter)==0;
189139      fts5MultiIterNext(p, pIter, 0, 0)
189140  ){
189141    Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
189142    int nPos;                     /* position-list size field value */
189143    int nTerm;
189144    const u8 *pTerm;
189145
189146    /* Check for key annihilation. */
189147    if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
189148
189149    pTerm = fts5MultiIterTerm(pIter, &nTerm);
189150    if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
189151      if( pnRem && writer.nLeafWritten>nRem ){
189152        break;
189153      }
189154
189155      /* This is a new term. Append a term to the output segment. */
189156      fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
189157      fts5BufferSet(&p->rc, &term, nTerm, pTerm);
189158    }
189159
189160    /* Append the rowid to the output */
189161    /* WRITEPOSLISTSIZE */
189162    fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
189163
189164    if( eDetail==FTS5_DETAIL_NONE ){
189165      if( pSegIter->bDel ){
189166        fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
189167        if( pSegIter->nPos>0 ){
189168          fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
189169        }
189170      }
189171    }else{
189172      /* Append the position-list data to the output */
189173      nPos = pSegIter->nPos*2 + pSegIter->bDel;
189174      fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
189175      fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
189176    }
189177  }
189178
189179  /* Flush the last leaf page to disk. Set the output segment b-tree height
189180  ** and last leaf page number at the same time.  */
189181  fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
189182
189183  if( fts5MultiIterEof(p, pIter) ){
189184    int i;
189185
189186    /* Remove the redundant segments from the %_data table */
189187    for(i=0; i<nInput; i++){
189188      fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
189189    }
189190
189191    /* Remove the redundant segments from the input level */
189192    if( pLvl->nSeg!=nInput ){
189193      int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
189194      memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
189195    }
189196    pStruct->nSegment -= nInput;
189197    pLvl->nSeg -= nInput;
189198    pLvl->nMerge = 0;
189199    if( pSeg->pgnoLast==0 ){
189200      pLvlOut->nSeg--;
189201      pStruct->nSegment--;
189202    }
189203  }else{
189204    assert( pSeg->pgnoLast>0 );
189205    fts5TrimSegments(p, pIter);
189206    pLvl->nMerge = nInput;
189207  }
189208
189209  fts5MultiIterFree(pIter);
189210  fts5BufferFree(&term);
189211  if( pnRem ) *pnRem -= writer.nLeafWritten;
189212}
189213
189214/*
189215** Do up to nPg pages of automerge work on the index.
189216**
189217** Return true if any changes were actually made, or false otherwise.
189218*/
189219static int fts5IndexMerge(
189220  Fts5Index *p,                   /* FTS5 backend object */
189221  Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
189222  int nPg,                        /* Pages of work to do */
189223  int nMin                        /* Minimum number of segments to merge */
189224){
189225  int nRem = nPg;
189226  int bRet = 0;
189227  Fts5Structure *pStruct = *ppStruct;
189228  while( nRem>0 && p->rc==SQLITE_OK ){
189229    int iLvl;                   /* To iterate through levels */
189230    int iBestLvl = 0;           /* Level offering the most input segments */
189231    int nBest = 0;              /* Number of input segments on best level */
189232
189233    /* Set iBestLvl to the level to read input segments from. */
189234    assert( pStruct->nLevel>0 );
189235    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
189236      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
189237      if( pLvl->nMerge ){
189238        if( pLvl->nMerge>nBest ){
189239          iBestLvl = iLvl;
189240          nBest = pLvl->nMerge;
189241        }
189242        break;
189243      }
189244      if( pLvl->nSeg>nBest ){
189245        nBest = pLvl->nSeg;
189246        iBestLvl = iLvl;
189247      }
189248    }
189249
189250    /* If nBest is still 0, then the index must be empty. */
189251#ifdef SQLITE_DEBUG
189252    for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
189253      assert( pStruct->aLevel[iLvl].nSeg==0 );
189254    }
189255#endif
189256
189257    if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
189258      break;
189259    }
189260    bRet = 1;
189261    fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
189262    if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
189263      fts5StructurePromote(p, iBestLvl+1, pStruct);
189264    }
189265  }
189266  *ppStruct = pStruct;
189267  return bRet;
189268}
189269
189270/*
189271** A total of nLeaf leaf pages of data has just been flushed to a level-0
189272** segment. This function updates the write-counter accordingly and, if
189273** necessary, performs incremental merge work.
189274**
189275** If an error occurs, set the Fts5Index.rc error code. If an error has
189276** already occurred, this function is a no-op.
189277*/
189278static void fts5IndexAutomerge(
189279  Fts5Index *p,                   /* FTS5 backend object */
189280  Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
189281  int nLeaf                       /* Number of output leaves just written */
189282){
189283  if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
189284    Fts5Structure *pStruct = *ppStruct;
189285    u64 nWrite;                   /* Initial value of write-counter */
189286    int nWork;                    /* Number of work-quanta to perform */
189287    int nRem;                     /* Number of leaf pages left to write */
189288
189289    /* Update the write-counter. While doing so, set nWork. */
189290    nWrite = pStruct->nWriteCounter;
189291    nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
189292    pStruct->nWriteCounter += nLeaf;
189293    nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
189294
189295    fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
189296  }
189297}
189298
189299static void fts5IndexCrisismerge(
189300  Fts5Index *p,                   /* FTS5 backend object */
189301  Fts5Structure **ppStruct        /* IN/OUT: Current structure of index */
189302){
189303  const int nCrisis = p->pConfig->nCrisisMerge;
189304  Fts5Structure *pStruct = *ppStruct;
189305  int iLvl = 0;
189306
189307  assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
189308  while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
189309    fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
189310    assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
189311    fts5StructurePromote(p, iLvl+1, pStruct);
189312    iLvl++;
189313  }
189314  *ppStruct = pStruct;
189315}
189316
189317static int fts5IndexReturn(Fts5Index *p){
189318  int rc = p->rc;
189319  p->rc = SQLITE_OK;
189320  return rc;
189321}
189322
189323typedef struct Fts5FlushCtx Fts5FlushCtx;
189324struct Fts5FlushCtx {
189325  Fts5Index *pIdx;
189326  Fts5SegWriter writer;
189327};
189328
189329/*
189330** Buffer aBuf[] contains a list of varints, all small enough to fit
189331** in a 32-bit integer. Return the size of the largest prefix of this
189332** list nMax bytes or less in size.
189333*/
189334static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
189335  int ret;
189336  u32 dummy;
189337  ret = fts5GetVarint32(aBuf, dummy);
189338  if( ret<nMax ){
189339    while( 1 ){
189340      int i = fts5GetVarint32(&aBuf[ret], dummy);
189341      if( (ret + i) > nMax ) break;
189342      ret += i;
189343    }
189344  }
189345  return ret;
189346}
189347
189348/*
189349** Flush the contents of in-memory hash table iHash to a new level-0
189350** segment on disk. Also update the corresponding structure record.
189351**
189352** If an error occurs, set the Fts5Index.rc error code. If an error has
189353** already occurred, this function is a no-op.
189354*/
189355static void fts5FlushOneHash(Fts5Index *p){
189356  Fts5Hash *pHash = p->pHash;
189357  Fts5Structure *pStruct;
189358  int iSegid;
189359  int pgnoLast = 0;                 /* Last leaf page number in segment */
189360
189361  /* Obtain a reference to the index structure and allocate a new segment-id
189362  ** for the new level-0 segment.  */
189363  pStruct = fts5StructureRead(p);
189364  iSegid = fts5AllocateSegid(p, pStruct);
189365  fts5StructureInvalidate(p);
189366
189367  if( iSegid ){
189368    const int pgsz = p->pConfig->pgsz;
189369    int eDetail = p->pConfig->eDetail;
189370    Fts5StructureSegment *pSeg;   /* New segment within pStruct */
189371    Fts5Buffer *pBuf;             /* Buffer in which to assemble leaf page */
189372    Fts5Buffer *pPgidx;           /* Buffer in which to assemble pgidx */
189373
189374    Fts5SegWriter writer;
189375    fts5WriteInit(p, &writer, iSegid);
189376
189377    pBuf = &writer.writer.buf;
189378    pPgidx = &writer.writer.pgidx;
189379
189380    /* fts5WriteInit() should have initialized the buffers to (most likely)
189381    ** the maximum space required. */
189382    assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
189383    assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
189384
189385    /* Begin scanning through hash table entries. This loop runs once for each
189386    ** term/doclist currently stored within the hash table. */
189387    if( p->rc==SQLITE_OK ){
189388      p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
189389    }
189390    while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
189391      const char *zTerm;          /* Buffer containing term */
189392      const u8 *pDoclist;         /* Pointer to doclist for this term */
189393      int nDoclist;               /* Size of doclist in bytes */
189394
189395      /* Write the term for this entry to disk. */
189396      sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
189397      fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
189398
189399      assert( writer.bFirstRowidInPage==0 );
189400      if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
189401        /* The entire doclist will fit on the current leaf. */
189402        fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
189403      }else{
189404        i64 iRowid = 0;
189405        i64 iDelta = 0;
189406        int iOff = 0;
189407
189408        /* The entire doclist will not fit on this leaf. The following
189409        ** loop iterates through the poslists that make up the current
189410        ** doclist.  */
189411        while( p->rc==SQLITE_OK && iOff<nDoclist ){
189412          iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
189413          iRowid += iDelta;
189414
189415          if( writer.bFirstRowidInPage ){
189416            fts5PutU16(&pBuf->p[0], (u16)pBuf->n);   /* first rowid on page */
189417            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
189418            writer.bFirstRowidInPage = 0;
189419            fts5WriteDlidxAppend(p, &writer, iRowid);
189420          }else{
189421            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
189422          }
189423          assert( pBuf->n<=pBuf->nSpace );
189424
189425          if( eDetail==FTS5_DETAIL_NONE ){
189426            if( iOff<nDoclist && pDoclist[iOff]==0 ){
189427              pBuf->p[pBuf->n++] = 0;
189428              iOff++;
189429              if( iOff<nDoclist && pDoclist[iOff]==0 ){
189430                pBuf->p[pBuf->n++] = 0;
189431                iOff++;
189432              }
189433            }
189434            if( (pBuf->n + pPgidx->n)>=pgsz ){
189435              fts5WriteFlushLeaf(p, &writer);
189436            }
189437          }else{
189438            int bDummy;
189439            int nPos;
189440            int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
189441            nCopy += nPos;
189442            if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
189443              /* The entire poslist will fit on the current leaf. So copy
189444              ** it in one go. */
189445              fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
189446            }else{
189447              /* The entire poslist will not fit on this leaf. So it needs
189448              ** to be broken into sections. The only qualification being
189449              ** that each varint must be stored contiguously.  */
189450              const u8 *pPoslist = &pDoclist[iOff];
189451              int iPos = 0;
189452              while( p->rc==SQLITE_OK ){
189453                int nSpace = pgsz - pBuf->n - pPgidx->n;
189454                int n = 0;
189455                if( (nCopy - iPos)<=nSpace ){
189456                  n = nCopy - iPos;
189457                }else{
189458                  n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
189459                }
189460                assert( n>0 );
189461                fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
189462                iPos += n;
189463                if( (pBuf->n + pPgidx->n)>=pgsz ){
189464                  fts5WriteFlushLeaf(p, &writer);
189465                }
189466                if( iPos>=nCopy ) break;
189467              }
189468            }
189469            iOff += nCopy;
189470          }
189471        }
189472      }
189473
189474      /* TODO2: Doclist terminator written here. */
189475      /* pBuf->p[pBuf->n++] = '\0'; */
189476      assert( pBuf->n<=pBuf->nSpace );
189477      sqlite3Fts5HashScanNext(pHash);
189478    }
189479    sqlite3Fts5HashClear(pHash);
189480    fts5WriteFinish(p, &writer, &pgnoLast);
189481
189482    /* Update the Fts5Structure. It is written back to the database by the
189483    ** fts5StructureRelease() call below.  */
189484    if( pStruct->nLevel==0 ){
189485      fts5StructureAddLevel(&p->rc, &pStruct);
189486    }
189487    fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
189488    if( p->rc==SQLITE_OK ){
189489      pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
189490      pSeg->iSegid = iSegid;
189491      pSeg->pgnoFirst = 1;
189492      pSeg->pgnoLast = pgnoLast;
189493      pStruct->nSegment++;
189494    }
189495    fts5StructurePromote(p, 0, pStruct);
189496  }
189497
189498  fts5IndexAutomerge(p, &pStruct, pgnoLast);
189499  fts5IndexCrisismerge(p, &pStruct);
189500  fts5StructureWrite(p, pStruct);
189501  fts5StructureRelease(pStruct);
189502}
189503
189504/*
189505** Flush any data stored in the in-memory hash tables to the database.
189506*/
189507static void fts5IndexFlush(Fts5Index *p){
189508  /* Unless it is empty, flush the hash table to disk */
189509  if( p->nPendingData ){
189510    assert( p->pHash );
189511    p->nPendingData = 0;
189512    fts5FlushOneHash(p);
189513  }
189514}
189515
189516static Fts5Structure *fts5IndexOptimizeStruct(
189517  Fts5Index *p,
189518  Fts5Structure *pStruct
189519){
189520  Fts5Structure *pNew = 0;
189521  int nByte = sizeof(Fts5Structure);
189522  int nSeg = pStruct->nSegment;
189523  int i;
189524
189525  /* Figure out if this structure requires optimization. A structure does
189526  ** not require optimization if either:
189527  **
189528  **  + it consists of fewer than two segments, or
189529  **  + all segments are on the same level, or
189530  **  + all segments except one are currently inputs to a merge operation.
189531  **
189532  ** In the first case, return NULL. In the second, increment the ref-count
189533  ** on *pStruct and return a copy of the pointer to it.
189534  */
189535  if( nSeg<2 ) return 0;
189536  for(i=0; i<pStruct->nLevel; i++){
189537    int nThis = pStruct->aLevel[i].nSeg;
189538    if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
189539      fts5StructureRef(pStruct);
189540      return pStruct;
189541    }
189542    assert( pStruct->aLevel[i].nMerge<=nThis );
189543  }
189544
189545  nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
189546  pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
189547
189548  if( pNew ){
189549    Fts5StructureLevel *pLvl;
189550    nByte = nSeg * sizeof(Fts5StructureSegment);
189551    pNew->nLevel = pStruct->nLevel+1;
189552    pNew->nRef = 1;
189553    pNew->nWriteCounter = pStruct->nWriteCounter;
189554    pLvl = &pNew->aLevel[pStruct->nLevel];
189555    pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
189556    if( pLvl->aSeg ){
189557      int iLvl, iSeg;
189558      int iSegOut = 0;
189559      /* Iterate through all segments, from oldest to newest. Add them to
189560      ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
189561      ** segment in the data structure.  */
189562      for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
189563        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
189564          pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
189565          iSegOut++;
189566        }
189567      }
189568      pNew->nSegment = pLvl->nSeg = nSeg;
189569    }else{
189570      sqlite3_free(pNew);
189571      pNew = 0;
189572    }
189573  }
189574
189575  return pNew;
189576}
189577
189578static int sqlite3Fts5IndexOptimize(Fts5Index *p){
189579  Fts5Structure *pStruct;
189580  Fts5Structure *pNew = 0;
189581
189582  assert( p->rc==SQLITE_OK );
189583  fts5IndexFlush(p);
189584  pStruct = fts5StructureRead(p);
189585  fts5StructureInvalidate(p);
189586
189587  if( pStruct ){
189588    pNew = fts5IndexOptimizeStruct(p, pStruct);
189589  }
189590  fts5StructureRelease(pStruct);
189591
189592  assert( pNew==0 || pNew->nSegment>0 );
189593  if( pNew ){
189594    int iLvl;
189595    for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
189596    while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
189597      int nRem = FTS5_OPT_WORK_UNIT;
189598      fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
189599    }
189600
189601    fts5StructureWrite(p, pNew);
189602    fts5StructureRelease(pNew);
189603  }
189604
189605  return fts5IndexReturn(p);
189606}
189607
189608/*
189609** This is called to implement the special "VALUES('merge', $nMerge)"
189610** INSERT command.
189611*/
189612static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
189613  Fts5Structure *pStruct = fts5StructureRead(p);
189614  if( pStruct ){
189615    int nMin = p->pConfig->nUsermerge;
189616    fts5StructureInvalidate(p);
189617    if( nMerge<0 ){
189618      Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
189619      fts5StructureRelease(pStruct);
189620      pStruct = pNew;
189621      nMin = 2;
189622      nMerge = nMerge*-1;
189623    }
189624    if( pStruct && pStruct->nLevel ){
189625      if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
189626        fts5StructureWrite(p, pStruct);
189627      }
189628    }
189629    fts5StructureRelease(pStruct);
189630  }
189631  return fts5IndexReturn(p);
189632}
189633
189634static void fts5AppendRowid(
189635  Fts5Index *p,
189636  i64 iDelta,
189637  Fts5Iter *pUnused,
189638  Fts5Buffer *pBuf
189639){
189640  UNUSED_PARAM(pUnused);
189641  fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
189642}
189643
189644static void fts5AppendPoslist(
189645  Fts5Index *p,
189646  i64 iDelta,
189647  Fts5Iter *pMulti,
189648  Fts5Buffer *pBuf
189649){
189650  int nData = pMulti->base.nData;
189651  assert( nData>0 );
189652  if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
189653    fts5BufferSafeAppendVarint(pBuf, iDelta);
189654    fts5BufferSafeAppendVarint(pBuf, nData*2);
189655    fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
189656  }
189657}
189658
189659
189660static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
189661  u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
189662
189663  assert( pIter->aPoslist );
189664  if( p>=pIter->aEof ){
189665    pIter->aPoslist = 0;
189666  }else{
189667    i64 iDelta;
189668
189669    p += fts5GetVarint(p, (u64*)&iDelta);
189670    pIter->iRowid += iDelta;
189671
189672    /* Read position list size */
189673    if( p[0] & 0x80 ){
189674      int nPos;
189675      pIter->nSize = fts5GetVarint32(p, nPos);
189676      pIter->nPoslist = (nPos>>1);
189677    }else{
189678      pIter->nPoslist = ((int)(p[0])) >> 1;
189679      pIter->nSize = 1;
189680    }
189681
189682    pIter->aPoslist = p;
189683  }
189684}
189685
189686static void fts5DoclistIterInit(
189687  Fts5Buffer *pBuf,
189688  Fts5DoclistIter *pIter
189689){
189690  memset(pIter, 0, sizeof(*pIter));
189691  pIter->aPoslist = pBuf->p;
189692  pIter->aEof = &pBuf->p[pBuf->n];
189693  fts5DoclistIterNext(pIter);
189694}
189695
189696#if 0
189697/*
189698** Append a doclist to buffer pBuf.
189699**
189700** This function assumes that space within the buffer has already been
189701** allocated.
189702*/
189703static void fts5MergeAppendDocid(
189704  Fts5Buffer *pBuf,               /* Buffer to write to */
189705  i64 *piLastRowid,               /* IN/OUT: Previous rowid written (if any) */
189706  i64 iRowid                      /* Rowid to append */
189707){
189708  assert( pBuf->n!=0 || (*piLastRowid)==0 );
189709  fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
189710  *piLastRowid = iRowid;
189711}
189712#endif
189713
189714#define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) {       \
189715  assert( (pBuf)->n!=0 || (iLastRowid)==0 );                   \
189716  fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
189717  (iLastRowid) = (iRowid);                                     \
189718}
189719
189720/*
189721** Swap the contents of buffer *p1 with that of *p2.
189722*/
189723static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
189724  Fts5Buffer tmp = *p1;
189725  *p1 = *p2;
189726  *p2 = tmp;
189727}
189728
189729static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
189730  int i = *piOff;
189731  if( i>=pBuf->n ){
189732    *piOff = -1;
189733  }else{
189734    u64 iVal;
189735    *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
189736    *piRowid += iVal;
189737  }
189738}
189739
189740/*
189741** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
189742** In this case the buffers consist of a delta-encoded list of rowids only.
189743*/
189744static void fts5MergeRowidLists(
189745  Fts5Index *p,                   /* FTS5 backend object */
189746  Fts5Buffer *p1,                 /* First list to merge */
189747  Fts5Buffer *p2                  /* Second list to merge */
189748){
189749  int i1 = 0;
189750  int i2 = 0;
189751  i64 iRowid1 = 0;
189752  i64 iRowid2 = 0;
189753  i64 iOut = 0;
189754
189755  Fts5Buffer out;
189756  memset(&out, 0, sizeof(out));
189757  sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
189758  if( p->rc ) return;
189759
189760  fts5NextRowid(p1, &i1, &iRowid1);
189761  fts5NextRowid(p2, &i2, &iRowid2);
189762  while( i1>=0 || i2>=0 ){
189763    if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
189764      assert( iOut==0 || iRowid1>iOut );
189765      fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
189766      iOut = iRowid1;
189767      fts5NextRowid(p1, &i1, &iRowid1);
189768    }else{
189769      assert( iOut==0 || iRowid2>iOut );
189770      fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
189771      iOut = iRowid2;
189772      if( i1>=0 && iRowid1==iRowid2 ){
189773        fts5NextRowid(p1, &i1, &iRowid1);
189774      }
189775      fts5NextRowid(p2, &i2, &iRowid2);
189776    }
189777  }
189778
189779  fts5BufferSwap(&out, p1);
189780  fts5BufferFree(&out);
189781}
189782
189783/*
189784** Buffers p1 and p2 contain doclists. This function merges the content
189785** of the two doclists together and sets buffer p1 to the result before
189786** returning.
189787**
189788** If an error occurs, an error code is left in p->rc. If an error has
189789** already occurred, this function is a no-op.
189790*/
189791static void fts5MergePrefixLists(
189792  Fts5Index *p,                   /* FTS5 backend object */
189793  Fts5Buffer *p1,                 /* First list to merge */
189794  Fts5Buffer *p2                  /* Second list to merge */
189795){
189796  if( p2->n ){
189797    i64 iLastRowid = 0;
189798    Fts5DoclistIter i1;
189799    Fts5DoclistIter i2;
189800    Fts5Buffer out = {0, 0, 0};
189801    Fts5Buffer tmp = {0, 0, 0};
189802
189803    if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n) ) return;
189804    fts5DoclistIterInit(p1, &i1);
189805    fts5DoclistIterInit(p2, &i2);
189806
189807    while( 1 ){
189808      if( i1.iRowid<i2.iRowid ){
189809        /* Copy entry from i1 */
189810        fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
189811        fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
189812        fts5DoclistIterNext(&i1);
189813        if( i1.aPoslist==0 ) break;
189814      }
189815      else if( i2.iRowid!=i1.iRowid ){
189816        /* Copy entry from i2 */
189817        fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
189818        fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
189819        fts5DoclistIterNext(&i2);
189820        if( i2.aPoslist==0 ) break;
189821      }
189822      else{
189823        /* Merge the two position lists. */
189824        i64 iPos1 = 0;
189825        i64 iPos2 = 0;
189826        int iOff1 = 0;
189827        int iOff2 = 0;
189828        u8 *a1 = &i1.aPoslist[i1.nSize];
189829        u8 *a2 = &i2.aPoslist[i2.nSize];
189830
189831        i64 iPrev = 0;
189832        Fts5PoslistWriter writer;
189833        memset(&writer, 0, sizeof(writer));
189834
189835        fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
189836        fts5BufferZero(&tmp);
189837        sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
189838        if( p->rc ) break;
189839
189840        sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
189841        sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
189842        assert( iPos1>=0 && iPos2>=0 );
189843
189844        if( iPos1<iPos2 ){
189845          sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
189846          sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
189847        }else{
189848          sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
189849          sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
189850        }
189851
189852        if( iPos1>=0 && iPos2>=0 ){
189853          while( 1 ){
189854            if( iPos1<iPos2 ){
189855              if( iPos1!=iPrev ){
189856                sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
189857              }
189858              sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
189859              if( iPos1<0 ) break;
189860            }else{
189861              assert( iPos2!=iPrev );
189862              sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
189863              sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
189864              if( iPos2<0 ) break;
189865            }
189866          }
189867        }
189868
189869        if( iPos1>=0 ){
189870          if( iPos1!=iPrev ){
189871            sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
189872          }
189873          fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
189874        }else{
189875          assert( iPos2>=0 && iPos2!=iPrev );
189876          sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
189877          fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
189878        }
189879
189880        /* WRITEPOSLISTSIZE */
189881        fts5BufferSafeAppendVarint(&out, tmp.n * 2);
189882        fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
189883        fts5DoclistIterNext(&i1);
189884        fts5DoclistIterNext(&i2);
189885        if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
189886      }
189887    }
189888
189889    if( i1.aPoslist ){
189890      fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
189891      fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
189892    }
189893    else if( i2.aPoslist ){
189894      fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
189895      fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
189896    }
189897
189898    fts5BufferSet(&p->rc, p1, out.n, out.p);
189899    fts5BufferFree(&tmp);
189900    fts5BufferFree(&out);
189901  }
189902}
189903
189904static void fts5SetupPrefixIter(
189905  Fts5Index *p,                   /* Index to read from */
189906  int bDesc,                      /* True for "ORDER BY rowid DESC" */
189907  const u8 *pToken,               /* Buffer containing prefix to match */
189908  int nToken,                     /* Size of buffer pToken in bytes */
189909  Fts5Colset *pColset,            /* Restrict matches to these columns */
189910  Fts5Iter **ppIter          /* OUT: New iterator */
189911){
189912  Fts5Structure *pStruct;
189913  Fts5Buffer *aBuf;
189914  const int nBuf = 32;
189915
189916  void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
189917  void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
189918  if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
189919    xMerge = fts5MergeRowidLists;
189920    xAppend = fts5AppendRowid;
189921  }else{
189922    xMerge = fts5MergePrefixLists;
189923    xAppend = fts5AppendPoslist;
189924  }
189925
189926  aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
189927  pStruct = fts5StructureRead(p);
189928
189929  if( aBuf && pStruct ){
189930    const int flags = FTS5INDEX_QUERY_SCAN
189931                    | FTS5INDEX_QUERY_SKIPEMPTY
189932                    | FTS5INDEX_QUERY_NOOUTPUT;
189933    int i;
189934    i64 iLastRowid = 0;
189935    Fts5Iter *p1 = 0;     /* Iterator used to gather data from index */
189936    Fts5Data *pData;
189937    Fts5Buffer doclist;
189938    int bNewTerm = 1;
189939
189940    memset(&doclist, 0, sizeof(doclist));
189941    fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
189942    fts5IterSetOutputCb(&p->rc, p1);
189943    for( /* no-op */ ;
189944        fts5MultiIterEof(p, p1)==0;
189945        fts5MultiIterNext2(p, p1, &bNewTerm)
189946    ){
189947      Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
189948      int nTerm = pSeg->term.n;
189949      const u8 *pTerm = pSeg->term.p;
189950      p1->xSetOutputs(p1, pSeg);
189951
189952      assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
189953      if( bNewTerm ){
189954        if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
189955      }
189956
189957      if( p1->base.nData==0 ) continue;
189958
189959      if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
189960        for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
189961          assert( i<nBuf );
189962          if( aBuf[i].n==0 ){
189963            fts5BufferSwap(&doclist, &aBuf[i]);
189964            fts5BufferZero(&doclist);
189965          }else{
189966            xMerge(p, &doclist, &aBuf[i]);
189967            fts5BufferZero(&aBuf[i]);
189968          }
189969        }
189970        iLastRowid = 0;
189971      }
189972
189973      xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
189974      iLastRowid = p1->base.iRowid;
189975    }
189976
189977    for(i=0; i<nBuf; i++){
189978      if( p->rc==SQLITE_OK ){
189979        xMerge(p, &doclist, &aBuf[i]);
189980      }
189981      fts5BufferFree(&aBuf[i]);
189982    }
189983    fts5MultiIterFree(p1);
189984
189985    pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
189986    if( pData ){
189987      pData->p = (u8*)&pData[1];
189988      pData->nn = pData->szLeaf = doclist.n;
189989      memcpy(pData->p, doclist.p, doclist.n);
189990      fts5MultiIterNew2(p, pData, bDesc, ppIter);
189991    }
189992    fts5BufferFree(&doclist);
189993  }
189994
189995  fts5StructureRelease(pStruct);
189996  sqlite3_free(aBuf);
189997}
189998
189999
190000/*
190001** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
190002** to the document with rowid iRowid.
190003*/
190004static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
190005  assert( p->rc==SQLITE_OK );
190006
190007  /* Allocate the hash table if it has not already been allocated */
190008  if( p->pHash==0 ){
190009    p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
190010  }
190011
190012  /* Flush the hash table to disk if required */
190013  if( iRowid<p->iWriteRowid
190014   || (iRowid==p->iWriteRowid && p->bDelete==0)
190015   || (p->nPendingData > p->pConfig->nHashSize)
190016  ){
190017    fts5IndexFlush(p);
190018  }
190019
190020  p->iWriteRowid = iRowid;
190021  p->bDelete = bDelete;
190022  return fts5IndexReturn(p);
190023}
190024
190025/*
190026** Commit data to disk.
190027*/
190028static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit){
190029  assert( p->rc==SQLITE_OK );
190030  fts5IndexFlush(p);
190031  if( bCommit ) fts5CloseReader(p);
190032  return fts5IndexReturn(p);
190033}
190034
190035/*
190036** Discard any data stored in the in-memory hash tables. Do not write it
190037** to the database. Additionally, assume that the contents of the %_data
190038** table may have changed on disk. So any in-memory caches of %_data
190039** records must be invalidated.
190040*/
190041static int sqlite3Fts5IndexRollback(Fts5Index *p){
190042  fts5CloseReader(p);
190043  fts5IndexDiscardData(p);
190044  fts5StructureInvalidate(p);
190045  /* assert( p->rc==SQLITE_OK ); */
190046  return SQLITE_OK;
190047}
190048
190049/*
190050** The %_data table is completely empty when this function is called. This
190051** function populates it with the initial structure objects for each index,
190052** and the initial version of the "averages" record (a zero-byte blob).
190053*/
190054static int sqlite3Fts5IndexReinit(Fts5Index *p){
190055  Fts5Structure s;
190056  fts5StructureInvalidate(p);
190057  memset(&s, 0, sizeof(Fts5Structure));
190058  fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
190059  fts5StructureWrite(p, &s);
190060  return fts5IndexReturn(p);
190061}
190062
190063/*
190064** Open a new Fts5Index handle. If the bCreate argument is true, create
190065** and initialize the underlying %_data table.
190066**
190067** If successful, set *pp to point to the new object and return SQLITE_OK.
190068** Otherwise, set *pp to NULL and return an SQLite error code.
190069*/
190070static int sqlite3Fts5IndexOpen(
190071  Fts5Config *pConfig,
190072  int bCreate,
190073  Fts5Index **pp,
190074  char **pzErr
190075){
190076  int rc = SQLITE_OK;
190077  Fts5Index *p;                   /* New object */
190078
190079  *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
190080  if( rc==SQLITE_OK ){
190081    p->pConfig = pConfig;
190082    p->nWorkUnit = FTS5_WORK_UNIT;
190083    p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
190084    if( p->zDataTbl && bCreate ){
190085      rc = sqlite3Fts5CreateTable(
190086          pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
190087      );
190088      if( rc==SQLITE_OK ){
190089        rc = sqlite3Fts5CreateTable(pConfig, "idx",
190090            "segid, term, pgno, PRIMARY KEY(segid, term)",
190091            1, pzErr
190092        );
190093      }
190094      if( rc==SQLITE_OK ){
190095        rc = sqlite3Fts5IndexReinit(p);
190096      }
190097    }
190098  }
190099
190100  assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
190101  if( rc ){
190102    sqlite3Fts5IndexClose(p);
190103    *pp = 0;
190104  }
190105  return rc;
190106}
190107
190108/*
190109** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
190110*/
190111static int sqlite3Fts5IndexClose(Fts5Index *p){
190112  int rc = SQLITE_OK;
190113  if( p ){
190114    assert( p->pReader==0 );
190115    fts5StructureInvalidate(p);
190116    sqlite3_finalize(p->pWriter);
190117    sqlite3_finalize(p->pDeleter);
190118    sqlite3_finalize(p->pIdxWriter);
190119    sqlite3_finalize(p->pIdxDeleter);
190120    sqlite3_finalize(p->pIdxSelect);
190121    sqlite3_finalize(p->pDataVersion);
190122    sqlite3Fts5HashFree(p->pHash);
190123    sqlite3_free(p->zDataTbl);
190124    sqlite3_free(p);
190125  }
190126  return rc;
190127}
190128
190129/*
190130** Argument p points to a buffer containing utf-8 text that is n bytes in
190131** size. Return the number of bytes in the nChar character prefix of the
190132** buffer, or 0 if there are less than nChar characters in total.
190133*/
190134static int sqlite3Fts5IndexCharlenToBytelen(
190135  const char *p,
190136  int nByte,
190137  int nChar
190138){
190139  int n = 0;
190140  int i;
190141  for(i=0; i<nChar; i++){
190142    if( n>=nByte ) return 0;      /* Input contains fewer than nChar chars */
190143    if( (unsigned char)p[n++]>=0xc0 ){
190144      while( (p[n] & 0xc0)==0x80 ) n++;
190145    }
190146  }
190147  return n;
190148}
190149
190150/*
190151** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
190152** unicode characters in the string.
190153*/
190154static int fts5IndexCharlen(const char *pIn, int nIn){
190155  int nChar = 0;
190156  int i = 0;
190157  while( i<nIn ){
190158    if( (unsigned char)pIn[i++]>=0xc0 ){
190159      while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
190160    }
190161    nChar++;
190162  }
190163  return nChar;
190164}
190165
190166/*
190167** Insert or remove data to or from the index. Each time a document is
190168** added to or removed from the index, this function is called one or more
190169** times.
190170**
190171** For an insert, it must be called once for each token in the new document.
190172** If the operation is a delete, it must be called (at least) once for each
190173** unique token in the document with an iCol value less than zero. The iPos
190174** argument is ignored for a delete.
190175*/
190176static int sqlite3Fts5IndexWrite(
190177  Fts5Index *p,                   /* Index to write to */
190178  int iCol,                       /* Column token appears in (-ve -> delete) */
190179  int iPos,                       /* Position of token within column */
190180  const char *pToken, int nToken  /* Token to add or remove to or from index */
190181){
190182  int i;                          /* Used to iterate through indexes */
190183  int rc = SQLITE_OK;             /* Return code */
190184  Fts5Config *pConfig = p->pConfig;
190185
190186  assert( p->rc==SQLITE_OK );
190187  assert( (iCol<0)==p->bDelete );
190188
190189  /* Add the entry to the main terms index. */
190190  rc = sqlite3Fts5HashWrite(
190191      p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
190192  );
190193
190194  for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
190195    const int nChar = pConfig->aPrefix[i];
190196    int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
190197    if( nByte ){
190198      rc = sqlite3Fts5HashWrite(p->pHash,
190199          p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
190200          nByte
190201      );
190202    }
190203  }
190204
190205  return rc;
190206}
190207
190208/*
190209** Open a new iterator to iterate though all rowid that match the
190210** specified token or token prefix.
190211*/
190212static int sqlite3Fts5IndexQuery(
190213  Fts5Index *p,                   /* FTS index to query */
190214  const char *pToken, int nToken, /* Token (or prefix) to query for */
190215  int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
190216  Fts5Colset *pColset,            /* Match these columns only */
190217  Fts5IndexIter **ppIter          /* OUT: New iterator object */
190218){
190219  Fts5Config *pConfig = p->pConfig;
190220  Fts5Iter *pRet = 0;
190221  Fts5Buffer buf = {0, 0, 0};
190222
190223  /* If the QUERY_SCAN flag is set, all other flags must be clear. */
190224  assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
190225
190226  if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
190227    int iIdx = 0;                 /* Index to search */
190228    memcpy(&buf.p[1], pToken, nToken);
190229
190230    /* Figure out which index to search and set iIdx accordingly. If this
190231    ** is a prefix query for which there is no prefix index, set iIdx to
190232    ** greater than pConfig->nPrefix to indicate that the query will be
190233    ** satisfied by scanning multiple terms in the main index.
190234    **
190235    ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
190236    ** prefix-query. Instead of using a prefix-index (if one exists),
190237    ** evaluate the prefix query using the main FTS index. This is used
190238    ** for internal sanity checking by the integrity-check in debug
190239    ** mode only.  */
190240#ifdef SQLITE_DEBUG
190241    if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
190242      assert( flags & FTS5INDEX_QUERY_PREFIX );
190243      iIdx = 1+pConfig->nPrefix;
190244    }else
190245#endif
190246    if( flags & FTS5INDEX_QUERY_PREFIX ){
190247      int nChar = fts5IndexCharlen(pToken, nToken);
190248      for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
190249        if( pConfig->aPrefix[iIdx-1]==nChar ) break;
190250      }
190251    }
190252
190253    if( iIdx<=pConfig->nPrefix ){
190254      /* Straight index lookup */
190255      Fts5Structure *pStruct = fts5StructureRead(p);
190256      buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
190257      if( pStruct ){
190258        fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
190259            pColset, buf.p, nToken+1, -1, 0, &pRet
190260        );
190261        fts5StructureRelease(pStruct);
190262      }
190263    }else{
190264      /* Scan multiple terms in the main index */
190265      int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
190266      buf.p[0] = FTS5_MAIN_PREFIX;
190267      fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
190268      assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
190269      fts5IterSetOutputCb(&p->rc, pRet);
190270      if( p->rc==SQLITE_OK ){
190271        Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
190272        if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
190273      }
190274    }
190275
190276    if( p->rc ){
190277      sqlite3Fts5IterClose(&pRet->base);
190278      pRet = 0;
190279      fts5CloseReader(p);
190280    }
190281
190282    *ppIter = &pRet->base;
190283    sqlite3Fts5BufferFree(&buf);
190284  }
190285  return fts5IndexReturn(p);
190286}
190287
190288/*
190289** Return true if the iterator passed as the only argument is at EOF.
190290*/
190291/*
190292** Move to the next matching rowid.
190293*/
190294static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
190295  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
190296  assert( pIter->pIndex->rc==SQLITE_OK );
190297  fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
190298  return fts5IndexReturn(pIter->pIndex);
190299}
190300
190301/*
190302** Move to the next matching term/rowid. Used by the fts5vocab module.
190303*/
190304static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
190305  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
190306  Fts5Index *p = pIter->pIndex;
190307
190308  assert( pIter->pIndex->rc==SQLITE_OK );
190309
190310  fts5MultiIterNext(p, pIter, 0, 0);
190311  if( p->rc==SQLITE_OK ){
190312    Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
190313    if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
190314      fts5DataRelease(pSeg->pLeaf);
190315      pSeg->pLeaf = 0;
190316      pIter->base.bEof = 1;
190317    }
190318  }
190319
190320  return fts5IndexReturn(pIter->pIndex);
190321}
190322
190323/*
190324** Move to the next matching rowid that occurs at or after iMatch. The
190325** definition of "at or after" depends on whether this iterator iterates
190326** in ascending or descending rowid order.
190327*/
190328static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
190329  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
190330  fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
190331  return fts5IndexReturn(pIter->pIndex);
190332}
190333
190334/*
190335** Return the current term.
190336*/
190337static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
190338  int n;
190339  const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
190340  *pn = n-1;
190341  return &z[1];
190342}
190343
190344/*
190345** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
190346*/
190347static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
190348  if( pIndexIter ){
190349    Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
190350    Fts5Index *pIndex = pIter->pIndex;
190351    fts5MultiIterFree(pIter);
190352    fts5CloseReader(pIndex);
190353  }
190354}
190355
190356/*
190357** Read and decode the "averages" record from the database.
190358**
190359** Parameter anSize must point to an array of size nCol, where nCol is
190360** the number of user defined columns in the FTS table.
190361*/
190362static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
190363  int nCol = p->pConfig->nCol;
190364  Fts5Data *pData;
190365
190366  *pnRow = 0;
190367  memset(anSize, 0, sizeof(i64) * nCol);
190368  pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
190369  if( p->rc==SQLITE_OK && pData->nn ){
190370    int i = 0;
190371    int iCol;
190372    i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
190373    for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
190374      i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
190375    }
190376  }
190377
190378  fts5DataRelease(pData);
190379  return fts5IndexReturn(p);
190380}
190381
190382/*
190383** Replace the current "averages" record with the contents of the buffer
190384** supplied as the second argument.
190385*/
190386static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
190387  assert( p->rc==SQLITE_OK );
190388  fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
190389  return fts5IndexReturn(p);
190390}
190391
190392/*
190393** Return the total number of blocks this module has read from the %_data
190394** table since it was created.
190395*/
190396static int sqlite3Fts5IndexReads(Fts5Index *p){
190397  return p->nRead;
190398}
190399
190400/*
190401** Set the 32-bit cookie value stored at the start of all structure
190402** records to the value passed as the second argument.
190403**
190404** Return SQLITE_OK if successful, or an SQLite error code if an error
190405** occurs.
190406*/
190407static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
190408  int rc;                              /* Return code */
190409  Fts5Config *pConfig = p->pConfig;    /* Configuration object */
190410  u8 aCookie[4];                       /* Binary representation of iNew */
190411  sqlite3_blob *pBlob = 0;
190412
190413  assert( p->rc==SQLITE_OK );
190414  sqlite3Fts5Put32(aCookie, iNew);
190415
190416  rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
190417      "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
190418  );
190419  if( rc==SQLITE_OK ){
190420    sqlite3_blob_write(pBlob, aCookie, 4, 0);
190421    rc = sqlite3_blob_close(pBlob);
190422  }
190423
190424  return rc;
190425}
190426
190427static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
190428  Fts5Structure *pStruct;
190429  pStruct = fts5StructureRead(p);
190430  fts5StructureRelease(pStruct);
190431  return fts5IndexReturn(p);
190432}
190433
190434
190435/*************************************************************************
190436**************************************************************************
190437** Below this point is the implementation of the integrity-check
190438** functionality.
190439*/
190440
190441/*
190442** Return a simple checksum value based on the arguments.
190443*/
190444static u64 sqlite3Fts5IndexEntryCksum(
190445  i64 iRowid,
190446  int iCol,
190447  int iPos,
190448  int iIdx,
190449  const char *pTerm,
190450  int nTerm
190451){
190452  int i;
190453  u64 ret = iRowid;
190454  ret += (ret<<3) + iCol;
190455  ret += (ret<<3) + iPos;
190456  if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
190457  for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
190458  return ret;
190459}
190460
190461#ifdef SQLITE_DEBUG
190462/*
190463** This function is purely an internal test. It does not contribute to
190464** FTS functionality, or even the integrity-check, in any way.
190465**
190466** Instead, it tests that the same set of pgno/rowid combinations are
190467** visited regardless of whether the doclist-index identified by parameters
190468** iSegid/iLeaf is iterated in forwards or reverse order.
190469*/
190470static void fts5TestDlidxReverse(
190471  Fts5Index *p,
190472  int iSegid,                     /* Segment id to load from */
190473  int iLeaf                       /* Load doclist-index for this leaf */
190474){
190475  Fts5DlidxIter *pDlidx = 0;
190476  u64 cksum1 = 13;
190477  u64 cksum2 = 13;
190478
190479  for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
190480      fts5DlidxIterEof(p, pDlidx)==0;
190481      fts5DlidxIterNext(p, pDlidx)
190482  ){
190483    i64 iRowid = fts5DlidxIterRowid(pDlidx);
190484    int pgno = fts5DlidxIterPgno(pDlidx);
190485    assert( pgno>iLeaf );
190486    cksum1 += iRowid + ((i64)pgno<<32);
190487  }
190488  fts5DlidxIterFree(pDlidx);
190489  pDlidx = 0;
190490
190491  for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
190492      fts5DlidxIterEof(p, pDlidx)==0;
190493      fts5DlidxIterPrev(p, pDlidx)
190494  ){
190495    i64 iRowid = fts5DlidxIterRowid(pDlidx);
190496    int pgno = fts5DlidxIterPgno(pDlidx);
190497    assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
190498    cksum2 += iRowid + ((i64)pgno<<32);
190499  }
190500  fts5DlidxIterFree(pDlidx);
190501  pDlidx = 0;
190502
190503  if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
190504}
190505
190506static int fts5QueryCksum(
190507  Fts5Index *p,                   /* Fts5 index object */
190508  int iIdx,
190509  const char *z,                  /* Index key to query for */
190510  int n,                          /* Size of index key in bytes */
190511  int flags,                      /* Flags for Fts5IndexQuery */
190512  u64 *pCksum                     /* IN/OUT: Checksum value */
190513){
190514  int eDetail = p->pConfig->eDetail;
190515  u64 cksum = *pCksum;
190516  Fts5IndexIter *pIter = 0;
190517  int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
190518
190519  while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
190520    i64 rowid = pIter->iRowid;
190521
190522    if( eDetail==FTS5_DETAIL_NONE ){
190523      cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
190524    }else{
190525      Fts5PoslistReader sReader;
190526      for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
190527          sReader.bEof==0;
190528          sqlite3Fts5PoslistReaderNext(&sReader)
190529      ){
190530        int iCol = FTS5_POS2COLUMN(sReader.iPos);
190531        int iOff = FTS5_POS2OFFSET(sReader.iPos);
190532        cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
190533      }
190534    }
190535    if( rc==SQLITE_OK ){
190536      rc = sqlite3Fts5IterNext(pIter);
190537    }
190538  }
190539  sqlite3Fts5IterClose(pIter);
190540
190541  *pCksum = cksum;
190542  return rc;
190543}
190544
190545
190546/*
190547** This function is also purely an internal test. It does not contribute to
190548** FTS functionality, or even the integrity-check, in any way.
190549*/
190550static void fts5TestTerm(
190551  Fts5Index *p,
190552  Fts5Buffer *pPrev,              /* Previous term */
190553  const char *z, int n,           /* Possibly new term to test */
190554  u64 expected,
190555  u64 *pCksum
190556){
190557  int rc = p->rc;
190558  if( pPrev->n==0 ){
190559    fts5BufferSet(&rc, pPrev, n, (const u8*)z);
190560  }else
190561  if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
190562    u64 cksum3 = *pCksum;
190563    const char *zTerm = (const char*)&pPrev->p[1];  /* term sans prefix-byte */
190564    int nTerm = pPrev->n-1;            /* Size of zTerm in bytes */
190565    int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
190566    int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
190567    u64 ck1 = 0;
190568    u64 ck2 = 0;
190569
190570    /* Check that the results returned for ASC and DESC queries are
190571    ** the same. If not, call this corruption.  */
190572    rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
190573    if( rc==SQLITE_OK ){
190574      int f = flags|FTS5INDEX_QUERY_DESC;
190575      rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
190576    }
190577    if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
190578
190579    /* If this is a prefix query, check that the results returned if the
190580    ** the index is disabled are the same. In both ASC and DESC order.
190581    **
190582    ** This check may only be performed if the hash table is empty. This
190583    ** is because the hash table only supports a single scan query at
190584    ** a time, and the multi-iter loop from which this function is called
190585    ** is already performing such a scan. */
190586    if( p->nPendingData==0 ){
190587      if( iIdx>0 && rc==SQLITE_OK ){
190588        int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
190589        ck2 = 0;
190590        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
190591        if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
190592      }
190593      if( iIdx>0 && rc==SQLITE_OK ){
190594        int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
190595        ck2 = 0;
190596        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
190597        if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
190598      }
190599    }
190600
190601    cksum3 ^= ck1;
190602    fts5BufferSet(&rc, pPrev, n, (const u8*)z);
190603
190604    if( rc==SQLITE_OK && cksum3!=expected ){
190605      rc = FTS5_CORRUPT;
190606    }
190607    *pCksum = cksum3;
190608  }
190609  p->rc = rc;
190610}
190611
190612#else
190613# define fts5TestDlidxReverse(x,y,z)
190614# define fts5TestTerm(u,v,w,x,y,z)
190615#endif
190616
190617/*
190618** Check that:
190619**
190620**   1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
190621**      contain zero terms.
190622**   2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
190623**      contain zero rowids.
190624*/
190625static void fts5IndexIntegrityCheckEmpty(
190626  Fts5Index *p,
190627  Fts5StructureSegment *pSeg,     /* Segment to check internal consistency */
190628  int iFirst,
190629  int iNoRowid,
190630  int iLast
190631){
190632  int i;
190633
190634  /* Now check that the iter.nEmpty leaves following the current leaf
190635  ** (a) exist and (b) contain no terms. */
190636  for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
190637    Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
190638    if( pLeaf ){
190639      if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
190640      if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
190641    }
190642    fts5DataRelease(pLeaf);
190643  }
190644}
190645
190646static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
190647  int iTermOff = 0;
190648  int ii;
190649
190650  Fts5Buffer buf1 = {0,0,0};
190651  Fts5Buffer buf2 = {0,0,0};
190652
190653  ii = pLeaf->szLeaf;
190654  while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
190655    int res;
190656    int iOff;
190657    int nIncr;
190658
190659    ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
190660    iTermOff += nIncr;
190661    iOff = iTermOff;
190662
190663    if( iOff>=pLeaf->szLeaf ){
190664      p->rc = FTS5_CORRUPT;
190665    }else if( iTermOff==nIncr ){
190666      int nByte;
190667      iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
190668      if( (iOff+nByte)>pLeaf->szLeaf ){
190669        p->rc = FTS5_CORRUPT;
190670      }else{
190671        fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
190672      }
190673    }else{
190674      int nKeep, nByte;
190675      iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
190676      iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
190677      if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
190678        p->rc = FTS5_CORRUPT;
190679      }else{
190680        buf1.n = nKeep;
190681        fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
190682      }
190683
190684      if( p->rc==SQLITE_OK ){
190685        res = fts5BufferCompare(&buf1, &buf2);
190686        if( res<=0 ) p->rc = FTS5_CORRUPT;
190687      }
190688    }
190689    fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
190690  }
190691
190692  fts5BufferFree(&buf1);
190693  fts5BufferFree(&buf2);
190694}
190695
190696static void fts5IndexIntegrityCheckSegment(
190697  Fts5Index *p,                   /* FTS5 backend object */
190698  Fts5StructureSegment *pSeg      /* Segment to check internal consistency */
190699){
190700  Fts5Config *pConfig = p->pConfig;
190701  sqlite3_stmt *pStmt = 0;
190702  int rc2;
190703  int iIdxPrevLeaf = pSeg->pgnoFirst-1;
190704  int iDlidxPrevLeaf = pSeg->pgnoLast;
190705
190706  if( pSeg->pgnoFirst==0 ) return;
190707
190708  fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
190709      "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
190710      pConfig->zDb, pConfig->zName, pSeg->iSegid
190711  ));
190712
190713  /* Iterate through the b-tree hierarchy.  */
190714  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
190715    i64 iRow;                     /* Rowid for this leaf */
190716    Fts5Data *pLeaf;              /* Data for this leaf */
190717
190718    int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
190719    const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
190720    int iIdxLeaf = sqlite3_column_int(pStmt, 2);
190721    int bIdxDlidx = sqlite3_column_int(pStmt, 3);
190722
190723    /* If the leaf in question has already been trimmed from the segment,
190724    ** ignore this b-tree entry. Otherwise, load it into memory. */
190725    if( iIdxLeaf<pSeg->pgnoFirst ) continue;
190726    iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
190727    pLeaf = fts5DataRead(p, iRow);
190728    if( pLeaf==0 ) break;
190729
190730    /* Check that the leaf contains at least one term, and that it is equal
190731    ** to or larger than the split-key in zIdxTerm.  Also check that if there
190732    ** is also a rowid pointer within the leaf page header, it points to a
190733    ** location before the term.  */
190734    if( pLeaf->nn<=pLeaf->szLeaf ){
190735      p->rc = FTS5_CORRUPT;
190736    }else{
190737      int iOff;                   /* Offset of first term on leaf */
190738      int iRowidOff;              /* Offset of first rowid on leaf */
190739      int nTerm;                  /* Size of term on leaf in bytes */
190740      int res;                    /* Comparison of term and split-key */
190741
190742      iOff = fts5LeafFirstTermOff(pLeaf);
190743      iRowidOff = fts5LeafFirstRowidOff(pLeaf);
190744      if( iRowidOff>=iOff ){
190745        p->rc = FTS5_CORRUPT;
190746      }else{
190747        iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
190748        res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
190749        if( res==0 ) res = nTerm - nIdxTerm;
190750        if( res<0 ) p->rc = FTS5_CORRUPT;
190751      }
190752
190753      fts5IntegrityCheckPgidx(p, pLeaf);
190754    }
190755    fts5DataRelease(pLeaf);
190756    if( p->rc ) break;
190757
190758    /* Now check that the iter.nEmpty leaves following the current leaf
190759    ** (a) exist and (b) contain no terms. */
190760    fts5IndexIntegrityCheckEmpty(
190761        p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
190762    );
190763    if( p->rc ) break;
190764
190765    /* If there is a doclist-index, check that it looks right. */
190766    if( bIdxDlidx ){
190767      Fts5DlidxIter *pDlidx = 0;  /* For iterating through doclist index */
190768      int iPrevLeaf = iIdxLeaf;
190769      int iSegid = pSeg->iSegid;
190770      int iPg = 0;
190771      i64 iKey;
190772
190773      for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
190774          fts5DlidxIterEof(p, pDlidx)==0;
190775          fts5DlidxIterNext(p, pDlidx)
190776      ){
190777
190778        /* Check any rowid-less pages that occur before the current leaf. */
190779        for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
190780          iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
190781          pLeaf = fts5DataRead(p, iKey);
190782          if( pLeaf ){
190783            if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
190784            fts5DataRelease(pLeaf);
190785          }
190786        }
190787        iPrevLeaf = fts5DlidxIterPgno(pDlidx);
190788
190789        /* Check that the leaf page indicated by the iterator really does
190790        ** contain the rowid suggested by the same. */
190791        iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
190792        pLeaf = fts5DataRead(p, iKey);
190793        if( pLeaf ){
190794          i64 iRowid;
190795          int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
190796          ASSERT_SZLEAF_OK(pLeaf);
190797          if( iRowidOff>=pLeaf->szLeaf ){
190798            p->rc = FTS5_CORRUPT;
190799          }else{
190800            fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
190801            if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
190802          }
190803          fts5DataRelease(pLeaf);
190804        }
190805      }
190806
190807      iDlidxPrevLeaf = iPg;
190808      fts5DlidxIterFree(pDlidx);
190809      fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
190810    }else{
190811      iDlidxPrevLeaf = pSeg->pgnoLast;
190812      /* TODO: Check there is no doclist index */
190813    }
190814
190815    iIdxPrevLeaf = iIdxLeaf;
190816  }
190817
190818  rc2 = sqlite3_finalize(pStmt);
190819  if( p->rc==SQLITE_OK ) p->rc = rc2;
190820
190821  /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
190822#if 0
190823  if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
190824    p->rc = FTS5_CORRUPT;
190825  }
190826#endif
190827}
190828
190829
190830/*
190831** Run internal checks to ensure that the FTS index (a) is internally
190832** consistent and (b) contains entries for which the XOR of the checksums
190833** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
190834**
190835** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
190836** checksum does not match. Return SQLITE_OK if all checks pass without
190837** error, or some other SQLite error code if another error (e.g. OOM)
190838** occurs.
190839*/
190840static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
190841  int eDetail = p->pConfig->eDetail;
190842  u64 cksum2 = 0;                 /* Checksum based on contents of indexes */
190843  Fts5Buffer poslist = {0,0,0};   /* Buffer used to hold a poslist */
190844  Fts5Iter *pIter;                /* Used to iterate through entire index */
190845  Fts5Structure *pStruct;         /* Index structure */
190846
190847#ifdef SQLITE_DEBUG
190848  /* Used by extra internal tests only run if NDEBUG is not defined */
190849  u64 cksum3 = 0;                 /* Checksum based on contents of indexes */
190850  Fts5Buffer term = {0,0,0};      /* Buffer used to hold most recent term */
190851#endif
190852  const int flags = FTS5INDEX_QUERY_NOOUTPUT;
190853
190854  /* Load the FTS index structure */
190855  pStruct = fts5StructureRead(p);
190856
190857  /* Check that the internal nodes of each segment match the leaves */
190858  if( pStruct ){
190859    int iLvl, iSeg;
190860    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
190861      for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
190862        Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
190863        fts5IndexIntegrityCheckSegment(p, pSeg);
190864      }
190865    }
190866  }
190867
190868  /* The cksum argument passed to this function is a checksum calculated
190869  ** based on all expected entries in the FTS index (including prefix index
190870  ** entries). This block checks that a checksum calculated based on the
190871  ** actual contents of FTS index is identical.
190872  **
190873  ** Two versions of the same checksum are calculated. The first (stack
190874  ** variable cksum2) based on entries extracted from the full-text index
190875  ** while doing a linear scan of each individual index in turn.
190876  **
190877  ** As each term visited by the linear scans, a separate query for the
190878  ** same term is performed. cksum3 is calculated based on the entries
190879  ** extracted by these queries.
190880  */
190881  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
190882      fts5MultiIterEof(p, pIter)==0;
190883      fts5MultiIterNext(p, pIter, 0, 0)
190884  ){
190885    int n;                      /* Size of term in bytes */
190886    i64 iPos = 0;               /* Position read from poslist */
190887    int iOff = 0;               /* Offset within poslist */
190888    i64 iRowid = fts5MultiIterRowid(pIter);
190889    char *z = (char*)fts5MultiIterTerm(pIter, &n);
190890
190891    /* If this is a new term, query for it. Update cksum3 with the results. */
190892    fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
190893
190894    if( eDetail==FTS5_DETAIL_NONE ){
190895      if( 0==fts5MultiIterIsEmpty(p, pIter) ){
190896        cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
190897      }
190898    }else{
190899      poslist.n = 0;
190900      fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
190901      while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
190902        int iCol = FTS5_POS2COLUMN(iPos);
190903        int iTokOff = FTS5_POS2OFFSET(iPos);
190904        cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
190905      }
190906    }
190907  }
190908  fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
190909
190910  fts5MultiIterFree(pIter);
190911  if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
190912
190913  fts5StructureRelease(pStruct);
190914#ifdef SQLITE_DEBUG
190915  fts5BufferFree(&term);
190916#endif
190917  fts5BufferFree(&poslist);
190918  return fts5IndexReturn(p);
190919}
190920
190921/*************************************************************************
190922**************************************************************************
190923** Below this point is the implementation of the fts5_decode() scalar
190924** function only.
190925*/
190926
190927/*
190928** Decode a segment-data rowid from the %_data table. This function is
190929** the opposite of macro FTS5_SEGMENT_ROWID().
190930*/
190931static void fts5DecodeRowid(
190932  i64 iRowid,                     /* Rowid from %_data table */
190933  int *piSegid,                   /* OUT: Segment id */
190934  int *pbDlidx,                   /* OUT: Dlidx flag */
190935  int *piHeight,                  /* OUT: Height */
190936  int *piPgno                     /* OUT: Page number */
190937){
190938  *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
190939  iRowid >>= FTS5_DATA_PAGE_B;
190940
190941  *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
190942  iRowid >>= FTS5_DATA_HEIGHT_B;
190943
190944  *pbDlidx = (int)(iRowid & 0x0001);
190945  iRowid >>= FTS5_DATA_DLI_B;
190946
190947  *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
190948}
190949
190950static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
190951  int iSegid, iHeight, iPgno, bDlidx;       /* Rowid compenents */
190952  fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
190953
190954  if( iSegid==0 ){
190955    if( iKey==FTS5_AVERAGES_ROWID ){
190956      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
190957    }else{
190958      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
190959    }
190960  }
190961  else{
190962    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
190963        bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
190964    );
190965  }
190966}
190967
190968static void fts5DebugStructure(
190969  int *pRc,                       /* IN/OUT: error code */
190970  Fts5Buffer *pBuf,
190971  Fts5Structure *p
190972){
190973  int iLvl, iSeg;                 /* Iterate through levels, segments */
190974
190975  for(iLvl=0; iLvl<p->nLevel; iLvl++){
190976    Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
190977    sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
190978        " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
190979    );
190980    for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
190981      Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
190982      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
190983          pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
190984      );
190985    }
190986    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
190987  }
190988}
190989
190990/*
190991** This is part of the fts5_decode() debugging aid.
190992**
190993** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
190994** function appends a human-readable representation of the same object
190995** to the buffer passed as the second argument.
190996*/
190997static void fts5DecodeStructure(
190998  int *pRc,                       /* IN/OUT: error code */
190999  Fts5Buffer *pBuf,
191000  const u8 *pBlob, int nBlob
191001){
191002  int rc;                         /* Return code */
191003  Fts5Structure *p = 0;           /* Decoded structure object */
191004
191005  rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
191006  if( rc!=SQLITE_OK ){
191007    *pRc = rc;
191008    return;
191009  }
191010
191011  fts5DebugStructure(pRc, pBuf, p);
191012  fts5StructureRelease(p);
191013}
191014
191015/*
191016** This is part of the fts5_decode() debugging aid.
191017**
191018** Arguments pBlob/nBlob contain an "averages" record. This function
191019** appends a human-readable representation of record to the buffer passed
191020** as the second argument.
191021*/
191022static void fts5DecodeAverages(
191023  int *pRc,                       /* IN/OUT: error code */
191024  Fts5Buffer *pBuf,
191025  const u8 *pBlob, int nBlob
191026){
191027  int i = 0;
191028  const char *zSpace = "";
191029
191030  while( i<nBlob ){
191031    u64 iVal;
191032    i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
191033    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
191034    zSpace = " ";
191035  }
191036}
191037
191038/*
191039** Buffer (a/n) is assumed to contain a list of serialized varints. Read
191040** each varint and append its string representation to buffer pBuf. Return
191041** after either the input buffer is exhausted or a 0 value is read.
191042**
191043** The return value is the number of bytes read from the input buffer.
191044*/
191045static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
191046  int iOff = 0;
191047  while( iOff<n ){
191048    int iVal;
191049    iOff += fts5GetVarint32(&a[iOff], iVal);
191050    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
191051  }
191052  return iOff;
191053}
191054
191055/*
191056** The start of buffer (a/n) contains the start of a doclist. The doclist
191057** may or may not finish within the buffer. This function appends a text
191058** representation of the part of the doclist that is present to buffer
191059** pBuf.
191060**
191061** The return value is the number of bytes read from the input buffer.
191062*/
191063static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
191064  i64 iDocid = 0;
191065  int iOff = 0;
191066
191067  if( n>0 ){
191068    iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
191069    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
191070  }
191071  while( iOff<n ){
191072    int nPos;
191073    int bDel;
191074    iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
191075    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
191076    iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
191077    if( iOff<n ){
191078      i64 iDelta;
191079      iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
191080      iDocid += iDelta;
191081      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
191082    }
191083  }
191084
191085  return iOff;
191086}
191087
191088/*
191089** This function is part of the fts5_decode() debugging function. It is
191090** only ever used with detail=none tables.
191091**
191092** Buffer (pData/nData) contains a doclist in the format used by detail=none
191093** tables. This function appends a human-readable version of that list to
191094** buffer pBuf.
191095**
191096** If *pRc is other than SQLITE_OK when this function is called, it is a
191097** no-op. If an OOM or other error occurs within this function, *pRc is
191098** set to an SQLite error code before returning. The final state of buffer
191099** pBuf is undefined in this case.
191100*/
191101static void fts5DecodeRowidList(
191102  int *pRc,                       /* IN/OUT: Error code */
191103  Fts5Buffer *pBuf,               /* Buffer to append text to */
191104  const u8 *pData, int nData      /* Data to decode list-of-rowids from */
191105){
191106  int i = 0;
191107  i64 iRowid = 0;
191108
191109  while( i<nData ){
191110    const char *zApp = "";
191111    u64 iVal;
191112    i += sqlite3Fts5GetVarint(&pData[i], &iVal);
191113    iRowid += iVal;
191114
191115    if( i<nData && pData[i]==0x00 ){
191116      i++;
191117      if( i<nData && pData[i]==0x00 ){
191118        i++;
191119        zApp = "+";
191120      }else{
191121        zApp = "*";
191122      }
191123    }
191124
191125    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
191126  }
191127}
191128
191129/*
191130** The implementation of user-defined scalar function fts5_decode().
191131*/
191132static void fts5DecodeFunction(
191133  sqlite3_context *pCtx,          /* Function call context */
191134  int nArg,                       /* Number of args (always 2) */
191135  sqlite3_value **apVal           /* Function arguments */
191136){
191137  i64 iRowid;                     /* Rowid for record being decoded */
191138  int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
191139  const u8 *aBlob; int n;         /* Record to decode */
191140  u8 *a = 0;
191141  Fts5Buffer s;                   /* Build up text to return here */
191142  int rc = SQLITE_OK;             /* Return code */
191143  int nSpace = 0;
191144  int eDetailNone = (sqlite3_user_data(pCtx)!=0);
191145
191146  assert( nArg==2 );
191147  UNUSED_PARAM(nArg);
191148  memset(&s, 0, sizeof(Fts5Buffer));
191149  iRowid = sqlite3_value_int64(apVal[0]);
191150
191151  /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
191152  ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
191153  ** buffer overreads even if the record is corrupt.  */
191154  n = sqlite3_value_bytes(apVal[1]);
191155  aBlob = sqlite3_value_blob(apVal[1]);
191156  nSpace = n + FTS5_DATA_ZERO_PADDING;
191157  a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
191158  if( a==0 ) goto decode_out;
191159  memcpy(a, aBlob, n);
191160
191161
191162  fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
191163
191164  fts5DebugRowid(&rc, &s, iRowid);
191165  if( bDlidx ){
191166    Fts5Data dlidx;
191167    Fts5DlidxLvl lvl;
191168
191169    dlidx.p = a;
191170    dlidx.nn = n;
191171
191172    memset(&lvl, 0, sizeof(Fts5DlidxLvl));
191173    lvl.pData = &dlidx;
191174    lvl.iLeafPgno = iPgno;
191175
191176    for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
191177      sqlite3Fts5BufferAppendPrintf(&rc, &s,
191178          " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
191179      );
191180    }
191181  }else if( iSegid==0 ){
191182    if( iRowid==FTS5_AVERAGES_ROWID ){
191183      fts5DecodeAverages(&rc, &s, a, n);
191184    }else{
191185      fts5DecodeStructure(&rc, &s, a, n);
191186    }
191187  }else if( eDetailNone ){
191188    Fts5Buffer term;              /* Current term read from page */
191189    int szLeaf;
191190    int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
191191    int iTermOff;
191192    int nKeep = 0;
191193    int iOff;
191194
191195    memset(&term, 0, sizeof(Fts5Buffer));
191196
191197    /* Decode any entries that occur before the first term. */
191198    if( szLeaf<n ){
191199      iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
191200    }else{
191201      iTermOff = szLeaf;
191202    }
191203    fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
191204
191205    iOff = iTermOff;
191206    while( iOff<szLeaf ){
191207      int nAppend;
191208
191209      /* Read the term data for the next term*/
191210      iOff += fts5GetVarint32(&a[iOff], nAppend);
191211      term.n = nKeep;
191212      fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
191213      sqlite3Fts5BufferAppendPrintf(
191214          &rc, &s, " term=%.*s", term.n, (const char*)term.p
191215      );
191216      iOff += nAppend;
191217
191218      /* Figure out where the doclist for this term ends */
191219      if( iPgidxOff<n ){
191220        int nIncr;
191221        iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
191222        iTermOff += nIncr;
191223      }else{
191224        iTermOff = szLeaf;
191225      }
191226
191227      fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
191228      iOff = iTermOff;
191229      if( iOff<szLeaf ){
191230        iOff += fts5GetVarint32(&a[iOff], nKeep);
191231      }
191232    }
191233
191234    fts5BufferFree(&term);
191235  }else{
191236    Fts5Buffer term;              /* Current term read from page */
191237    int szLeaf;                   /* Offset of pgidx in a[] */
191238    int iPgidxOff;
191239    int iPgidxPrev = 0;           /* Previous value read from pgidx */
191240    int iTermOff = 0;
191241    int iRowidOff = 0;
191242    int iOff;
191243    int nDoclist;
191244
191245    memset(&term, 0, sizeof(Fts5Buffer));
191246
191247    if( n<4 ){
191248      sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
191249      goto decode_out;
191250    }else{
191251      iRowidOff = fts5GetU16(&a[0]);
191252      iPgidxOff = szLeaf = fts5GetU16(&a[2]);
191253      if( iPgidxOff<n ){
191254        fts5GetVarint32(&a[iPgidxOff], iTermOff);
191255      }
191256    }
191257
191258    /* Decode the position list tail at the start of the page */
191259    if( iRowidOff!=0 ){
191260      iOff = iRowidOff;
191261    }else if( iTermOff!=0 ){
191262      iOff = iTermOff;
191263    }else{
191264      iOff = szLeaf;
191265    }
191266    fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
191267
191268    /* Decode any more doclist data that appears on the page before the
191269    ** first term. */
191270    nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
191271    fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
191272
191273    while( iPgidxOff<n ){
191274      int bFirst = (iPgidxOff==szLeaf);     /* True for first term on page */
191275      int nByte;                            /* Bytes of data */
191276      int iEnd;
191277
191278      iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
191279      iPgidxPrev += nByte;
191280      iOff = iPgidxPrev;
191281
191282      if( iPgidxOff<n ){
191283        fts5GetVarint32(&a[iPgidxOff], nByte);
191284        iEnd = iPgidxPrev + nByte;
191285      }else{
191286        iEnd = szLeaf;
191287      }
191288
191289      if( bFirst==0 ){
191290        iOff += fts5GetVarint32(&a[iOff], nByte);
191291        term.n = nByte;
191292      }
191293      iOff += fts5GetVarint32(&a[iOff], nByte);
191294      fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
191295      iOff += nByte;
191296
191297      sqlite3Fts5BufferAppendPrintf(
191298          &rc, &s, " term=%.*s", term.n, (const char*)term.p
191299      );
191300      iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
191301    }
191302
191303    fts5BufferFree(&term);
191304  }
191305
191306 decode_out:
191307  sqlite3_free(a);
191308  if( rc==SQLITE_OK ){
191309    sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
191310  }else{
191311    sqlite3_result_error_code(pCtx, rc);
191312  }
191313  fts5BufferFree(&s);
191314}
191315
191316/*
191317** The implementation of user-defined scalar function fts5_rowid().
191318*/
191319static void fts5RowidFunction(
191320  sqlite3_context *pCtx,          /* Function call context */
191321  int nArg,                       /* Number of args (always 2) */
191322  sqlite3_value **apVal           /* Function arguments */
191323){
191324  const char *zArg;
191325  if( nArg==0 ){
191326    sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
191327  }else{
191328    zArg = (const char*)sqlite3_value_text(apVal[0]);
191329    if( 0==sqlite3_stricmp(zArg, "segment") ){
191330      i64 iRowid;
191331      int segid, pgno;
191332      if( nArg!=3 ){
191333        sqlite3_result_error(pCtx,
191334            "should be: fts5_rowid('segment', segid, pgno))", -1
191335        );
191336      }else{
191337        segid = sqlite3_value_int(apVal[1]);
191338        pgno = sqlite3_value_int(apVal[2]);
191339        iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
191340        sqlite3_result_int64(pCtx, iRowid);
191341      }
191342    }else{
191343      sqlite3_result_error(pCtx,
191344        "first arg to fts5_rowid() must be 'segment'" , -1
191345      );
191346    }
191347  }
191348}
191349
191350/*
191351** This is called as part of registering the FTS5 module with database
191352** connection db. It registers several user-defined scalar functions useful
191353** with FTS5.
191354**
191355** If successful, SQLITE_OK is returned. If an error occurs, some other
191356** SQLite error code is returned instead.
191357*/
191358static int sqlite3Fts5IndexInit(sqlite3 *db){
191359  int rc = sqlite3_create_function(
191360      db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
191361  );
191362
191363  if( rc==SQLITE_OK ){
191364    rc = sqlite3_create_function(
191365        db, "fts5_decode_none", 2,
191366        SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
191367    );
191368  }
191369
191370  if( rc==SQLITE_OK ){
191371    rc = sqlite3_create_function(
191372        db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
191373    );
191374  }
191375  return rc;
191376}
191377
191378
191379static int sqlite3Fts5IndexReset(Fts5Index *p){
191380  assert( p->pStruct==0 || p->iStructVersion!=0 );
191381  if( fts5IndexDataVersion(p)!=p->iStructVersion ){
191382    fts5StructureInvalidate(p);
191383  }
191384  return fts5IndexReturn(p);
191385}
191386
191387/*
191388** 2014 Jun 09
191389**
191390** The author disclaims copyright to this source code.  In place of
191391** a legal notice, here is a blessing:
191392**
191393**    May you do good and not evil.
191394**    May you find forgiveness for yourself and forgive others.
191395**    May you share freely, never taking more than you give.
191396**
191397******************************************************************************
191398**
191399** This is an SQLite module implementing full-text search.
191400*/
191401
191402
191403/* #include "fts5Int.h" */
191404
191405/*
191406** This variable is set to false when running tests for which the on disk
191407** structures should not be corrupt. Otherwise, true. If it is false, extra
191408** assert() conditions in the fts5 code are activated - conditions that are
191409** only true if it is guaranteed that the fts5 database is not corrupt.
191410*/
191411SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
191412
191413
191414typedef struct Fts5Auxdata Fts5Auxdata;
191415typedef struct Fts5Auxiliary Fts5Auxiliary;
191416typedef struct Fts5Cursor Fts5Cursor;
191417typedef struct Fts5Sorter Fts5Sorter;
191418typedef struct Fts5Table Fts5Table;
191419typedef struct Fts5TokenizerModule Fts5TokenizerModule;
191420
191421/*
191422** NOTES ON TRANSACTIONS:
191423**
191424** SQLite invokes the following virtual table methods as transactions are
191425** opened and closed by the user:
191426**
191427**     xBegin():    Start of a new transaction.
191428**     xSync():     Initial part of two-phase commit.
191429**     xCommit():   Final part of two-phase commit.
191430**     xRollback(): Rollback the transaction.
191431**
191432** Anything that is required as part of a commit that may fail is performed
191433** in the xSync() callback. Current versions of SQLite ignore any errors
191434** returned by xCommit().
191435**
191436** And as sub-transactions are opened/closed:
191437**
191438**     xSavepoint(int S):  Open savepoint S.
191439**     xRelease(int S):    Commit and close savepoint S.
191440**     xRollbackTo(int S): Rollback to start of savepoint S.
191441**
191442** During a write-transaction the fts5_index.c module may cache some data
191443** in-memory. It is flushed to disk whenever xSync(), xRelease() or
191444** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
191445** is called.
191446**
191447** Additionally, if SQLITE_DEBUG is defined, an instance of the following
191448** structure is used to record the current transaction state. This information
191449** is not required, but it is used in the assert() statements executed by
191450** function fts5CheckTransactionState() (see below).
191451*/
191452struct Fts5TransactionState {
191453  int eState;                     /* 0==closed, 1==open, 2==synced */
191454  int iSavepoint;                 /* Number of open savepoints (0 -> none) */
191455};
191456
191457/*
191458** A single object of this type is allocated when the FTS5 module is
191459** registered with a database handle. It is used to store pointers to
191460** all registered FTS5 extensions - tokenizers and auxiliary functions.
191461*/
191462struct Fts5Global {
191463  fts5_api api;                   /* User visible part of object (see fts5.h) */
191464  sqlite3 *db;                    /* Associated database connection */
191465  i64 iNextId;                    /* Used to allocate unique cursor ids */
191466  Fts5Auxiliary *pAux;            /* First in list of all aux. functions */
191467  Fts5TokenizerModule *pTok;      /* First in list of all tokenizer modules */
191468  Fts5TokenizerModule *pDfltTok;  /* Default tokenizer module */
191469  Fts5Cursor *pCsr;               /* First in list of all open cursors */
191470};
191471
191472/*
191473** Each auxiliary function registered with the FTS5 module is represented
191474** by an object of the following type. All such objects are stored as part
191475** of the Fts5Global.pAux list.
191476*/
191477struct Fts5Auxiliary {
191478  Fts5Global *pGlobal;            /* Global context for this function */
191479  char *zFunc;                    /* Function name (nul-terminated) */
191480  void *pUserData;                /* User-data pointer */
191481  fts5_extension_function xFunc;  /* Callback function */
191482  void (*xDestroy)(void*);        /* Destructor function */
191483  Fts5Auxiliary *pNext;           /* Next registered auxiliary function */
191484};
191485
191486/*
191487** Each tokenizer module registered with the FTS5 module is represented
191488** by an object of the following type. All such objects are stored as part
191489** of the Fts5Global.pTok list.
191490*/
191491struct Fts5TokenizerModule {
191492  char *zName;                    /* Name of tokenizer */
191493  void *pUserData;                /* User pointer passed to xCreate() */
191494  fts5_tokenizer x;               /* Tokenizer functions */
191495  void (*xDestroy)(void*);        /* Destructor function */
191496  Fts5TokenizerModule *pNext;     /* Next registered tokenizer module */
191497};
191498
191499/*
191500** Virtual-table object.
191501*/
191502struct Fts5Table {
191503  sqlite3_vtab base;              /* Base class used by SQLite core */
191504  Fts5Config *pConfig;            /* Virtual table configuration */
191505  Fts5Index *pIndex;              /* Full-text index */
191506  Fts5Storage *pStorage;          /* Document store */
191507  Fts5Global *pGlobal;            /* Global (connection wide) data */
191508  Fts5Cursor *pSortCsr;           /* Sort data from this cursor */
191509#ifdef SQLITE_DEBUG
191510  struct Fts5TransactionState ts;
191511#endif
191512};
191513
191514struct Fts5MatchPhrase {
191515  Fts5Buffer *pPoslist;           /* Pointer to current poslist */
191516  int nTerm;                      /* Size of phrase in terms */
191517};
191518
191519/*
191520** pStmt:
191521**   SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
191522**
191523** aIdx[]:
191524**   There is one entry in the aIdx[] array for each phrase in the query,
191525**   the value of which is the offset within aPoslist[] following the last
191526**   byte of the position list for the corresponding phrase.
191527*/
191528struct Fts5Sorter {
191529  sqlite3_stmt *pStmt;
191530  i64 iRowid;                     /* Current rowid */
191531  const u8 *aPoslist;             /* Position lists for current row */
191532  int nIdx;                       /* Number of entries in aIdx[] */
191533  int aIdx[1];                    /* Offsets into aPoslist for current row */
191534};
191535
191536
191537/*
191538** Virtual-table cursor object.
191539**
191540** iSpecial:
191541**   If this is a 'special' query (refer to function fts5SpecialMatch()),
191542**   then this variable contains the result of the query.
191543**
191544** iFirstRowid, iLastRowid:
191545**   These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
191546**   cursor iterates in ascending order of rowids, iFirstRowid is the lower
191547**   limit of rowids to return, and iLastRowid the upper. In other words, the
191548**   WHERE clause in the user's query might have been:
191549**
191550**       <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
191551**
191552**   If the cursor iterates in descending order of rowid, iFirstRowid
191553**   is the upper limit (i.e. the "first" rowid visited) and iLastRowid
191554**   the lower.
191555*/
191556struct Fts5Cursor {
191557  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
191558  Fts5Cursor *pNext;              /* Next cursor in Fts5Cursor.pCsr list */
191559  int *aColumnSize;               /* Values for xColumnSize() */
191560  i64 iCsrId;                     /* Cursor id */
191561
191562  /* Zero from this point onwards on cursor reset */
191563  int ePlan;                      /* FTS5_PLAN_XXX value */
191564  int bDesc;                      /* True for "ORDER BY rowid DESC" queries */
191565  i64 iFirstRowid;                /* Return no rowids earlier than this */
191566  i64 iLastRowid;                 /* Return no rowids later than this */
191567  sqlite3_stmt *pStmt;            /* Statement used to read %_content */
191568  Fts5Expr *pExpr;                /* Expression for MATCH queries */
191569  Fts5Sorter *pSorter;            /* Sorter for "ORDER BY rank" queries */
191570  int csrflags;                   /* Mask of cursor flags (see below) */
191571  i64 iSpecial;                   /* Result of special query */
191572
191573  /* "rank" function. Populated on demand from vtab.xColumn(). */
191574  char *zRank;                    /* Custom rank function */
191575  char *zRankArgs;                /* Custom rank function args */
191576  Fts5Auxiliary *pRank;           /* Rank callback (or NULL) */
191577  int nRankArg;                   /* Number of trailing arguments for rank() */
191578  sqlite3_value **apRankArg;      /* Array of trailing arguments */
191579  sqlite3_stmt *pRankArgStmt;     /* Origin of objects in apRankArg[] */
191580
191581  /* Auxiliary data storage */
191582  Fts5Auxiliary *pAux;            /* Currently executing extension function */
191583  Fts5Auxdata *pAuxdata;          /* First in linked list of saved aux-data */
191584
191585  /* Cache used by auxiliary functions xInst() and xInstCount() */
191586  Fts5PoslistReader *aInstIter;   /* One for each phrase */
191587  int nInstAlloc;                 /* Size of aInst[] array (entries / 3) */
191588  int nInstCount;                 /* Number of phrase instances */
191589  int *aInst;                     /* 3 integers per phrase instance */
191590};
191591
191592/*
191593** Bits that make up the "idxNum" parameter passed indirectly by
191594** xBestIndex() to xFilter().
191595*/
191596#define FTS5_BI_MATCH        0x0001         /* <tbl> MATCH ? */
191597#define FTS5_BI_RANK         0x0002         /* rank MATCH ? */
191598#define FTS5_BI_ROWID_EQ     0x0004         /* rowid == ? */
191599#define FTS5_BI_ROWID_LE     0x0008         /* rowid <= ? */
191600#define FTS5_BI_ROWID_GE     0x0010         /* rowid >= ? */
191601
191602#define FTS5_BI_ORDER_RANK   0x0020
191603#define FTS5_BI_ORDER_ROWID  0x0040
191604#define FTS5_BI_ORDER_DESC   0x0080
191605
191606/*
191607** Values for Fts5Cursor.csrflags
191608*/
191609#define FTS5CSR_EOF               0x01
191610#define FTS5CSR_REQUIRE_CONTENT   0x02
191611#define FTS5CSR_REQUIRE_DOCSIZE   0x04
191612#define FTS5CSR_REQUIRE_INST      0x08
191613#define FTS5CSR_FREE_ZRANK        0x10
191614#define FTS5CSR_REQUIRE_RESEEK    0x20
191615#define FTS5CSR_REQUIRE_POSLIST   0x40
191616
191617#define BitFlagAllTest(x,y) (((x) & (y))==(y))
191618#define BitFlagTest(x,y)    (((x) & (y))!=0)
191619
191620
191621/*
191622** Macros to Set(), Clear() and Test() cursor flags.
191623*/
191624#define CsrFlagSet(pCsr, flag)   ((pCsr)->csrflags |= (flag))
191625#define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
191626#define CsrFlagTest(pCsr, flag)  ((pCsr)->csrflags & (flag))
191627
191628struct Fts5Auxdata {
191629  Fts5Auxiliary *pAux;            /* Extension to which this belongs */
191630  void *pPtr;                     /* Pointer value */
191631  void(*xDelete)(void*);          /* Destructor */
191632  Fts5Auxdata *pNext;             /* Next object in linked list */
191633};
191634
191635#ifdef SQLITE_DEBUG
191636#define FTS5_BEGIN      1
191637#define FTS5_SYNC       2
191638#define FTS5_COMMIT     3
191639#define FTS5_ROLLBACK   4
191640#define FTS5_SAVEPOINT  5
191641#define FTS5_RELEASE    6
191642#define FTS5_ROLLBACKTO 7
191643static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
191644  switch( op ){
191645    case FTS5_BEGIN:
191646      assert( p->ts.eState==0 );
191647      p->ts.eState = 1;
191648      p->ts.iSavepoint = -1;
191649      break;
191650
191651    case FTS5_SYNC:
191652      assert( p->ts.eState==1 );
191653      p->ts.eState = 2;
191654      break;
191655
191656    case FTS5_COMMIT:
191657      assert( p->ts.eState==2 );
191658      p->ts.eState = 0;
191659      break;
191660
191661    case FTS5_ROLLBACK:
191662      assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
191663      p->ts.eState = 0;
191664      break;
191665
191666    case FTS5_SAVEPOINT:
191667      assert( p->ts.eState==1 );
191668      assert( iSavepoint>=0 );
191669      assert( iSavepoint>p->ts.iSavepoint );
191670      p->ts.iSavepoint = iSavepoint;
191671      break;
191672
191673    case FTS5_RELEASE:
191674      assert( p->ts.eState==1 );
191675      assert( iSavepoint>=0 );
191676      assert( iSavepoint<=p->ts.iSavepoint );
191677      p->ts.iSavepoint = iSavepoint-1;
191678      break;
191679
191680    case FTS5_ROLLBACKTO:
191681      assert( p->ts.eState==1 );
191682      assert( iSavepoint>=0 );
191683      assert( iSavepoint<=p->ts.iSavepoint );
191684      p->ts.iSavepoint = iSavepoint;
191685      break;
191686  }
191687}
191688#else
191689# define fts5CheckTransactionState(x,y,z)
191690#endif
191691
191692/*
191693** Return true if pTab is a contentless table.
191694*/
191695static int fts5IsContentless(Fts5Table *pTab){
191696  return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
191697}
191698
191699/*
191700** Delete a virtual table handle allocated by fts5InitVtab().
191701*/
191702static void fts5FreeVtab(Fts5Table *pTab){
191703  if( pTab ){
191704    sqlite3Fts5IndexClose(pTab->pIndex);
191705    sqlite3Fts5StorageClose(pTab->pStorage);
191706    sqlite3Fts5ConfigFree(pTab->pConfig);
191707    sqlite3_free(pTab);
191708  }
191709}
191710
191711/*
191712** The xDisconnect() virtual table method.
191713*/
191714static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
191715  fts5FreeVtab((Fts5Table*)pVtab);
191716  return SQLITE_OK;
191717}
191718
191719/*
191720** The xDestroy() virtual table method.
191721*/
191722static int fts5DestroyMethod(sqlite3_vtab *pVtab){
191723  Fts5Table *pTab = (Fts5Table*)pVtab;
191724  int rc = sqlite3Fts5DropAll(pTab->pConfig);
191725  if( rc==SQLITE_OK ){
191726    fts5FreeVtab((Fts5Table*)pVtab);
191727  }
191728  return rc;
191729}
191730
191731/*
191732** This function is the implementation of both the xConnect and xCreate
191733** methods of the FTS3 virtual table.
191734**
191735** The argv[] array contains the following:
191736**
191737**   argv[0]   -> module name  ("fts5")
191738**   argv[1]   -> database name
191739**   argv[2]   -> table name
191740**   argv[...] -> "column name" and other module argument fields.
191741*/
191742static int fts5InitVtab(
191743  int bCreate,                    /* True for xCreate, false for xConnect */
191744  sqlite3 *db,                    /* The SQLite database connection */
191745  void *pAux,                     /* Hash table containing tokenizers */
191746  int argc,                       /* Number of elements in argv array */
191747  const char * const *argv,       /* xCreate/xConnect argument array */
191748  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
191749  char **pzErr                    /* Write any error message here */
191750){
191751  Fts5Global *pGlobal = (Fts5Global*)pAux;
191752  const char **azConfig = (const char**)argv;
191753  int rc = SQLITE_OK;             /* Return code */
191754  Fts5Config *pConfig = 0;        /* Results of parsing argc/argv */
191755  Fts5Table *pTab = 0;            /* New virtual table object */
191756
191757  /* Allocate the new vtab object and parse the configuration */
191758  pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
191759  if( rc==SQLITE_OK ){
191760    rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
191761    assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
191762  }
191763  if( rc==SQLITE_OK ){
191764    pTab->pConfig = pConfig;
191765    pTab->pGlobal = pGlobal;
191766  }
191767
191768  /* Open the index sub-system */
191769  if( rc==SQLITE_OK ){
191770    rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
191771  }
191772
191773  /* Open the storage sub-system */
191774  if( rc==SQLITE_OK ){
191775    rc = sqlite3Fts5StorageOpen(
191776        pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
191777    );
191778  }
191779
191780  /* Call sqlite3_declare_vtab() */
191781  if( rc==SQLITE_OK ){
191782    rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
191783  }
191784
191785  /* Load the initial configuration */
191786  if( rc==SQLITE_OK ){
191787    assert( pConfig->pzErrmsg==0 );
191788    pConfig->pzErrmsg = pzErr;
191789    rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
191790    sqlite3Fts5IndexRollback(pTab->pIndex);
191791    pConfig->pzErrmsg = 0;
191792  }
191793
191794  if( rc!=SQLITE_OK ){
191795    fts5FreeVtab(pTab);
191796    pTab = 0;
191797  }else if( bCreate ){
191798    fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
191799  }
191800  *ppVTab = (sqlite3_vtab*)pTab;
191801  return rc;
191802}
191803
191804/*
191805** The xConnect() and xCreate() methods for the virtual table. All the
191806** work is done in function fts5InitVtab().
191807*/
191808static int fts5ConnectMethod(
191809  sqlite3 *db,                    /* Database connection */
191810  void *pAux,                     /* Pointer to tokenizer hash table */
191811  int argc,                       /* Number of elements in argv array */
191812  const char * const *argv,       /* xCreate/xConnect argument array */
191813  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
191814  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
191815){
191816  return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
191817}
191818static int fts5CreateMethod(
191819  sqlite3 *db,                    /* Database connection */
191820  void *pAux,                     /* Pointer to tokenizer hash table */
191821  int argc,                       /* Number of elements in argv array */
191822  const char * const *argv,       /* xCreate/xConnect argument array */
191823  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
191824  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
191825){
191826  return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
191827}
191828
191829/*
191830** The different query plans.
191831*/
191832#define FTS5_PLAN_MATCH          1       /* (<tbl> MATCH ?) */
191833#define FTS5_PLAN_SOURCE         2       /* A source cursor for SORTED_MATCH */
191834#define FTS5_PLAN_SPECIAL        3       /* An internal query */
191835#define FTS5_PLAN_SORTED_MATCH   4       /* (<tbl> MATCH ? ORDER BY rank) */
191836#define FTS5_PLAN_SCAN           5       /* No usable constraint */
191837#define FTS5_PLAN_ROWID          6       /* (rowid = ?) */
191838
191839/*
191840** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
191841** extension is currently being used by a version of SQLite too old to
191842** support index-info flags. In that case this function is a no-op.
191843*/
191844static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
191845#if SQLITE_VERSION_NUMBER>=3008012
191846#ifndef SQLITE_CORE
191847  if( sqlite3_libversion_number()>=3008012 )
191848#endif
191849  {
191850    pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
191851  }
191852#endif
191853}
191854
191855/*
191856** Implementation of the xBestIndex method for FTS5 tables. Within the
191857** WHERE constraint, it searches for the following:
191858**
191859**   1. A MATCH constraint against the special column.
191860**   2. A MATCH constraint against the "rank" column.
191861**   3. An == constraint against the rowid column.
191862**   4. A < or <= constraint against the rowid column.
191863**   5. A > or >= constraint against the rowid column.
191864**
191865** Within the ORDER BY, either:
191866**
191867**   5. ORDER BY rank [ASC|DESC]
191868**   6. ORDER BY rowid [ASC|DESC]
191869**
191870** Costs are assigned as follows:
191871**
191872**  a) If an unusable MATCH operator is present in the WHERE clause, the
191873**     cost is unconditionally set to 1e50 (a really big number).
191874**
191875**  a) If a MATCH operator is present, the cost depends on the other
191876**     constraints also present. As follows:
191877**
191878**       * No other constraints:         cost=1000.0
191879**       * One rowid range constraint:   cost=750.0
191880**       * Both rowid range constraints: cost=500.0
191881**       * An == rowid constraint:       cost=100.0
191882**
191883**  b) Otherwise, if there is no MATCH:
191884**
191885**       * No other constraints:         cost=1000000.0
191886**       * One rowid range constraint:   cost=750000.0
191887**       * Both rowid range constraints: cost=250000.0
191888**       * An == rowid constraint:       cost=10.0
191889**
191890** Costs are not modified by the ORDER BY clause.
191891*/
191892static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
191893  Fts5Table *pTab = (Fts5Table*)pVTab;
191894  Fts5Config *pConfig = pTab->pConfig;
191895  int idxFlags = 0;               /* Parameter passed through to xFilter() */
191896  int bHasMatch;
191897  int iNext;
191898  int i;
191899
191900  struct Constraint {
191901    int op;                       /* Mask against sqlite3_index_constraint.op */
191902    int fts5op;                   /* FTS5 mask for idxFlags */
191903    int iCol;                     /* 0==rowid, 1==tbl, 2==rank */
191904    int omit;                     /* True to omit this if found */
191905    int iConsIndex;               /* Index in pInfo->aConstraint[] */
191906  } aConstraint[] = {
191907    {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
191908                                    FTS5_BI_MATCH,    1, 1, -1},
191909    {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
191910                                    FTS5_BI_RANK,     2, 1, -1},
191911    {SQLITE_INDEX_CONSTRAINT_EQ,    FTS5_BI_ROWID_EQ, 0, 0, -1},
191912    {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
191913                                    FTS5_BI_ROWID_LE, 0, 0, -1},
191914    {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
191915                                    FTS5_BI_ROWID_GE, 0, 0, -1},
191916  };
191917
191918  int aColMap[3];
191919  aColMap[0] = -1;
191920  aColMap[1] = pConfig->nCol;
191921  aColMap[2] = pConfig->nCol+1;
191922
191923  /* Set idxFlags flags for all WHERE clause terms that will be used. */
191924  for(i=0; i<pInfo->nConstraint; i++){
191925    struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
191926    int j;
191927    for(j=0; j<ArraySize(aConstraint); j++){
191928      struct Constraint *pC = &aConstraint[j];
191929      if( p->iColumn==aColMap[pC->iCol] && p->op & pC->op ){
191930        if( p->usable ){
191931          pC->iConsIndex = i;
191932          idxFlags |= pC->fts5op;
191933        }else if( j==0 ){
191934          /* As there exists an unusable MATCH constraint this is an
191935          ** unusable plan. Set a prohibitively high cost. */
191936          pInfo->estimatedCost = 1e50;
191937          return SQLITE_OK;
191938        }
191939      }
191940    }
191941  }
191942
191943  /* Set idxFlags flags for the ORDER BY clause */
191944  if( pInfo->nOrderBy==1 ){
191945    int iSort = pInfo->aOrderBy[0].iColumn;
191946    if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
191947      idxFlags |= FTS5_BI_ORDER_RANK;
191948    }else if( iSort==-1 ){
191949      idxFlags |= FTS5_BI_ORDER_ROWID;
191950    }
191951    if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
191952      pInfo->orderByConsumed = 1;
191953      if( pInfo->aOrderBy[0].desc ){
191954        idxFlags |= FTS5_BI_ORDER_DESC;
191955      }
191956    }
191957  }
191958
191959  /* Calculate the estimated cost based on the flags set in idxFlags. */
191960  bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
191961  if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
191962    pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
191963    if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
191964  }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
191965    pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
191966  }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
191967    pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
191968  }else{
191969    pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
191970  }
191971
191972  /* Assign argvIndex values to each constraint in use. */
191973  iNext = 1;
191974  for(i=0; i<ArraySize(aConstraint); i++){
191975    struct Constraint *pC = &aConstraint[i];
191976    if( pC->iConsIndex>=0 ){
191977      pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
191978      pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
191979    }
191980  }
191981
191982  pInfo->idxNum = idxFlags;
191983  return SQLITE_OK;
191984}
191985
191986static int fts5NewTransaction(Fts5Table *pTab){
191987  Fts5Cursor *pCsr;
191988  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
191989    if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
191990  }
191991  return sqlite3Fts5StorageReset(pTab->pStorage);
191992}
191993
191994/*
191995** Implementation of xOpen method.
191996*/
191997static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
191998  Fts5Table *pTab = (Fts5Table*)pVTab;
191999  Fts5Config *pConfig = pTab->pConfig;
192000  Fts5Cursor *pCsr = 0;           /* New cursor object */
192001  int nByte;                      /* Bytes of space to allocate */
192002  int rc;                         /* Return code */
192003
192004  rc = fts5NewTransaction(pTab);
192005  if( rc==SQLITE_OK ){
192006    nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
192007    pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
192008    if( pCsr ){
192009      Fts5Global *pGlobal = pTab->pGlobal;
192010      memset(pCsr, 0, nByte);
192011      pCsr->aColumnSize = (int*)&pCsr[1];
192012      pCsr->pNext = pGlobal->pCsr;
192013      pGlobal->pCsr = pCsr;
192014      pCsr->iCsrId = ++pGlobal->iNextId;
192015    }else{
192016      rc = SQLITE_NOMEM;
192017    }
192018  }
192019  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
192020  return rc;
192021}
192022
192023static int fts5StmtType(Fts5Cursor *pCsr){
192024  if( pCsr->ePlan==FTS5_PLAN_SCAN ){
192025    return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
192026  }
192027  return FTS5_STMT_LOOKUP;
192028}
192029
192030/*
192031** This function is called after the cursor passed as the only argument
192032** is moved to point at a different row. It clears all cached data
192033** specific to the previous row stored by the cursor object.
192034*/
192035static void fts5CsrNewrow(Fts5Cursor *pCsr){
192036  CsrFlagSet(pCsr,
192037      FTS5CSR_REQUIRE_CONTENT
192038    | FTS5CSR_REQUIRE_DOCSIZE
192039    | FTS5CSR_REQUIRE_INST
192040    | FTS5CSR_REQUIRE_POSLIST
192041  );
192042}
192043
192044static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
192045  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
192046  Fts5Auxdata *pData;
192047  Fts5Auxdata *pNext;
192048
192049  sqlite3_free(pCsr->aInstIter);
192050  sqlite3_free(pCsr->aInst);
192051  if( pCsr->pStmt ){
192052    int eStmt = fts5StmtType(pCsr);
192053    sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
192054  }
192055  if( pCsr->pSorter ){
192056    Fts5Sorter *pSorter = pCsr->pSorter;
192057    sqlite3_finalize(pSorter->pStmt);
192058    sqlite3_free(pSorter);
192059  }
192060
192061  if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
192062    sqlite3Fts5ExprFree(pCsr->pExpr);
192063  }
192064
192065  for(pData=pCsr->pAuxdata; pData; pData=pNext){
192066    pNext = pData->pNext;
192067    if( pData->xDelete ) pData->xDelete(pData->pPtr);
192068    sqlite3_free(pData);
192069  }
192070
192071  sqlite3_finalize(pCsr->pRankArgStmt);
192072  sqlite3_free(pCsr->apRankArg);
192073
192074  if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
192075    sqlite3_free(pCsr->zRank);
192076    sqlite3_free(pCsr->zRankArgs);
192077  }
192078
192079  memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
192080}
192081
192082
192083/*
192084** Close the cursor.  For additional information see the documentation
192085** on the xClose method of the virtual table interface.
192086*/
192087static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
192088  if( pCursor ){
192089    Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
192090    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
192091    Fts5Cursor **pp;
192092
192093    fts5FreeCursorComponents(pCsr);
192094    /* Remove the cursor from the Fts5Global.pCsr list */
192095    for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
192096    *pp = pCsr->pNext;
192097
192098    sqlite3_free(pCsr);
192099  }
192100  return SQLITE_OK;
192101}
192102
192103static int fts5SorterNext(Fts5Cursor *pCsr){
192104  Fts5Sorter *pSorter = pCsr->pSorter;
192105  int rc;
192106
192107  rc = sqlite3_step(pSorter->pStmt);
192108  if( rc==SQLITE_DONE ){
192109    rc = SQLITE_OK;
192110    CsrFlagSet(pCsr, FTS5CSR_EOF);
192111  }else if( rc==SQLITE_ROW ){
192112    const u8 *a;
192113    const u8 *aBlob;
192114    int nBlob;
192115    int i;
192116    int iOff = 0;
192117    rc = SQLITE_OK;
192118
192119    pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
192120    nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
192121    aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
192122
192123    /* nBlob==0 in detail=none mode. */
192124    if( nBlob>0 ){
192125      for(i=0; i<(pSorter->nIdx-1); i++){
192126        int iVal;
192127        a += fts5GetVarint32(a, iVal);
192128        iOff += iVal;
192129        pSorter->aIdx[i] = iOff;
192130      }
192131      pSorter->aIdx[i] = &aBlob[nBlob] - a;
192132      pSorter->aPoslist = a;
192133    }
192134
192135    fts5CsrNewrow(pCsr);
192136  }
192137
192138  return rc;
192139}
192140
192141
192142/*
192143** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
192144** open on table pTab.
192145*/
192146static void fts5TripCursors(Fts5Table *pTab){
192147  Fts5Cursor *pCsr;
192148  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
192149    if( pCsr->ePlan==FTS5_PLAN_MATCH
192150     && pCsr->base.pVtab==(sqlite3_vtab*)pTab
192151    ){
192152      CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
192153    }
192154  }
192155}
192156
192157/*
192158** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
192159** argument, close and reopen all Fts5IndexIter iterators that the cursor
192160** is using. Then attempt to move the cursor to a rowid equal to or laster
192161** (in the cursors sort order - ASC or DESC) than the current rowid.
192162**
192163** If the new rowid is not equal to the old, set output parameter *pbSkip
192164** to 1 before returning. Otherwise, leave it unchanged.
192165**
192166** Return SQLITE_OK if successful or if no reseek was required, or an
192167** error code if an error occurred.
192168*/
192169static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
192170  int rc = SQLITE_OK;
192171  assert( *pbSkip==0 );
192172  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
192173    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
192174    int bDesc = pCsr->bDesc;
192175    i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
192176
192177    rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
192178    if( rc==SQLITE_OK &&  iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
192179      *pbSkip = 1;
192180    }
192181
192182    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
192183    fts5CsrNewrow(pCsr);
192184    if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
192185      CsrFlagSet(pCsr, FTS5CSR_EOF);
192186      *pbSkip = 1;
192187    }
192188  }
192189  return rc;
192190}
192191
192192
192193/*
192194** Advance the cursor to the next row in the table that matches the
192195** search criteria.
192196**
192197** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
192198** even if we reach end-of-file.  The fts5EofMethod() will be called
192199** subsequently to determine whether or not an EOF was hit.
192200*/
192201static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
192202  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
192203  int rc;
192204
192205  assert( (pCsr->ePlan<3)==
192206          (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
192207  );
192208  assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
192209
192210  if( pCsr->ePlan<3 ){
192211    int bSkip = 0;
192212    if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
192213    rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
192214    CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
192215    fts5CsrNewrow(pCsr);
192216  }else{
192217    switch( pCsr->ePlan ){
192218      case FTS5_PLAN_SPECIAL: {
192219        CsrFlagSet(pCsr, FTS5CSR_EOF);
192220        rc = SQLITE_OK;
192221        break;
192222      }
192223
192224      case FTS5_PLAN_SORTED_MATCH: {
192225        rc = fts5SorterNext(pCsr);
192226        break;
192227      }
192228
192229      default:
192230        rc = sqlite3_step(pCsr->pStmt);
192231        if( rc!=SQLITE_ROW ){
192232          CsrFlagSet(pCsr, FTS5CSR_EOF);
192233          rc = sqlite3_reset(pCsr->pStmt);
192234        }else{
192235          rc = SQLITE_OK;
192236        }
192237        break;
192238    }
192239  }
192240
192241  return rc;
192242}
192243
192244
192245static int fts5PrepareStatement(
192246  sqlite3_stmt **ppStmt,
192247  Fts5Config *pConfig,
192248  const char *zFmt,
192249  ...
192250){
192251  sqlite3_stmt *pRet = 0;
192252  int rc;
192253  char *zSql;
192254  va_list ap;
192255
192256  va_start(ap, zFmt);
192257  zSql = sqlite3_vmprintf(zFmt, ap);
192258  if( zSql==0 ){
192259    rc = SQLITE_NOMEM;
192260  }else{
192261    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pRet, 0);
192262    if( rc!=SQLITE_OK ){
192263      *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
192264    }
192265    sqlite3_free(zSql);
192266  }
192267
192268  va_end(ap);
192269  *ppStmt = pRet;
192270  return rc;
192271}
192272
192273static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
192274  Fts5Config *pConfig = pTab->pConfig;
192275  Fts5Sorter *pSorter;
192276  int nPhrase;
192277  int nByte;
192278  int rc;
192279  const char *zRank = pCsr->zRank;
192280  const char *zRankArgs = pCsr->zRankArgs;
192281
192282  nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
192283  nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
192284  pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
192285  if( pSorter==0 ) return SQLITE_NOMEM;
192286  memset(pSorter, 0, nByte);
192287  pSorter->nIdx = nPhrase;
192288
192289  /* TODO: It would be better to have some system for reusing statement
192290  ** handles here, rather than preparing a new one for each query. But that
192291  ** is not possible as SQLite reference counts the virtual table objects.
192292  ** And since the statement required here reads from this very virtual
192293  ** table, saving it creates a circular reference.
192294  **
192295  ** If SQLite a built-in statement cache, this wouldn't be a problem. */
192296  rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
192297      "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
192298      pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
192299      (zRankArgs ? ", " : ""),
192300      (zRankArgs ? zRankArgs : ""),
192301      bDesc ? "DESC" : "ASC"
192302  );
192303
192304  pCsr->pSorter = pSorter;
192305  if( rc==SQLITE_OK ){
192306    assert( pTab->pSortCsr==0 );
192307    pTab->pSortCsr = pCsr;
192308    rc = fts5SorterNext(pCsr);
192309    pTab->pSortCsr = 0;
192310  }
192311
192312  if( rc!=SQLITE_OK ){
192313    sqlite3_finalize(pSorter->pStmt);
192314    sqlite3_free(pSorter);
192315    pCsr->pSorter = 0;
192316  }
192317
192318  return rc;
192319}
192320
192321static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
192322  int rc;
192323  Fts5Expr *pExpr = pCsr->pExpr;
192324  rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
192325  if( sqlite3Fts5ExprEof(pExpr) ){
192326    CsrFlagSet(pCsr, FTS5CSR_EOF);
192327  }
192328  fts5CsrNewrow(pCsr);
192329  return rc;
192330}
192331
192332/*
192333** Process a "special" query. A special query is identified as one with a
192334** MATCH expression that begins with a '*' character. The remainder of
192335** the text passed to the MATCH operator are used as  the special query
192336** parameters.
192337*/
192338static int fts5SpecialMatch(
192339  Fts5Table *pTab,
192340  Fts5Cursor *pCsr,
192341  const char *zQuery
192342){
192343  int rc = SQLITE_OK;             /* Return code */
192344  const char *z = zQuery;         /* Special query text */
192345  int n;                          /* Number of bytes in text at z */
192346
192347  while( z[0]==' ' ) z++;
192348  for(n=0; z[n] && z[n]!=' '; n++);
192349
192350  assert( pTab->base.zErrMsg==0 );
192351  pCsr->ePlan = FTS5_PLAN_SPECIAL;
192352
192353  if( 0==sqlite3_strnicmp("reads", z, n) ){
192354    pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
192355  }
192356  else if( 0==sqlite3_strnicmp("id", z, n) ){
192357    pCsr->iSpecial = pCsr->iCsrId;
192358  }
192359  else{
192360    /* An unrecognized directive. Return an error message. */
192361    pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
192362    rc = SQLITE_ERROR;
192363  }
192364
192365  return rc;
192366}
192367
192368/*
192369** Search for an auxiliary function named zName that can be used with table
192370** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
192371** structure. Otherwise, if no such function exists, return NULL.
192372*/
192373static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
192374  Fts5Auxiliary *pAux;
192375
192376  for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
192377    if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
192378  }
192379
192380  /* No function of the specified name was found. Return 0. */
192381  return 0;
192382}
192383
192384
192385static int fts5FindRankFunction(Fts5Cursor *pCsr){
192386  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
192387  Fts5Config *pConfig = pTab->pConfig;
192388  int rc = SQLITE_OK;
192389  Fts5Auxiliary *pAux = 0;
192390  const char *zRank = pCsr->zRank;
192391  const char *zRankArgs = pCsr->zRankArgs;
192392
192393  if( zRankArgs ){
192394    char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
192395    if( zSql ){
192396      sqlite3_stmt *pStmt = 0;
192397      rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pStmt, 0);
192398      sqlite3_free(zSql);
192399      assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
192400      if( rc==SQLITE_OK ){
192401        if( SQLITE_ROW==sqlite3_step(pStmt) ){
192402          int nByte;
192403          pCsr->nRankArg = sqlite3_column_count(pStmt);
192404          nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
192405          pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
192406          if( rc==SQLITE_OK ){
192407            int i;
192408            for(i=0; i<pCsr->nRankArg; i++){
192409              pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
192410            }
192411          }
192412          pCsr->pRankArgStmt = pStmt;
192413        }else{
192414          rc = sqlite3_finalize(pStmt);
192415          assert( rc!=SQLITE_OK );
192416        }
192417      }
192418    }
192419  }
192420
192421  if( rc==SQLITE_OK ){
192422    pAux = fts5FindAuxiliary(pTab, zRank);
192423    if( pAux==0 ){
192424      assert( pTab->base.zErrMsg==0 );
192425      pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
192426      rc = SQLITE_ERROR;
192427    }
192428  }
192429
192430  pCsr->pRank = pAux;
192431  return rc;
192432}
192433
192434
192435static int fts5CursorParseRank(
192436  Fts5Config *pConfig,
192437  Fts5Cursor *pCsr,
192438  sqlite3_value *pRank
192439){
192440  int rc = SQLITE_OK;
192441  if( pRank ){
192442    const char *z = (const char*)sqlite3_value_text(pRank);
192443    char *zRank = 0;
192444    char *zRankArgs = 0;
192445
192446    if( z==0 ){
192447      if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
192448    }else{
192449      rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
192450    }
192451    if( rc==SQLITE_OK ){
192452      pCsr->zRank = zRank;
192453      pCsr->zRankArgs = zRankArgs;
192454      CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
192455    }else if( rc==SQLITE_ERROR ){
192456      pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
192457          "parse error in rank function: %s", z
192458      );
192459    }
192460  }else{
192461    if( pConfig->zRank ){
192462      pCsr->zRank = (char*)pConfig->zRank;
192463      pCsr->zRankArgs = (char*)pConfig->zRankArgs;
192464    }else{
192465      pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
192466      pCsr->zRankArgs = 0;
192467    }
192468  }
192469  return rc;
192470}
192471
192472static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
192473  if( pVal ){
192474    int eType = sqlite3_value_numeric_type(pVal);
192475    if( eType==SQLITE_INTEGER ){
192476      return sqlite3_value_int64(pVal);
192477    }
192478  }
192479  return iDefault;
192480}
192481
192482/*
192483** This is the xFilter interface for the virtual table.  See
192484** the virtual table xFilter method documentation for additional
192485** information.
192486**
192487** There are three possible query strategies:
192488**
192489**   1. Full-text search using a MATCH operator.
192490**   2. A by-rowid lookup.
192491**   3. A full-table scan.
192492*/
192493static int fts5FilterMethod(
192494  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
192495  int idxNum,                     /* Strategy index */
192496  const char *zUnused,            /* Unused */
192497  int nVal,                       /* Number of elements in apVal */
192498  sqlite3_value **apVal           /* Arguments for the indexing scheme */
192499){
192500  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
192501  Fts5Config *pConfig = pTab->pConfig;
192502  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
192503  int rc = SQLITE_OK;             /* Error code */
192504  int iVal = 0;                   /* Counter for apVal[] */
192505  int bDesc;                      /* True if ORDER BY [rank|rowid] DESC */
192506  int bOrderByRank;               /* True if ORDER BY rank */
192507  sqlite3_value *pMatch = 0;      /* <tbl> MATCH ? expression (or NULL) */
192508  sqlite3_value *pRank = 0;       /* rank MATCH ? expression (or NULL) */
192509  sqlite3_value *pRowidEq = 0;    /* rowid = ? expression (or NULL) */
192510  sqlite3_value *pRowidLe = 0;    /* rowid <= ? expression (or NULL) */
192511  sqlite3_value *pRowidGe = 0;    /* rowid >= ? expression (or NULL) */
192512  char **pzErrmsg = pConfig->pzErrmsg;
192513
192514  UNUSED_PARAM(zUnused);
192515  UNUSED_PARAM(nVal);
192516
192517  if( pCsr->ePlan ){
192518    fts5FreeCursorComponents(pCsr);
192519    memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
192520  }
192521
192522  assert( pCsr->pStmt==0 );
192523  assert( pCsr->pExpr==0 );
192524  assert( pCsr->csrflags==0 );
192525  assert( pCsr->pRank==0 );
192526  assert( pCsr->zRank==0 );
192527  assert( pCsr->zRankArgs==0 );
192528
192529  assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
192530  pConfig->pzErrmsg = &pTab->base.zErrMsg;
192531
192532  /* Decode the arguments passed through to this function.
192533  **
192534  ** Note: The following set of if(...) statements must be in the same
192535  ** order as the corresponding entries in the struct at the top of
192536  ** fts5BestIndexMethod().  */
192537  if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
192538  if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
192539  if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
192540  if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
192541  if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
192542  assert( iVal==nVal );
192543  bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
192544  pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
192545
192546  /* Set the cursor upper and lower rowid limits. Only some strategies
192547  ** actually use them. This is ok, as the xBestIndex() method leaves the
192548  ** sqlite3_index_constraint.omit flag clear for range constraints
192549  ** on the rowid field.  */
192550  if( pRowidEq ){
192551    pRowidLe = pRowidGe = pRowidEq;
192552  }
192553  if( bDesc ){
192554    pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
192555    pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
192556  }else{
192557    pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
192558    pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
192559  }
192560
192561  if( pTab->pSortCsr ){
192562    /* If pSortCsr is non-NULL, then this call is being made as part of
192563    ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
192564    ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
192565    ** return results to the user for this query. The current cursor
192566    ** (pCursor) is used to execute the query issued by function
192567    ** fts5CursorFirstSorted() above.  */
192568    assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
192569    assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
192570    assert( pCsr->iLastRowid==LARGEST_INT64 );
192571    assert( pCsr->iFirstRowid==SMALLEST_INT64 );
192572    pCsr->ePlan = FTS5_PLAN_SOURCE;
192573    pCsr->pExpr = pTab->pSortCsr->pExpr;
192574    rc = fts5CursorFirst(pTab, pCsr, bDesc);
192575  }else if( pMatch ){
192576    const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
192577    if( zExpr==0 ) zExpr = "";
192578
192579    rc = fts5CursorParseRank(pConfig, pCsr, pRank);
192580    if( rc==SQLITE_OK ){
192581      if( zExpr[0]=='*' ){
192582        /* The user has issued a query of the form "MATCH '*...'". This
192583        ** indicates that the MATCH expression is not a full text query,
192584        ** but a request for an internal parameter.  */
192585        rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
192586      }else{
192587        char **pzErr = &pTab->base.zErrMsg;
192588        rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pCsr->pExpr, pzErr);
192589        if( rc==SQLITE_OK ){
192590          if( bOrderByRank ){
192591            pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
192592            rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
192593          }else{
192594            pCsr->ePlan = FTS5_PLAN_MATCH;
192595            rc = fts5CursorFirst(pTab, pCsr, bDesc);
192596          }
192597        }
192598      }
192599    }
192600  }else if( pConfig->zContent==0 ){
192601    *pConfig->pzErrmsg = sqlite3_mprintf(
192602        "%s: table does not support scanning", pConfig->zName
192603    );
192604    rc = SQLITE_ERROR;
192605  }else{
192606    /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
192607    ** by rowid (ePlan==FTS5_PLAN_ROWID).  */
192608    pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
192609    rc = sqlite3Fts5StorageStmt(
192610        pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
192611    );
192612    if( rc==SQLITE_OK ){
192613      if( pCsr->ePlan==FTS5_PLAN_ROWID ){
192614        sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
192615      }else{
192616        sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
192617        sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
192618      }
192619      rc = fts5NextMethod(pCursor);
192620    }
192621  }
192622
192623  pConfig->pzErrmsg = pzErrmsg;
192624  return rc;
192625}
192626
192627/*
192628** This is the xEof method of the virtual table. SQLite calls this
192629** routine to find out if it has reached the end of a result set.
192630*/
192631static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
192632  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
192633  return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
192634}
192635
192636/*
192637** Return the rowid that the cursor currently points to.
192638*/
192639static i64 fts5CursorRowid(Fts5Cursor *pCsr){
192640  assert( pCsr->ePlan==FTS5_PLAN_MATCH
192641       || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
192642       || pCsr->ePlan==FTS5_PLAN_SOURCE
192643  );
192644  if( pCsr->pSorter ){
192645    return pCsr->pSorter->iRowid;
192646  }else{
192647    return sqlite3Fts5ExprRowid(pCsr->pExpr);
192648  }
192649}
192650
192651/*
192652** This is the xRowid method. The SQLite core calls this routine to
192653** retrieve the rowid for the current row of the result set. fts5
192654** exposes %_content.rowid as the rowid for the virtual table. The
192655** rowid should be written to *pRowid.
192656*/
192657static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
192658  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
192659  int ePlan = pCsr->ePlan;
192660
192661  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
192662  switch( ePlan ){
192663    case FTS5_PLAN_SPECIAL:
192664      *pRowid = 0;
192665      break;
192666
192667    case FTS5_PLAN_SOURCE:
192668    case FTS5_PLAN_MATCH:
192669    case FTS5_PLAN_SORTED_MATCH:
192670      *pRowid = fts5CursorRowid(pCsr);
192671      break;
192672
192673    default:
192674      *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
192675      break;
192676  }
192677
192678  return SQLITE_OK;
192679}
192680
192681/*
192682** If the cursor requires seeking (bSeekRequired flag is set), seek it.
192683** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
192684**
192685** If argument bErrormsg is true and an error occurs, an error message may
192686** be left in sqlite3_vtab.zErrMsg.
192687*/
192688static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
192689  int rc = SQLITE_OK;
192690
192691  /* If the cursor does not yet have a statement handle, obtain one now. */
192692  if( pCsr->pStmt==0 ){
192693    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
192694    int eStmt = fts5StmtType(pCsr);
192695    rc = sqlite3Fts5StorageStmt(
192696        pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
192697    );
192698    assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
192699    assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
192700  }
192701
192702  if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
192703    assert( pCsr->pExpr );
192704    sqlite3_reset(pCsr->pStmt);
192705    sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
192706    rc = sqlite3_step(pCsr->pStmt);
192707    if( rc==SQLITE_ROW ){
192708      rc = SQLITE_OK;
192709      CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
192710    }else{
192711      rc = sqlite3_reset(pCsr->pStmt);
192712      if( rc==SQLITE_OK ){
192713        rc = FTS5_CORRUPT;
192714      }
192715    }
192716  }
192717  return rc;
192718}
192719
192720static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
192721  va_list ap;                     /* ... printf arguments */
192722  va_start(ap, zFormat);
192723  assert( p->base.zErrMsg==0 );
192724  p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
192725  va_end(ap);
192726}
192727
192728/*
192729** This function is called to handle an FTS INSERT command. In other words,
192730** an INSERT statement of the form:
192731**
192732**     INSERT INTO fts(fts) VALUES($pCmd)
192733**     INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
192734**
192735** Argument pVal is the value assigned to column "fts" by the INSERT
192736** statement. This function returns SQLITE_OK if successful, or an SQLite
192737** error code if an error occurs.
192738**
192739** The commands implemented by this function are documented in the "Special
192740** INSERT Directives" section of the documentation. It should be updated if
192741** more commands are added to this function.
192742*/
192743static int fts5SpecialInsert(
192744  Fts5Table *pTab,                /* Fts5 table object */
192745  const char *zCmd,               /* Text inserted into table-name column */
192746  sqlite3_value *pVal             /* Value inserted into rank column */
192747){
192748  Fts5Config *pConfig = pTab->pConfig;
192749  int rc = SQLITE_OK;
192750  int bError = 0;
192751
192752  if( 0==sqlite3_stricmp("delete-all", zCmd) ){
192753    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
192754      fts5SetVtabError(pTab,
192755          "'delete-all' may only be used with a "
192756          "contentless or external content fts5 table"
192757      );
192758      rc = SQLITE_ERROR;
192759    }else{
192760      rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
192761    }
192762  }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
192763    if( pConfig->eContent==FTS5_CONTENT_NONE ){
192764      fts5SetVtabError(pTab,
192765          "'rebuild' may not be used with a contentless fts5 table"
192766      );
192767      rc = SQLITE_ERROR;
192768    }else{
192769      rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
192770    }
192771  }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
192772    rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
192773  }else if( 0==sqlite3_stricmp("merge", zCmd) ){
192774    int nMerge = sqlite3_value_int(pVal);
192775    rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
192776  }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
192777    rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
192778#ifdef SQLITE_DEBUG
192779  }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
192780    pConfig->bPrefixIndex = sqlite3_value_int(pVal);
192781#endif
192782  }else{
192783    rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
192784    if( rc==SQLITE_OK ){
192785      rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
192786    }
192787    if( rc==SQLITE_OK ){
192788      if( bError ){
192789        rc = SQLITE_ERROR;
192790      }else{
192791        rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
192792      }
192793    }
192794  }
192795  return rc;
192796}
192797
192798static int fts5SpecialDelete(
192799  Fts5Table *pTab,
192800  sqlite3_value **apVal
192801){
192802  int rc = SQLITE_OK;
192803  int eType1 = sqlite3_value_type(apVal[1]);
192804  if( eType1==SQLITE_INTEGER ){
192805    sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
192806    rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
192807  }
192808  return rc;
192809}
192810
192811static void fts5StorageInsert(
192812  int *pRc,
192813  Fts5Table *pTab,
192814  sqlite3_value **apVal,
192815  i64 *piRowid
192816){
192817  int rc = *pRc;
192818  if( rc==SQLITE_OK ){
192819    rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
192820  }
192821  if( rc==SQLITE_OK ){
192822    rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
192823  }
192824  *pRc = rc;
192825}
192826
192827/*
192828** This function is the implementation of the xUpdate callback used by
192829** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
192830** inserted, updated or deleted.
192831**
192832** A delete specifies a single argument - the rowid of the row to remove.
192833**
192834** Update and insert operations pass:
192835**
192836**   1. The "old" rowid, or NULL.
192837**   2. The "new" rowid.
192838**   3. Values for each of the nCol matchable columns.
192839**   4. Values for the two hidden columns (<tablename> and "rank").
192840*/
192841static int fts5UpdateMethod(
192842  sqlite3_vtab *pVtab,            /* Virtual table handle */
192843  int nArg,                       /* Size of argument array */
192844  sqlite3_value **apVal,          /* Array of arguments */
192845  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
192846){
192847  Fts5Table *pTab = (Fts5Table*)pVtab;
192848  Fts5Config *pConfig = pTab->pConfig;
192849  int eType0;                     /* value_type() of apVal[0] */
192850  int rc = SQLITE_OK;             /* Return code */
192851
192852  /* A transaction must be open when this is called. */
192853  assert( pTab->ts.eState==1 );
192854
192855  assert( pVtab->zErrMsg==0 );
192856  assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
192857  assert( nArg==1
192858      || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
192859      || sqlite3_value_type(apVal[1])==SQLITE_NULL
192860  );
192861  assert( pTab->pConfig->pzErrmsg==0 );
192862  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
192863
192864  /* Put any active cursors into REQUIRE_SEEK state. */
192865  fts5TripCursors(pTab);
192866
192867  eType0 = sqlite3_value_type(apVal[0]);
192868  if( eType0==SQLITE_NULL
192869   && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
192870  ){
192871    /* A "special" INSERT op. These are handled separately. */
192872    const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
192873    if( pConfig->eContent!=FTS5_CONTENT_NORMAL
192874      && 0==sqlite3_stricmp("delete", z)
192875    ){
192876      rc = fts5SpecialDelete(pTab, apVal);
192877    }else{
192878      rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
192879    }
192880  }else{
192881    /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
192882    ** any conflict on the rowid value must be detected before any
192883    ** modifications are made to the database file. There are 4 cases:
192884    **
192885    **   1) DELETE
192886    **   2) UPDATE (rowid not modified)
192887    **   3) UPDATE (rowid modified)
192888    **   4) INSERT
192889    **
192890    ** Cases 3 and 4 may violate the rowid constraint.
192891    */
192892    int eConflict = SQLITE_ABORT;
192893    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
192894      eConflict = sqlite3_vtab_on_conflict(pConfig->db);
192895    }
192896
192897    assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
192898    assert( nArg!=1 || eType0==SQLITE_INTEGER );
192899
192900    /* Filter out attempts to run UPDATE or DELETE on contentless tables.
192901    ** This is not suported.  */
192902    if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
192903      pTab->base.zErrMsg = sqlite3_mprintf(
192904          "cannot %s contentless fts5 table: %s",
192905          (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
192906      );
192907      rc = SQLITE_ERROR;
192908    }
192909
192910    /* DELETE */
192911    else if( nArg==1 ){
192912      i64 iDel = sqlite3_value_int64(apVal[0]);  /* Rowid to delete */
192913      rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
192914    }
192915
192916    /* INSERT */
192917    else if( eType0!=SQLITE_INTEGER ){
192918      /* If this is a REPLACE, first remove the current entry (if any) */
192919      if( eConflict==SQLITE_REPLACE
192920       && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
192921      ){
192922        i64 iNew = sqlite3_value_int64(apVal[1]);  /* Rowid to delete */
192923        rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
192924      }
192925      fts5StorageInsert(&rc, pTab, apVal, pRowid);
192926    }
192927
192928    /* UPDATE */
192929    else{
192930      i64 iOld = sqlite3_value_int64(apVal[0]);  /* Old rowid */
192931      i64 iNew = sqlite3_value_int64(apVal[1]);  /* New rowid */
192932      if( iOld!=iNew ){
192933        if( eConflict==SQLITE_REPLACE ){
192934          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
192935          if( rc==SQLITE_OK ){
192936            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
192937          }
192938          fts5StorageInsert(&rc, pTab, apVal, pRowid);
192939        }else{
192940          rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
192941          if( rc==SQLITE_OK ){
192942            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
192943          }
192944          if( rc==SQLITE_OK ){
192945            rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
192946          }
192947        }
192948      }else{
192949        rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
192950        fts5StorageInsert(&rc, pTab, apVal, pRowid);
192951      }
192952    }
192953  }
192954
192955  pTab->pConfig->pzErrmsg = 0;
192956  return rc;
192957}
192958
192959/*
192960** Implementation of xSync() method.
192961*/
192962static int fts5SyncMethod(sqlite3_vtab *pVtab){
192963  int rc;
192964  Fts5Table *pTab = (Fts5Table*)pVtab;
192965  fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
192966  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
192967  fts5TripCursors(pTab);
192968  rc = sqlite3Fts5StorageSync(pTab->pStorage, 1);
192969  pTab->pConfig->pzErrmsg = 0;
192970  return rc;
192971}
192972
192973/*
192974** Implementation of xBegin() method.
192975*/
192976static int fts5BeginMethod(sqlite3_vtab *pVtab){
192977  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
192978  fts5NewTransaction((Fts5Table*)pVtab);
192979  return SQLITE_OK;
192980}
192981
192982/*
192983** Implementation of xCommit() method. This is a no-op. The contents of
192984** the pending-terms hash-table have already been flushed into the database
192985** by fts5SyncMethod().
192986*/
192987static int fts5CommitMethod(sqlite3_vtab *pVtab){
192988  UNUSED_PARAM(pVtab);  /* Call below is a no-op for NDEBUG builds */
192989  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
192990  return SQLITE_OK;
192991}
192992
192993/*
192994** Implementation of xRollback(). Discard the contents of the pending-terms
192995** hash-table. Any changes made to the database are reverted by SQLite.
192996*/
192997static int fts5RollbackMethod(sqlite3_vtab *pVtab){
192998  int rc;
192999  Fts5Table *pTab = (Fts5Table*)pVtab;
193000  fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
193001  rc = sqlite3Fts5StorageRollback(pTab->pStorage);
193002  return rc;
193003}
193004
193005static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
193006
193007static void *fts5ApiUserData(Fts5Context *pCtx){
193008  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193009  return pCsr->pAux->pUserData;
193010}
193011
193012static int fts5ApiColumnCount(Fts5Context *pCtx){
193013  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193014  return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
193015}
193016
193017static int fts5ApiColumnTotalSize(
193018  Fts5Context *pCtx,
193019  int iCol,
193020  sqlite3_int64 *pnToken
193021){
193022  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193023  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193024  return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
193025}
193026
193027static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
193028  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193029  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193030  return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
193031}
193032
193033static int fts5ApiTokenize(
193034  Fts5Context *pCtx,
193035  const char *pText, int nText,
193036  void *pUserData,
193037  int (*xToken)(void*, int, const char*, int, int, int)
193038){
193039  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193040  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193041  return sqlite3Fts5Tokenize(
193042      pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
193043  );
193044}
193045
193046static int fts5ApiPhraseCount(Fts5Context *pCtx){
193047  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193048  return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
193049}
193050
193051static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
193052  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193053  return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
193054}
193055
193056static int fts5ApiColumnText(
193057  Fts5Context *pCtx,
193058  int iCol,
193059  const char **pz,
193060  int *pn
193061){
193062  int rc = SQLITE_OK;
193063  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193064  if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
193065    *pz = 0;
193066    *pn = 0;
193067  }else{
193068    rc = fts5SeekCursor(pCsr, 0);
193069    if( rc==SQLITE_OK ){
193070      *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
193071      *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
193072    }
193073  }
193074  return rc;
193075}
193076
193077static int fts5CsrPoslist(
193078  Fts5Cursor *pCsr,
193079  int iPhrase,
193080  const u8 **pa,
193081  int *pn
193082){
193083  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
193084  int rc = SQLITE_OK;
193085  int bLive = (pCsr->pSorter==0);
193086
193087  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
193088
193089    if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
193090      Fts5PoslistPopulator *aPopulator;
193091      int i;
193092      aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
193093      if( aPopulator==0 ) rc = SQLITE_NOMEM;
193094      for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
193095        int n; const char *z;
193096        rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
193097        if( rc==SQLITE_OK ){
193098          rc = sqlite3Fts5ExprPopulatePoslists(
193099              pConfig, pCsr->pExpr, aPopulator, i, z, n
193100          );
193101        }
193102      }
193103      sqlite3_free(aPopulator);
193104
193105      if( pCsr->pSorter ){
193106        sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
193107      }
193108    }
193109    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
193110  }
193111
193112  if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
193113    Fts5Sorter *pSorter = pCsr->pSorter;
193114    int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
193115    *pn = pSorter->aIdx[iPhrase] - i1;
193116    *pa = &pSorter->aPoslist[i1];
193117  }else{
193118    *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
193119  }
193120
193121  return rc;
193122}
193123
193124/*
193125** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
193126** correctly for the current view. Return SQLITE_OK if successful, or an
193127** SQLite error code otherwise.
193128*/
193129static int fts5CacheInstArray(Fts5Cursor *pCsr){
193130  int rc = SQLITE_OK;
193131  Fts5PoslistReader *aIter;       /* One iterator for each phrase */
193132  int nIter;                      /* Number of iterators/phrases */
193133
193134  nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
193135  if( pCsr->aInstIter==0 ){
193136    int nByte = sizeof(Fts5PoslistReader) * nIter;
193137    pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
193138  }
193139  aIter = pCsr->aInstIter;
193140
193141  if( aIter ){
193142    int nInst = 0;                /* Number instances seen so far */
193143    int i;
193144
193145    /* Initialize all iterators */
193146    for(i=0; i<nIter && rc==SQLITE_OK; i++){
193147      const u8 *a;
193148      int n;
193149      rc = fts5CsrPoslist(pCsr, i, &a, &n);
193150      if( rc==SQLITE_OK ){
193151        sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
193152      }
193153    }
193154
193155    if( rc==SQLITE_OK ){
193156      while( 1 ){
193157        int *aInst;
193158        int iBest = -1;
193159        for(i=0; i<nIter; i++){
193160          if( (aIter[i].bEof==0)
193161              && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
193162            ){
193163            iBest = i;
193164          }
193165        }
193166        if( iBest<0 ) break;
193167
193168        nInst++;
193169        if( nInst>=pCsr->nInstAlloc ){
193170          pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
193171          aInst = (int*)sqlite3_realloc(
193172              pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
193173              );
193174          if( aInst ){
193175            pCsr->aInst = aInst;
193176          }else{
193177            rc = SQLITE_NOMEM;
193178            break;
193179          }
193180        }
193181
193182        aInst = &pCsr->aInst[3 * (nInst-1)];
193183        aInst[0] = iBest;
193184        aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
193185        aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
193186        sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
193187      }
193188    }
193189
193190    pCsr->nInstCount = nInst;
193191    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
193192  }
193193  return rc;
193194}
193195
193196static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
193197  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193198  int rc = SQLITE_OK;
193199  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
193200   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
193201    *pnInst = pCsr->nInstCount;
193202  }
193203  return rc;
193204}
193205
193206static int fts5ApiInst(
193207  Fts5Context *pCtx,
193208  int iIdx,
193209  int *piPhrase,
193210  int *piCol,
193211  int *piOff
193212){
193213  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193214  int rc = SQLITE_OK;
193215  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
193216   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
193217  ){
193218    if( iIdx<0 || iIdx>=pCsr->nInstCount ){
193219      rc = SQLITE_RANGE;
193220#if 0
193221    }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
193222      *piPhrase = pCsr->aInst[iIdx*3];
193223      *piCol = pCsr->aInst[iIdx*3 + 2];
193224      *piOff = -1;
193225#endif
193226    }else{
193227      *piPhrase = pCsr->aInst[iIdx*3];
193228      *piCol = pCsr->aInst[iIdx*3 + 1];
193229      *piOff = pCsr->aInst[iIdx*3 + 2];
193230    }
193231  }
193232  return rc;
193233}
193234
193235static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
193236  return fts5CursorRowid((Fts5Cursor*)pCtx);
193237}
193238
193239static int fts5ColumnSizeCb(
193240  void *pContext,                 /* Pointer to int */
193241  int tflags,
193242  const char *pUnused,            /* Buffer containing token */
193243  int nUnused,                    /* Size of token in bytes */
193244  int iUnused1,                   /* Start offset of token */
193245  int iUnused2                    /* End offset of token */
193246){
193247  int *pCnt = (int*)pContext;
193248  UNUSED_PARAM2(pUnused, nUnused);
193249  UNUSED_PARAM2(iUnused1, iUnused2);
193250  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
193251    (*pCnt)++;
193252  }
193253  return SQLITE_OK;
193254}
193255
193256static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
193257  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193258  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193259  Fts5Config *pConfig = pTab->pConfig;
193260  int rc = SQLITE_OK;
193261
193262  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
193263    if( pConfig->bColumnsize ){
193264      i64 iRowid = fts5CursorRowid(pCsr);
193265      rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
193266    }else if( pConfig->zContent==0 ){
193267      int i;
193268      for(i=0; i<pConfig->nCol; i++){
193269        if( pConfig->abUnindexed[i]==0 ){
193270          pCsr->aColumnSize[i] = -1;
193271        }
193272      }
193273    }else{
193274      int i;
193275      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
193276        if( pConfig->abUnindexed[i]==0 ){
193277          const char *z; int n;
193278          void *p = (void*)(&pCsr->aColumnSize[i]);
193279          pCsr->aColumnSize[i] = 0;
193280          rc = fts5ApiColumnText(pCtx, i, &z, &n);
193281          if( rc==SQLITE_OK ){
193282            rc = sqlite3Fts5Tokenize(
193283                pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
193284            );
193285          }
193286        }
193287      }
193288    }
193289    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
193290  }
193291  if( iCol<0 ){
193292    int i;
193293    *pnToken = 0;
193294    for(i=0; i<pConfig->nCol; i++){
193295      *pnToken += pCsr->aColumnSize[i];
193296    }
193297  }else if( iCol<pConfig->nCol ){
193298    *pnToken = pCsr->aColumnSize[iCol];
193299  }else{
193300    *pnToken = 0;
193301    rc = SQLITE_RANGE;
193302  }
193303  return rc;
193304}
193305
193306/*
193307** Implementation of the xSetAuxdata() method.
193308*/
193309static int fts5ApiSetAuxdata(
193310  Fts5Context *pCtx,              /* Fts5 context */
193311  void *pPtr,                     /* Pointer to save as auxdata */
193312  void(*xDelete)(void*)           /* Destructor for pPtr (or NULL) */
193313){
193314  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193315  Fts5Auxdata *pData;
193316
193317  /* Search through the cursors list of Fts5Auxdata objects for one that
193318  ** corresponds to the currently executing auxiliary function.  */
193319  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
193320    if( pData->pAux==pCsr->pAux ) break;
193321  }
193322
193323  if( pData ){
193324    if( pData->xDelete ){
193325      pData->xDelete(pData->pPtr);
193326    }
193327  }else{
193328    int rc = SQLITE_OK;
193329    pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
193330    if( pData==0 ){
193331      if( xDelete ) xDelete(pPtr);
193332      return rc;
193333    }
193334    pData->pAux = pCsr->pAux;
193335    pData->pNext = pCsr->pAuxdata;
193336    pCsr->pAuxdata = pData;
193337  }
193338
193339  pData->xDelete = xDelete;
193340  pData->pPtr = pPtr;
193341  return SQLITE_OK;
193342}
193343
193344static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
193345  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193346  Fts5Auxdata *pData;
193347  void *pRet = 0;
193348
193349  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
193350    if( pData->pAux==pCsr->pAux ) break;
193351  }
193352
193353  if( pData ){
193354    pRet = pData->pPtr;
193355    if( bClear ){
193356      pData->pPtr = 0;
193357      pData->xDelete = 0;
193358    }
193359  }
193360
193361  return pRet;
193362}
193363
193364static void fts5ApiPhraseNext(
193365  Fts5Context *pUnused,
193366  Fts5PhraseIter *pIter,
193367  int *piCol, int *piOff
193368){
193369  UNUSED_PARAM(pUnused);
193370  if( pIter->a>=pIter->b ){
193371    *piCol = -1;
193372    *piOff = -1;
193373  }else{
193374    int iVal;
193375    pIter->a += fts5GetVarint32(pIter->a, iVal);
193376    if( iVal==1 ){
193377      pIter->a += fts5GetVarint32(pIter->a, iVal);
193378      *piCol = iVal;
193379      *piOff = 0;
193380      pIter->a += fts5GetVarint32(pIter->a, iVal);
193381    }
193382    *piOff += (iVal-2);
193383  }
193384}
193385
193386static int fts5ApiPhraseFirst(
193387  Fts5Context *pCtx,
193388  int iPhrase,
193389  Fts5PhraseIter *pIter,
193390  int *piCol, int *piOff
193391){
193392  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193393  int n;
193394  int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
193395  if( rc==SQLITE_OK ){
193396    pIter->b = &pIter->a[n];
193397    *piCol = 0;
193398    *piOff = 0;
193399    fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
193400  }
193401  return rc;
193402}
193403
193404static void fts5ApiPhraseNextColumn(
193405  Fts5Context *pCtx,
193406  Fts5PhraseIter *pIter,
193407  int *piCol
193408){
193409  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193410  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
193411
193412  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
193413    if( pIter->a>=pIter->b ){
193414      *piCol = -1;
193415    }else{
193416      int iIncr;
193417      pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
193418      *piCol += (iIncr-2);
193419    }
193420  }else{
193421    while( 1 ){
193422      int dummy;
193423      if( pIter->a>=pIter->b ){
193424        *piCol = -1;
193425        return;
193426      }
193427      if( pIter->a[0]==0x01 ) break;
193428      pIter->a += fts5GetVarint32(pIter->a, dummy);
193429    }
193430    pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
193431  }
193432}
193433
193434static int fts5ApiPhraseFirstColumn(
193435  Fts5Context *pCtx,
193436  int iPhrase,
193437  Fts5PhraseIter *pIter,
193438  int *piCol
193439){
193440  int rc = SQLITE_OK;
193441  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193442  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
193443
193444  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
193445    Fts5Sorter *pSorter = pCsr->pSorter;
193446    int n;
193447    if( pSorter ){
193448      int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
193449      n = pSorter->aIdx[iPhrase] - i1;
193450      pIter->a = &pSorter->aPoslist[i1];
193451    }else{
193452      rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
193453    }
193454    if( rc==SQLITE_OK ){
193455      pIter->b = &pIter->a[n];
193456      *piCol = 0;
193457      fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
193458    }
193459  }else{
193460    int n;
193461    rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
193462    if( rc==SQLITE_OK ){
193463      pIter->b = &pIter->a[n];
193464      if( n<=0 ){
193465        *piCol = -1;
193466      }else if( pIter->a[0]==0x01 ){
193467        pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
193468      }else{
193469        *piCol = 0;
193470      }
193471    }
193472  }
193473
193474  return rc;
193475}
193476
193477
193478static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
193479    int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
193480);
193481
193482static const Fts5ExtensionApi sFts5Api = {
193483  2,                            /* iVersion */
193484  fts5ApiUserData,
193485  fts5ApiColumnCount,
193486  fts5ApiRowCount,
193487  fts5ApiColumnTotalSize,
193488  fts5ApiTokenize,
193489  fts5ApiPhraseCount,
193490  fts5ApiPhraseSize,
193491  fts5ApiInstCount,
193492  fts5ApiInst,
193493  fts5ApiRowid,
193494  fts5ApiColumnText,
193495  fts5ApiColumnSize,
193496  fts5ApiQueryPhrase,
193497  fts5ApiSetAuxdata,
193498  fts5ApiGetAuxdata,
193499  fts5ApiPhraseFirst,
193500  fts5ApiPhraseNext,
193501  fts5ApiPhraseFirstColumn,
193502  fts5ApiPhraseNextColumn,
193503};
193504
193505/*
193506** Implementation of API function xQueryPhrase().
193507*/
193508static int fts5ApiQueryPhrase(
193509  Fts5Context *pCtx,
193510  int iPhrase,
193511  void *pUserData,
193512  int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
193513){
193514  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193515  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193516  int rc;
193517  Fts5Cursor *pNew = 0;
193518
193519  rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
193520  if( rc==SQLITE_OK ){
193521    pNew->ePlan = FTS5_PLAN_MATCH;
193522    pNew->iFirstRowid = SMALLEST_INT64;
193523    pNew->iLastRowid = LARGEST_INT64;
193524    pNew->base.pVtab = (sqlite3_vtab*)pTab;
193525    rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
193526  }
193527
193528  if( rc==SQLITE_OK ){
193529    for(rc = fts5CursorFirst(pTab, pNew, 0);
193530        rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
193531        rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
193532    ){
193533      rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
193534      if( rc!=SQLITE_OK ){
193535        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
193536        break;
193537      }
193538    }
193539  }
193540
193541  fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
193542  return rc;
193543}
193544
193545static void fts5ApiInvoke(
193546  Fts5Auxiliary *pAux,
193547  Fts5Cursor *pCsr,
193548  sqlite3_context *context,
193549  int argc,
193550  sqlite3_value **argv
193551){
193552  assert( pCsr->pAux==0 );
193553  pCsr->pAux = pAux;
193554  pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
193555  pCsr->pAux = 0;
193556}
193557
193558static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
193559  Fts5Cursor *pCsr;
193560  for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
193561    if( pCsr->iCsrId==iCsrId ) break;
193562  }
193563  return pCsr;
193564}
193565
193566static void fts5ApiCallback(
193567  sqlite3_context *context,
193568  int argc,
193569  sqlite3_value **argv
193570){
193571
193572  Fts5Auxiliary *pAux;
193573  Fts5Cursor *pCsr;
193574  i64 iCsrId;
193575
193576  assert( argc>=1 );
193577  pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
193578  iCsrId = sqlite3_value_int64(argv[0]);
193579
193580  pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
193581  if( pCsr==0 ){
193582    char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
193583    sqlite3_result_error(context, zErr, -1);
193584    sqlite3_free(zErr);
193585  }else{
193586    fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
193587  }
193588}
193589
193590
193591/*
193592** Given cursor id iId, return a pointer to the corresponding Fts5Index
193593** object. Or NULL If the cursor id does not exist.
193594**
193595** If successful, set *ppConfig to point to the associated config object
193596** before returning.
193597*/
193598static Fts5Index *sqlite3Fts5IndexFromCsrid(
193599  Fts5Global *pGlobal,            /* FTS5 global context for db handle */
193600  i64 iCsrId,                     /* Id of cursor to find */
193601  Fts5Config **ppConfig           /* OUT: Configuration object */
193602){
193603  Fts5Cursor *pCsr;
193604  Fts5Table *pTab;
193605
193606  pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
193607  pTab = (Fts5Table*)pCsr->base.pVtab;
193608  *ppConfig = pTab->pConfig;
193609
193610  return pTab->pIndex;
193611}
193612
193613/*
193614** Return a "position-list blob" corresponding to the current position of
193615** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
193616** the current position-list for each phrase in the query associated with
193617** cursor pCsr.
193618**
193619** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
193620** the number of phrases in the query. Following the varints are the
193621** concatenated position lists for each phrase, in order.
193622**
193623** The first varint (if it exists) contains the size of the position list
193624** for phrase 0. The second (same disclaimer) contains the size of position
193625** list 1. And so on. There is no size field for the final position list,
193626** as it can be derived from the total size of the blob.
193627*/
193628static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
193629  int i;
193630  int rc = SQLITE_OK;
193631  int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
193632  Fts5Buffer val;
193633
193634  memset(&val, 0, sizeof(Fts5Buffer));
193635  switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
193636    case FTS5_DETAIL_FULL:
193637
193638      /* Append the varints */
193639      for(i=0; i<(nPhrase-1); i++){
193640        const u8 *dummy;
193641        int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
193642        sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
193643      }
193644
193645      /* Append the position lists */
193646      for(i=0; i<nPhrase; i++){
193647        const u8 *pPoslist;
193648        int nPoslist;
193649        nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
193650        sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
193651      }
193652      break;
193653
193654    case FTS5_DETAIL_COLUMNS:
193655
193656      /* Append the varints */
193657      for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
193658        const u8 *dummy;
193659        int nByte;
193660        rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
193661        sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
193662      }
193663
193664      /* Append the position lists */
193665      for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
193666        const u8 *pPoslist;
193667        int nPoslist;
193668        rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
193669        sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
193670      }
193671      break;
193672
193673    default:
193674      break;
193675  }
193676
193677  sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
193678  return rc;
193679}
193680
193681/*
193682** This is the xColumn method, called by SQLite to request a value from
193683** the row that the supplied cursor currently points to.
193684*/
193685static int fts5ColumnMethod(
193686  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
193687  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
193688  int iCol                        /* Index of column to read value from */
193689){
193690  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
193691  Fts5Config *pConfig = pTab->pConfig;
193692  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
193693  int rc = SQLITE_OK;
193694
193695  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
193696
193697  if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
193698    if( iCol==pConfig->nCol ){
193699      sqlite3_result_int64(pCtx, pCsr->iSpecial);
193700    }
193701  }else
193702
193703  if( iCol==pConfig->nCol ){
193704    /* User is requesting the value of the special column with the same name
193705    ** as the table. Return the cursor integer id number. This value is only
193706    ** useful in that it may be passed as the first argument to an FTS5
193707    ** auxiliary function.  */
193708    sqlite3_result_int64(pCtx, pCsr->iCsrId);
193709  }else if( iCol==pConfig->nCol+1 ){
193710
193711    /* The value of the "rank" column. */
193712    if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
193713      fts5PoslistBlob(pCtx, pCsr);
193714    }else if(
193715        pCsr->ePlan==FTS5_PLAN_MATCH
193716     || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
193717    ){
193718      if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
193719        fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
193720      }
193721    }
193722  }else if( !fts5IsContentless(pTab) ){
193723    rc = fts5SeekCursor(pCsr, 1);
193724    if( rc==SQLITE_OK ){
193725      sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
193726    }
193727  }
193728  return rc;
193729}
193730
193731
193732/*
193733** This routine implements the xFindFunction method for the FTS3
193734** virtual table.
193735*/
193736static int fts5FindFunctionMethod(
193737  sqlite3_vtab *pVtab,            /* Virtual table handle */
193738  int nUnused,                    /* Number of SQL function arguments */
193739  const char *zName,              /* Name of SQL function */
193740  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
193741  void **ppArg                    /* OUT: User data for *pxFunc */
193742){
193743  Fts5Table *pTab = (Fts5Table*)pVtab;
193744  Fts5Auxiliary *pAux;
193745
193746  UNUSED_PARAM(nUnused);
193747  pAux = fts5FindAuxiliary(pTab, zName);
193748  if( pAux ){
193749    *pxFunc = fts5ApiCallback;
193750    *ppArg = (void*)pAux;
193751    return 1;
193752  }
193753
193754  /* No function of the specified name was found. Return 0. */
193755  return 0;
193756}
193757
193758/*
193759** Implementation of FTS5 xRename method. Rename an fts5 table.
193760*/
193761static int fts5RenameMethod(
193762  sqlite3_vtab *pVtab,            /* Virtual table handle */
193763  const char *zName               /* New name of table */
193764){
193765  Fts5Table *pTab = (Fts5Table*)pVtab;
193766  return sqlite3Fts5StorageRename(pTab->pStorage, zName);
193767}
193768
193769/*
193770** The xSavepoint() method.
193771**
193772** Flush the contents of the pending-terms table to disk.
193773*/
193774static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
193775  Fts5Table *pTab = (Fts5Table*)pVtab;
193776  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
193777  fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
193778  fts5TripCursors(pTab);
193779  return sqlite3Fts5StorageSync(pTab->pStorage, 0);
193780}
193781
193782/*
193783** The xRelease() method.
193784**
193785** This is a no-op.
193786*/
193787static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
193788  Fts5Table *pTab = (Fts5Table*)pVtab;
193789  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
193790  fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
193791  fts5TripCursors(pTab);
193792  return sqlite3Fts5StorageSync(pTab->pStorage, 0);
193793}
193794
193795/*
193796** The xRollbackTo() method.
193797**
193798** Discard the contents of the pending terms table.
193799*/
193800static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
193801  Fts5Table *pTab = (Fts5Table*)pVtab;
193802  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
193803  fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
193804  fts5TripCursors(pTab);
193805  return sqlite3Fts5StorageRollback(pTab->pStorage);
193806}
193807
193808/*
193809** Register a new auxiliary function with global context pGlobal.
193810*/
193811static int fts5CreateAux(
193812  fts5_api *pApi,                 /* Global context (one per db handle) */
193813  const char *zName,              /* Name of new function */
193814  void *pUserData,                /* User data for aux. function */
193815  fts5_extension_function xFunc,  /* Aux. function implementation */
193816  void(*xDestroy)(void*)          /* Destructor for pUserData */
193817){
193818  Fts5Global *pGlobal = (Fts5Global*)pApi;
193819  int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
193820  if( rc==SQLITE_OK ){
193821    Fts5Auxiliary *pAux;
193822    int nName;                      /* Size of zName in bytes, including \0 */
193823    int nByte;                      /* Bytes of space to allocate */
193824
193825    nName = (int)strlen(zName) + 1;
193826    nByte = sizeof(Fts5Auxiliary) + nName;
193827    pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
193828    if( pAux ){
193829      memset(pAux, 0, nByte);
193830      pAux->zFunc = (char*)&pAux[1];
193831      memcpy(pAux->zFunc, zName, nName);
193832      pAux->pGlobal = pGlobal;
193833      pAux->pUserData = pUserData;
193834      pAux->xFunc = xFunc;
193835      pAux->xDestroy = xDestroy;
193836      pAux->pNext = pGlobal->pAux;
193837      pGlobal->pAux = pAux;
193838    }else{
193839      rc = SQLITE_NOMEM;
193840    }
193841  }
193842
193843  return rc;
193844}
193845
193846/*
193847** Register a new tokenizer. This is the implementation of the
193848** fts5_api.xCreateTokenizer() method.
193849*/
193850static int fts5CreateTokenizer(
193851  fts5_api *pApi,                 /* Global context (one per db handle) */
193852  const char *zName,              /* Name of new function */
193853  void *pUserData,                /* User data for aux. function */
193854  fts5_tokenizer *pTokenizer,     /* Tokenizer implementation */
193855  void(*xDestroy)(void*)          /* Destructor for pUserData */
193856){
193857  Fts5Global *pGlobal = (Fts5Global*)pApi;
193858  Fts5TokenizerModule *pNew;
193859  int nName;                      /* Size of zName and its \0 terminator */
193860  int nByte;                      /* Bytes of space to allocate */
193861  int rc = SQLITE_OK;
193862
193863  nName = (int)strlen(zName) + 1;
193864  nByte = sizeof(Fts5TokenizerModule) + nName;
193865  pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
193866  if( pNew ){
193867    memset(pNew, 0, nByte);
193868    pNew->zName = (char*)&pNew[1];
193869    memcpy(pNew->zName, zName, nName);
193870    pNew->pUserData = pUserData;
193871    pNew->x = *pTokenizer;
193872    pNew->xDestroy = xDestroy;
193873    pNew->pNext = pGlobal->pTok;
193874    pGlobal->pTok = pNew;
193875    if( pNew->pNext==0 ){
193876      pGlobal->pDfltTok = pNew;
193877    }
193878  }else{
193879    rc = SQLITE_NOMEM;
193880  }
193881
193882  return rc;
193883}
193884
193885static Fts5TokenizerModule *fts5LocateTokenizer(
193886  Fts5Global *pGlobal,
193887  const char *zName
193888){
193889  Fts5TokenizerModule *pMod = 0;
193890
193891  if( zName==0 ){
193892    pMod = pGlobal->pDfltTok;
193893  }else{
193894    for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
193895      if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
193896    }
193897  }
193898
193899  return pMod;
193900}
193901
193902/*
193903** Find a tokenizer. This is the implementation of the
193904** fts5_api.xFindTokenizer() method.
193905*/
193906static int fts5FindTokenizer(
193907  fts5_api *pApi,                 /* Global context (one per db handle) */
193908  const char *zName,              /* Name of new function */
193909  void **ppUserData,
193910  fts5_tokenizer *pTokenizer      /* Populate this object */
193911){
193912  int rc = SQLITE_OK;
193913  Fts5TokenizerModule *pMod;
193914
193915  pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
193916  if( pMod ){
193917    *pTokenizer = pMod->x;
193918    *ppUserData = pMod->pUserData;
193919  }else{
193920    memset(pTokenizer, 0, sizeof(fts5_tokenizer));
193921    rc = SQLITE_ERROR;
193922  }
193923
193924  return rc;
193925}
193926
193927static int sqlite3Fts5GetTokenizer(
193928  Fts5Global *pGlobal,
193929  const char **azArg,
193930  int nArg,
193931  Fts5Tokenizer **ppTok,
193932  fts5_tokenizer **ppTokApi,
193933  char **pzErr
193934){
193935  Fts5TokenizerModule *pMod;
193936  int rc = SQLITE_OK;
193937
193938  pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
193939  if( pMod==0 ){
193940    assert( nArg>0 );
193941    rc = SQLITE_ERROR;
193942    *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
193943  }else{
193944    rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
193945    *ppTokApi = &pMod->x;
193946    if( rc!=SQLITE_OK && pzErr ){
193947      *pzErr = sqlite3_mprintf("error in tokenizer constructor");
193948    }
193949  }
193950
193951  if( rc!=SQLITE_OK ){
193952    *ppTokApi = 0;
193953    *ppTok = 0;
193954  }
193955
193956  return rc;
193957}
193958
193959static void fts5ModuleDestroy(void *pCtx){
193960  Fts5TokenizerModule *pTok, *pNextTok;
193961  Fts5Auxiliary *pAux, *pNextAux;
193962  Fts5Global *pGlobal = (Fts5Global*)pCtx;
193963
193964  for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
193965    pNextAux = pAux->pNext;
193966    if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
193967    sqlite3_free(pAux);
193968  }
193969
193970  for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
193971    pNextTok = pTok->pNext;
193972    if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
193973    sqlite3_free(pTok);
193974  }
193975
193976  sqlite3_free(pGlobal);
193977}
193978
193979static void fts5Fts5Func(
193980  sqlite3_context *pCtx,          /* Function call context */
193981  int nArg,                       /* Number of args */
193982  sqlite3_value **apUnused        /* Function arguments */
193983){
193984  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
193985  char buf[8];
193986  UNUSED_PARAM2(nArg, apUnused);
193987  assert( nArg==0 );
193988  assert( sizeof(buf)>=sizeof(pGlobal) );
193989  memcpy(buf, (void*)&pGlobal, sizeof(pGlobal));
193990  sqlite3_result_blob(pCtx, buf, sizeof(pGlobal), SQLITE_TRANSIENT);
193991}
193992
193993/*
193994** Implementation of fts5_source_id() function.
193995*/
193996static void fts5SourceIdFunc(
193997  sqlite3_context *pCtx,          /* Function call context */
193998  int nArg,                       /* Number of args */
193999  sqlite3_value **apUnused        /* Function arguments */
194000){
194001  assert( nArg==0 );
194002  UNUSED_PARAM2(nArg, apUnused);
194003  sqlite3_result_text(pCtx, "fts5: 2016-08-08 13:40:27 d5e98057028abcf7217d0d2b2e29bbbcdf09d6de", -1, SQLITE_TRANSIENT);
194004}
194005
194006static int fts5Init(sqlite3 *db){
194007  static const sqlite3_module fts5Mod = {
194008    /* iVersion      */ 2,
194009    /* xCreate       */ fts5CreateMethod,
194010    /* xConnect      */ fts5ConnectMethod,
194011    /* xBestIndex    */ fts5BestIndexMethod,
194012    /* xDisconnect   */ fts5DisconnectMethod,
194013    /* xDestroy      */ fts5DestroyMethod,
194014    /* xOpen         */ fts5OpenMethod,
194015    /* xClose        */ fts5CloseMethod,
194016    /* xFilter       */ fts5FilterMethod,
194017    /* xNext         */ fts5NextMethod,
194018    /* xEof          */ fts5EofMethod,
194019    /* xColumn       */ fts5ColumnMethod,
194020    /* xRowid        */ fts5RowidMethod,
194021    /* xUpdate       */ fts5UpdateMethod,
194022    /* xBegin        */ fts5BeginMethod,
194023    /* xSync         */ fts5SyncMethod,
194024    /* xCommit       */ fts5CommitMethod,
194025    /* xRollback     */ fts5RollbackMethod,
194026    /* xFindFunction */ fts5FindFunctionMethod,
194027    /* xRename       */ fts5RenameMethod,
194028    /* xSavepoint    */ fts5SavepointMethod,
194029    /* xRelease      */ fts5ReleaseMethod,
194030    /* xRollbackTo   */ fts5RollbackToMethod,
194031  };
194032
194033  int rc;
194034  Fts5Global *pGlobal = 0;
194035
194036  pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
194037  if( pGlobal==0 ){
194038    rc = SQLITE_NOMEM;
194039  }else{
194040    void *p = (void*)pGlobal;
194041    memset(pGlobal, 0, sizeof(Fts5Global));
194042    pGlobal->db = db;
194043    pGlobal->api.iVersion = 2;
194044    pGlobal->api.xCreateFunction = fts5CreateAux;
194045    pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
194046    pGlobal->api.xFindTokenizer = fts5FindTokenizer;
194047    rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
194048    if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
194049    if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
194050    if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
194051    if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
194052    if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
194053    if( rc==SQLITE_OK ){
194054      rc = sqlite3_create_function(
194055          db, "fts5", 0, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
194056      );
194057    }
194058    if( rc==SQLITE_OK ){
194059      rc = sqlite3_create_function(
194060          db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
194061      );
194062    }
194063  }
194064
194065  /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
194066  ** fts5_test_mi.c is compiled and linked into the executable. And call
194067  ** its entry point to enable the matchinfo() demo.  */
194068#ifdef SQLITE_FTS5_ENABLE_TEST_MI
194069  if( rc==SQLITE_OK ){
194070    extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
194071    rc = sqlite3Fts5TestRegisterMatchinfo(db);
194072  }
194073#endif
194074
194075  return rc;
194076}
194077
194078/*
194079** The following functions are used to register the module with SQLite. If
194080** this module is being built as part of the SQLite core (SQLITE_CORE is
194081** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
194082**
194083** Or, if this module is being built as a loadable extension,
194084** sqlite3Fts5Init() is omitted and the two standard entry points
194085** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
194086*/
194087#ifndef SQLITE_CORE
194088#ifdef _WIN32
194089__declspec(dllexport)
194090#endif
194091SQLITE_API int SQLITE_STDCALL sqlite3_fts_init(
194092  sqlite3 *db,
194093  char **pzErrMsg,
194094  const sqlite3_api_routines *pApi
194095){
194096  SQLITE_EXTENSION_INIT2(pApi);
194097  (void)pzErrMsg;  /* Unused parameter */
194098  return fts5Init(db);
194099}
194100
194101#ifdef _WIN32
194102__declspec(dllexport)
194103#endif
194104SQLITE_API int SQLITE_STDCALL sqlite3_fts5_init(
194105  sqlite3 *db,
194106  char **pzErrMsg,
194107  const sqlite3_api_routines *pApi
194108){
194109  SQLITE_EXTENSION_INIT2(pApi);
194110  (void)pzErrMsg;  /* Unused parameter */
194111  return fts5Init(db);
194112}
194113#else
194114SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
194115  return fts5Init(db);
194116}
194117#endif
194118
194119/*
194120** 2014 May 31
194121**
194122** The author disclaims copyright to this source code.  In place of
194123** a legal notice, here is a blessing:
194124**
194125**    May you do good and not evil.
194126**    May you find forgiveness for yourself and forgive others.
194127**    May you share freely, never taking more than you give.
194128**
194129******************************************************************************
194130**
194131*/
194132
194133
194134
194135/* #include "fts5Int.h" */
194136
194137struct Fts5Storage {
194138  Fts5Config *pConfig;
194139  Fts5Index *pIndex;
194140  int bTotalsValid;               /* True if nTotalRow/aTotalSize[] are valid */
194141  i64 nTotalRow;                  /* Total number of rows in FTS table */
194142  i64 *aTotalSize;                /* Total sizes of each column */
194143  sqlite3_stmt *aStmt[11];
194144};
194145
194146
194147#if FTS5_STMT_SCAN_ASC!=0
194148# error "FTS5_STMT_SCAN_ASC mismatch"
194149#endif
194150#if FTS5_STMT_SCAN_DESC!=1
194151# error "FTS5_STMT_SCAN_DESC mismatch"
194152#endif
194153#if FTS5_STMT_LOOKUP!=2
194154# error "FTS5_STMT_LOOKUP mismatch"
194155#endif
194156
194157#define FTS5_STMT_INSERT_CONTENT  3
194158#define FTS5_STMT_REPLACE_CONTENT 4
194159#define FTS5_STMT_DELETE_CONTENT  5
194160#define FTS5_STMT_REPLACE_DOCSIZE  6
194161#define FTS5_STMT_DELETE_DOCSIZE  7
194162#define FTS5_STMT_LOOKUP_DOCSIZE  8
194163#define FTS5_STMT_REPLACE_CONFIG 9
194164#define FTS5_STMT_SCAN 10
194165
194166/*
194167** Prepare the two insert statements - Fts5Storage.pInsertContent and
194168** Fts5Storage.pInsertDocsize - if they have not already been prepared.
194169** Return SQLITE_OK if successful, or an SQLite error code if an error
194170** occurs.
194171*/
194172static int fts5StorageGetStmt(
194173  Fts5Storage *p,                 /* Storage handle */
194174  int eStmt,                      /* FTS5_STMT_XXX constant */
194175  sqlite3_stmt **ppStmt,          /* OUT: Prepared statement handle */
194176  char **pzErrMsg                 /* OUT: Error message (if any) */
194177){
194178  int rc = SQLITE_OK;
194179
194180  /* If there is no %_docsize table, there should be no requests for
194181  ** statements to operate on it.  */
194182  assert( p->pConfig->bColumnsize || (
194183        eStmt!=FTS5_STMT_REPLACE_DOCSIZE
194184     && eStmt!=FTS5_STMT_DELETE_DOCSIZE
194185     && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
194186  ));
194187
194188  assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
194189  if( p->aStmt[eStmt]==0 ){
194190    const char *azStmt[] = {
194191      "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
194192      "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
194193      "SELECT %s FROM %s T WHERE T.%Q=?",               /* LOOKUP  */
194194
194195      "INSERT INTO %Q.'%q_content' VALUES(%s)",         /* INSERT_CONTENT  */
194196      "REPLACE INTO %Q.'%q_content' VALUES(%s)",        /* REPLACE_CONTENT */
194197      "DELETE FROM %Q.'%q_content' WHERE id=?",         /* DELETE_CONTENT  */
194198      "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",       /* REPLACE_DOCSIZE  */
194199      "DELETE FROM %Q.'%q_docsize' WHERE id=?",         /* DELETE_DOCSIZE  */
194200
194201      "SELECT sz FROM %Q.'%q_docsize' WHERE id=?",      /* LOOKUP_DOCSIZE  */
194202
194203      "REPLACE INTO %Q.'%q_config' VALUES(?,?)",        /* REPLACE_CONFIG */
194204      "SELECT %s FROM %s AS T",                         /* SCAN */
194205    };
194206    Fts5Config *pC = p->pConfig;
194207    char *zSql = 0;
194208
194209    switch( eStmt ){
194210      case FTS5_STMT_SCAN:
194211        zSql = sqlite3_mprintf(azStmt[eStmt],
194212            pC->zContentExprlist, pC->zContent
194213        );
194214        break;
194215
194216      case FTS5_STMT_SCAN_ASC:
194217      case FTS5_STMT_SCAN_DESC:
194218        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
194219            pC->zContent, pC->zContentRowid, pC->zContentRowid,
194220            pC->zContentRowid
194221        );
194222        break;
194223
194224      case FTS5_STMT_LOOKUP:
194225        zSql = sqlite3_mprintf(azStmt[eStmt],
194226            pC->zContentExprlist, pC->zContent, pC->zContentRowid
194227        );
194228        break;
194229
194230      case FTS5_STMT_INSERT_CONTENT:
194231      case FTS5_STMT_REPLACE_CONTENT: {
194232        int nCol = pC->nCol + 1;
194233        char *zBind;
194234        int i;
194235
194236        zBind = sqlite3_malloc(1 + nCol*2);
194237        if( zBind ){
194238          for(i=0; i<nCol; i++){
194239            zBind[i*2] = '?';
194240            zBind[i*2 + 1] = ',';
194241          }
194242          zBind[i*2-1] = '\0';
194243          zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
194244          sqlite3_free(zBind);
194245        }
194246        break;
194247      }
194248
194249      default:
194250        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
194251        break;
194252    }
194253
194254    if( zSql==0 ){
194255      rc = SQLITE_NOMEM;
194256    }else{
194257      rc = sqlite3_prepare_v2(pC->db, zSql, -1, &p->aStmt[eStmt], 0);
194258      sqlite3_free(zSql);
194259      if( rc!=SQLITE_OK && pzErrMsg ){
194260        *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
194261      }
194262    }
194263  }
194264
194265  *ppStmt = p->aStmt[eStmt];
194266  sqlite3_reset(*ppStmt);
194267  return rc;
194268}
194269
194270
194271static int fts5ExecPrintf(
194272  sqlite3 *db,
194273  char **pzErr,
194274  const char *zFormat,
194275  ...
194276){
194277  int rc;
194278  va_list ap;                     /* ... printf arguments */
194279  char *zSql;
194280
194281  va_start(ap, zFormat);
194282  zSql = sqlite3_vmprintf(zFormat, ap);
194283
194284  if( zSql==0 ){
194285    rc = SQLITE_NOMEM;
194286  }else{
194287    rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
194288    sqlite3_free(zSql);
194289  }
194290
194291  va_end(ap);
194292  return rc;
194293}
194294
194295/*
194296** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
194297** code otherwise.
194298*/
194299static int sqlite3Fts5DropAll(Fts5Config *pConfig){
194300  int rc = fts5ExecPrintf(pConfig->db, 0,
194301      "DROP TABLE IF EXISTS %Q.'%q_data';"
194302      "DROP TABLE IF EXISTS %Q.'%q_idx';"
194303      "DROP TABLE IF EXISTS %Q.'%q_config';",
194304      pConfig->zDb, pConfig->zName,
194305      pConfig->zDb, pConfig->zName,
194306      pConfig->zDb, pConfig->zName
194307  );
194308  if( rc==SQLITE_OK && pConfig->bColumnsize ){
194309    rc = fts5ExecPrintf(pConfig->db, 0,
194310        "DROP TABLE IF EXISTS %Q.'%q_docsize';",
194311        pConfig->zDb, pConfig->zName
194312    );
194313  }
194314  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
194315    rc = fts5ExecPrintf(pConfig->db, 0,
194316        "DROP TABLE IF EXISTS %Q.'%q_content';",
194317        pConfig->zDb, pConfig->zName
194318    );
194319  }
194320  return rc;
194321}
194322
194323static void fts5StorageRenameOne(
194324  Fts5Config *pConfig,            /* Current FTS5 configuration */
194325  int *pRc,                       /* IN/OUT: Error code */
194326  const char *zTail,              /* Tail of table name e.g. "data", "config" */
194327  const char *zName               /* New name of FTS5 table */
194328){
194329  if( *pRc==SQLITE_OK ){
194330    *pRc = fts5ExecPrintf(pConfig->db, 0,
194331        "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
194332        pConfig->zDb, pConfig->zName, zTail, zName, zTail
194333    );
194334  }
194335}
194336
194337static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
194338  Fts5Config *pConfig = pStorage->pConfig;
194339  int rc = sqlite3Fts5StorageSync(pStorage, 1);
194340
194341  fts5StorageRenameOne(pConfig, &rc, "data", zName);
194342  fts5StorageRenameOne(pConfig, &rc, "idx", zName);
194343  fts5StorageRenameOne(pConfig, &rc, "config", zName);
194344  if( pConfig->bColumnsize ){
194345    fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
194346  }
194347  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
194348    fts5StorageRenameOne(pConfig, &rc, "content", zName);
194349  }
194350  return rc;
194351}
194352
194353/*
194354** Create the shadow table named zPost, with definition zDefn. Return
194355** SQLITE_OK if successful, or an SQLite error code otherwise.
194356*/
194357static int sqlite3Fts5CreateTable(
194358  Fts5Config *pConfig,            /* FTS5 configuration */
194359  const char *zPost,              /* Shadow table to create (e.g. "content") */
194360  const char *zDefn,              /* Columns etc. for shadow table */
194361  int bWithout,                   /* True for without rowid */
194362  char **pzErr                    /* OUT: Error message */
194363){
194364  int rc;
194365  char *zErr = 0;
194366
194367  rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
194368      pConfig->zDb, pConfig->zName, zPost, zDefn,
194369#ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
194370      bWithout?" WITHOUT ROWID":
194371#endif
194372      ""
194373  );
194374  if( zErr ){
194375    *pzErr = sqlite3_mprintf(
194376        "fts5: error creating shadow table %q_%s: %s",
194377        pConfig->zName, zPost, zErr
194378    );
194379    sqlite3_free(zErr);
194380  }
194381
194382  return rc;
194383}
194384
194385/*
194386** Open a new Fts5Index handle. If the bCreate argument is true, create
194387** and initialize the underlying tables
194388**
194389** If successful, set *pp to point to the new object and return SQLITE_OK.
194390** Otherwise, set *pp to NULL and return an SQLite error code.
194391*/
194392static int sqlite3Fts5StorageOpen(
194393  Fts5Config *pConfig,
194394  Fts5Index *pIndex,
194395  int bCreate,
194396  Fts5Storage **pp,
194397  char **pzErr                    /* OUT: Error message */
194398){
194399  int rc = SQLITE_OK;
194400  Fts5Storage *p;                 /* New object */
194401  int nByte;                      /* Bytes of space to allocate */
194402
194403  nByte = sizeof(Fts5Storage)               /* Fts5Storage object */
194404        + pConfig->nCol * sizeof(i64);      /* Fts5Storage.aTotalSize[] */
194405  *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
194406  if( !p ) return SQLITE_NOMEM;
194407
194408  memset(p, 0, nByte);
194409  p->aTotalSize = (i64*)&p[1];
194410  p->pConfig = pConfig;
194411  p->pIndex = pIndex;
194412
194413  if( bCreate ){
194414    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
194415      int nDefn = 32 + pConfig->nCol*10;
194416      char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
194417      if( zDefn==0 ){
194418        rc = SQLITE_NOMEM;
194419      }else{
194420        int i;
194421        int iOff;
194422        sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
194423        iOff = (int)strlen(zDefn);
194424        for(i=0; i<pConfig->nCol; i++){
194425          sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
194426          iOff += (int)strlen(&zDefn[iOff]);
194427        }
194428        rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
194429      }
194430      sqlite3_free(zDefn);
194431    }
194432
194433    if( rc==SQLITE_OK && pConfig->bColumnsize ){
194434      rc = sqlite3Fts5CreateTable(
194435          pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
194436      );
194437    }
194438    if( rc==SQLITE_OK ){
194439      rc = sqlite3Fts5CreateTable(
194440          pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
194441      );
194442    }
194443    if( rc==SQLITE_OK ){
194444      rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
194445    }
194446  }
194447
194448  if( rc ){
194449    sqlite3Fts5StorageClose(p);
194450    *pp = 0;
194451  }
194452  return rc;
194453}
194454
194455/*
194456** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
194457*/
194458static int sqlite3Fts5StorageClose(Fts5Storage *p){
194459  int rc = SQLITE_OK;
194460  if( p ){
194461    int i;
194462
194463    /* Finalize all SQL statements */
194464    for(i=0; i<ArraySize(p->aStmt); i++){
194465      sqlite3_finalize(p->aStmt[i]);
194466    }
194467
194468    sqlite3_free(p);
194469  }
194470  return rc;
194471}
194472
194473typedef struct Fts5InsertCtx Fts5InsertCtx;
194474struct Fts5InsertCtx {
194475  Fts5Storage *pStorage;
194476  int iCol;
194477  int szCol;                      /* Size of column value in tokens */
194478};
194479
194480/*
194481** Tokenization callback used when inserting tokens into the FTS index.
194482*/
194483static int fts5StorageInsertCallback(
194484  void *pContext,                 /* Pointer to Fts5InsertCtx object */
194485  int tflags,
194486  const char *pToken,             /* Buffer containing token */
194487  int nToken,                     /* Size of token in bytes */
194488  int iUnused1,                   /* Start offset of token */
194489  int iUnused2                    /* End offset of token */
194490){
194491  Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
194492  Fts5Index *pIdx = pCtx->pStorage->pIndex;
194493  UNUSED_PARAM2(iUnused1, iUnused2);
194494  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
194495  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
194496    pCtx->szCol++;
194497  }
194498  return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
194499}
194500
194501/*
194502** If a row with rowid iDel is present in the %_content table, add the
194503** delete-markers to the FTS index necessary to delete it. Do not actually
194504** remove the %_content row at this time though.
194505*/
194506static int fts5StorageDeleteFromIndex(
194507  Fts5Storage *p,
194508  i64 iDel,
194509  sqlite3_value **apVal
194510){
194511  Fts5Config *pConfig = p->pConfig;
194512  sqlite3_stmt *pSeek = 0;        /* SELECT to read row iDel from %_data */
194513  int rc;                         /* Return code */
194514  int rc2;                        /* sqlite3_reset() return code */
194515  int iCol;
194516  Fts5InsertCtx ctx;
194517
194518  if( apVal==0 ){
194519    rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
194520    if( rc!=SQLITE_OK ) return rc;
194521    sqlite3_bind_int64(pSeek, 1, iDel);
194522    if( sqlite3_step(pSeek)!=SQLITE_ROW ){
194523      return sqlite3_reset(pSeek);
194524    }
194525  }
194526
194527  ctx.pStorage = p;
194528  ctx.iCol = -1;
194529  rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
194530  for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
194531    if( pConfig->abUnindexed[iCol-1]==0 ){
194532      const char *zText;
194533      int nText;
194534      if( pSeek ){
194535        zText = (const char*)sqlite3_column_text(pSeek, iCol);
194536        nText = sqlite3_column_bytes(pSeek, iCol);
194537      }else{
194538        zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
194539        nText = sqlite3_value_bytes(apVal[iCol-1]);
194540      }
194541      ctx.szCol = 0;
194542      rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
194543          zText, nText, (void*)&ctx, fts5StorageInsertCallback
194544      );
194545      p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
194546    }
194547  }
194548  p->nTotalRow--;
194549
194550  rc2 = sqlite3_reset(pSeek);
194551  if( rc==SQLITE_OK ) rc = rc2;
194552  return rc;
194553}
194554
194555
194556/*
194557** Insert a record into the %_docsize table. Specifically, do:
194558**
194559**   INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
194560**
194561** If there is no %_docsize table (as happens if the columnsize=0 option
194562** is specified when the FTS5 table is created), this function is a no-op.
194563*/
194564static int fts5StorageInsertDocsize(
194565  Fts5Storage *p,                 /* Storage module to write to */
194566  i64 iRowid,                     /* id value */
194567  Fts5Buffer *pBuf                /* sz value */
194568){
194569  int rc = SQLITE_OK;
194570  if( p->pConfig->bColumnsize ){
194571    sqlite3_stmt *pReplace = 0;
194572    rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
194573    if( rc==SQLITE_OK ){
194574      sqlite3_bind_int64(pReplace, 1, iRowid);
194575      sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
194576      sqlite3_step(pReplace);
194577      rc = sqlite3_reset(pReplace);
194578    }
194579  }
194580  return rc;
194581}
194582
194583/*
194584** Load the contents of the "averages" record from disk into the
194585** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
194586** argument bCache is true, set the p->bTotalsValid flag to indicate
194587** that the contents of aTotalSize[] and nTotalRow are valid until
194588** further notice.
194589**
194590** Return SQLITE_OK if successful, or an SQLite error code if an error
194591** occurs.
194592*/
194593static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
194594  int rc = SQLITE_OK;
194595  if( p->bTotalsValid==0 ){
194596    rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
194597    p->bTotalsValid = bCache;
194598  }
194599  return rc;
194600}
194601
194602/*
194603** Store the current contents of the p->nTotalRow and p->aTotalSize[]
194604** variables in the "averages" record on disk.
194605**
194606** Return SQLITE_OK if successful, or an SQLite error code if an error
194607** occurs.
194608*/
194609static int fts5StorageSaveTotals(Fts5Storage *p){
194610  int nCol = p->pConfig->nCol;
194611  int i;
194612  Fts5Buffer buf;
194613  int rc = SQLITE_OK;
194614  memset(&buf, 0, sizeof(buf));
194615
194616  sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
194617  for(i=0; i<nCol; i++){
194618    sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
194619  }
194620  if( rc==SQLITE_OK ){
194621    rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
194622  }
194623  sqlite3_free(buf.p);
194624
194625  return rc;
194626}
194627
194628/*
194629** Remove a row from the FTS table.
194630*/
194631static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
194632  Fts5Config *pConfig = p->pConfig;
194633  int rc;
194634  sqlite3_stmt *pDel = 0;
194635
194636  assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
194637  rc = fts5StorageLoadTotals(p, 1);
194638
194639  /* Delete the index records */
194640  if( rc==SQLITE_OK ){
194641    rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
194642  }
194643
194644  /* Delete the %_docsize record */
194645  if( rc==SQLITE_OK && pConfig->bColumnsize ){
194646    rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
194647    if( rc==SQLITE_OK ){
194648      sqlite3_bind_int64(pDel, 1, iDel);
194649      sqlite3_step(pDel);
194650      rc = sqlite3_reset(pDel);
194651    }
194652  }
194653
194654  /* Delete the %_content record */
194655  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
194656    if( rc==SQLITE_OK ){
194657      rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
194658    }
194659    if( rc==SQLITE_OK ){
194660      sqlite3_bind_int64(pDel, 1, iDel);
194661      sqlite3_step(pDel);
194662      rc = sqlite3_reset(pDel);
194663    }
194664  }
194665
194666  /* Write the averages record */
194667  if( rc==SQLITE_OK ){
194668    rc = fts5StorageSaveTotals(p);
194669  }
194670
194671  return rc;
194672}
194673
194674/*
194675** Delete all entries in the FTS5 index.
194676*/
194677static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
194678  Fts5Config *pConfig = p->pConfig;
194679  int rc;
194680
194681  /* Delete the contents of the %_data and %_docsize tables. */
194682  rc = fts5ExecPrintf(pConfig->db, 0,
194683      "DELETE FROM %Q.'%q_data';"
194684      "DELETE FROM %Q.'%q_idx';",
194685      pConfig->zDb, pConfig->zName,
194686      pConfig->zDb, pConfig->zName
194687  );
194688  if( rc==SQLITE_OK && pConfig->bColumnsize ){
194689    rc = fts5ExecPrintf(pConfig->db, 0,
194690        "DELETE FROM %Q.'%q_docsize';",
194691        pConfig->zDb, pConfig->zName
194692    );
194693  }
194694
194695  /* Reinitialize the %_data table. This call creates the initial structure
194696  ** and averages records.  */
194697  if( rc==SQLITE_OK ){
194698    rc = sqlite3Fts5IndexReinit(p->pIndex);
194699  }
194700  if( rc==SQLITE_OK ){
194701    rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
194702  }
194703  return rc;
194704}
194705
194706static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
194707  Fts5Buffer buf = {0,0,0};
194708  Fts5Config *pConfig = p->pConfig;
194709  sqlite3_stmt *pScan = 0;
194710  Fts5InsertCtx ctx;
194711  int rc;
194712
194713  memset(&ctx, 0, sizeof(Fts5InsertCtx));
194714  ctx.pStorage = p;
194715  rc = sqlite3Fts5StorageDeleteAll(p);
194716  if( rc==SQLITE_OK ){
194717    rc = fts5StorageLoadTotals(p, 1);
194718  }
194719
194720  if( rc==SQLITE_OK ){
194721    rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
194722  }
194723
194724  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
194725    i64 iRowid = sqlite3_column_int64(pScan, 0);
194726
194727    sqlite3Fts5BufferZero(&buf);
194728    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
194729    for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
194730      ctx.szCol = 0;
194731      if( pConfig->abUnindexed[ctx.iCol]==0 ){
194732        rc = sqlite3Fts5Tokenize(pConfig,
194733            FTS5_TOKENIZE_DOCUMENT,
194734            (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
194735            sqlite3_column_bytes(pScan, ctx.iCol+1),
194736            (void*)&ctx,
194737            fts5StorageInsertCallback
194738        );
194739      }
194740      sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
194741      p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
194742    }
194743    p->nTotalRow++;
194744
194745    if( rc==SQLITE_OK ){
194746      rc = fts5StorageInsertDocsize(p, iRowid, &buf);
194747    }
194748  }
194749  sqlite3_free(buf.p);
194750
194751  /* Write the averages record */
194752  if( rc==SQLITE_OK ){
194753    rc = fts5StorageSaveTotals(p);
194754  }
194755  return rc;
194756}
194757
194758static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
194759  return sqlite3Fts5IndexOptimize(p->pIndex);
194760}
194761
194762static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
194763  return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
194764}
194765
194766static int sqlite3Fts5StorageReset(Fts5Storage *p){
194767  return sqlite3Fts5IndexReset(p->pIndex);
194768}
194769
194770/*
194771** Allocate a new rowid. This is used for "external content" tables when
194772** a NULL value is inserted into the rowid column. The new rowid is allocated
194773** by inserting a dummy row into the %_docsize table. The dummy will be
194774** overwritten later.
194775**
194776** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
194777** this case the user is required to provide a rowid explicitly.
194778*/
194779static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
194780  int rc = SQLITE_MISMATCH;
194781  if( p->pConfig->bColumnsize ){
194782    sqlite3_stmt *pReplace = 0;
194783    rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
194784    if( rc==SQLITE_OK ){
194785      sqlite3_bind_null(pReplace, 1);
194786      sqlite3_bind_null(pReplace, 2);
194787      sqlite3_step(pReplace);
194788      rc = sqlite3_reset(pReplace);
194789    }
194790    if( rc==SQLITE_OK ){
194791      *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
194792    }
194793  }
194794  return rc;
194795}
194796
194797/*
194798** Insert a new row into the FTS content table.
194799*/
194800static int sqlite3Fts5StorageContentInsert(
194801  Fts5Storage *p,
194802  sqlite3_value **apVal,
194803  i64 *piRowid
194804){
194805  Fts5Config *pConfig = p->pConfig;
194806  int rc = SQLITE_OK;
194807
194808  /* Insert the new row into the %_content table. */
194809  if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
194810    if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
194811      *piRowid = sqlite3_value_int64(apVal[1]);
194812    }else{
194813      rc = fts5StorageNewRowid(p, piRowid);
194814    }
194815  }else{
194816    sqlite3_stmt *pInsert = 0;    /* Statement to write %_content table */
194817    int i;                        /* Counter variable */
194818    rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
194819    for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
194820      rc = sqlite3_bind_value(pInsert, i, apVal[i]);
194821    }
194822    if( rc==SQLITE_OK ){
194823      sqlite3_step(pInsert);
194824      rc = sqlite3_reset(pInsert);
194825    }
194826    *piRowid = sqlite3_last_insert_rowid(pConfig->db);
194827  }
194828
194829  return rc;
194830}
194831
194832/*
194833** Insert new entries into the FTS index and %_docsize table.
194834*/
194835static int sqlite3Fts5StorageIndexInsert(
194836  Fts5Storage *p,
194837  sqlite3_value **apVal,
194838  i64 iRowid
194839){
194840  Fts5Config *pConfig = p->pConfig;
194841  int rc = SQLITE_OK;             /* Return code */
194842  Fts5InsertCtx ctx;              /* Tokenization callback context object */
194843  Fts5Buffer buf;                 /* Buffer used to build up %_docsize blob */
194844
194845  memset(&buf, 0, sizeof(Fts5Buffer));
194846  ctx.pStorage = p;
194847  rc = fts5StorageLoadTotals(p, 1);
194848
194849  if( rc==SQLITE_OK ){
194850    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
194851  }
194852  for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
194853    ctx.szCol = 0;
194854    if( pConfig->abUnindexed[ctx.iCol]==0 ){
194855      rc = sqlite3Fts5Tokenize(pConfig,
194856          FTS5_TOKENIZE_DOCUMENT,
194857          (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
194858          sqlite3_value_bytes(apVal[ctx.iCol+2]),
194859          (void*)&ctx,
194860          fts5StorageInsertCallback
194861      );
194862    }
194863    sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
194864    p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
194865  }
194866  p->nTotalRow++;
194867
194868  /* Write the %_docsize record */
194869  if( rc==SQLITE_OK ){
194870    rc = fts5StorageInsertDocsize(p, iRowid, &buf);
194871  }
194872  sqlite3_free(buf.p);
194873
194874  /* Write the averages record */
194875  if( rc==SQLITE_OK ){
194876    rc = fts5StorageSaveTotals(p);
194877  }
194878
194879  return rc;
194880}
194881
194882static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
194883  Fts5Config *pConfig = p->pConfig;
194884  char *zSql;
194885  int rc;
194886
194887  zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
194888      pConfig->zDb, pConfig->zName, zSuffix
194889  );
194890  if( zSql==0 ){
194891    rc = SQLITE_NOMEM;
194892  }else{
194893    sqlite3_stmt *pCnt = 0;
194894    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
194895    if( rc==SQLITE_OK ){
194896      if( SQLITE_ROW==sqlite3_step(pCnt) ){
194897        *pnRow = sqlite3_column_int64(pCnt, 0);
194898      }
194899      rc = sqlite3_finalize(pCnt);
194900    }
194901  }
194902
194903  sqlite3_free(zSql);
194904  return rc;
194905}
194906
194907/*
194908** Context object used by sqlite3Fts5StorageIntegrity().
194909*/
194910typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
194911struct Fts5IntegrityCtx {
194912  i64 iRowid;
194913  int iCol;
194914  int szCol;
194915  u64 cksum;
194916  Fts5Termset *pTermset;
194917  Fts5Config *pConfig;
194918};
194919
194920
194921/*
194922** Tokenization callback used by integrity check.
194923*/
194924static int fts5StorageIntegrityCallback(
194925  void *pContext,                 /* Pointer to Fts5IntegrityCtx object */
194926  int tflags,
194927  const char *pToken,             /* Buffer containing token */
194928  int nToken,                     /* Size of token in bytes */
194929  int iUnused1,                   /* Start offset of token */
194930  int iUnused2                    /* End offset of token */
194931){
194932  Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
194933  Fts5Termset *pTermset = pCtx->pTermset;
194934  int bPresent;
194935  int ii;
194936  int rc = SQLITE_OK;
194937  int iPos;
194938  int iCol;
194939
194940  UNUSED_PARAM2(iUnused1, iUnused2);
194941  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
194942
194943  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
194944    pCtx->szCol++;
194945  }
194946
194947  switch( pCtx->pConfig->eDetail ){
194948    case FTS5_DETAIL_FULL:
194949      iPos = pCtx->szCol-1;
194950      iCol = pCtx->iCol;
194951      break;
194952
194953    case FTS5_DETAIL_COLUMNS:
194954      iPos = pCtx->iCol;
194955      iCol = 0;
194956      break;
194957
194958    default:
194959      assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
194960      iPos = 0;
194961      iCol = 0;
194962      break;
194963  }
194964
194965  rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
194966  if( rc==SQLITE_OK && bPresent==0 ){
194967    pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
194968        pCtx->iRowid, iCol, iPos, 0, pToken, nToken
194969    );
194970  }
194971
194972  for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
194973    const int nChar = pCtx->pConfig->aPrefix[ii];
194974    int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
194975    if( nByte ){
194976      rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
194977      if( bPresent==0 ){
194978        pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
194979            pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
194980        );
194981      }
194982    }
194983  }
194984
194985  return rc;
194986}
194987
194988/*
194989** Check that the contents of the FTS index match that of the %_content
194990** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
194991** some other SQLite error code if an error occurs while attempting to
194992** determine this.
194993*/
194994static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
194995  Fts5Config *pConfig = p->pConfig;
194996  int rc;                         /* Return code */
194997  int *aColSize;                  /* Array of size pConfig->nCol */
194998  i64 *aTotalSize;                /* Array of size pConfig->nCol */
194999  Fts5IntegrityCtx ctx;
195000  sqlite3_stmt *pScan;
195001
195002  memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
195003  ctx.pConfig = p->pConfig;
195004  aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
195005  if( !aTotalSize ) return SQLITE_NOMEM;
195006  aColSize = (int*)&aTotalSize[pConfig->nCol];
195007  memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
195008
195009  /* Generate the expected index checksum based on the contents of the
195010  ** %_content table. This block stores the checksum in ctx.cksum. */
195011  rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
195012  if( rc==SQLITE_OK ){
195013    int rc2;
195014    while( SQLITE_ROW==sqlite3_step(pScan) ){
195015      int i;
195016      ctx.iRowid = sqlite3_column_int64(pScan, 0);
195017      ctx.szCol = 0;
195018      if( pConfig->bColumnsize ){
195019        rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
195020      }
195021      if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
195022        rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
195023      }
195024      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
195025        if( pConfig->abUnindexed[i] ) continue;
195026        ctx.iCol = i;
195027        ctx.szCol = 0;
195028        if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
195029          rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
195030        }
195031        if( rc==SQLITE_OK ){
195032          rc = sqlite3Fts5Tokenize(pConfig,
195033              FTS5_TOKENIZE_DOCUMENT,
195034              (const char*)sqlite3_column_text(pScan, i+1),
195035              sqlite3_column_bytes(pScan, i+1),
195036              (void*)&ctx,
195037              fts5StorageIntegrityCallback
195038          );
195039        }
195040        if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
195041          rc = FTS5_CORRUPT;
195042        }
195043        aTotalSize[i] += ctx.szCol;
195044        if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
195045          sqlite3Fts5TermsetFree(ctx.pTermset);
195046          ctx.pTermset = 0;
195047        }
195048      }
195049      sqlite3Fts5TermsetFree(ctx.pTermset);
195050      ctx.pTermset = 0;
195051
195052      if( rc!=SQLITE_OK ) break;
195053    }
195054    rc2 = sqlite3_reset(pScan);
195055    if( rc==SQLITE_OK ) rc = rc2;
195056  }
195057
195058  /* Test that the "totals" (sometimes called "averages") record looks Ok */
195059  if( rc==SQLITE_OK ){
195060    int i;
195061    rc = fts5StorageLoadTotals(p, 0);
195062    for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
195063      if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
195064    }
195065  }
195066
195067  /* Check that the %_docsize and %_content tables contain the expected
195068  ** number of rows.  */
195069  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
195070    i64 nRow = 0;
195071    rc = fts5StorageCount(p, "content", &nRow);
195072    if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
195073  }
195074  if( rc==SQLITE_OK && pConfig->bColumnsize ){
195075    i64 nRow = 0;
195076    rc = fts5StorageCount(p, "docsize", &nRow);
195077    if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
195078  }
195079
195080  /* Pass the expected checksum down to the FTS index module. It will
195081  ** verify, amongst other things, that it matches the checksum generated by
195082  ** inspecting the index itself.  */
195083  if( rc==SQLITE_OK ){
195084    rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
195085  }
195086
195087  sqlite3_free(aTotalSize);
195088  return rc;
195089}
195090
195091/*
195092** Obtain an SQLite statement handle that may be used to read data from the
195093** %_content table.
195094*/
195095static int sqlite3Fts5StorageStmt(
195096  Fts5Storage *p,
195097  int eStmt,
195098  sqlite3_stmt **pp,
195099  char **pzErrMsg
195100){
195101  int rc;
195102  assert( eStmt==FTS5_STMT_SCAN_ASC
195103       || eStmt==FTS5_STMT_SCAN_DESC
195104       || eStmt==FTS5_STMT_LOOKUP
195105  );
195106  rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
195107  if( rc==SQLITE_OK ){
195108    assert( p->aStmt[eStmt]==*pp );
195109    p->aStmt[eStmt] = 0;
195110  }
195111  return rc;
195112}
195113
195114/*
195115** Release an SQLite statement handle obtained via an earlier call to
195116** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
195117** must match that passed to the sqlite3Fts5StorageStmt() call.
195118*/
195119static void sqlite3Fts5StorageStmtRelease(
195120  Fts5Storage *p,
195121  int eStmt,
195122  sqlite3_stmt *pStmt
195123){
195124  assert( eStmt==FTS5_STMT_SCAN_ASC
195125       || eStmt==FTS5_STMT_SCAN_DESC
195126       || eStmt==FTS5_STMT_LOOKUP
195127  );
195128  if( p->aStmt[eStmt]==0 ){
195129    sqlite3_reset(pStmt);
195130    p->aStmt[eStmt] = pStmt;
195131  }else{
195132    sqlite3_finalize(pStmt);
195133  }
195134}
195135
195136static int fts5StorageDecodeSizeArray(
195137  int *aCol, int nCol,            /* Array to populate */
195138  const u8 *aBlob, int nBlob      /* Record to read varints from */
195139){
195140  int i;
195141  int iOff = 0;
195142  for(i=0; i<nCol; i++){
195143    if( iOff>=nBlob ) return 1;
195144    iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
195145  }
195146  return (iOff!=nBlob);
195147}
195148
195149/*
195150** Argument aCol points to an array of integers containing one entry for
195151** each table column. This function reads the %_docsize record for the
195152** specified rowid and populates aCol[] with the results.
195153**
195154** An SQLite error code is returned if an error occurs, or SQLITE_OK
195155** otherwise.
195156*/
195157static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
195158  int nCol = p->pConfig->nCol;    /* Number of user columns in table */
195159  sqlite3_stmt *pLookup = 0;      /* Statement to query %_docsize */
195160  int rc;                         /* Return Code */
195161
195162  assert( p->pConfig->bColumnsize );
195163  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
195164  if( rc==SQLITE_OK ){
195165    int bCorrupt = 1;
195166    sqlite3_bind_int64(pLookup, 1, iRowid);
195167    if( SQLITE_ROW==sqlite3_step(pLookup) ){
195168      const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
195169      int nBlob = sqlite3_column_bytes(pLookup, 0);
195170      if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
195171        bCorrupt = 0;
195172      }
195173    }
195174    rc = sqlite3_reset(pLookup);
195175    if( bCorrupt && rc==SQLITE_OK ){
195176      rc = FTS5_CORRUPT;
195177    }
195178  }
195179
195180  return rc;
195181}
195182
195183static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
195184  int rc = fts5StorageLoadTotals(p, 0);
195185  if( rc==SQLITE_OK ){
195186    *pnToken = 0;
195187    if( iCol<0 ){
195188      int i;
195189      for(i=0; i<p->pConfig->nCol; i++){
195190        *pnToken += p->aTotalSize[i];
195191      }
195192    }else if( iCol<p->pConfig->nCol ){
195193      *pnToken = p->aTotalSize[iCol];
195194    }else{
195195      rc = SQLITE_RANGE;
195196    }
195197  }
195198  return rc;
195199}
195200
195201static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
195202  int rc = fts5StorageLoadTotals(p, 0);
195203  if( rc==SQLITE_OK ){
195204    *pnRow = p->nTotalRow;
195205  }
195206  return rc;
195207}
195208
195209/*
195210** Flush any data currently held in-memory to disk.
195211*/
195212static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit){
195213  if( bCommit && p->bTotalsValid ){
195214    int rc = fts5StorageSaveTotals(p);
195215    p->bTotalsValid = 0;
195216    if( rc!=SQLITE_OK ) return rc;
195217  }
195218  return sqlite3Fts5IndexSync(p->pIndex, bCommit);
195219}
195220
195221static int sqlite3Fts5StorageRollback(Fts5Storage *p){
195222  p->bTotalsValid = 0;
195223  return sqlite3Fts5IndexRollback(p->pIndex);
195224}
195225
195226static int sqlite3Fts5StorageConfigValue(
195227  Fts5Storage *p,
195228  const char *z,
195229  sqlite3_value *pVal,
195230  int iVal
195231){
195232  sqlite3_stmt *pReplace = 0;
195233  int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
195234  if( rc==SQLITE_OK ){
195235    sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
195236    if( pVal ){
195237      sqlite3_bind_value(pReplace, 2, pVal);
195238    }else{
195239      sqlite3_bind_int(pReplace, 2, iVal);
195240    }
195241    sqlite3_step(pReplace);
195242    rc = sqlite3_reset(pReplace);
195243  }
195244  if( rc==SQLITE_OK && pVal ){
195245    int iNew = p->pConfig->iCookie + 1;
195246    rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
195247    if( rc==SQLITE_OK ){
195248      p->pConfig->iCookie = iNew;
195249    }
195250  }
195251  return rc;
195252}
195253
195254/*
195255** 2014 May 31
195256**
195257** The author disclaims copyright to this source code.  In place of
195258** a legal notice, here is a blessing:
195259**
195260**    May you do good and not evil.
195261**    May you find forgiveness for yourself and forgive others.
195262**    May you share freely, never taking more than you give.
195263**
195264******************************************************************************
195265*/
195266
195267
195268/* #include "fts5Int.h" */
195269
195270/**************************************************************************
195271** Start of ascii tokenizer implementation.
195272*/
195273
195274/*
195275** For tokenizers with no "unicode" modifier, the set of token characters
195276** is the same as the set of ASCII range alphanumeric characters.
195277*/
195278static unsigned char aAsciiTokenChar[128] = {
195279  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00..0x0F */
195280  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x10..0x1F */
195281  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20..0x2F */
195282  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30..0x3F */
195283  0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40..0x4F */
195284  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x50..0x5F */
195285  0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60..0x6F */
195286  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x70..0x7F */
195287};
195288
195289typedef struct AsciiTokenizer AsciiTokenizer;
195290struct AsciiTokenizer {
195291  unsigned char aTokenChar[128];
195292};
195293
195294static void fts5AsciiAddExceptions(
195295  AsciiTokenizer *p,
195296  const char *zArg,
195297  int bTokenChars
195298){
195299  int i;
195300  for(i=0; zArg[i]; i++){
195301    if( (zArg[i] & 0x80)==0 ){
195302      p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
195303    }
195304  }
195305}
195306
195307/*
195308** Delete a "ascii" tokenizer.
195309*/
195310static void fts5AsciiDelete(Fts5Tokenizer *p){
195311  sqlite3_free(p);
195312}
195313
195314/*
195315** Create an "ascii" tokenizer.
195316*/
195317static int fts5AsciiCreate(
195318  void *pUnused,
195319  const char **azArg, int nArg,
195320  Fts5Tokenizer **ppOut
195321){
195322  int rc = SQLITE_OK;
195323  AsciiTokenizer *p = 0;
195324  UNUSED_PARAM(pUnused);
195325  if( nArg%2 ){
195326    rc = SQLITE_ERROR;
195327  }else{
195328    p = sqlite3_malloc(sizeof(AsciiTokenizer));
195329    if( p==0 ){
195330      rc = SQLITE_NOMEM;
195331    }else{
195332      int i;
195333      memset(p, 0, sizeof(AsciiTokenizer));
195334      memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
195335      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
195336        const char *zArg = azArg[i+1];
195337        if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
195338          fts5AsciiAddExceptions(p, zArg, 1);
195339        }else
195340        if( 0==sqlite3_stricmp(azArg[i], "separators") ){
195341          fts5AsciiAddExceptions(p, zArg, 0);
195342        }else{
195343          rc = SQLITE_ERROR;
195344        }
195345      }
195346      if( rc!=SQLITE_OK ){
195347        fts5AsciiDelete((Fts5Tokenizer*)p);
195348        p = 0;
195349      }
195350    }
195351  }
195352
195353  *ppOut = (Fts5Tokenizer*)p;
195354  return rc;
195355}
195356
195357
195358static void asciiFold(char *aOut, const char *aIn, int nByte){
195359  int i;
195360  for(i=0; i<nByte; i++){
195361    char c = aIn[i];
195362    if( c>='A' && c<='Z' ) c += 32;
195363    aOut[i] = c;
195364  }
195365}
195366
195367/*
195368** Tokenize some text using the ascii tokenizer.
195369*/
195370static int fts5AsciiTokenize(
195371  Fts5Tokenizer *pTokenizer,
195372  void *pCtx,
195373  int iUnused,
195374  const char *pText, int nText,
195375  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
195376){
195377  AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
195378  int rc = SQLITE_OK;
195379  int ie;
195380  int is = 0;
195381
195382  char aFold[64];
195383  int nFold = sizeof(aFold);
195384  char *pFold = aFold;
195385  unsigned char *a = p->aTokenChar;
195386
195387  UNUSED_PARAM(iUnused);
195388
195389  while( is<nText && rc==SQLITE_OK ){
195390    int nByte;
195391
195392    /* Skip any leading divider characters. */
195393    while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
195394      is++;
195395    }
195396    if( is==nText ) break;
195397
195398    /* Count the token characters */
195399    ie = is+1;
195400    while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
195401      ie++;
195402    }
195403
195404    /* Fold to lower case */
195405    nByte = ie-is;
195406    if( nByte>nFold ){
195407      if( pFold!=aFold ) sqlite3_free(pFold);
195408      pFold = sqlite3_malloc(nByte*2);
195409      if( pFold==0 ){
195410        rc = SQLITE_NOMEM;
195411        break;
195412      }
195413      nFold = nByte*2;
195414    }
195415    asciiFold(pFold, &pText[is], nByte);
195416
195417    /* Invoke the token callback */
195418    rc = xToken(pCtx, 0, pFold, nByte, is, ie);
195419    is = ie+1;
195420  }
195421
195422  if( pFold!=aFold ) sqlite3_free(pFold);
195423  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
195424  return rc;
195425}
195426
195427/**************************************************************************
195428** Start of unicode61 tokenizer implementation.
195429*/
195430
195431
195432/*
195433** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
195434** from the sqlite3 source file utf.c. If this file is compiled as part
195435** of the amalgamation, they are not required.
195436*/
195437#ifndef SQLITE_AMALGAMATION
195438
195439static const unsigned char sqlite3Utf8Trans1[] = {
195440  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
195441  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
195442  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
195443  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
195444  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
195445  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
195446  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
195447  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
195448};
195449
195450#define READ_UTF8(zIn, zTerm, c)                           \
195451  c = *(zIn++);                                            \
195452  if( c>=0xc0 ){                                           \
195453    c = sqlite3Utf8Trans1[c-0xc0];                         \
195454    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
195455      c = (c<<6) + (0x3f & *(zIn++));                      \
195456    }                                                      \
195457    if( c<0x80                                             \
195458        || (c&0xFFFFF800)==0xD800                          \
195459        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
195460  }
195461
195462
195463#define WRITE_UTF8(zOut, c) {                          \
195464  if( c<0x00080 ){                                     \
195465    *zOut++ = (unsigned char)(c&0xFF);                 \
195466  }                                                    \
195467  else if( c<0x00800 ){                                \
195468    *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F);     \
195469    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
195470  }                                                    \
195471  else if( c<0x10000 ){                                \
195472    *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F);    \
195473    *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
195474    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
195475  }else{                                               \
195476    *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07);  \
195477    *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F);  \
195478    *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
195479    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
195480  }                                                    \
195481}
195482
195483#endif /* ifndef SQLITE_AMALGAMATION */
195484
195485typedef struct Unicode61Tokenizer Unicode61Tokenizer;
195486struct Unicode61Tokenizer {
195487  unsigned char aTokenChar[128];  /* ASCII range token characters */
195488  char *aFold;                    /* Buffer to fold text into */
195489  int nFold;                      /* Size of aFold[] in bytes */
195490  int bRemoveDiacritic;           /* True if remove_diacritics=1 is set */
195491  int nException;
195492  int *aiException;
195493};
195494
195495static int fts5UnicodeAddExceptions(
195496  Unicode61Tokenizer *p,          /* Tokenizer object */
195497  const char *z,                  /* Characters to treat as exceptions */
195498  int bTokenChars                 /* 1 for 'tokenchars', 0 for 'separators' */
195499){
195500  int rc = SQLITE_OK;
195501  int n = (int)strlen(z);
195502  int *aNew;
195503
195504  if( n>0 ){
195505    aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
195506    if( aNew ){
195507      int nNew = p->nException;
195508      const unsigned char *zCsr = (const unsigned char*)z;
195509      const unsigned char *zTerm = (const unsigned char*)&z[n];
195510      while( zCsr<zTerm ){
195511        int iCode;
195512        int bToken;
195513        READ_UTF8(zCsr, zTerm, iCode);
195514        if( iCode<128 ){
195515          p->aTokenChar[iCode] = (unsigned char)bTokenChars;
195516        }else{
195517          bToken = sqlite3Fts5UnicodeIsalnum(iCode);
195518          assert( (bToken==0 || bToken==1) );
195519          assert( (bTokenChars==0 || bTokenChars==1) );
195520          if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
195521            int i;
195522            for(i=0; i<nNew; i++){
195523              if( aNew[i]>iCode ) break;
195524            }
195525            memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
195526            aNew[i] = iCode;
195527            nNew++;
195528          }
195529        }
195530      }
195531      p->aiException = aNew;
195532      p->nException = nNew;
195533    }else{
195534      rc = SQLITE_NOMEM;
195535    }
195536  }
195537
195538  return rc;
195539}
195540
195541/*
195542** Return true if the p->aiException[] array contains the value iCode.
195543*/
195544static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
195545  if( p->nException>0 ){
195546    int *a = p->aiException;
195547    int iLo = 0;
195548    int iHi = p->nException-1;
195549
195550    while( iHi>=iLo ){
195551      int iTest = (iHi + iLo) / 2;
195552      if( iCode==a[iTest] ){
195553        return 1;
195554      }else if( iCode>a[iTest] ){
195555        iLo = iTest+1;
195556      }else{
195557        iHi = iTest-1;
195558      }
195559    }
195560  }
195561
195562  return 0;
195563}
195564
195565/*
195566** Delete a "unicode61" tokenizer.
195567*/
195568static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
195569  if( pTok ){
195570    Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
195571    sqlite3_free(p->aiException);
195572    sqlite3_free(p->aFold);
195573    sqlite3_free(p);
195574  }
195575  return;
195576}
195577
195578/*
195579** Create a "unicode61" tokenizer.
195580*/
195581static int fts5UnicodeCreate(
195582  void *pUnused,
195583  const char **azArg, int nArg,
195584  Fts5Tokenizer **ppOut
195585){
195586  int rc = SQLITE_OK;             /* Return code */
195587  Unicode61Tokenizer *p = 0;      /* New tokenizer object */
195588
195589  UNUSED_PARAM(pUnused);
195590
195591  if( nArg%2 ){
195592    rc = SQLITE_ERROR;
195593  }else{
195594    p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
195595    if( p ){
195596      int i;
195597      memset(p, 0, sizeof(Unicode61Tokenizer));
195598      memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
195599      p->bRemoveDiacritic = 1;
195600      p->nFold = 64;
195601      p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
195602      if( p->aFold==0 ){
195603        rc = SQLITE_NOMEM;
195604      }
195605      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
195606        const char *zArg = azArg[i+1];
195607        if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
195608          if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
195609            rc = SQLITE_ERROR;
195610          }
195611          p->bRemoveDiacritic = (zArg[0]=='1');
195612        }else
195613        if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
195614          rc = fts5UnicodeAddExceptions(p, zArg, 1);
195615        }else
195616        if( 0==sqlite3_stricmp(azArg[i], "separators") ){
195617          rc = fts5UnicodeAddExceptions(p, zArg, 0);
195618        }else{
195619          rc = SQLITE_ERROR;
195620        }
195621      }
195622    }else{
195623      rc = SQLITE_NOMEM;
195624    }
195625    if( rc!=SQLITE_OK ){
195626      fts5UnicodeDelete((Fts5Tokenizer*)p);
195627      p = 0;
195628    }
195629    *ppOut = (Fts5Tokenizer*)p;
195630  }
195631  return rc;
195632}
195633
195634/*
195635** Return true if, for the purposes of tokenizing with the tokenizer
195636** passed as the first argument, codepoint iCode is considered a token
195637** character (not a separator).
195638*/
195639static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
195640  assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
195641  return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
195642}
195643
195644static int fts5UnicodeTokenize(
195645  Fts5Tokenizer *pTokenizer,
195646  void *pCtx,
195647  int iUnused,
195648  const char *pText, int nText,
195649  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
195650){
195651  Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
195652  int rc = SQLITE_OK;
195653  unsigned char *a = p->aTokenChar;
195654
195655  unsigned char *zTerm = (unsigned char*)&pText[nText];
195656  unsigned char *zCsr = (unsigned char *)pText;
195657
195658  /* Output buffer */
195659  char *aFold = p->aFold;
195660  int nFold = p->nFold;
195661  const char *pEnd = &aFold[nFold-6];
195662
195663  UNUSED_PARAM(iUnused);
195664
195665  /* Each iteration of this loop gobbles up a contiguous run of separators,
195666  ** then the next token.  */
195667  while( rc==SQLITE_OK ){
195668    int iCode;                    /* non-ASCII codepoint read from input */
195669    char *zOut = aFold;
195670    int is;
195671    int ie;
195672
195673    /* Skip any separator characters. */
195674    while( 1 ){
195675      if( zCsr>=zTerm ) goto tokenize_done;
195676      if( *zCsr & 0x80 ) {
195677        /* A character outside of the ascii range. Skip past it if it is
195678        ** a separator character. Or break out of the loop if it is not. */
195679        is = zCsr - (unsigned char*)pText;
195680        READ_UTF8(zCsr, zTerm, iCode);
195681        if( fts5UnicodeIsAlnum(p, iCode) ){
195682          goto non_ascii_tokenchar;
195683        }
195684      }else{
195685        if( a[*zCsr] ){
195686          is = zCsr - (unsigned char*)pText;
195687          goto ascii_tokenchar;
195688        }
195689        zCsr++;
195690      }
195691    }
195692
195693    /* Run through the tokenchars. Fold them into the output buffer along
195694    ** the way.  */
195695    while( zCsr<zTerm ){
195696
195697      /* Grow the output buffer so that there is sufficient space to fit the
195698      ** largest possible utf-8 character.  */
195699      if( zOut>pEnd ){
195700        aFold = sqlite3_malloc(nFold*2);
195701        if( aFold==0 ){
195702          rc = SQLITE_NOMEM;
195703          goto tokenize_done;
195704        }
195705        zOut = &aFold[zOut - p->aFold];
195706        memcpy(aFold, p->aFold, nFold);
195707        sqlite3_free(p->aFold);
195708        p->aFold = aFold;
195709        p->nFold = nFold = nFold*2;
195710        pEnd = &aFold[nFold-6];
195711      }
195712
195713      if( *zCsr & 0x80 ){
195714        /* An non-ascii-range character. Fold it into the output buffer if
195715        ** it is a token character, or break out of the loop if it is not. */
195716        READ_UTF8(zCsr, zTerm, iCode);
195717        if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
195718 non_ascii_tokenchar:
195719          iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
195720          if( iCode ) WRITE_UTF8(zOut, iCode);
195721        }else{
195722          break;
195723        }
195724      }else if( a[*zCsr]==0 ){
195725        /* An ascii-range separator character. End of token. */
195726        break;
195727      }else{
195728 ascii_tokenchar:
195729        if( *zCsr>='A' && *zCsr<='Z' ){
195730          *zOut++ = *zCsr + 32;
195731        }else{
195732          *zOut++ = *zCsr;
195733        }
195734        zCsr++;
195735      }
195736      ie = zCsr - (unsigned char*)pText;
195737    }
195738
195739    /* Invoke the token callback */
195740    rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
195741  }
195742
195743 tokenize_done:
195744  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
195745  return rc;
195746}
195747
195748/**************************************************************************
195749** Start of porter stemmer implementation.
195750*/
195751
195752/* Any tokens larger than this (in bytes) are passed through without
195753** stemming. */
195754#define FTS5_PORTER_MAX_TOKEN 64
195755
195756typedef struct PorterTokenizer PorterTokenizer;
195757struct PorterTokenizer {
195758  fts5_tokenizer tokenizer;       /* Parent tokenizer module */
195759  Fts5Tokenizer *pTokenizer;      /* Parent tokenizer instance */
195760  char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
195761};
195762
195763/*
195764** Delete a "porter" tokenizer.
195765*/
195766static void fts5PorterDelete(Fts5Tokenizer *pTok){
195767  if( pTok ){
195768    PorterTokenizer *p = (PorterTokenizer*)pTok;
195769    if( p->pTokenizer ){
195770      p->tokenizer.xDelete(p->pTokenizer);
195771    }
195772    sqlite3_free(p);
195773  }
195774}
195775
195776/*
195777** Create a "porter" tokenizer.
195778*/
195779static int fts5PorterCreate(
195780  void *pCtx,
195781  const char **azArg, int nArg,
195782  Fts5Tokenizer **ppOut
195783){
195784  fts5_api *pApi = (fts5_api*)pCtx;
195785  int rc = SQLITE_OK;
195786  PorterTokenizer *pRet;
195787  void *pUserdata = 0;
195788  const char *zBase = "unicode61";
195789
195790  if( nArg>0 ){
195791    zBase = azArg[0];
195792  }
195793
195794  pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
195795  if( pRet ){
195796    memset(pRet, 0, sizeof(PorterTokenizer));
195797    rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
195798  }else{
195799    rc = SQLITE_NOMEM;
195800  }
195801  if( rc==SQLITE_OK ){
195802    int nArg2 = (nArg>0 ? nArg-1 : 0);
195803    const char **azArg2 = (nArg2 ? &azArg[1] : 0);
195804    rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
195805  }
195806
195807  if( rc!=SQLITE_OK ){
195808    fts5PorterDelete((Fts5Tokenizer*)pRet);
195809    pRet = 0;
195810  }
195811  *ppOut = (Fts5Tokenizer*)pRet;
195812  return rc;
195813}
195814
195815typedef struct PorterContext PorterContext;
195816struct PorterContext {
195817  void *pCtx;
195818  int (*xToken)(void*, int, const char*, int, int, int);
195819  char *aBuf;
195820};
195821
195822typedef struct PorterRule PorterRule;
195823struct PorterRule {
195824  const char *zSuffix;
195825  int nSuffix;
195826  int (*xCond)(char *zStem, int nStem);
195827  const char *zOutput;
195828  int nOutput;
195829};
195830
195831#if 0
195832static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
195833  int ret = -1;
195834  int nBuf = *pnBuf;
195835  PorterRule *p;
195836
195837  for(p=aRule; p->zSuffix; p++){
195838    assert( strlen(p->zSuffix)==p->nSuffix );
195839    assert( strlen(p->zOutput)==p->nOutput );
195840    if( nBuf<p->nSuffix ) continue;
195841    if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
195842  }
195843
195844  if( p->zSuffix ){
195845    int nStem = nBuf - p->nSuffix;
195846    if( p->xCond==0 || p->xCond(aBuf, nStem) ){
195847      memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
195848      *pnBuf = nStem + p->nOutput;
195849      ret = p - aRule;
195850    }
195851  }
195852
195853  return ret;
195854}
195855#endif
195856
195857static int fts5PorterIsVowel(char c, int bYIsVowel){
195858  return (
195859      c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
195860  );
195861}
195862
195863static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
195864  int i;
195865  int bCons = bPrevCons;
195866
195867  /* Scan for a vowel */
195868  for(i=0; i<nStem; i++){
195869    if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
195870  }
195871
195872  /* Scan for a consonent */
195873  for(i++; i<nStem; i++){
195874    if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
195875  }
195876  return 0;
195877}
195878
195879/* porter rule condition: (m > 0) */
195880static int fts5Porter_MGt0(char *zStem, int nStem){
195881  return !!fts5PorterGobbleVC(zStem, nStem, 0);
195882}
195883
195884/* porter rule condition: (m > 1) */
195885static int fts5Porter_MGt1(char *zStem, int nStem){
195886  int n;
195887  n = fts5PorterGobbleVC(zStem, nStem, 0);
195888  if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
195889    return 1;
195890  }
195891  return 0;
195892}
195893
195894/* porter rule condition: (m = 1) */
195895static int fts5Porter_MEq1(char *zStem, int nStem){
195896  int n;
195897  n = fts5PorterGobbleVC(zStem, nStem, 0);
195898  if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
195899    return 1;
195900  }
195901  return 0;
195902}
195903
195904/* porter rule condition: (*o) */
195905static int fts5Porter_Ostar(char *zStem, int nStem){
195906  if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
195907    return 0;
195908  }else{
195909    int i;
195910    int mask = 0;
195911    int bCons = 0;
195912    for(i=0; i<nStem; i++){
195913      bCons = !fts5PorterIsVowel(zStem[i], bCons);
195914      assert( bCons==0 || bCons==1 );
195915      mask = (mask << 1) + bCons;
195916    }
195917    return ((mask & 0x0007)==0x0005);
195918  }
195919}
195920
195921/* porter rule condition: (m > 1 and (*S or *T)) */
195922static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
195923  assert( nStem>0 );
195924  return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
195925      && fts5Porter_MGt1(zStem, nStem);
195926}
195927
195928/* porter rule condition: (*v*) */
195929static int fts5Porter_Vowel(char *zStem, int nStem){
195930  int i;
195931  for(i=0; i<nStem; i++){
195932    if( fts5PorterIsVowel(zStem[i], i>0) ){
195933      return 1;
195934    }
195935  }
195936  return 0;
195937}
195938
195939
195940/**************************************************************************
195941***************************************************************************
195942** GENERATED CODE STARTS HERE (mkportersteps.tcl)
195943*/
195944
195945static int fts5PorterStep4(char *aBuf, int *pnBuf){
195946  int ret = 0;
195947  int nBuf = *pnBuf;
195948  switch( aBuf[nBuf-2] ){
195949
195950    case 'a':
195951      if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
195952        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
195953          *pnBuf = nBuf - 2;
195954        }
195955      }
195956      break;
195957
195958    case 'c':
195959      if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
195960        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
195961          *pnBuf = nBuf - 4;
195962        }
195963      }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
195964        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
195965          *pnBuf = nBuf - 4;
195966        }
195967      }
195968      break;
195969
195970    case 'e':
195971      if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
195972        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
195973          *pnBuf = nBuf - 2;
195974        }
195975      }
195976      break;
195977
195978    case 'i':
195979      if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
195980        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
195981          *pnBuf = nBuf - 2;
195982        }
195983      }
195984      break;
195985
195986    case 'l':
195987      if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
195988        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
195989          *pnBuf = nBuf - 4;
195990        }
195991      }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
195992        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
195993          *pnBuf = nBuf - 4;
195994        }
195995      }
195996      break;
195997
195998    case 'n':
195999      if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
196000        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196001          *pnBuf = nBuf - 3;
196002        }
196003      }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
196004        if( fts5Porter_MGt1(aBuf, nBuf-5) ){
196005          *pnBuf = nBuf - 5;
196006        }
196007      }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
196008        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
196009          *pnBuf = nBuf - 4;
196010        }
196011      }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
196012        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196013          *pnBuf = nBuf - 3;
196014        }
196015      }
196016      break;
196017
196018    case 'o':
196019      if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
196020        if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
196021          *pnBuf = nBuf - 3;
196022        }
196023      }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
196024        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
196025          *pnBuf = nBuf - 2;
196026        }
196027      }
196028      break;
196029
196030    case 's':
196031      if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
196032        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196033          *pnBuf = nBuf - 3;
196034        }
196035      }
196036      break;
196037
196038    case 't':
196039      if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
196040        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196041          *pnBuf = nBuf - 3;
196042        }
196043      }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
196044        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196045          *pnBuf = nBuf - 3;
196046        }
196047      }
196048      break;
196049
196050    case 'u':
196051      if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
196052        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196053          *pnBuf = nBuf - 3;
196054        }
196055      }
196056      break;
196057
196058    case 'v':
196059      if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
196060        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196061          *pnBuf = nBuf - 3;
196062        }
196063      }
196064      break;
196065
196066    case 'z':
196067      if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
196068        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196069          *pnBuf = nBuf - 3;
196070        }
196071      }
196072      break;
196073
196074  }
196075  return ret;
196076}
196077
196078
196079static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
196080  int ret = 0;
196081  int nBuf = *pnBuf;
196082  switch( aBuf[nBuf-2] ){
196083
196084    case 'a':
196085      if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
196086        memcpy(&aBuf[nBuf-2], "ate", 3);
196087        *pnBuf = nBuf - 2 + 3;
196088        ret = 1;
196089      }
196090      break;
196091
196092    case 'b':
196093      if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
196094        memcpy(&aBuf[nBuf-2], "ble", 3);
196095        *pnBuf = nBuf - 2 + 3;
196096        ret = 1;
196097      }
196098      break;
196099
196100    case 'i':
196101      if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
196102        memcpy(&aBuf[nBuf-2], "ize", 3);
196103        *pnBuf = nBuf - 2 + 3;
196104        ret = 1;
196105      }
196106      break;
196107
196108  }
196109  return ret;
196110}
196111
196112
196113static int fts5PorterStep2(char *aBuf, int *pnBuf){
196114  int ret = 0;
196115  int nBuf = *pnBuf;
196116  switch( aBuf[nBuf-2] ){
196117
196118    case 'a':
196119      if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
196120        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
196121          memcpy(&aBuf[nBuf-7], "ate", 3);
196122          *pnBuf = nBuf - 7 + 3;
196123        }
196124      }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
196125        if( fts5Porter_MGt0(aBuf, nBuf-6) ){
196126          memcpy(&aBuf[nBuf-6], "tion", 4);
196127          *pnBuf = nBuf - 6 + 4;
196128        }
196129      }
196130      break;
196131
196132    case 'c':
196133      if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
196134        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196135          memcpy(&aBuf[nBuf-4], "ence", 4);
196136          *pnBuf = nBuf - 4 + 4;
196137        }
196138      }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
196139        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196140          memcpy(&aBuf[nBuf-4], "ance", 4);
196141          *pnBuf = nBuf - 4 + 4;
196142        }
196143      }
196144      break;
196145
196146    case 'e':
196147      if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
196148        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196149          memcpy(&aBuf[nBuf-4], "ize", 3);
196150          *pnBuf = nBuf - 4 + 3;
196151        }
196152      }
196153      break;
196154
196155    case 'g':
196156      if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
196157        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196158          memcpy(&aBuf[nBuf-4], "log", 3);
196159          *pnBuf = nBuf - 4 + 3;
196160        }
196161      }
196162      break;
196163
196164    case 'l':
196165      if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
196166        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
196167          memcpy(&aBuf[nBuf-3], "ble", 3);
196168          *pnBuf = nBuf - 3 + 3;
196169        }
196170      }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
196171        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196172          memcpy(&aBuf[nBuf-4], "al", 2);
196173          *pnBuf = nBuf - 4 + 2;
196174        }
196175      }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
196176        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196177          memcpy(&aBuf[nBuf-5], "ent", 3);
196178          *pnBuf = nBuf - 5 + 3;
196179        }
196180      }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
196181        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
196182          memcpy(&aBuf[nBuf-3], "e", 1);
196183          *pnBuf = nBuf - 3 + 1;
196184        }
196185      }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
196186        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196187          memcpy(&aBuf[nBuf-5], "ous", 3);
196188          *pnBuf = nBuf - 5 + 3;
196189        }
196190      }
196191      break;
196192
196193    case 'o':
196194      if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
196195        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
196196          memcpy(&aBuf[nBuf-7], "ize", 3);
196197          *pnBuf = nBuf - 7 + 3;
196198        }
196199      }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
196200        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196201          memcpy(&aBuf[nBuf-5], "ate", 3);
196202          *pnBuf = nBuf - 5 + 3;
196203        }
196204      }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
196205        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196206          memcpy(&aBuf[nBuf-4], "ate", 3);
196207          *pnBuf = nBuf - 4 + 3;
196208        }
196209      }
196210      break;
196211
196212    case 's':
196213      if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
196214        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196215          memcpy(&aBuf[nBuf-5], "al", 2);
196216          *pnBuf = nBuf - 5 + 2;
196217        }
196218      }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
196219        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
196220          memcpy(&aBuf[nBuf-7], "ive", 3);
196221          *pnBuf = nBuf - 7 + 3;
196222        }
196223      }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
196224        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
196225          memcpy(&aBuf[nBuf-7], "ful", 3);
196226          *pnBuf = nBuf - 7 + 3;
196227        }
196228      }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
196229        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
196230          memcpy(&aBuf[nBuf-7], "ous", 3);
196231          *pnBuf = nBuf - 7 + 3;
196232        }
196233      }
196234      break;
196235
196236    case 't':
196237      if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
196238        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196239          memcpy(&aBuf[nBuf-5], "al", 2);
196240          *pnBuf = nBuf - 5 + 2;
196241        }
196242      }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
196243        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196244          memcpy(&aBuf[nBuf-5], "ive", 3);
196245          *pnBuf = nBuf - 5 + 3;
196246        }
196247      }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
196248        if( fts5Porter_MGt0(aBuf, nBuf-6) ){
196249          memcpy(&aBuf[nBuf-6], "ble", 3);
196250          *pnBuf = nBuf - 6 + 3;
196251        }
196252      }
196253      break;
196254
196255  }
196256  return ret;
196257}
196258
196259
196260static int fts5PorterStep3(char *aBuf, int *pnBuf){
196261  int ret = 0;
196262  int nBuf = *pnBuf;
196263  switch( aBuf[nBuf-2] ){
196264
196265    case 'a':
196266      if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
196267        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196268          memcpy(&aBuf[nBuf-4], "ic", 2);
196269          *pnBuf = nBuf - 4 + 2;
196270        }
196271      }
196272      break;
196273
196274    case 's':
196275      if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
196276        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196277          *pnBuf = nBuf - 4;
196278        }
196279      }
196280      break;
196281
196282    case 't':
196283      if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
196284        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196285          memcpy(&aBuf[nBuf-5], "ic", 2);
196286          *pnBuf = nBuf - 5 + 2;
196287        }
196288      }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
196289        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196290          memcpy(&aBuf[nBuf-5], "ic", 2);
196291          *pnBuf = nBuf - 5 + 2;
196292        }
196293      }
196294      break;
196295
196296    case 'u':
196297      if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
196298        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
196299          *pnBuf = nBuf - 3;
196300        }
196301      }
196302      break;
196303
196304    case 'v':
196305      if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
196306        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196307          *pnBuf = nBuf - 5;
196308        }
196309      }
196310      break;
196311
196312    case 'z':
196313      if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
196314        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196315          memcpy(&aBuf[nBuf-5], "al", 2);
196316          *pnBuf = nBuf - 5 + 2;
196317        }
196318      }
196319      break;
196320
196321  }
196322  return ret;
196323}
196324
196325
196326static int fts5PorterStep1B(char *aBuf, int *pnBuf){
196327  int ret = 0;
196328  int nBuf = *pnBuf;
196329  switch( aBuf[nBuf-2] ){
196330
196331    case 'e':
196332      if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
196333        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
196334          memcpy(&aBuf[nBuf-3], "ee", 2);
196335          *pnBuf = nBuf - 3 + 2;
196336        }
196337      }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
196338        if( fts5Porter_Vowel(aBuf, nBuf-2) ){
196339          *pnBuf = nBuf - 2;
196340          ret = 1;
196341        }
196342      }
196343      break;
196344
196345    case 'n':
196346      if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
196347        if( fts5Porter_Vowel(aBuf, nBuf-3) ){
196348          *pnBuf = nBuf - 3;
196349          ret = 1;
196350        }
196351      }
196352      break;
196353
196354  }
196355  return ret;
196356}
196357
196358/*
196359** GENERATED CODE ENDS HERE (mkportersteps.tcl)
196360***************************************************************************
196361**************************************************************************/
196362
196363static void fts5PorterStep1A(char *aBuf, int *pnBuf){
196364  int nBuf = *pnBuf;
196365  if( aBuf[nBuf-1]=='s' ){
196366    if( aBuf[nBuf-2]=='e' ){
196367      if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
196368       || (nBuf>3 && aBuf[nBuf-3]=='i' )
196369      ){
196370        *pnBuf = nBuf-2;
196371      }else{
196372        *pnBuf = nBuf-1;
196373      }
196374    }
196375    else if( aBuf[nBuf-2]!='s' ){
196376      *pnBuf = nBuf-1;
196377    }
196378  }
196379}
196380
196381static int fts5PorterCb(
196382  void *pCtx,
196383  int tflags,
196384  const char *pToken,
196385  int nToken,
196386  int iStart,
196387  int iEnd
196388){
196389  PorterContext *p = (PorterContext*)pCtx;
196390
196391  char *aBuf;
196392  int nBuf;
196393
196394  if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
196395  aBuf = p->aBuf;
196396  nBuf = nToken;
196397  memcpy(aBuf, pToken, nBuf);
196398
196399  /* Step 1. */
196400  fts5PorterStep1A(aBuf, &nBuf);
196401  if( fts5PorterStep1B(aBuf, &nBuf) ){
196402    if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
196403      char c = aBuf[nBuf-1];
196404      if( fts5PorterIsVowel(c, 0)==0
196405       && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
196406      ){
196407        nBuf--;
196408      }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
196409        aBuf[nBuf++] = 'e';
196410      }
196411    }
196412  }
196413
196414  /* Step 1C. */
196415  if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
196416    aBuf[nBuf-1] = 'i';
196417  }
196418
196419  /* Steps 2 through 4. */
196420  fts5PorterStep2(aBuf, &nBuf);
196421  fts5PorterStep3(aBuf, &nBuf);
196422  fts5PorterStep4(aBuf, &nBuf);
196423
196424  /* Step 5a. */
196425  assert( nBuf>0 );
196426  if( aBuf[nBuf-1]=='e' ){
196427    if( fts5Porter_MGt1(aBuf, nBuf-1)
196428     || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
196429    ){
196430      nBuf--;
196431    }
196432  }
196433
196434  /* Step 5b. */
196435  if( nBuf>1 && aBuf[nBuf-1]=='l'
196436   && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
196437  ){
196438    nBuf--;
196439  }
196440
196441  return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
196442
196443 pass_through:
196444  return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
196445}
196446
196447/*
196448** Tokenize using the porter tokenizer.
196449*/
196450static int fts5PorterTokenize(
196451  Fts5Tokenizer *pTokenizer,
196452  void *pCtx,
196453  int flags,
196454  const char *pText, int nText,
196455  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
196456){
196457  PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
196458  PorterContext sCtx;
196459  sCtx.xToken = xToken;
196460  sCtx.pCtx = pCtx;
196461  sCtx.aBuf = p->aBuf;
196462  return p->tokenizer.xTokenize(
196463      p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
196464  );
196465}
196466
196467/*
196468** Register all built-in tokenizers with FTS5.
196469*/
196470static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
196471  struct BuiltinTokenizer {
196472    const char *zName;
196473    fts5_tokenizer x;
196474  } aBuiltin[] = {
196475    { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
196476    { "ascii",     {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
196477    { "porter",    {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
196478  };
196479
196480  int rc = SQLITE_OK;             /* Return code */
196481  int i;                          /* To iterate through builtin functions */
196482
196483  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
196484    rc = pApi->xCreateTokenizer(pApi,
196485        aBuiltin[i].zName,
196486        (void*)pApi,
196487        &aBuiltin[i].x,
196488        0
196489    );
196490  }
196491
196492  return rc;
196493}
196494
196495
196496
196497/*
196498** 2012 May 25
196499**
196500** The author disclaims copyright to this source code.  In place of
196501** a legal notice, here is a blessing:
196502**
196503**    May you do good and not evil.
196504**    May you find forgiveness for yourself and forgive others.
196505**    May you share freely, never taking more than you give.
196506**
196507******************************************************************************
196508*/
196509
196510/*
196511** DO NOT EDIT THIS MACHINE GENERATED FILE.
196512*/
196513
196514
196515/* #include <assert.h> */
196516
196517/*
196518** Return true if the argument corresponds to a unicode codepoint
196519** classified as either a letter or a number. Otherwise false.
196520**
196521** The results are undefined if the value passed to this function
196522** is less than zero.
196523*/
196524static int sqlite3Fts5UnicodeIsalnum(int c){
196525  /* Each unsigned integer in the following array corresponds to a contiguous
196526  ** range of unicode codepoints that are not either letters or numbers (i.e.
196527  ** codepoints for which this function should return 0).
196528  **
196529  ** The most significant 22 bits in each 32-bit value contain the first
196530  ** codepoint in the range. The least significant 10 bits are used to store
196531  ** the size of the range (always at least 1). In other words, the value
196532  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
196533  ** C. It is not possible to represent a range larger than 1023 codepoints
196534  ** using this format.
196535  */
196536  static const unsigned int aEntry[] = {
196537    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
196538    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
196539    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
196540    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
196541    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
196542    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
196543    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
196544    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
196545    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
196546    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
196547    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
196548    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
196549    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
196550    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
196551    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
196552    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
196553    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
196554    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
196555    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
196556    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
196557    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
196558    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
196559    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
196560    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
196561    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
196562    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
196563    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
196564    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
196565    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
196566    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
196567    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
196568    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
196569    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
196570    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
196571    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
196572    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
196573    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
196574    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
196575    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
196576    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
196577    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
196578    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
196579    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
196580    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
196581    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
196582    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
196583    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
196584    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
196585    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
196586    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
196587    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
196588    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
196589    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
196590    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
196591    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
196592    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
196593    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
196594    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
196595    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
196596    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
196597    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
196598    0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
196599    0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
196600    0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
196601    0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
196602    0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
196603    0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
196604    0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
196605    0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
196606    0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
196607    0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
196608    0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
196609    0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
196610    0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
196611    0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
196612    0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
196613    0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
196614    0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
196615    0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
196616    0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
196617    0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
196618    0x380400F0,
196619  };
196620  static const unsigned int aAscii[4] = {
196621    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
196622  };
196623
196624  if( (unsigned int)c<128 ){
196625    return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
196626  }else if( (unsigned int)c<(1<<22) ){
196627    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
196628    int iRes = 0;
196629    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
196630    int iLo = 0;
196631    while( iHi>=iLo ){
196632      int iTest = (iHi + iLo) / 2;
196633      if( key >= aEntry[iTest] ){
196634        iRes = iTest;
196635        iLo = iTest+1;
196636      }else{
196637        iHi = iTest-1;
196638      }
196639    }
196640    assert( aEntry[0]<key );
196641    assert( key>=aEntry[iRes] );
196642    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
196643  }
196644  return 1;
196645}
196646
196647
196648/*
196649** If the argument is a codepoint corresponding to a lowercase letter
196650** in the ASCII range with a diacritic added, return the codepoint
196651** of the ASCII letter only. For example, if passed 235 - "LATIN
196652** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
196653** E"). The resuls of passing a codepoint that corresponds to an
196654** uppercase letter are undefined.
196655*/
196656static int fts5_remove_diacritic(int c){
196657  unsigned short aDia[] = {
196658        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
196659     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
196660     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
196661     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
196662     3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
196663     3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
196664     4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
196665     6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
196666    61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
196667    61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
196668    62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
196669    62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
196670    62924, 63050, 63082, 63274, 63390,
196671  };
196672  char aChar[] = {
196673    '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
196674    'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
196675    's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
196676    'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
196677    'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
196678    '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
196679    'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
196680    'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
196681    'e',  'i',  'o',  'u',  'y',
196682  };
196683
196684  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
196685  int iRes = 0;
196686  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
196687  int iLo = 0;
196688  while( iHi>=iLo ){
196689    int iTest = (iHi + iLo) / 2;
196690    if( key >= aDia[iTest] ){
196691      iRes = iTest;
196692      iLo = iTest+1;
196693    }else{
196694      iHi = iTest-1;
196695    }
196696  }
196697  assert( key>=aDia[iRes] );
196698  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
196699}
196700
196701
196702/*
196703** Return true if the argument interpreted as a unicode codepoint
196704** is a diacritical modifier character.
196705*/
196706static int sqlite3Fts5UnicodeIsdiacritic(int c){
196707  unsigned int mask0 = 0x08029FDF;
196708  unsigned int mask1 = 0x000361F8;
196709  if( c<768 || c>817 ) return 0;
196710  return (c < 768+32) ?
196711      (mask0 & (1 << (c-768))) :
196712      (mask1 & (1 << (c-768-32)));
196713}
196714
196715
196716/*
196717** Interpret the argument as a unicode codepoint. If the codepoint
196718** is an upper case character that has a lower case equivalent,
196719** return the codepoint corresponding to the lower case version.
196720** Otherwise, return a copy of the argument.
196721**
196722** The results are undefined if the value passed to this function
196723** is less than zero.
196724*/
196725static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
196726  /* Each entry in the following array defines a rule for folding a range
196727  ** of codepoints to lower case. The rule applies to a range of nRange
196728  ** codepoints starting at codepoint iCode.
196729  **
196730  ** If the least significant bit in flags is clear, then the rule applies
196731  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
196732  ** need to be folded). Or, if it is set, then the rule only applies to
196733  ** every second codepoint in the range, starting with codepoint C.
196734  **
196735  ** The 7 most significant bits in flags are an index into the aiOff[]
196736  ** array. If a specific codepoint C does require folding, then its lower
196737  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
196738  **
196739  ** The contents of this array are generated by parsing the CaseFolding.txt
196740  ** file distributed as part of the "Unicode Character Database". See
196741  ** http://www.unicode.org for details.
196742  */
196743  static const struct TableEntry {
196744    unsigned short iCode;
196745    unsigned char flags;
196746    unsigned char nRange;
196747  } aEntry[] = {
196748    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
196749    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
196750    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
196751    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
196752    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
196753    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
196754    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
196755    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
196756    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
196757    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
196758    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
196759    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
196760    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
196761    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
196762    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
196763    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
196764    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
196765    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
196766    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
196767    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
196768    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
196769    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
196770    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
196771    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
196772    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
196773    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
196774    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
196775    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
196776    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
196777    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
196778    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
196779    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
196780    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
196781    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
196782    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
196783    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
196784    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
196785    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
196786    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
196787    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
196788    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
196789    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
196790    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
196791    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
196792    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
196793    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
196794    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
196795    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
196796    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
196797    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
196798    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
196799    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
196800    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
196801    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
196802    {65313, 14, 26},
196803  };
196804  static const unsigned short aiOff[] = {
196805   1,     2,     8,     15,    16,    26,    28,    32,
196806   37,    38,    40,    48,    63,    64,    69,    71,
196807   79,    80,    116,   202,   203,   205,   206,   207,
196808   209,   210,   211,   213,   214,   217,   218,   219,
196809   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
196810   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
196811   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
196812   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
196813   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
196814   65514, 65521, 65527, 65528, 65529,
196815  };
196816
196817  int ret = c;
196818
196819  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
196820
196821  if( c<128 ){
196822    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
196823  }else if( c<65536 ){
196824    const struct TableEntry *p;
196825    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
196826    int iLo = 0;
196827    int iRes = -1;
196828
196829    assert( c>aEntry[0].iCode );
196830    while( iHi>=iLo ){
196831      int iTest = (iHi + iLo) / 2;
196832      int cmp = (c - aEntry[iTest].iCode);
196833      if( cmp>=0 ){
196834        iRes = iTest;
196835        iLo = iTest+1;
196836      }else{
196837        iHi = iTest-1;
196838      }
196839    }
196840
196841    assert( iRes>=0 && c>=aEntry[iRes].iCode );
196842    p = &aEntry[iRes];
196843    if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
196844      ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
196845      assert( ret>0 );
196846    }
196847
196848    if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
196849  }
196850
196851  else if( c>=66560 && c<66600 ){
196852    ret = c + 40;
196853  }
196854
196855  return ret;
196856}
196857
196858/*
196859** 2015 May 30
196860**
196861** The author disclaims copyright to this source code.  In place of
196862** a legal notice, here is a blessing:
196863**
196864**    May you do good and not evil.
196865**    May you find forgiveness for yourself and forgive others.
196866**    May you share freely, never taking more than you give.
196867**
196868******************************************************************************
196869**
196870** Routines for varint serialization and deserialization.
196871*/
196872
196873
196874/* #include "fts5Int.h" */
196875
196876/*
196877** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
196878** Except, this version does handle the single byte case that the core
196879** version depends on being handled before its function is called.
196880*/
196881static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
196882  u32 a,b;
196883
196884  /* The 1-byte case. Overwhelmingly the most common. */
196885  a = *p;
196886  /* a: p0 (unmasked) */
196887  if (!(a&0x80))
196888  {
196889    /* Values between 0 and 127 */
196890    *v = a;
196891    return 1;
196892  }
196893
196894  /* The 2-byte case */
196895  p++;
196896  b = *p;
196897  /* b: p1 (unmasked) */
196898  if (!(b&0x80))
196899  {
196900    /* Values between 128 and 16383 */
196901    a &= 0x7f;
196902    a = a<<7;
196903    *v = a | b;
196904    return 2;
196905  }
196906
196907  /* The 3-byte case */
196908  p++;
196909  a = a<<14;
196910  a |= *p;
196911  /* a: p0<<14 | p2 (unmasked) */
196912  if (!(a&0x80))
196913  {
196914    /* Values between 16384 and 2097151 */
196915    a &= (0x7f<<14)|(0x7f);
196916    b &= 0x7f;
196917    b = b<<7;
196918    *v = a | b;
196919    return 3;
196920  }
196921
196922  /* A 32-bit varint is used to store size information in btrees.
196923  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
196924  ** A 3-byte varint is sufficient, for example, to record the size
196925  ** of a 1048569-byte BLOB or string.
196926  **
196927  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
196928  ** rare larger cases can be handled by the slower 64-bit varint
196929  ** routine.
196930  */
196931  {
196932    u64 v64;
196933    u8 n;
196934    p -= 2;
196935    n = sqlite3Fts5GetVarint(p, &v64);
196936    *v = (u32)v64;
196937    assert( n>3 && n<=9 );
196938    return n;
196939  }
196940}
196941
196942
196943/*
196944** Bitmasks used by sqlite3GetVarint().  These precomputed constants
196945** are defined here rather than simply putting the constant expressions
196946** inline in order to work around bugs in the RVT compiler.
196947**
196948** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
196949**
196950** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
196951*/
196952#define SLOT_2_0     0x001fc07f
196953#define SLOT_4_2_0   0xf01fc07f
196954
196955/*
196956** Read a 64-bit variable-length integer from memory starting at p[0].
196957** Return the number of bytes read.  The value is stored in *v.
196958*/
196959static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
196960  u32 a,b,s;
196961
196962  a = *p;
196963  /* a: p0 (unmasked) */
196964  if (!(a&0x80))
196965  {
196966    *v = a;
196967    return 1;
196968  }
196969
196970  p++;
196971  b = *p;
196972  /* b: p1 (unmasked) */
196973  if (!(b&0x80))
196974  {
196975    a &= 0x7f;
196976    a = a<<7;
196977    a |= b;
196978    *v = a;
196979    return 2;
196980  }
196981
196982  /* Verify that constants are precomputed correctly */
196983  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
196984  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
196985
196986  p++;
196987  a = a<<14;
196988  a |= *p;
196989  /* a: p0<<14 | p2 (unmasked) */
196990  if (!(a&0x80))
196991  {
196992    a &= SLOT_2_0;
196993    b &= 0x7f;
196994    b = b<<7;
196995    a |= b;
196996    *v = a;
196997    return 3;
196998  }
196999
197000  /* CSE1 from below */
197001  a &= SLOT_2_0;
197002  p++;
197003  b = b<<14;
197004  b |= *p;
197005  /* b: p1<<14 | p3 (unmasked) */
197006  if (!(b&0x80))
197007  {
197008    b &= SLOT_2_0;
197009    /* moved CSE1 up */
197010    /* a &= (0x7f<<14)|(0x7f); */
197011    a = a<<7;
197012    a |= b;
197013    *v = a;
197014    return 4;
197015  }
197016
197017  /* a: p0<<14 | p2 (masked) */
197018  /* b: p1<<14 | p3 (unmasked) */
197019  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
197020  /* moved CSE1 up */
197021  /* a &= (0x7f<<14)|(0x7f); */
197022  b &= SLOT_2_0;
197023  s = a;
197024  /* s: p0<<14 | p2 (masked) */
197025
197026  p++;
197027  a = a<<14;
197028  a |= *p;
197029  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
197030  if (!(a&0x80))
197031  {
197032    /* we can skip these cause they were (effectively) done above in calc'ing s */
197033    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
197034    /* b &= (0x7f<<14)|(0x7f); */
197035    b = b<<7;
197036    a |= b;
197037    s = s>>18;
197038    *v = ((u64)s)<<32 | a;
197039    return 5;
197040  }
197041
197042  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
197043  s = s<<7;
197044  s |= b;
197045  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
197046
197047  p++;
197048  b = b<<14;
197049  b |= *p;
197050  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
197051  if (!(b&0x80))
197052  {
197053    /* we can skip this cause it was (effectively) done above in calc'ing s */
197054    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
197055    a &= SLOT_2_0;
197056    a = a<<7;
197057    a |= b;
197058    s = s>>18;
197059    *v = ((u64)s)<<32 | a;
197060    return 6;
197061  }
197062
197063  p++;
197064  a = a<<14;
197065  a |= *p;
197066  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
197067  if (!(a&0x80))
197068  {
197069    a &= SLOT_4_2_0;
197070    b &= SLOT_2_0;
197071    b = b<<7;
197072    a |= b;
197073    s = s>>11;
197074    *v = ((u64)s)<<32 | a;
197075    return 7;
197076  }
197077
197078  /* CSE2 from below */
197079  a &= SLOT_2_0;
197080  p++;
197081  b = b<<14;
197082  b |= *p;
197083  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
197084  if (!(b&0x80))
197085  {
197086    b &= SLOT_4_2_0;
197087    /* moved CSE2 up */
197088    /* a &= (0x7f<<14)|(0x7f); */
197089    a = a<<7;
197090    a |= b;
197091    s = s>>4;
197092    *v = ((u64)s)<<32 | a;
197093    return 8;
197094  }
197095
197096  p++;
197097  a = a<<15;
197098  a |= *p;
197099  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
197100
197101  /* moved CSE2 up */
197102  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
197103  b &= SLOT_2_0;
197104  b = b<<8;
197105  a |= b;
197106
197107  s = s<<4;
197108  b = p[-4];
197109  b &= 0x7f;
197110  b = b>>3;
197111  s |= b;
197112
197113  *v = ((u64)s)<<32 | a;
197114
197115  return 9;
197116}
197117
197118/*
197119** The variable-length integer encoding is as follows:
197120**
197121** KEY:
197122**         A = 0xxxxxxx    7 bits of data and one flag bit
197123**         B = 1xxxxxxx    7 bits of data and one flag bit
197124**         C = xxxxxxxx    8 bits of data
197125**
197126**  7 bits - A
197127** 14 bits - BA
197128** 21 bits - BBA
197129** 28 bits - BBBA
197130** 35 bits - BBBBA
197131** 42 bits - BBBBBA
197132** 49 bits - BBBBBBA
197133** 56 bits - BBBBBBBA
197134** 64 bits - BBBBBBBBC
197135*/
197136
197137#ifdef SQLITE_NOINLINE
197138# define FTS5_NOINLINE SQLITE_NOINLINE
197139#else
197140# define FTS5_NOINLINE
197141#endif
197142
197143/*
197144** Write a 64-bit variable-length integer to memory starting at p[0].
197145** The length of data write will be between 1 and 9 bytes.  The number
197146** of bytes written is returned.
197147**
197148** A variable-length integer consists of the lower 7 bits of each byte
197149** for all bytes that have the 8th bit set and one byte with the 8th
197150** bit clear.  Except, if we get to the 9th byte, it stores the full
197151** 8 bits and is the last byte.
197152*/
197153static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
197154  int i, j, n;
197155  u8 buf[10];
197156  if( v & (((u64)0xff000000)<<32) ){
197157    p[8] = (u8)v;
197158    v >>= 8;
197159    for(i=7; i>=0; i--){
197160      p[i] = (u8)((v & 0x7f) | 0x80);
197161      v >>= 7;
197162    }
197163    return 9;
197164  }
197165  n = 0;
197166  do{
197167    buf[n++] = (u8)((v & 0x7f) | 0x80);
197168    v >>= 7;
197169  }while( v!=0 );
197170  buf[0] &= 0x7f;
197171  assert( n<=9 );
197172  for(i=0, j=n-1; j>=0; j--, i++){
197173    p[i] = buf[j];
197174  }
197175  return n;
197176}
197177
197178static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
197179  if( v<=0x7f ){
197180    p[0] = v&0x7f;
197181    return 1;
197182  }
197183  if( v<=0x3fff ){
197184    p[0] = ((v>>7)&0x7f)|0x80;
197185    p[1] = v&0x7f;
197186    return 2;
197187  }
197188  return fts5PutVarint64(p,v);
197189}
197190
197191
197192static int sqlite3Fts5GetVarintLen(u32 iVal){
197193#if 0
197194  if( iVal<(1 << 7 ) ) return 1;
197195#endif
197196  assert( iVal>=(1 << 7) );
197197  if( iVal<(1 << 14) ) return 2;
197198  if( iVal<(1 << 21) ) return 3;
197199  if( iVal<(1 << 28) ) return 4;
197200  return 5;
197201}
197202
197203
197204/*
197205** 2015 May 08
197206**
197207** The author disclaims copyright to this source code.  In place of
197208** a legal notice, here is a blessing:
197209**
197210**    May you do good and not evil.
197211**    May you find forgiveness for yourself and forgive others.
197212**    May you share freely, never taking more than you give.
197213**
197214******************************************************************************
197215**
197216** This is an SQLite virtual table module implementing direct access to an
197217** existing FTS5 index. The module may create several different types of
197218** tables:
197219**
197220** col:
197221**     CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
197222**
197223**   One row for each term/column combination. The value of $doc is set to
197224**   the number of fts5 rows that contain at least one instance of term
197225**   $term within column $col. Field $cnt is set to the total number of
197226**   instances of term $term in column $col (in any row of the fts5 table).
197227**
197228** row:
197229**     CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
197230**
197231**   One row for each term in the database. The value of $doc is set to
197232**   the number of fts5 rows that contain at least one instance of term
197233**   $term. Field $cnt is set to the total number of instances of term
197234**   $term in the database.
197235*/
197236
197237
197238/* #include "fts5Int.h" */
197239
197240
197241typedef struct Fts5VocabTable Fts5VocabTable;
197242typedef struct Fts5VocabCursor Fts5VocabCursor;
197243
197244struct Fts5VocabTable {
197245  sqlite3_vtab base;
197246  char *zFts5Tbl;                 /* Name of fts5 table */
197247  char *zFts5Db;                  /* Db containing fts5 table */
197248  sqlite3 *db;                    /* Database handle */
197249  Fts5Global *pGlobal;            /* FTS5 global object for this database */
197250  int eType;                      /* FTS5_VOCAB_COL or ROW */
197251};
197252
197253struct Fts5VocabCursor {
197254  sqlite3_vtab_cursor base;
197255  sqlite3_stmt *pStmt;            /* Statement holding lock on pIndex */
197256  Fts5Index *pIndex;              /* Associated FTS5 index */
197257
197258  int bEof;                       /* True if this cursor is at EOF */
197259  Fts5IndexIter *pIter;           /* Term/rowid iterator object */
197260
197261  int nLeTerm;                    /* Size of zLeTerm in bytes */
197262  char *zLeTerm;                  /* (term <= $zLeTerm) paramater, or NULL */
197263
197264  /* These are used by 'col' tables only */
197265  Fts5Config *pConfig;            /* Fts5 table configuration */
197266  int iCol;
197267  i64 *aCnt;
197268  i64 *aDoc;
197269
197270  /* Output values used by 'row' and 'col' tables */
197271  i64 rowid;                      /* This table's current rowid value */
197272  Fts5Buffer term;                /* Current value of 'term' column */
197273};
197274
197275#define FTS5_VOCAB_COL    0
197276#define FTS5_VOCAB_ROW    1
197277
197278#define FTS5_VOCAB_COL_SCHEMA  "term, col, doc, cnt"
197279#define FTS5_VOCAB_ROW_SCHEMA  "term, doc, cnt"
197280
197281/*
197282** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
197283*/
197284#define FTS5_VOCAB_TERM_EQ 0x01
197285#define FTS5_VOCAB_TERM_GE 0x02
197286#define FTS5_VOCAB_TERM_LE 0x04
197287
197288
197289/*
197290** Translate a string containing an fts5vocab table type to an
197291** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
197292** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
197293** and return SQLITE_ERROR.
197294*/
197295static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
197296  int rc = SQLITE_OK;
197297  char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
197298  if( rc==SQLITE_OK ){
197299    sqlite3Fts5Dequote(zCopy);
197300    if( sqlite3_stricmp(zCopy, "col")==0 ){
197301      *peType = FTS5_VOCAB_COL;
197302    }else
197303
197304    if( sqlite3_stricmp(zCopy, "row")==0 ){
197305      *peType = FTS5_VOCAB_ROW;
197306    }else
197307    {
197308      *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
197309      rc = SQLITE_ERROR;
197310    }
197311    sqlite3_free(zCopy);
197312  }
197313
197314  return rc;
197315}
197316
197317
197318/*
197319** The xDisconnect() virtual table method.
197320*/
197321static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
197322  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
197323  sqlite3_free(pTab);
197324  return SQLITE_OK;
197325}
197326
197327/*
197328** The xDestroy() virtual table method.
197329*/
197330static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
197331  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
197332  sqlite3_free(pTab);
197333  return SQLITE_OK;
197334}
197335
197336/*
197337** This function is the implementation of both the xConnect and xCreate
197338** methods of the FTS3 virtual table.
197339**
197340** The argv[] array contains the following:
197341**
197342**   argv[0]   -> module name  ("fts5vocab")
197343**   argv[1]   -> database name
197344**   argv[2]   -> table name
197345**
197346** then:
197347**
197348**   argv[3]   -> name of fts5 table
197349**   argv[4]   -> type of fts5vocab table
197350**
197351** or, for tables in the TEMP schema only.
197352**
197353**   argv[3]   -> name of fts5 tables database
197354**   argv[4]   -> name of fts5 table
197355**   argv[5]   -> type of fts5vocab table
197356*/
197357static int fts5VocabInitVtab(
197358  sqlite3 *db,                    /* The SQLite database connection */
197359  void *pAux,                     /* Pointer to Fts5Global object */
197360  int argc,                       /* Number of elements in argv array */
197361  const char * const *argv,       /* xCreate/xConnect argument array */
197362  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
197363  char **pzErr                    /* Write any error message here */
197364){
197365  const char *azSchema[] = {
197366    "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA  ")",
197367    "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA  ")"
197368  };
197369
197370  Fts5VocabTable *pRet = 0;
197371  int rc = SQLITE_OK;             /* Return code */
197372  int bDb;
197373
197374  bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
197375
197376  if( argc!=5 && bDb==0 ){
197377    *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
197378    rc = SQLITE_ERROR;
197379  }else{
197380    int nByte;                      /* Bytes of space to allocate */
197381    const char *zDb = bDb ? argv[3] : argv[1];
197382    const char *zTab = bDb ? argv[4] : argv[3];
197383    const char *zType = bDb ? argv[5] : argv[4];
197384    int nDb = (int)strlen(zDb)+1;
197385    int nTab = (int)strlen(zTab)+1;
197386    int eType = 0;
197387
197388    rc = fts5VocabTableType(zType, pzErr, &eType);
197389    if( rc==SQLITE_OK ){
197390      assert( eType>=0 && eType<ArraySize(azSchema) );
197391      rc = sqlite3_declare_vtab(db, azSchema[eType]);
197392    }
197393
197394    nByte = sizeof(Fts5VocabTable) + nDb + nTab;
197395    pRet = sqlite3Fts5MallocZero(&rc, nByte);
197396    if( pRet ){
197397      pRet->pGlobal = (Fts5Global*)pAux;
197398      pRet->eType = eType;
197399      pRet->db = db;
197400      pRet->zFts5Tbl = (char*)&pRet[1];
197401      pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
197402      memcpy(pRet->zFts5Tbl, zTab, nTab);
197403      memcpy(pRet->zFts5Db, zDb, nDb);
197404      sqlite3Fts5Dequote(pRet->zFts5Tbl);
197405      sqlite3Fts5Dequote(pRet->zFts5Db);
197406    }
197407  }
197408
197409  *ppVTab = (sqlite3_vtab*)pRet;
197410  return rc;
197411}
197412
197413
197414/*
197415** The xConnect() and xCreate() methods for the virtual table. All the
197416** work is done in function fts5VocabInitVtab().
197417*/
197418static int fts5VocabConnectMethod(
197419  sqlite3 *db,                    /* Database connection */
197420  void *pAux,                     /* Pointer to tokenizer hash table */
197421  int argc,                       /* Number of elements in argv array */
197422  const char * const *argv,       /* xCreate/xConnect argument array */
197423  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
197424  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
197425){
197426  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
197427}
197428static int fts5VocabCreateMethod(
197429  sqlite3 *db,                    /* Database connection */
197430  void *pAux,                     /* Pointer to tokenizer hash table */
197431  int argc,                       /* Number of elements in argv array */
197432  const char * const *argv,       /* xCreate/xConnect argument array */
197433  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
197434  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
197435){
197436  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
197437}
197438
197439/*
197440** Implementation of the xBestIndex method.
197441*/
197442static int fts5VocabBestIndexMethod(
197443  sqlite3_vtab *pUnused,
197444  sqlite3_index_info *pInfo
197445){
197446  int i;
197447  int iTermEq = -1;
197448  int iTermGe = -1;
197449  int iTermLe = -1;
197450  int idxNum = 0;
197451  int nArg = 0;
197452
197453  UNUSED_PARAM(pUnused);
197454
197455  for(i=0; i<pInfo->nConstraint; i++){
197456    struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
197457    if( p->usable==0 ) continue;
197458    if( p->iColumn==0 ){          /* term column */
197459      if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
197460      if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
197461      if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
197462      if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
197463      if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
197464    }
197465  }
197466
197467  if( iTermEq>=0 ){
197468    idxNum |= FTS5_VOCAB_TERM_EQ;
197469    pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
197470    pInfo->estimatedCost = 100;
197471  }else{
197472    pInfo->estimatedCost = 1000000;
197473    if( iTermGe>=0 ){
197474      idxNum |= FTS5_VOCAB_TERM_GE;
197475      pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
197476      pInfo->estimatedCost = pInfo->estimatedCost / 2;
197477    }
197478    if( iTermLe>=0 ){
197479      idxNum |= FTS5_VOCAB_TERM_LE;
197480      pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
197481      pInfo->estimatedCost = pInfo->estimatedCost / 2;
197482    }
197483  }
197484
197485  pInfo->idxNum = idxNum;
197486
197487  return SQLITE_OK;
197488}
197489
197490/*
197491** Implementation of xOpen method.
197492*/
197493static int fts5VocabOpenMethod(
197494  sqlite3_vtab *pVTab,
197495  sqlite3_vtab_cursor **ppCsr
197496){
197497  Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
197498  Fts5Index *pIndex = 0;
197499  Fts5Config *pConfig = 0;
197500  Fts5VocabCursor *pCsr = 0;
197501  int rc = SQLITE_OK;
197502  sqlite3_stmt *pStmt = 0;
197503  char *zSql = 0;
197504
197505  zSql = sqlite3Fts5Mprintf(&rc,
197506      "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
197507      pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
197508  );
197509  if( zSql ){
197510    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
197511  }
197512  sqlite3_free(zSql);
197513  assert( rc==SQLITE_OK || pStmt==0 );
197514  if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
197515
197516  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
197517    i64 iId = sqlite3_column_int64(pStmt, 0);
197518    pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
197519  }
197520
197521  if( rc==SQLITE_OK && pIndex==0 ){
197522    rc = sqlite3_finalize(pStmt);
197523    pStmt = 0;
197524    if( rc==SQLITE_OK ){
197525      pVTab->zErrMsg = sqlite3_mprintf(
197526          "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
197527      );
197528      rc = SQLITE_ERROR;
197529    }
197530  }
197531
197532  if( rc==SQLITE_OK ){
197533    int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
197534    pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
197535  }
197536
197537  if( pCsr ){
197538    pCsr->pIndex = pIndex;
197539    pCsr->pStmt = pStmt;
197540    pCsr->pConfig = pConfig;
197541    pCsr->aCnt = (i64*)&pCsr[1];
197542    pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
197543  }else{
197544    sqlite3_finalize(pStmt);
197545  }
197546
197547  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
197548  return rc;
197549}
197550
197551static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
197552  pCsr->rowid = 0;
197553  sqlite3Fts5IterClose(pCsr->pIter);
197554  pCsr->pIter = 0;
197555  sqlite3_free(pCsr->zLeTerm);
197556  pCsr->nLeTerm = -1;
197557  pCsr->zLeTerm = 0;
197558}
197559
197560/*
197561** Close the cursor.  For additional information see the documentation
197562** on the xClose method of the virtual table interface.
197563*/
197564static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
197565  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197566  fts5VocabResetCursor(pCsr);
197567  sqlite3Fts5BufferFree(&pCsr->term);
197568  sqlite3_finalize(pCsr->pStmt);
197569  sqlite3_free(pCsr);
197570  return SQLITE_OK;
197571}
197572
197573
197574/*
197575** Advance the cursor to the next row in the table.
197576*/
197577static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
197578  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197579  Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
197580  int rc = SQLITE_OK;
197581  int nCol = pCsr->pConfig->nCol;
197582
197583  pCsr->rowid++;
197584
197585  if( pTab->eType==FTS5_VOCAB_COL ){
197586    for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
197587      if( pCsr->aDoc[pCsr->iCol] ) break;
197588    }
197589  }
197590
197591  if( pTab->eType==FTS5_VOCAB_ROW || pCsr->iCol>=nCol ){
197592    if( sqlite3Fts5IterEof(pCsr->pIter) ){
197593      pCsr->bEof = 1;
197594    }else{
197595      const char *zTerm;
197596      int nTerm;
197597
197598      zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
197599      if( pCsr->nLeTerm>=0 ){
197600        int nCmp = MIN(nTerm, pCsr->nLeTerm);
197601        int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
197602        if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
197603          pCsr->bEof = 1;
197604          return SQLITE_OK;
197605        }
197606      }
197607
197608      sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
197609      memset(pCsr->aCnt, 0, nCol * sizeof(i64));
197610      memset(pCsr->aDoc, 0, nCol * sizeof(i64));
197611      pCsr->iCol = 0;
197612
197613      assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
197614      while( rc==SQLITE_OK ){
197615        const u8 *pPos; int nPos;   /* Position list */
197616        i64 iPos = 0;               /* 64-bit position read from poslist */
197617        int iOff = 0;               /* Current offset within position list */
197618
197619        pPos = pCsr->pIter->pData;
197620        nPos = pCsr->pIter->nData;
197621        switch( pCsr->pConfig->eDetail ){
197622          case FTS5_DETAIL_FULL:
197623            pPos = pCsr->pIter->pData;
197624            nPos = pCsr->pIter->nData;
197625            if( pTab->eType==FTS5_VOCAB_ROW ){
197626              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
197627                pCsr->aCnt[0]++;
197628              }
197629              pCsr->aDoc[0]++;
197630            }else{
197631              int iCol = -1;
197632              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
197633                int ii = FTS5_POS2COLUMN(iPos);
197634                pCsr->aCnt[ii]++;
197635                if( iCol!=ii ){
197636                  if( ii>=nCol ){
197637                    rc = FTS5_CORRUPT;
197638                    break;
197639                  }
197640                  pCsr->aDoc[ii]++;
197641                  iCol = ii;
197642                }
197643              }
197644            }
197645            break;
197646
197647          case FTS5_DETAIL_COLUMNS:
197648            if( pTab->eType==FTS5_VOCAB_ROW ){
197649              pCsr->aDoc[0]++;
197650            }else{
197651              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
197652                assert_nc( iPos>=0 && iPos<nCol );
197653                if( iPos>=nCol ){
197654                  rc = FTS5_CORRUPT;
197655                  break;
197656                }
197657                pCsr->aDoc[iPos]++;
197658              }
197659            }
197660            break;
197661
197662          default:
197663            assert( pCsr->pConfig->eDetail==FTS5_DETAIL_NONE );
197664            pCsr->aDoc[0]++;
197665            break;
197666        }
197667
197668        if( rc==SQLITE_OK ){
197669          rc = sqlite3Fts5IterNextScan(pCsr->pIter);
197670        }
197671
197672        if( rc==SQLITE_OK ){
197673          zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
197674          if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
197675            break;
197676          }
197677          if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
197678        }
197679      }
197680    }
197681  }
197682
197683  if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
197684    while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
197685    assert( pCsr->iCol<pCsr->pConfig->nCol );
197686  }
197687  return rc;
197688}
197689
197690/*
197691** This is the xFilter implementation for the virtual table.
197692*/
197693static int fts5VocabFilterMethod(
197694  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
197695  int idxNum,                     /* Strategy index */
197696  const char *zUnused,            /* Unused */
197697  int nUnused,                    /* Number of elements in apVal */
197698  sqlite3_value **apVal           /* Arguments for the indexing scheme */
197699){
197700  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197701  int rc = SQLITE_OK;
197702
197703  int iVal = 0;
197704  int f = FTS5INDEX_QUERY_SCAN;
197705  const char *zTerm = 0;
197706  int nTerm = 0;
197707
197708  sqlite3_value *pEq = 0;
197709  sqlite3_value *pGe = 0;
197710  sqlite3_value *pLe = 0;
197711
197712  UNUSED_PARAM2(zUnused, nUnused);
197713
197714  fts5VocabResetCursor(pCsr);
197715  if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
197716  if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
197717  if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
197718
197719  if( pEq ){
197720    zTerm = (const char *)sqlite3_value_text(pEq);
197721    nTerm = sqlite3_value_bytes(pEq);
197722    f = 0;
197723  }else{
197724    if( pGe ){
197725      zTerm = (const char *)sqlite3_value_text(pGe);
197726      nTerm = sqlite3_value_bytes(pGe);
197727    }
197728    if( pLe ){
197729      const char *zCopy = (const char *)sqlite3_value_text(pLe);
197730      pCsr->nLeTerm = sqlite3_value_bytes(pLe);
197731      pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
197732      if( pCsr->zLeTerm==0 ){
197733        rc = SQLITE_NOMEM;
197734      }else{
197735        memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
197736      }
197737    }
197738  }
197739
197740
197741  if( rc==SQLITE_OK ){
197742    rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
197743  }
197744  if( rc==SQLITE_OK ){
197745    rc = fts5VocabNextMethod(pCursor);
197746  }
197747
197748  return rc;
197749}
197750
197751/*
197752** This is the xEof method of the virtual table. SQLite calls this
197753** routine to find out if it has reached the end of a result set.
197754*/
197755static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
197756  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197757  return pCsr->bEof;
197758}
197759
197760static int fts5VocabColumnMethod(
197761  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
197762  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
197763  int iCol                        /* Index of column to read value from */
197764){
197765  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197766  int eDetail = pCsr->pConfig->eDetail;
197767  int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
197768  i64 iVal = 0;
197769
197770  if( iCol==0 ){
197771    sqlite3_result_text(
197772        pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
197773    );
197774  }else if( eType==FTS5_VOCAB_COL ){
197775    assert( iCol==1 || iCol==2 || iCol==3 );
197776    if( iCol==1 ){
197777      if( eDetail!=FTS5_DETAIL_NONE ){
197778        const char *z = pCsr->pConfig->azCol[pCsr->iCol];
197779        sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
197780      }
197781    }else if( iCol==2 ){
197782      iVal = pCsr->aDoc[pCsr->iCol];
197783    }else{
197784      iVal = pCsr->aCnt[pCsr->iCol];
197785    }
197786  }else{
197787    assert( iCol==1 || iCol==2 );
197788    if( iCol==1 ){
197789      iVal = pCsr->aDoc[0];
197790    }else{
197791      iVal = pCsr->aCnt[0];
197792    }
197793  }
197794
197795  if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
197796  return SQLITE_OK;
197797}
197798
197799/*
197800** This is the xRowid method. The SQLite core calls this routine to
197801** retrieve the rowid for the current row of the result set. The
197802** rowid should be written to *pRowid.
197803*/
197804static int fts5VocabRowidMethod(
197805  sqlite3_vtab_cursor *pCursor,
197806  sqlite_int64 *pRowid
197807){
197808  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197809  *pRowid = pCsr->rowid;
197810  return SQLITE_OK;
197811}
197812
197813static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
197814  static const sqlite3_module fts5Vocab = {
197815    /* iVersion      */ 2,
197816    /* xCreate       */ fts5VocabCreateMethod,
197817    /* xConnect      */ fts5VocabConnectMethod,
197818    /* xBestIndex    */ fts5VocabBestIndexMethod,
197819    /* xDisconnect   */ fts5VocabDisconnectMethod,
197820    /* xDestroy      */ fts5VocabDestroyMethod,
197821    /* xOpen         */ fts5VocabOpenMethod,
197822    /* xClose        */ fts5VocabCloseMethod,
197823    /* xFilter       */ fts5VocabFilterMethod,
197824    /* xNext         */ fts5VocabNextMethod,
197825    /* xEof          */ fts5VocabEofMethod,
197826    /* xColumn       */ fts5VocabColumnMethod,
197827    /* xRowid        */ fts5VocabRowidMethod,
197828    /* xUpdate       */ 0,
197829    /* xBegin        */ 0,
197830    /* xSync         */ 0,
197831    /* xCommit       */ 0,
197832    /* xRollback     */ 0,
197833    /* xFindFunction */ 0,
197834    /* xRename       */ 0,
197835    /* xSavepoint    */ 0,
197836    /* xRelease      */ 0,
197837    /* xRollbackTo   */ 0,
197838  };
197839  void *p = (void*)pGlobal;
197840
197841  return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
197842}
197843
197844
197845
197846
197847
197848#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
197849
197850/************** End of fts5.c ************************************************/
197851